text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: How can I populate this 2d array with values from a char array So I have a grid that is 6 by 7
char[][] grid = new char[6][7];
And is populated with blank spaces using this loop:
for (int row = 0; row < grid.length; row++) {
for (int col = 0; col < grid[0].length; col++) {
grid[row][col] = ' ';
}
}
I also have a char[] array that holds 'A's 'B's and blank spaces. For example ch[0] = B, ch[1] = A, ch[8] = " ".
And I am simply trying to populate each slot of the 2d array 'grid' with the contents of the char array one at a time.
I tried to use the same for loop with some changes to populate the grid but when I run it only populates the top row of my grid and I'm not sure why. I have tried to move the i++, and change the for loop parameters but nothing is working and I need help. This is how I am trying to do it:
int i = 0;
for (int row = 0; row < grid.length; row++) {
for (int col = 0; col < grid[0].length; col++) {
grid[row][col] = ch[i];
i++;
}
}
If it helps to know I am getting the contents of ch[] from a .csv file and storing it in a char array. When I run this code as is, it perfectly populates the top row of my grid (first row) but then it does not do anything to the remaining rows.
I don't want to change the data types of anything, I know I can get this too work I just need some help.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74130838",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why does the mongo shell work without mongod server being explicitly run? Running MongoDB Shell v-3.2.8
I've noticed that articles and tutorials always mention to run the mongod server before running the mongo shell.
However, when I skip the first step and simply type mongo into my terminal, the mongo shell works without any errors / interruptions.
MacBook:Desktop user$ mongo
MongoDB shell version: 3.2.8
connecting to: test
Why does this work? Does mongo call mongod?
A: The mongod is being ran as a service or daemon, which means that there is always a mongod process running listening to a port. I use ubuntu, and when I install mongodb through the package manager, it immediately starts up a mongod process and begins listening on the standard port.
Running mongo is simply a small utility that attempts to connect to the localhost at the standard ip. The data reading, writing, and querying is done by the mongod process while mongo is a small program that sends the the commands to mongod.
If mongod wasn't running, you would see an error stating "Unable to connect to mongodb server"
A: I noticed the same. I think mongoose is doing some smart things there, which I'm not sure how it works. But I have noticed such things before, like mongoose will automatically add an "s" to your database's name when you declare it, which is a very thoughtful act =)).
A: I encountered the same thing and found that in the background services if MongoDB server is running, the mongo shell will work without any error. If we stop the service, the shell will throw an error.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39988477",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: "Unable to connect to server" error while attempting to get street address by entering latitude and longitude this is my code to return address for providing latitude and longitude of a place.
public string GetLocation()
{
HttpWebRequest request = default(HttpWebRequest);
HttpWebResponse response = null;
StreamReader reader = default(StreamReader);
string json = null;
try
{
//Create the web request
request = (HttpWebRequest)WebRequest.Create("http://maps.googleapis.com/maps/api/geocode/json?latlng=27.7121753,85.3434027&sensor=true");
//Get response
response = (HttpWebResponse)request.GetResponse();
//Get the response stream into a reader
reader = new StreamReader(response.GetResponseStream());
json = reader.ReadToEnd();
response.Close();
TextBox1.Text = json;
if (json.Contains("ZERO_RESULTS"))
{
TextBox2.Text = "No Address Available";
};
if (json.Contains("formatted_address"))
{
//CurrentAddress.Text = "Address Available";
int start = json.IndexOf("formatted_address");
int end = json.IndexOf(", Nepal");
string AddStart = json.Substring(start + 21);
string EndStart = json.Substring(end);
string FinalAddress = AddStart.Replace(EndStart, ""); //Gives Full Address, One Line
TextBox2.Text = FinalAddress;
};
}
catch (Exception ex)
{
string Message = "Error: " + ex.ToString();
}
}
as the code reaches response = (HttpWebResponse)request.GetResponse(); it throws an error
"Unable to connect to the remote server".. can anyone tell how can i solve it?
A: The Web Request code works for me in US. Ensure the following:
*
*You're not using Proxy etc.
*You can enter this URL in the browser and see JSON results: http://maps.googleapis.com/maps/api/geocode/json?latlng=27.7121753,85.3434027&sensor=true
*Run Fiddler and see what is your request/response.
*Google MAP API access is allowed in the country you're trying from.
Most probably this looks like a proxy issue, since Google APIs would give back better error messages for country access/excessive requests etc.
Try setting your proxy in the config as follows:
<system.net>
<defaultProxy>
<proxy usesystemdefault = "false" proxyaddress="http://address:port" bypassonlocal="false" />
</defaultProxy>
</system.net>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22854111",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Google Static Maps With Traffic and Public Transport Overlays I use the following to get a png image of the location I want:
string.Format(
"http://maps.googleapis.com/maps/api/staticmap?center={0},{1}&zoom={2}&size={3}x{4}&maptype={5}&sensor=false",
latitude,
longitude,
zoomLevel,
width,
height,
(char)this.Type);
How can I add traffic or public transport overlays to the image via the URL? Is there an alternative URL api?
A: Appending the following, for example for traffic overlay;
&layer=t
For other overlays just use the link button in the top right of the bottom left hand pane after selecting the layer you want to see which parameters need to be added to the URL to show the given overlay(s)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/9298326",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Kubernetes volume snapshot Vs. sql backup? I am running database inside Kubernetes pod. i am planning to run K8s job to take automatic backup of databases from pod.
There is also i can write shell script to take snapshot of volume(PV).
which method will be better to use? in emergency which one will save time restore data ?
A: You can use Stash by AppsCode which is a great solution to backup Kubernetes volumes.
For supported versions check here
Stash by AppsCode is a Kubernetes operator for restic. If you are
running production workloads in Kubernetes, you might want to take
backup of your disks. Traditional tools are too complex to setup and
maintain in a dynamic compute environment like Kubernetes. restic is a
backup program that is fast, efficient and secure with few moving
parts. Stash is a CRD controller for Kubernetes built around restic to
address these issues.
Using Stash, you can backup Kubernetes volumes mounted in following
types of workloads:
Deployment, DaemonSet, ReplicaSet, ReplicationController, StatefulSet
After installing stash using Script or HELM you would want to follow
Instructions for Backup and Restore if you are not familiar
I find it very useful
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54820956",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Insert an array into MySQL using LabVIEW and Workbench I am running an experiment and want to log a double array of 500 values to a MySQL table using LabVIEW. The amount of results will vary per test, and may be up to 2,000 but usually 500.
Firstly, I am instantiating a database. I am thinking of setting the column to mediumtext, is that the best type?
Secondly, advice such as here, suggests first converting all double arrays to comma separated strings. Is that the best approach?
It all seems very contrived, is there a better way of storing arrays in MySQL?
A: An array usually consists of values all of the same type. That fits perfectly to a database column, where all values have the same type as well. Hence, for e.g. an array of double, you could create a column that takes float values and insert each member of the array as individual row. 500 rows is nothing, you could insert millions that way.
A: *
*below query works to insert array of string to the column in MYSql Workbench
insert into tableName (column1) values ('["Lorem Ipsum","Lorem Ipsum","Lorem Ipsum","Lorem Ipsum","Lorem Ipsum"]')
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37456594",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: model name to controller name How can I get the controller name out of the object if I don't know what the object is?
I am trying to do:
object.class.tableize
but Rails says:
undefined method `tableize' for #<Class:0xb6f8ee20>
I tried adding demodulize with same result.
thanks
A: object.class.to_s.tableize
A: For semantic reasons, you might want to do:
object.class.name #=> 'FooBar'
You can also use tableize with this sequence, like so:
object.class.name.tableize #=> 'foo_bars'
I prefer it that way due to readability.
As well, note that tableize also does pluralization. If unwanted use underscore.
Hope it helps anyone, even if it's an old thread :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1631577",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Ball arithmetic vs interval arithmetic What are the advantages of ball arithmetic (Arb) over interval arithmetic (MPFI)?
In other words, what are the advantages of representing an interval as [center, radius] over [left, right]?
This is not about particular library (Arb vs MPFI), rather it is about advantages of a particular representation.
I'm especially interested whether one representation allows for faster arithmetic (fewer primitive operations), lesser error over-estimation and more frugal memory usage.
A: In arbitrary-precision arithmetic, ball arithmetic is about twice as fast as interval arithmetic and uses half as much space. The reason is that only the center of a ball needs high precision, whereas in interval arithmetic, both endpoints need high precision. Details depend on the implementation, of course. (In practice, Arb is faster than MPFI by much more than a factor two, but this is largely due to implementation effort.)
In hardware arithmetic, balls don't really have a speed advantage over intervals, at least for scalar arithmetic. There is an obvious advantage if you look at more general forms of ball arithmetic and consider, for example, a ball matrix as a floating-point matrix + a single floating-point number for the error bound of the whole matrix in some norm, instead of working with a matrix of individual intervals or balls.
Joris van der Hoeven's article on ball arithmetic is a good take on the differences between ball and interval arithmetic: http://www.texmacs.org/joris/ball/ball.html
An important quote is: "Roughly speaking, balls should be used for the reliable approximation of numbers, whereas intervals are mainly useful for certified algorithms which rely on the subdivision of space."
Ignoring performance concerns, balls and intervals are usually interchangeable, although intervals are better suited for subdivision algorithms. Conceptually, balls are nice for representing numbers because the center-radius form corresponds naturally to how we think of approximations in mathematics. This notion also extends naturally to more general normed vector spaces.
Personally, I often think of ball arithmetic as floating-point arithmetic + error analysis, but with the error bound propagation done automatically by the computer rather than by hand. In this sense, it is a better way (for certain applications!) of doing floating-point arithmetic, not just a better way of doing interval arithmetic.
For computations with single numbers, error over-estimation has more to do with the algorithms than with the representation. MPFI guarantees that all its atomic functions compute the tightest possible intervals, but this property is not preserved as soon as you start composing functions. With either ball or interval arithmetic, blow-up tends to happen in the same way as soon as you run calculations with many dependent steps. To track error bounds resulting from large uncertainties in initial conditions, techniques such as Taylor models are often better than direct interval or ball arithmetic.
True complex balls (complex center + single radius) are sometimes better than rectangular complex intervals for representing complex numbers because the wrapping effect for multiplications is smaller. (However, Arb uses rectangular "balls" for complex numbers, so it does not have this particular advantage.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53123151",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: SSIS - Loading Japanese Double byte data from DB2 to SQL Server 2017 is giving conversion error I am trying import data from DB2 which has double byte Japanese(1027) data into SQL Server 2017 using SSIS
Tried using data conversion before inserting data "932 (ANSI/OEM - Japanese Shift- JIS)". Tried using Unicode string[DT_WSTR] still the same issue
[Data Conversion [2]] Error: Data conversion failed while converting column "ABC" (286) to column "A\cABC"(38). The conversion returned status value 4 and status text "Text was truncated or one or more characters had no match in the target code page.".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56478750",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: c# console application run matlab function I have some code written in Matlab however I wish to call this code from a C# console application.
I do not require any data to be returned from Matlab to my app (although if easy would be nice to see).
There appears to be a few options however not sure which is best. Speed is not important as this will be an automated task.
A: MATLAB has a .Net interface that's well-documented. What you need to do is covered in the Call MATLAB Function from C# Client article.
For a simple MATLAB function, say:
function [x,y] = myfunc(a,b,c)
x = a + b;
y = sprintf('Hello %s',c);
..it boils down to creating an MLApp and invoking the Feval method:
class Program
{
static void Main(string[] args)
{
// Create the MATLAB instance
MLApp.MLApp matlab = new MLApp.MLApp();
// Change to the directory where the function is located
matlab.Execute(@"cd c:\temp\example");
// Define the output
object result = null;
// Call the MATLAB function myfunc
matlab.Feval("myfunc", 2, out result, 3.14, 42.0, "world");
// Display result
object[] res = result as object[];
Console.WriteLine(res[0]);
Console.WriteLine(res[1]);
Console.ReadLine();
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29941192",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Gradle project sync failed after Android-Studio (3.1) update After an update I made on 27-03-2018, my gradle sync is failing.I am getting the error
Could not find org.jetbrains.kotlin:kotlin-stdlib:1.1.3-2.
I am posting my gradle files below. I have tried cleaning and rebuilding the project, but it is still not working.
Project level gradle
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
maven {
url 'https://maven.google.com/'
}
}
dependencies {
classpath 'com.android.tools.build:gradle:3.1.0'
classpath 'com.google.gms:google-services:3.0.0'
classpath 'com.loopj.android:android-async-http:1.4.9'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
App level gradle
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'
apply plugin: 'com.google.gms.google-services'
buildscript {
repositories {
maven { url 'https://maven.fabric.io/public' }
google()
}
dependencies {
classpath 'io.fabric.tools:gradle:1.+'
}
}
buildscript {
dependencies {
classpath 'com.android.tools.build:gradle:3.0.1'
}
}
android {
compileSdkVersion 25
buildToolsVersion '26.0.2'
lintOptions {
disable 'InvalidPackage'
}
defaultConfig {
applicationId 'app.myapp.com'
minSdkVersion 15
targetSdkVersion 25
versionCode 33
versionName "1.1.30"
useLibrary 'org.apache.http.legacy'
// Enabling multidex support.
multiDexEnabled true
vectorDrawables.useSupportLibrary = true
}
dexOptions {
preDexLibraries = false
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
productFlavors {
}
lintOptions {
checkReleaseBuilds false
}
packagingOptions {
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/NOTICE'
exclude 'META-INF/LICENSE'
}
}
repositories {
mavenCentral()
jcenter()
maven { url 'https://maven.fabric.io/public'
}
maven {
url 'https://maven.google.com/'
name 'Google'
}
google()
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile project(':android-async-http-1.4.9')
// compile 'com.daimajia.androidanimations:library:1.0.3@aar'
compile project(':PayTabs_SDK_NOSCAN')
compile('com.twitter.sdk.android:twitter:1.14.1@aar') {
transitive = true;
}
compile('org.apache.httpcomponents:httpmime:4.3') {
exclude module: "httpclient"
}
compile files('libs/signpost-core-1.2.1.2.jar')
// Discovery and Outlook services
compile('com.microsoft.services:discovery-services:1.0.0@aar') {
transitive = true
}
compile('com.microsoft.services:outlook-services:1.0.0@aar') {
transitive = true
}
compile 'org.sufficientlysecure:html-textview:3.3'
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support:design:25.3.1'
compile 'com.android.support:support-v4:25.3.1'
compile 'cz.msebera.android:httpclient:4.3.6'
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.nineoldandroids:library:2.4.0'
compile 'com.daimajia.slider:library:1.1.5@aar'
compile 'me.dm7.barcodescanner:zxing:1.8.4'
compile 'com.google.android.gms:play-services:9.0.0'
compile 'com.android.support:multidex:1.0.1'
compile 'com.google.gms:google-services:3.0.0'
compile 'com.google.android.gms:play-services-ads:9.0.0'
compile 'com.google.android.gms:play-services-auth:9.0.0'
compile 'com.google.android.gms:play-services-gcm:9.0.0'
compile 'org.codepond:wizardroid:1.3.1'
compile 'com.facebook.android:facebook-android-sdk:4.0.0'
compile 'com.google.code.gson:gson:2.3.1'
compile 'com.google.zxing:core:3.2.0'
compile 'io.card:android-sdk:5.3.0'
compile 'com.google.firebase:firebase-messaging:9.0.1'
compile 'com.mcxiaoke.volley:library-aar:1.0.0'
compile 'me.dm7.barcodescanner:zbar:1.8.2'
compile 'com.journeyapps:zxing-android-embedded:3.0.2@aar'
compile 'de.hdodenhof:circleimageview:2.0.0'
compile 'com.cloudrail:cloudrail-si-android:2.11.0'
compile 'org.apache.httpcomponents:httpclient-android:4.3.5.1'
compile 'com.davemorrissey.labs:subsampling-scale-image-view:3.6.0'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.android.support:recyclerview-v7:25.3.1'
compile 'com.ss.bannerslider:bannerslider:1.8.0'
compile 'com.marshalchen.ultimaterecyclerview:library:0.7.3'
// compile "org.jetbrains.kotlin:kotlin-stdlib-jdk7"
testCompile 'junit:junit:4.12'
}
configurations.all {
resolutionStrategy.eachDependency { DependencyResolveDetails details ->
def requested = details.requested
if (requested.group == 'com.android.support') {
if (!requested.name.startsWith("multidex")) {
details.useVersion '25.3.1'
}
}
}
}
I tried all that I know, but nothing is working for now. Android Studio and Gradle are updated to the latest version. The app used to work before the update. I followed the instructions in developer.android.com about gradle migration, but nothing is mentioned there that might help me with the issue.
I am posting the error I get here
Could not find org.jetbrains.kotlin:kotlin-stdlib:1.1.3-2.
Searched in the following locations:
https://maven.fabric.io/public/org/jetbrains/kotlin/kotlin-stdlib/1.1.3-2/kotlin-stdlib-1.1.3-2.pom
https://maven.fabric.io/public/org/jetbrains/kotlin/kotlin-stdlib/1.1.3-2/kotlin-stdlib-1.1.3-2.jar
https://dl.google.com/dl/android/maven2/org/jetbrains/kotlin/kotlin-stdlib/1.1.3-2/kotlin-stdlib-1.1.3-2.pom
https://dl.google.com/dl/android/maven2/org/jetbrains/kotlin/kotlin-stdlib/1.1.3-2/kotlin-stdlib-1.1.3-2.jar
Required by:
project :app > com.android.tools.build:gradle:3.0.1 > com.android.tools.build:gradle-core:3.0.1
project :app > com.android.tools.build:gradle:3.0.1 > com.android.tools.build:gradle-core:3.0.1 > com.android.tools.build:builder:3.0.1
project :app > com.android.tools.build:gradle:3.0.1 > com.android.tools.build:gradle-core:3.0.1 > com.android.tools.lint:lint:26.0.1
project :app > com.android.tools.build:gradle:3.0.1 > com.android.tools.build:gradle-core:3.0.1 > com.android.tools.build:builder:3.0.1 > com.android.tools:sdk-common:26.0.1
project :app > com.android.tools.build:gradle:3.0.1 > com.android.tools.build:gradle-core:3.0.1 > com.android.tools.build:builder:3.0.1 > com.android.tools:sdklib:26.0.1 > com.android.tools:repository:26.0.1
project :app > com.android.tools.build:gradle:3.0.1 > com.android.tools.build:gradle-core:3.0.1 > com.android.tools.lint:lint:26.0.1 > com.android.tools.lint:lint-checks:26.0.1 > com.android.tools.lint:lint-api:26.0.1
A: i too came up with the same issue. seems like android studio seeking to update the kotlin plugin as well.
go to Tools > Kotlin > Configure Kotlin Plugin Update and update the plugin.
then restart studio, and it will sync the gradle on restart.
A: I found the answer. I changed the versions of gradle plugins.I am adding my Gradle files below
Project Level
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
maven {
url 'https://maven.google.com/'
name 'Google'
}
}
dependencies {
classpath 'com.android.tools.build:gradle:3.1.0'
classpath 'com.google.gms:google-services:3.1.1'
classpath 'com.loopj.android:android-async-http:1.4.9'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
App Level build.gradle file
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'
apply plugin: 'com.google.gms.google-services'
buildscript {
repositories {
maven { url 'https://maven.fabric.io/public' }
}
dependencies {
classpath 'io.fabric.tools:gradle:1.+'
}
}
buildscript {
repositories {
jcenter()
google()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.1'
}
}
android {
compileSdkVersion 25
buildToolsVersion '26.0.2'
lintOptions {
disable 'InvalidPackage'
}
defaultConfig {
applicationId 'app.ecopon.com'
minSdkVersion 15
targetSdkVersion 25
versionCode 33
versionName "1.1.30"
useLibrary 'org.apache.http.legacy'
// Enabling multidex support.
multiDexEnabled true
vectorDrawables.useSupportLibrary = true
}
dexOptions {
preDexLibraries = false
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
productFlavors {
}
lintOptions {
checkReleaseBuilds false
}
packagingOptions {
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/NOTICE'
exclude 'META-INF/LICENSE'
}
}
repositories {
mavenCentral()
jcenter()
maven { url 'https://maven.fabric.io/public'
}
maven {
url 'https://maven.google.com/'
name 'Google'
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile project(':android-async-http-1.4.9')
// compile 'com.daimajia.androidanimations:library:1.0.3@aar'
compile project(':PayTabs_SDK_NOSCAN')
compile('com.twitter.sdk.android:twitter:1.14.1@aar') {
transitive = true;
}
compile('org.apache.httpcomponents:httpmime:4.3') {
exclude module: "httpclient"
}
compile files('libs/signpost-core-1.2.1.2.jar')
// Discovery and Outlook services
compile('com.microsoft.services:discovery-services:1.0.0@aar') {
transitive = true
}
compile('com.microsoft.services:outlook-services:1.0.0@aar') {
transitive = true
}
compile 'org.sufficientlysecure:html-textview:3.3'
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support:design:25.3.1'
compile 'com.android.support:support-v4:25.3.1'
compile 'cz.msebera.android:httpclient:4.3.6'
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.nineoldandroids:library:2.4.0'
compile 'com.daimajia.slider:library:1.1.5@aar'
compile 'me.dm7.barcodescanner:zxing:1.8.4'
compile 'com.google.android.gms:play-services:9.0.0'
compile 'com.android.support:multidex:1.0.1'
compile 'com.google.gms:google-services:3.0.0'
compile 'com.google.android.gms:play-services-ads:9.0.0'
compile 'com.google.android.gms:play-services-auth:9.0.0'
compile 'com.google.android.gms:play-services-gcm:9.0.0'
compile 'org.codepond:wizardroid:1.3.1'
compile 'com.facebook.android:facebook-android-sdk:4.0.0'
compile 'com.google.code.gson:gson:2.3.1'
compile 'com.google.zxing:core:3.2.0'
compile 'io.card:android-sdk:5.3.0'
compile 'com.google.firebase:firebase-messaging:9.0.0'
compile 'com.mcxiaoke.volley:library-aar:1.0.0'
compile 'me.dm7.barcodescanner:zbar:1.8.2'
compile 'com.journeyapps:zxing-android-embedded:3.0.2@aar'
compile 'de.hdodenhof:circleimageview:2.0.0'
compile 'com.cloudrail:cloudrail-si-android:2.11.0'
compile 'org.apache.httpcomponents:httpclient-android:4.3.5.1'
compile 'com.davemorrissey.labs:subsampling-scale-image-view:3.6.0'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.android.support:recyclerview-v7:25.3.1'
compile 'com.ss.bannerslider:bannerslider:1.8.0'
compile 'com.marshalchen.ultimaterecyclerview:library:0.7.3'
compile 'com.github.barteksc:android-pdf-viewer:2.8.2'
testCompile 'junit:junit:4.12'
}
configurations.all {
resolutionStrategy.eachDependency { DependencyResolveDetails details ->
def requested = details.requested
if (requested.group == 'com.android.support') {
if (!requested.name.startsWith("multidex")) {
details.useVersion '25.3.1'
}
}
}
}
Now, everything is working perfectly
A: Found a solution to this. You need to add google() to the buildscript and allprojects repository section as below:
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.1.1'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
A: 1- Go to http://services.gradle.org
2- Go to Distributions
3- Click on the latest one to download it (I downloaded "gradle-4.6-rc-2-all.zip")
4- Unzip or Extract it
5- In Android Studio go to File > Settings > Build, Execution, Deployment > Gradle > Use local gradle distribution > then choose the file (that you just download and unzip it) from your computer
6- Click Ok
7- Inside "build.gradle(Module:app)" make sure that compileSdkVersion and targetSdkVersion are same
8- Click Sync Now
Resource: https://www.youtube.com/watch?v=q_qWUQNbFLY
A: Change your Buildscript part of your build.gradle To this , Actully Remove google() & jcenter(). This Worked for me.
buildscript {
repositories {
maven { url 'https://jitpack.io' }
mavenCentral()
maven { url "https://maven.google.com" }
}
dependencies {
classpath 'com.android.tools.build:gradle:3.1.0'
}
}
A: You could try updating your Kotlin version and maybe add https://maven.google.com to the repositories tag of allProjects.
Your project level build.gradle should look something like this afterwards:
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = '1.2.30'
repositories {
jcenter()
google()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.1.0'
classpath 'com.google.gms:google-services:3.1.0'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath 'com.loopj.android:android-async-http:1.4.9'
}
}
allprojects {
repositories {
jcenter()
maven { url 'https://jitpack.io' }
maven { url "https://maven.google.com" }
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
Besides that, try cleaning the project and maybe removing your .gradle folders manually
A: Try to invalidate cache(did it a few times) or reinstall studio, or check gradle-wrapper.properties distributionUrl should be like this:
distributionUrl=https://services.gradle.org/distributions/gradle-4.4-all.zip
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49506307",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
} |
Q: What is the syntax for the input for a def function with multiple nested functions? I'm learning Python right now and I am just trying to get to grips with all of the syntax options.
Currently, the only thing that I can't seem to google up is what to do if I for some reason want to define a function which contains multiple other defines.
While I understand what to do if there's only 1 define inside the the larger define (val = f()(3,4) returns 7 if you exclude the second def below), I don't know how to correctly use the function below.
If it's possible, what is the syntax for a def function with an arbitrary amount of defined functions within it?
Code:
def f():
def x(a,b):
return a + b
return x
def y(c,d):
return c + d
return y
val = f()(3,4)(5,6)
print(val)
I expected the above to return either (7,11) or 11. However, it returns 'int object is not callable'
A: When you write val = f()(3,4)(5,6), you want f to return a function that also returns a function; compare with the simpler multi-line call:
t1 = f()
t2 = t1(3,4)
val = t2(5,6)
The function f defines and returns also has to define and return a function that can be called with 2 arguments. So, as @jonrsharpe said, you need more nesting:
def f():
def x(a, b):
def y(c, d):
return c + d
return y
return x
Now, f() produces the function named x, and f()(3,4) produces the function named y (ignoring its arguments 3 and 4 in the process), and f()(3,4)(5,6) evaluates (ultimately) to 5 + 6.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54312700",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Installing Glassfish to work with Eclipse I am stock here with glassfish configuration at Eclipse.
Take a look:
The finish button is disabled. What should I do here? I am pointing it to the directory in which I have installed glassfish. Plz help.
A: I think the problem might be that you were trying to register GF 3.1.2 to use Java SE 5. Java EE 6 requires a Java SE 6 JDK to run successfully.
A: Okay I don't know what was wrong with it. Just tried it one more time and it worked! Sry for taking your times.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10924036",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Decode a special character...? I am pulling through the field item_name from a database. It should read : "Reminisce Basic £11.99 + Card £4.99 + Free"
But when its coming through the £ signs are coming out as � is there a method to decode this to at least make it look like a £ sign?
My code is as follows :
<?php
$con = mysql_connect("localhost","","");
mysql_select_db("", $con);
$result = mysql_query("SELECT custom, item_name from paypalsub WHERE custom = '$_SESSION[uid]'");
while($row = mysql_fetch_array($result))
{
$sub_type = $row['item_name'];
}
?>
<h2>You are currently subscribed to : <?php echo ($sub_type); ?></h2>
The H2 is outputting it like this :
You are currently subscribed to : Reminisce Basic �11.99 + Card �4.99 + Free
Any help.. Much appreciated.
A: Try with utf8_encode($string) or utf8_decode($string). I never remember which one to use, sorry.
A: 1.) Are you sending the output in UTF-8?
header('content-type: text/html; charset=utf-8')
2.) Have you also set the MySQL connection to UTF-8?
mysql_query("SET NAMES 'utf-8'");
A: It looks like your database is in some encoding (not UTF-8) and your output is in a different encoding.
Find out which encoding the database uses.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8152587",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Arrangement properties in WPF styles Is it normal to store Alignments, Margins, Paddings and other arrangement properties in styles?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13524347",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Get Woocommerce product reviews via rest api I tried to get product reviews with rest api but I got an error woocommerce_rest_cannot_view
https://example.com/wp-json/wc/v3/products/reviews?product=ID
I don't know where is the problem
A: In some how it was an issue on woocommerce api
I edited the class-wc-rest-product-reviews.php
$prepared_args['type'] = 'review';
changed review to comment and it works
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59228477",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Object of class [org.jongo.bson.RelaxedLazyDBObject] must be an instance of class com.mongodb.BasicDBObject I'm trying to setup tests with Spring Boot and Mongo Embedded (JHipster, Flapdoodle).
In general it works. I can see database in Robomongo with created test collections and objects (migrations using Mongobee).
But when I want to access Clients collection:
List clients = clientRepository.findAll();
It throws:
java.lang.IllegalArgumentException: Given DBObject must be a BasicDBObject! Object of class [org.jongo.bson.RelaxedLazyDBObject] must be an instance of class com.mongodb.BasicDBObject
When I run application with real Mongo instance:
./mvnw -Pdev
there are no errors even though test and dev configurations use the same Mongobee mibrations.
Spring documentation is very laconic:
http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-mongo-embedded
My test configuration file application.yml is:
spring:
mongodb:
embedded:
version: 3.2.1
data:
mongodb:
host: localhost
port: 27117
database: mydb-test
I use Mongo (real instance) version v3.2.7, in configuration highest possible version of Embedded Mongo which I set is 3.2.1, maybe this could be a problem?
Maybe someone could share his configuration with example working tests?
A: I find my self the solution.
Problem was that I used org.jongo.Jongo instead of JHipster default com.mongodb.Db in @ChangeSet.
For some reasons Jongo doesn't work well with Embedded Mongo.
When I switched to Db, all problems has gone.
NOT WORKING:
@ChangeSet(...)
public void someChange(Jongo jongo) throws IOException {
org.jongo.MongoCollection collection = jongo.getCollection("collection");
DBObject basicDBObject = new BasicDBObject();
collection.insert(basicDBObject);
...
}
WORKING:
@ChangeSet(...)
public void someChange(Db db) throws IOException {
com.mongodb.MongoCollection collection = db.getCollection("collection");
DBObject basicDBObject = new BasicDBObject();
collection.insert(basicDBObject);
...
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38368872",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Backbone trigger event after custom function possible? Excuse my backbone i'm not an expert, Must execute function Show absolutely and only after ResetQuestions
ResetQuestions:function () {
//Great Code Here
}),
I tried this:
initialize: function () {
this.on("Show", this.Show, this);
},
ResetQuestions:function () {
//Great Code Here
this.trigger("Show");
}),
But that was unsuccessful, does anyone know how i can accomplish this?
A: no need of events you can simply call the function from other function
var sampleView = Backbone.View.extend({
initialize: function () {
this.ResetQuestions();
},
Show: function () {
alert('i am at show');
},
ResetQuestions: function () {
// Execute all you code atlast call Show function as below.
this.Show();
}
});
var view = new sampleView();
A: var sampleView = Backbone.View.extend({
initialize: function(){
this.ResetQuestions().promise().done(function() { // Using promise here.
this.Show();
});
},
Show: function(){
},
ResetQuestions: function(){
// Execute all you code atlast call Show function as below.
}
});
Then initiate your view,
var view = new sampleView();
Hope this works!!
A: Perhaps you just got confused what runs what and by naming event and method with same name Show. I have created a jsfiddle with your code - http://jsfiddle.net/yuraji/aqymbeyy/ - you call ResetQuestion method, it triggers Show event, and the Show event runs Show method.
EDIT: I have updated the fiddle to demonstrate that you probably have to bind the methods to the instance, I used _.bindAll for that. If you don't do that you may get event as the context (this).
EDIT: Then, if your ResetQuestions runs asynchronous code, like an ajax request to get new questions, you will have to make sure that your Show event is triggered when the request is completed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25971445",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Pentaho SDK, how to define a text file input I'm trying to define a Pentaho Kettle (ktr) transformation via code. I would like to add to the transformation a Text File Input Step: http://wiki.pentaho.com/display/EAI/Text+File+Input.
I don't know how to do this (note that I want to achieve the result in a custom Java application, not using the standard Spoon GUI). I think I should use the TextFileInputMeta class, but when I try to define the filename the trasformation doesn't work anymore (it seems empty in Spoon).
This is the code I'm using. I think the third line has something wrong:
PluginRegistry registry = PluginRegistry.getInstance();
TextFileInputMeta fileInMeta = new TextFileInputMeta();
fileInMeta.setFileName(new String[] {myFileName});
String fileInPluginId = registry.getPluginId(StepPluginType.class, fileInMeta);
StepMeta fileInStepMeta = new StepMeta(fileInPluginId, myStepName, fileInMeta);
fileInStepMeta.setDraw(true);
fileInStepMeta.setLocation(100, 200);
transAWMMeta.addStep(fileInStepMeta);
A: To run a transformation programmatically, you should do the following:
*
*Initialise Kettle
*Prepare a TransMeta object
*Prepare your steps
*
*Don't forget about Meta and Data objects!
*Add them to TransMeta
*Create Trans and run it
*
*By default, each transformation germinates a thread per step, so use trans.waitUntilFinished() to force your thread to wait until execution completes
*Pick execution's results if necessary
Use this test as example: https://github.com/pentaho/pentaho-kettle/blob/master/test/org/pentaho/di/trans/steps/textfileinput/TextFileInputTests.java
Also, I would recommend you create the transformation manually and to load it from file, if it is acceptable for your circumstances. This will help to avoid lots of boilerplate code. It is quite easy to run transformations in this case, see an example here: https://github.com/pentaho/pentaho-kettle/blob/master/test/org/pentaho/di/TestUtilities.java#L346
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34004353",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to access kubernetes CRD using client-go? I have few CRDs, but I am not exactly sure how to query kube-apiserver to get list of CRs. Can anyone please provide any sample code?
A: my sample code for an out of cluster config
var kubeconfig *string
kubeconfig = flag.String("kubeconfig", "./config", "(optional) relative path to the kubeconfig file")
flag.Parse()
// kubernetes config loaded from ./config or whatever the flag was set to
config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
if err != nil {
panic(err)
}
// instantiate our client with config
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err)
}
// get a list of our CRs
pl := PingerList{}
d, err := clientset.RESTClient().Get().AbsPath("/apis/pinger.hel.lo/v1/pingers").DoRaw(context.TODO())
if err != nil {
panic(err)
}
if err := json.Unmarshal(d, &pl); err != nil {
panic(err)
}
PingerList{} is an object generated from Kubebuilder that I unmarshal to later in the code. However, you could just straight up println(string(d)) to get that json.
The components in the AbsPath() are "/apis/group/verison/plural version of resource name"
if you're using minikube, you can get the config file with kubectl config view
Kubernetes-related imports are the following
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/kubernetes"
A: Refer this page to get information on how to access the crd using this repo
and for more information refer this document
document
A: Either you need to use the Unstructured client, or generate a client stub. The dynamic client in the controller-runtime library is a lot nicer for this and I recommend it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60764908",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Which of these is more python-like? I'm doing some exploring of various languages I hadn't used before, using a simple Perl script as a basis for what I want to accomplish. I have a couple of versions of something, and I'm curious which is the preferred method when using Python -- or if neither is, what is?
Version 1:
workflowname = []
paramname = []
value = []
for line in lines:
wfn, pn, v = line.split(",")
workflowname.append(wfn)
paramname.append(pn)
value.append(v)
Version 2:
workflowname = []
paramname = []
value = []
i = 0;
for line in lines:
workflowname.append("")
paramname.append("")
value.append("")
workflowname[i], paramname[i], value[i] = line.split(",")
i = i + 1
Personally, I prefer the second, but, as I said, I'm curious what someone who really knows Python would prefer.
A: Of your two attepts the 2nd one doesn't make any sense to me. Maybe in other languages it would. So from your two proposed approaces the 1st one is better.
Still I think the pythonic way would be something like Matt Luongo suggested.
A: Bogdan's answer is best. In general, if you need a loop counter (which you don't in this case), you should use enumerate instead of incrementing a counter:
for index, value in enumerate(lines):
# do something with the value and the index
A: A Pythonic solution might a bit like @Bogdan's, but using zip and argument unpacking
workflowname, paramname, value = zip(*[line.split(',') for line in lines])
If you're determined to use a for construct, though, the 1st is better.
A: Version 1 is definitely better than version 2 (why put something in a list if you're just going to replace it?) but depending on what you're planning to do later, neither one may be a good idea. Parallel lists are almost never more convenient than lists of objects or tuples, so I'd consider:
# list of (workflow,paramname,value) tuples
items = []
for line in lines:
items.append( line.split(",") )
Or:
class WorkflowItem(object):
def __init__(self,workflow,paramname,value):
self.workflow = workflow
self.paramname = paramname
self.value = value
# list of objects
items = []
for line in lines:
items.append( WorkflowItem(*line.split(",")) )
(Also, nitpick: 4-space tabs are preferable to 8-space.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/9114256",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how do you make display:table-cell width:100% - 270px here's my code:
<div id="banner" style="position:absolute; top:0px; width:100%; background:url('../../images/banner_repeat.jpg'); background-repeat:repeat-x; <!-- border:solid pink 1px; -->">
<ul id="banner_ul">
<li id="wrm"><a href="http://whiterootmedia.com"><i>The homepage of White Root Media!</i></a></li>
<li id="google"><a href="https://plus.google.com/u/0/b/115943543157099352927/115943543157099352927" target="_blank"><i>+1 us on Google!</i></a></li>
<li id="facebook"><a href="http://www.facebook.com/pages/White-Root-Media/194381903928501" target="_blank"><i>Like us on Facebook!</i></a></li>
<li id="twitter"><a href="http://twitter.com/#!/WhiteRootMedia" target="_blank"><i>Tweet about us on Twitter!</i></a></li>
</ul>
</div>
<div id="container" style="<!-- border:solid yellow 1px -->; display: table;">
<div id="content" style="padding-top:90px; display:table-cell; min-width:945px; <!-- width:100% - 270px; -->">
This content will determine the height
</div>
<div id="right_column" style="display: table-cell; <!-- border:solid orange 1px; --> height:100%; width:270px; background-image:url('../../images/treetrunk7.png');background-repeat:repeat-y;">tree</div>
</div>
<div id="footer" style="position:relative; top:-1px; background-image:url('../../images/grass.png'); background-repeat:repeat-x; width:100%; height:100px;">grass</div>
here's the live page:
http://whiterootmedia.com/test/test4/
I would like the content div that is display:table-cell to go the full width of the page minus 270px. The tree should be all the way to the right.
Any help is greatly appreciated!
Thanks,
Dusty
A: You can use absolute positioning in the child div's
#foo {
display: table;
height: 400px;
position: relative;
width: 500px;
}
#foo > div {
display: table-cell;
height: 100%;
position: absolute;
}
#left {
background: blue;
left: 0;
right: 200px;
}
#right {
background: green;
right: 0;
width: 200px;
}
click here for demo
there are other methods of achieving the same effect such as changing the margins, I personally prefer the method above
| {
"language": "en",
"url": "https://stackoverflow.com/questions/9042274",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to get the geolocation location with best accuracy in iOS? I am using CLLocationManager to retrieve user's current location.It seems that the retrieved location is around 2000 feet away from the actual location. I have set the "DesiredAccuracy" to "kCLLocationAccuracyNearestTenMeters" but it didn't helped.
I thing, the device might have accessed location from the network provider.
I have also tried by adding "gps" in "UIRequiredDeviceCapabilities" in plist.
But it also giving a far location from the actual one.
So is there any way to retrieve the current position only with GPS Satellites?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24553438",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Can limit the amount if values a user can input in Dash-Ploty component trying to limit the amount of inputs a user can enter in my multi-dropdown. In my code below, I have it set to 4 values MAX!
This code doesn't bring back errors, but it's not functioning like I want it to. I want the callback to stop users from entering more inputs once the number exceeds 4.
@app.callback(
[dash.dependencies.Output("input-warning", "children"),
dash.dependencies.Output("dynamic-dropdown", "options")],
[dash.dependencies.Input("dynamic-dropdown", "search_value")],
[dash.dependencies.State("dynamic-dropdown", "value")],
)
def update_multi_options(search_value, value):
conn.rollback()
if search_value is None:
raise PreventUpdate
elif len(value) >= 4:
children = html.P("limit reached",id='input-warning')
return [children, [o for o in OPTIONS if o["value"] in value]]
else:
# Make sure that the set values are in the option list, else they will disappear
# from the shown select list, but still part of the `value`.
return [
o for o in OPTIONS if search_value.upper() in o["label"].upper() or o["value"] in (value or [])
]
I made an elif conditional to try and limit the inputs, I couldn't get it to work however.
Would greatly appreciate some guidance on why my code doesn't achieve what I want it to.
A: You could set the disabled key value for each option to True when the max number of options has been reached so the remaining options can't be selected anymore. When you have not reached the threshold you can return your original list of options (Which are implicitly enabled).
from dash import Dash, html, dcc
from dash.dependencies import Output, Input
default_options = [
{"label": "A", "value": "A"},
{"label": "B", "value": "B"},
{"label": "C", "value": "C"},
{"label": "D", "value": "D"},
{"label": "E", "value": "E"},
{"label": "F", "value": "F"},
]
app = Dash(__name__)
app.layout = html.Div(
[
dcc.Dropdown(
id="dropdown",
options=default_options,
value=["MTL", "NYC"],
multi=True,
),
html.Div(id="warning"),
]
)
@app.callback(
Output("dropdown", "options"),
Output("warning", "children"),
Input("dropdown", "value"),
)
def update_multi_options(value):
options = default_options
input_warning = None
if len(value) >= 4:
input_warning = html.P(id="warning", children="Limit reached")
options = [
{"label": option["label"], "value": option["value"], "disabled": True}
for option in options
]
return options, input_warning
if __name__ == "__main__":
app.run_server()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64867063",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How do I globally configure RSpec to keep the '--color' and '--format specdoc' options turned on How do I set global configuration for RSpec in Ubuntu.
Specifically so, --color and --format specdoc stay turned on, across all my projects (ie every time I run rspec anywhere).
A: If you use rake to run rspec tests then you can edit spec/spec.opts
http://rspec.info/rails/runners.html
A: As you can see in the docs here, the intended use is creating ~/.rspec and in it putting your options, such as --color.
To quickly create an ~/.rspec file with the --color option, just run:
echo '--color' >> ~/.rspec
A: Or simply add alias spec=spec --color --format specdoc to your ~/.bashrc file like me.
A: One can also use a spec_helper.rb file in all projects. The file should include the following:
RSpec.configure do |config|
# Use color in STDOUT
config.color = true
# Use color not only in STDOUT but also in pagers and files
config.tty = true
# Use the specified formatter
config.formatter = :documentation # :progress, :html,
# :json, CustomFormatterClass
end
Any example file must require the helper to be able to use that options.
A: In your spec_helper.rb file, include the following option:
RSpec.configure do |config|
config.color_enabled = true
end
You then must require in each *_spec.rb file that should use that option.
A: One thing to be aware of is the impact of the different ways of running RSpec.
I was trying to turn on the option with the following code in spec/spec_helper.rb -
Rspec.configure do |config|
config.tty = $stdout.tty?
end
*
*calling the 'rspec' binary directly - or as 'bundle exec rspec' and checking $stdout.tty? will return true.
*invoking the 'rake spec' task - or as 'bundle exec rake spec' - Rake will invoke rspec in a separate process, and $stdout.tty? will return false.
In the end I used the ~/.rspec option, with just --tty as its contents. Works well for me and keeps our CI server output clean.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1819614",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "160"
} |
Q: How to fix Newtonsoft.Json assembly loading error? I'm attempting to load a pre-existing Umbraco CMS site into a Visual Studio project and am caught up in a bit of DLL hell.
Here is the error message I get when attempting to compile the site:
Could not load types from assembly Umbraco.Core, Version=1.0.5462.37503, Culture=neutral, PublicKeyToken=null, errors:
Exception: System.IO.FileNotFoundException: Could not load file or assembly 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The system cannot find the file specified.
File name: 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'
I've attempted to re-install Newtonsoft from NuGet, re-install Umbraco from NuGet, delete all DLLs and re-install, removed the Newtonsoft dependentAssembly, every possible solution I've been able to find and this error continues to come up.
Any suggestions?
A: I'm guessing the binding redirect isn't set up correctly in the web.config file. Try running this in the nuget package manager console:
PM> Get-Project –All | Add-BindingRedirect
A: This ended up being a bit of a misunderstanding on my part from following the Umbraco videos. I was attempting to set up a new Visual Studio project, import all the DLLs needed, and then move the site content into the project.
All I really needed to do was create a blank project, then move the site content, with all of its DLLs, into the project. This let me immediately start editing the project.
A: The best solution was to install an earlier version of the package and then upgrade.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28547579",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Which Feature Selection Techniques for NLP is this represent I have a dataset that came from NLP for technical documents
my dataset has 60,000 records
There are 30,000 features in the dataset
and the value is the number of repetitions that word/feature appeared
here is a sample of the dataset
RowID Microsoft Internet PCI Laptop Google AWS iPhone Chrome
1 8 2 0 0 5 1 0 0
2 0 1 0 1 1 4 1 0
3 0 0 0 7 1 0 5 0
4 1 0 0 1 6 7 5 0
5 5 1 0 0 5 0 3 1
6 1 5 0 8 0 1 0 0
-------------------------------------------------------------------------
Total 9,470 821 5 107 4,605 719 25 8
Appearance
There are some words that only appeared less than 10 times in the whole dataset
The technique is to select only words/features that appeared in the dataset for more than a certain number (say 100)
what is this technique called? the one that only uses features that in total appeared more than a certain number.
A: This technique for feature selection is rather trivial so I don't believe it has a particular name beyond something intuitive like "low-frequency feature filtering", "k-occurrence feature filtering" "top k-occurrence feature selection" in the machine learning sense; and "term-frequency filtering" and "rare word removal" in the Natural Language Processing (NLP) sense.
If you'd like to use more sophisticated means of feature selection, I'd recommend looking into the various supervised and unsupervised methods available. Cai et al. [1] provide a comprehensive survey, if you can't access the article, then this page by JavaTPoint covers some of the supervised methods. A quick web search for supervised/unsupervised feature selection also yields many good blogs, most of which make use of the sciPy and sklean Python libraries.
References
[1] Cai, J., Luo, J., Wang, S. and Yang, S., 2018. Feature selection in machine learning: A new perspective. Neurocomputing, 300, pp.70-79.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74973008",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: What can be alternative metrics to code coverage? Code coverage is propably the most controversial code metric. Some say, you have to reach 80% code coverage, other say, it's superficial and does not say anything about your testing quality. (See Jon Limjap's good answer on "What is a reasonable code coverage % for unit tests (and why)?".)
People tend to measure everything. They need comparisons, benchmarks etc.
Project teams need a pointer, how good their testing is.
So what are alternatives to code coverage? What would be a good metric that says more than "I touched this line of code"?
Are there real alternatives?
A: Crap4j is one fairly good metrics that I'm aware of...
Its a Java implementation of the Change Risk Analysis and Predictions software metric which combines cyclomatic complexity and code coverage from automated tests.
A: If you are looking for some useful metrics that tell you about the quality (or lack there of) of your code, you should look into the following metrics:
*
*Cyclomatic Complexity
*
*This is a measure of how complex a method is.
*Usually 10 and lower is good, 11-25 is poor, higher is terrible.
*Nesting Depth
*
*This is a measure of how many nested scopes are in a method.
*Usually 4 and lower is good, 5-8 is poor, higher is terrible.
*Relational Cohesion
*
*This is a measure of how well related the types in a package or assembly are.
*Relational cohesion is somewhat of a relative metric, but useful none the less.
*Acceptable levels depends on the formula. Given the following:
*
*R: number of relationships in package/assembly
*N: number of types in package/assembly
*H: Cohesion of relationship between types
*Formula: H = (R+1)/N
*Given the above formula, acceptable range is 1.5 - 4.0
*Lack of Cohesion of Methods (LCOM)
*
*This is a measure of how cohesive a class is.
*Cohesion of a class is a measure of how many fields each method references.
*Good indication of whether your class meets the Principal of Single Responsibility.
*Formula: LCOM = 1 - (sum(MF)/M*F)
*
*M: number of methods in class
*F: number of instance fields in class
*MF: number of methods in class accessing a particular instance field
*sum(MF): the sum of MF over all instance fields
*A class that is totally cohesive will have an LCOM of 0.
*A class that is completely non-cohesive will have an LCOM of 1.
*The closer to 0 you approach, the more cohesive, and maintainable, your class.
These are just some of the key metrics that NDepend, a .NET metrics and dependency mapping utility, can provide for you. I recently did a lot of work with code metrics, and these 4 metrics are the core key metrics that we have found to be most useful. NDepend offers several other useful metrics, however, including Efferent & Afferent coupling and Abstractness & Instability, which combined provide a good measure of how maintainable your code will be (and whether or not your in what NDepend calls the Zone of Pain or the Zone of Uselessness.)
Even if you are not working with the .NET platform, I recommend taking a look at the NDepend metrics page. There is a lot of useful information there that you might be able to use to calculate these metrics on whatever platform you develop on.
A: Bug metrics are also important:
*
*Number of bugs coming in
*Number of bugs resolved
To detect for instance if bugs are not resolved as fast as new come in.
A: Code Coverage is just an indicator and helps pointing out lines which are not executed at all in your tests, which is quite interesting. If you reach 80% code coverage or so, it starts making sense to look at the remaining 20% of lines to identify if you are missing some use case. If you see "aha, this line gets executed if I pass an empty vector" then you can actually write a test which passes an empty vector.
As an alternative I can think of, if you have a specs document with Use Cases and Functional Requirements, you should map the unit tests to them and see how many UC are covered by FR (of course it should be 100%) and how many FR are covered by UT (again, it should be 100%).
If you don't have specs, who cares? Anything that happens will be ok :)
A: What about watching the trend of code coverage during your project?
As it is the case with many other metrics a single number does not say very much.
For example it is hard to tell wether there is a problem if "we have a Checkstyle rules compliance of 78.765432%". If yesterday's compliance was 100%, we are definitely in trouble. If it was 50% yesterday, we are probably doing a good job.
I alway get nervous when code coverage has gotten lower and lower over time. There are cases when this is okay, so you cannot turn off your head when looking at charts and numbers.
BTW, sonar (http://sonar.codehaus.org/) is a great tool for watching trends.
A: Using code coverage on it's own is mostly pointless, it gives you only insight if you are looking for unnecessary code.
Using it together with unit-tests and aiming for 100% coverage will tell you that all the 'tested' parts (assumed it was all successfully too) work as specified in the unit-test.
Writing unit-tests from a technical design/functional design, having 100% coverage and 100% successful tests will tell you that the program is working like described in the documentation.
Now the only thing you need is good documentation, especially the functional design, a programmer should not write that unless (s)he is an expert of that specific field.
A: Scenario coverage.
I don't think you really want to have 100% code coverage. Testing say, simple getters and setters looks like a waste of time.
The code always runs in some context, so you may list as many scenarios as you can (depending on the problem complexity sometimes even all of them) and test them.
Example:
// parses a line from .ini configuration file
// e.g. in the form of name=value1,value2
List parseConfig(string setting)
{
(name, values) = split_string_to_name_and_values(setting, '=')
values_list = split_values(values, ',')
return values_list
}
Now, you have many scenarios to test. Some of them:
*
*Passing correct value
*List item
*Passing null
*Passing empty string
*Passing ill-formated parameter
*Passing string with with leading or ending comma e.g. name=value1, or name=,value2
Running just first test may give you (depending on the code) 100% code coverage. But you haven't considered all the posibilities, so that metric by itself doesn't tell you much.
A: How about (lines of code)/(number of test cases)? Not extremely meaningful (since it depends on LOC), but at least it's easy to calculate.
Another one could be (number of test cases)/(number of methods).
A: As a rule of thumb, defect injection rates proportionally trail code yield and they both typically follow a Rayleigh distribution curve.
At some point your defect detection rate will peak and then start to diminish.
This apex represents 40% of discovered defects.
Moving forward with simple regression analysis you can estimate how many defects remain in your product at any point following the peak.
This is one component of Lawrence Putnam's model.
A: I wrote a blog post about why High Test Coverage Ratio is a Good Thing Anyway.
I agree that: when a portion of code is executed by tests, it doesn’t mean that the validity of the results produced by this portion of code is verified by tests.
But still, if you are heavily using contracts to check states validity during tests execution, high test coverage will mean a lot of verification anyway.
A: The value in code coverage is it gives you some idea of what has been exercised by tests.
The phrase "code coverage" is often used to mean statement coverage, e.g., "how much of my code (in lines) has been executed", but in fact there are over a hundred varieties of "coverage". These other versions of coverage try to provide a more sophisticated view what it means to exercise code.
For example, condition coverage measures how many of the separate elements of conditional expressions have been exercised. This is different than statement coverage. MC/DC
"modified condition/decision coverage" determines whether the elements of all conditional expressions have all been demonstrated to control the outcome of the conditional, and is required by the FAA for aircraft software. Path coverage meaures how many of the possible execution paths through your code have been exercised. This is a better measure than statement coverage, in that paths essentially represent different cases in the code. Which of these measures is best to use depends on how concerned you are about the effectiveness of your tests.
Wikipedia discusses many variations of test coverage reasonably well.
http://en.wikipedia.org/wiki/Code_coverage
A: This hasn't been mentioned, but the amount of change in a given file of code or method (by looking at version control history) is interesting particularly when you're building up a test suite for poorly tested code. Focus your testing on the parts of the code you change a lot. Leave the ones you don't for later.
Watch out for a reversal of cause and effect. You might avoid changing untested code and you might tend to change tested code more.
A: SQLite is an extremely well-tested library, and you can extract all kinds of metrics from it.
As of version 3.6.14 (all statistics in the report are against that release of SQLite), the SQLite library consists of approximately 63.2 KSLOC of C code. (KSLOC means thousands of "Source Lines Of Code" or, in other words, lines of code excluding blank lines and comments.) By comparison, the project has 715 times as much test code and test scripts - 45261.5 KSLOC.
In the end, what always strikes me as the most significant is none of those possible metrics seem to be as important as the simple statement, "it meets all the requirements." (So don't lose sight of that goal in the process of achieving it.)
If you want something to judge a team's progress, then you have to lay down individual requirements. This gives you something to point to and say "this one's done, this one isn't". It's not linear (solving each requirement will require varying work), and the only way you can linearize it is if the problem has already been solved elsewhere (and thus you can quantize work per requirement).
A: I like revenue, sales numbers, profit. They are pretty good metrics of a code base.
A: Probably not only measuring the code covered (touched) by the unit tests but how good the assertions are.
One metric easy to implement is to measure the size of the Assert.AreEqual
You can create your own Assert implementation calling Assert.AreEqual and measuring the size of the object passed as second parameter.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1047758",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
} |
Q: Why one facebook have two id Why one facebook have two id:
https://graph.facebook.com/1000059xxxxxxxx
https://graph.facebook.com/2392797xxxxxxxx
they are same facebook account, WHY?
A: Most likely one is the "real" (or "global") ID, the other one is an "App Scoped ID". See the changelog for more information: https://developers.facebook.com/docs/apps/changelog#v2_0_graph_api
You don´t get the global IDs anymore (except for browsing through a Facebook Page), and there is no way to match global IDs with App Scoped ones.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29643698",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
} |
Q: java Send email with attachement pdf not working I've been searching about how to add pdf and send it in mail for a long time .. but all codes failed with me i finally tried this and it sounded correct for me but it's still showing error
here is my essay :
public static void send(String to, Document document) {
String content = "dummy content"; //this will be the text of the email
String subject = "dummy subject"; //this will be the subject of the email
String receiver="[email protected]";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.localhost", "https://fr.yahoo.com/");
properties.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
//2) compose message
ByteArrayOutputStream outputStream = null;
try {
//construct the text body part
MimeBodyPart textBodyPart = new MimeBodyPart();
textBodyPart.setText(content);
//now write the PDF content to the output stream
outputStream = new ByteArrayOutputStream();
PdfWriter.getInstance(document, outputStream);
byte[] bytes = outputStream.toByteArray();
//construct the pdf body part
DataSource dataSource = new ByteArrayDataSource(bytes, "application/pdf");
MimeBodyPart pdfBodyPart = new MimeBodyPart();
pdfBodyPart.setDataHandler(new DataHandler(dataSource));
pdfBodyPart.setFileName("test.pdf");
//construct the mime multi part
MimeMultipart mimeMultipart = new MimeMultipart();
mimeMultipart.addBodyPart(textBodyPart);
mimeMultipart.addBodyPart(pdfBodyPart);
//create the sender/recipient addresses
InternetAddress iaSender = new InternetAddress(username);
InternetAddress iaRecipient = new InternetAddress(receiver);
//construct the mime message
MimeMessage mimeMessage = new MimeMessage(session);
mimeMessage.setSender(iaSender);
mimeMessage.setSubject(subject);
mimeMessage.setRecipient(Message.RecipientType.TO, iaRecipient);
mimeMessage.setContent(mimeMultipart);
//send off the email
Transport.send(mimeMessage);
System.out.println("sent from " + username
+ ", to " + to
+ "; server = " + ", port = ");
} catch (Exception ex) {
ex.printStackTrace();
} finally {
//clean off
if (null != outputStream) {
try {
outputStream.close();
outputStream = null;
} catch (Exception ex) {
}
}
}
}
At frist it used to show me errore about host but i corrected them and now that's the error showing
com.sun.mail.util.MailConnectException: Couldn't connect to host, port: localhost, 25; timeout -1;
nested exception is:
java.net.ConnectException: Connection refused: connect
can anyone correct my code pleaze
A: You are making it very difficult for yourself!
Take a look at Simple Java Mail (open source, layer around Jakarta Mail / JavaMail), which comes with a gmail example which should be easy to modify. For your case the code would be:
private void sendPdf(Document document) {
// be sure to enable a one-time app password in Google, so 2-factor won't block you
Mailer mailer = MailerBuilder.buildMailer("smtp.gmail.com", 25, username, password, TransportStrategy.SMTP);
// or: MailerBuilder.buildMailer("smtp.gmail.com", 587, username, password, TransportStrategy.SMTP_TLS);
// or: MailerBuilder.buildMailer("smtp.gmail.com", 465, username, password, TransportStrategy.SMTPS);
Email email = EmailBuilder.startingBlank()
.from(username)
.to("[email protected]")
.withSubject("dummy subject")
.withPlainText("dummy content")
.withAttachment("test.pdf", producePdfData(document), "application/pdf");
mailer.sendMail(email);
}
private byte[] producePdfData(Document document) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
PdfWriter.getInstance(document, outputStream);
return outputStream.toByteArray();
}
Now you just need to fill in the right Yahoo server and port and transport method, but it should work.
If you still can't get a connection, then I'm guessing you are trying from a corporate environment and you are probably blocked by a proxy (or less likely a firewall). Simple Java Mail supports proxy connections (including authenticated proxy), but if it's a firewall, then you are out of luck unless you setup an SSH tunnel or something (probably not allowed).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64091148",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: node const variable also be changed I want to protect the object and try const like below
const foo = {'test': 'content'}
foo // {test: 'content'}
foo['test'] = 'change'
foo // {test: 'change'}
I don't know how to protect the object like dictionary correctly, could anyone help me out?
thanks for your time.
regards.
A: As Rayon Dabre says, const means that the value of the variable cannot be changed. The value of the variable foo in your example is unchanged: it is still the same object. That object's property changed.
In order to make an object itself unchangeable, you can use Object.freeze:
var foo = {'test': 'content'};
Object.freeze(foo);
foo.test = 'change';
foo.test
// => "content"
A: See Object.freeze:
const foo = Object.freeze( {'test': 'content'} );
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36214978",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Find absolute path to a directory if given path to start search from (in a batch file) A user will give me an absolute path - say "C:\src" (passed into %1 in the batch file). Then, I need to find the directory entitled "SQLScripts" that is in some subfolder of "C:\src".
How can I find the absolute path to the "SQLScripts" directory? Also, I'm not worrying about multiple instances of the SQLScripts directory existing.
From my Googling, the solution may involve a for loop and some batch modifier such as %~$PATH:1. This link may be beneficial - Special Batch Characters.
All solutions need to work on Windows XP and above.
Note that I'm constrained to using a batch file, and can't use other "easier" methods such as a simple Python code snippet to solve my problem.
Thanks!
A: This code saves the path to SQLScripts into %SQLSCRIPTSPATH% variable, and it works on WinXP:
DIR SQLScripts /B /P /S>tmp.txt
for /f "delims=" %%a in (tmp.txt) do set SQLSCRIPTSPATH=%%a
del tmp.txt
EDIT:
Better solution (without using a temporary file) suggested by Joe:
for /f "tokens=*" %%i in ('DIR SqlScripts /B /P /S') do SET SQLSCRIPTSPATH=%%i
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1956903",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Create a Timer to send HTTP request Periodically - Android I want to end HTTP request from a Android device to a web server and check a particular data of a database periodically (once a minute). I couldn't implement a timer for this.
Thanks
A: Try AlarmManager running Service. I wouldn't recommend sending request each minute thou, unless it's happening only when user manually triggered this.
A: public class MyActivity extends Activity {
Timer t ;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
t = new Timer();
t.schedule(new TimerTask() {
public void run() {
//Your code will be here
}
}, 1000);
}
}
A: TimerTask doAsynchronousTask;
final Handler handler = new Handler();
Timer timer = new Timer();
doAsynchronousTask = new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
public void run() {
if(isOnline){// check net connection
//what u want to do....
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 10000);// execute in every 10 s
A: The most easy method is to loop a Handler:
private Handler iSender = new Handler() {
@Override
public void handleMessage(final Message msg) {
//Do your code here
iSender.sendEmptyMessageDelayed(0, 60*1000);
}
};
To start the loop call this sentence:
iSender.sendEmptyMessage(0);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11667064",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: custom keyboard extension image copied but not paste automatically from keyboard i have created custom keyboard with image buttons. when click on image button its copied and paste to message box in any application. I have faced issue is image copied to pasteboard but not paste automatically. Once i have copy and clicking message box for get pasteboard options like select, select all, paste. after clicking paste button image pasted. I need click button in keyboard to send image in message box
i have used this code...
let pb = UIPasteboard.generalPasteboard()
let image: UIImage = UIImage(named:String(self.imgArray.objectAtIndex(indexPath.row)))!
let imgData: NSData = UIImagePNGRepresentation(image)!
pb.setData(imgData, forPasteboardType: UIPasteboardTypeListImage[0] as! String)
self.textDocumentProxy.insertText(pb.string!)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36499654",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: SQL integer range variable defined + PHP Is it possible to define a range of integers in SQL ? Something like this:
course_id | course_name | description | range/number
-----------+-----------------------------+--------------------------------------+----------------
1 | PostgreSQL for Develop | desc1 | 5
2 | PostgreSQL Admininstration | desc2 |20
3 | Mastering PostgreSQL | desc3 |(12,18)
So I want the column range/number to be user either as an integer number or a range integers. I later want to use PHP to compare a variable ( containing an integer ), if it is different/not part from that number/range of numbers. Is this possible and how could I do this ? Thanks.
A: If you don't want to use the value in SQL, then you can just store it as a string. It is a string, not a range.
If you want it as a range in the database, then use two columns, a lower bound and an upper bound. I would make the bounds inclusive, so the single value 20 would be represented as 20 rather than 19/21.
Some databases (notably Postgres) do support a range data type, but that is specific to those databases.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65979861",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to connect console application and Windows form application C# I put all of my input on my console application, and I like it this way. My question is, how can I fix example read input in the console application, and then do something with it in the windows form app? I want both of my applications running at the same time. Console application will be doing something while Win App is doing something else, but if I will want to, I can connect them.
I have tried :
Form1 win = new Form1();
win.show();
but it didn't work. The window switch I see is stacked, and it is not able to run as it should.
A: 1- Create a winforms application
2- Set output type as a Console Applcation by Project/Properties/Application/Output Type
Now You have a windows application together with a console
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16640009",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is Microsoft serious about XBAP? As a developer, can I count on XBAP? or is Microsoft slowly removing support in favor of Silverlight?
One of the selling points of XBAP is multi browser support (IE and Firefox).
However, the Firefox add-in for XBAP is not in the .NET 4.0 install.
I understand there was a security issue but this has been a while and Microsoft has not released any new add-in.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5575083",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: What makes the action of this lwp program different between directly loading in commend line and using load procedure? I use guile 2.0.13 as my scheme interpreter and i wrote file 3.3.3.scm as follow:
(define lwp-list '())
(define quit-k #f)
(define lwp
(lambda (thunk)
(set! lwp-list (append lwp-list (list thunk)))))
(define start
(lambda ()
(if (not quit-k)
(set! quit-k (call/cc (lambda (k) k))))
(if (not (null? lwp-list))
(let ([p (car lwp-list)])
(set! lwp-list (cdr lwp-list))
(p)))))
(define pause
(lambda ()
(call/cc
(lambda (k)
(lwp (lambda () (k #f)))
(start)))))
(define quit
(lambda ()
(set! lwp-list '())
(quit-k #f)))
(lwp (lambda () (let f () (pause) (display "h") (f))))
(lwp (lambda () (let f () (pause) (display "e") (f))))
(lwp (lambda () (let f () (pause) (display "y") (f))))
(lwp (lambda () (let f () (pause) (display "!") (f))))
(lwp (lambda () (let f () (pause) (newline) (f))))
(lwp (lambda () (let f () (pause) (quit))))
(start)
It seems that 3.3.3.scm runs all right if i use (load "3.3.3.scm") in interactive interface. But when i directly run guile 3.3.3.scm, procedure quit will be called after guile called it first time:
hey!
Backtrace:
In ice-9/boot-9.scm:
160: 3 [catch #t #<catch-closure 17db460> ...]
In unknown file:
?: 2 [apply-smob/1 #<catch-closure 17db460>]
In ice-9/boot-9.scm:
66: 1 [call-with-prompt prompt0 ...]
In unknown file:
?: 0 [#f #f]
ERROR: In procedure #f:
ERROR: Wrong type to apply: #f
What case this difference?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40993463",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Rails, RSpec: How to test, that a specific mailer action gets triggered I need to ensure that running an importer results in sending out an email.
This is what I got so far:
describe '#import' do
it 'triggers the correct mailer and action', :vcr do
expect(OrderMailer).to receive(:delivery_confirmation).with(order)
Importer.new(@file).import
remove_backed_up_file
end
end
It fails with:
pry(#<ActiveRecord::ConnectionAdapters::TransactionManager>)> error
=> #<NoMethodError: undefined method `deliver_now' for nil:NilClass>
Which obviously can't work out as I am expecting the Mailer class to receive the (instance) method call. But how can I get a hold of the mailer instance that will receive the call? How would you test that a unit's method triggers a certain mailer?
A: I assume the delivery_confirmation method in reality returns a Mail object. The problem is that ActionMailer will call the deliver method of the mail object. You've set an expectation stubbing out the delivery_confirmation method but you haven't specified what should be the return value. Try this
mail_mock = double(deliver: true)
# or mail_mock = double(deliver_now: true)
expect(mail_mock).to receive(:deliver)
# or expect(mail_mock).to receive(:deliver_now)
allow(OrderMailer).to receive(:delivery_confirmation).with(order).and_return(mail_mock)
# the rest of your test code
A: If I got you right,
expect_any_instance_of(OrderMailer).to receive(:delivery_confirmation).with(order)
will test the mailer instance that will receive the call.
For more precision you may want to set up your test with the particular instance of OrderMailer (let's say order_mailer) and write your expectation the following way
expect(order_mailer).to receive(:delivery_confirmation).with(order)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42551997",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: What is -p doing in bash regex test? I have this test in a bash script and, while I have some vague idea, I want to be sure what exactly is going on.
if [[ "$FLAGS" =~ -p' '+-?[0-9]+ ]]
I can tell that it is testing some regex on $FLAGS, but I am not sure why the -p is needed.
In general, I want to know what is the -p doing in a bash regex test. (and, ideally, where to look for similar things in manpages.)
A: "-p" in this context is part of the regexp. The regexp is looking for a match to any of the following patterns:
-p 123
-p123
-p -123
-p-123
The " " and the second "-" are optional.
A: BASH will treat everything after =~ operator as regex so BASH will try to match against this regex:
-p' '+-?[0-9]+
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19583262",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Fast iteration over vectors in a multidimensional numpy array I'm writing some python + numpy + cython code, and am trying to find the most elegant and efficient way of doing the following kind of iteration over an array:
Let's say I have a function f(x, y) that takes a vector x of shape (3,) and a vector y of shape (10,) and returns a vector of shape (10,). Now I have two arrays X and Y of shape sx + (3,) and sy + (10,), where the sx and sy are two shapes that can be broadcast together (i.e. either sx == sy, or when an axis differs, one of the two has length 1, in which case it will be repeated). I want to produce an array Z that has the shape zs + (10,), where zs is the shape of the broadcasting of sx with sy. Each 10 dimensional vector in Z is equal to f(x, y) of the vectors x and y at the corresponding locations in X and Y.
I looked into np.nditer and while it plays nice with cython (see bottom of linked page), it doesn't seem to allow iterating over vectors from a multidimensional array, instead of elements. I also looked at index grids, but the problem there is that cython indexing is only fast when the number of indexes is equal to the dimensionality of the array, and are stored as cython integers instead of python tuples.
Any help is greatly appreciated!
A: You are describing what Numpy calls a Generalized Universal FUNCtion, or gufunc. As it name suggests, it is an extension of ufuncs. You probably want to start by reading these two pages:
*
*Writing your own ufunc
*Building a ufunc from scratch
The second example uses Cython and has some material on gufuncs. To fully go down the gufunc road, you will need to read the corresponding section in the numpy C API documentation:
*
*Generalized Universal Function API
I do not know of any example of gufuncs being coded in Cython, although it shouldn't be too hard to do following the examples above. If you want to look at gufuncs coded in C, you can take a look at the source code for np.linalg here, although that can be a daunting experience. A while back I bored my local Python User Group to death giving a talk on extending numpy with C, which was mostly about writing gufuncs in C, the slides of that talk and a sample Python module providing a new gufunc can be found here.
A: If you want to stick with nditer, here's a way using your example dimensions. It's pure Python here, but shouldn't be hard to implement with cython (though it still has the tuple iterator). I'm borrowing ideas from ndindex as described in shallow iteration with nditer
The idea is to find the common broadcasting shape, sz, and construct a multi_index iterator over it.
I'm using as_strided to expand X and Y to usable views, and passing the appropriate vectors (actually (1,n) arrays) to the f(x,y) function.
import numpy as np
from numpy.lib.stride_tricks import as_strided
def f(x,y):
# sample that takes (10,) and (3,) arrays, and returns (10,) array
assert x.shape==(1,10), x.shape
assert y.shape==(1,3), y.shape
z = x*10 + y.mean()
return z
def brdcast(X, X1):
# broadcast X to shape of X1 (keep last dim of X)
# modeled on np.broadcast_arrays
shape = X1.shape + (X.shape[-1],)
strides = X1.strides + (X.strides[-1],)
X1 = as_strided(X, shape=shape, strides=strides)
return X1
def F(X, Y):
X1, Y1 = np.broadcast_arrays(X[...,0], Y[...,0])
Z = np.zeros(X1.shape + (10,))
it = np.nditer(X1, flags=['multi_index'])
X1 = brdcast(X, X1)
Y1 = brdcast(Y, Y1)
while not it.finished:
I = it.multi_index + (None,)
Z[I] = f(X1[I], Y1[I])
it.iternext()
return Z
sx = (2,3) # works with (2,1)
sy = (1,3)
# X, Y = np.ones(sx+(10,)), np.ones(sy+(3,))
X = np.repeat(np.arange(np.prod(sx)).reshape(sx)[...,None], 10, axis=-1)
Y = np.repeat(np.arange(np.prod(sy)).reshape(sy)[...,None], 3, axis=-1)
Z = F(X,Y)
print Z.shape
print Z[...,0]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27025788",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: making a model from table mySQL with PDO I am developing an application for fun, and I am purposefully NOT using any frameworks aside from mustache for PHP and JS, etc on either the client or server side of the modest application.
Each view has a table which holds all data used for each one. I wish to execute a query that selects each column in the table and makes it available to my mustache template.
I do NOT want to change methods in order to access any particular column at runtime. fetchAll gives me a ton of null fields in the data returned that I do not want while fetch() gives me a nice JSON structure containing all of the proper data aside from a column containing more than one row of data only shows for the first row/instance.
Here is my PHP method:
public function get_view($view_name , $out_type = "raw"){
// Col names may vary from view table to view table
$statement = $this->prep_sql("SELECT * FROM `$view_name`");
$statement->execute(array());
$view_data = $statement->fetch(); // I know fetchAll will work for arrays but how then will my mustache template bind to data returned from columns with more than one row?
return (strtoupper($out_type) === "JSON" ? json_encode($view_data) : $view_data);
}
What I want is to ignore any fields with null or empty as if they do not exist and form an array with columns in the database with multiple rows of data. I also realize that using fetch for single instances like a page title and fetchAll would work for multiple rows however I want to eliminate this.
In order for the templates to bind correctly the data output must look similar to:
{
module_name: 'main',
module_title: 'Main',
module_images: ['http://...', 'http://...', 'http://...'],
module_scripts: ['http://...','http://...','http://...',]
}
Instead with fetchAll I get
[{
module_name: 'main',
module_title: 'Main',
module_images: 'http://...', // 1
module_scripts: 'http://...' // 1
}, {
module_name: null,
module_title: null,
module_images: 'http://..', // 2
module_scripts: 'http://..' // 2
}];
I am aware SELECT * is not a traditional way to select all of your view data however the number of cols in each view table will be less than 100 max and no tables besides view tables will be accessed using a wildcard select. That said along with the dynamic col names from view to view mean ALOT less code to write. I hope that this doesnt offend anybody :)
Thank you all kindly for the help.
A: Is this what you are after??
CREATE TABLE view_data_main (
module_name VARCHAR(30),
module_title VARCHAR(30),
module_images VARCHAR(30),
module_scripts VARCHAR(30)
)
INSERT INTO `view_data_main` (module_name,module_title,module_images,module_scripts) VALUES
('welcome','main','http://www.test.com','http://www.test2.com'),
(NULL,NULL,'http://www.test.com','http://www.test2.com'),
(NULL,NULL,'http://www.test.com','http://www.test2.com')
SELECT module_name,module_title,GROUP_CONCAT(module_images),GROUP_CONCAT(module_scripts)
FROM `view_data_main`
WHERE module_images IS NOT NULL AND module_scripts IS NOT NULL
GROUP BY CONCAT(module_images,',',module_scripts)
Having re-read the question I don't think the subquery is necessary unless I'm missing something?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34145620",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: After building QT from source, theme color is white I successfully built QT from source on a virtual machine. I then compiled a small app. It built just fine, except that when I moved the executable to the host machine. It background color is white, not dark like the theme. This problem does not happen when I build the app on the host. So my question is, is there a flag, or a file I can change it make the background color dark?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27216724",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to protect PHPSESSID in php? I am really clueless on how to protect PHPSESSID. Does the value of session_id come from PHPSESSID? It would be disastrous if the session_id got compromised. Anyone have any ideas?
A: Here is the article from PHP manual that explains sessions security in PHP: link
Probably the most effective way to protect your sessions will be to enable SSL on your site and forcing storing of session id in cookies. Then cookies will be encrypted as they will be passed to your site and that should guarantee enough protection.
A: You can use HTTPS as RaYell said, but if you can't afford a certificate, there are some ways to secure a session even with HTTP:
*
*Store the user-agent in the session when you create the session. Check the user-agent on every request. If the user-agent changes, delete the session.
*Same as above, but with the IP address. The annoying thing there is that a lot of ISP provide dynamic IPs, and the session can be deleted illegitimately.
*Set a low session timeout. This will not prevent session hijacking, but it reduces the risks. Beware, this can annoy users though.
*Set a low session lifetime (1 day). This will force users to reauthenticate after 1 day, so even if a session is hijacked, it won't be hijacked for more than one day.
Remember these advices will not prevent session hijacking. They will dramatically reduce the risks, but there will always be a risk, unless you use HTTPS.
A: the session_id is stored in a cookie on the users system. Not sure what you mean by protecting it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1226177",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Display Image using object (Iphone) Here is what I have:
smallURL:(@"bundle://image.jpg")
this line will display me a picture store in the local path, no problem everything works fine. Now I'm using an object because the name for my picture will be store in my database, so I want to use the line like that:
smallURL:(@"bundle://%s", [visuel lpath])
My problem is "%s" its not working do I have to use %@, %i... can someone help me and explain all the diference..
Thanks,
A: smallURL:([NSString stringWithFormat:@"bundle://%@", [visuel lpath]])
A: If lpath is of type NSString then you should use %@. It is used every time you need to convert a Cocoa object (or any other descendant of NSObject) into its string representation.
smallURL:(@"bundle://%@", [visuel lpath])
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1994501",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Solving multi-armed bandit problems with continuous action space My problem has a single state and an infinite amount of actions on a certain interval (0,1). After quite some time of googling I found a few paper about an algorithm called zooming algorithm which can solve problems with a continous action space. However my implementation is bad at exploiting. Therefore I'm thinking about adding an epsilon-greedy kind of behavior.
Is it reasonable to combine different methods?
Do you know other approaches to my problem?
Code samples:
import portion as P
def choose_action(self, i_ph):
# Activation rule
not_covered = P.closed(lower=0, upper=1)
for arm in self.active_arms:
confidence_radius = calc_confidence_radius(i_ph, arm)
confidence_interval = P.closed(arm.norm_value - confidence_radius, arm.norm_value + confidence_radius)
not_covered = not_covered - confidence_interval
if not_covered != P.empty():
rans = []
height = 0
heights = []
for i in not_covered:
rans.append(np.random.uniform(i.lower, i.upper))
height += i.upper - i.lower
heights.append(i.upper - i.lower)
ran_n = np.random.uniform(0, height)
j = 0
ran = 0
for i in range(len(heights)):
if j < ran_n < j + heights[i]:
ran = rans[i]
j += heights[i]
self.active_arms.append(Arm(len(self.active_arms), ran * (self.sigma_square - lower) + lower, ran))
# Selection rule
max_index = float('-inf')
max_index_arm = None
for arm in self.active_arms:
confidence_radius = calc_confidence_radius(i_ph, arm)
# indexfunction from zooming algorithm
index = arm.avg_learning_reward + 2 * confidence_radius
if index > max_index:
max_index = index
max_index_arm = arm
action = max_index_arm.value
self.current_arm = max_index_arm
return action
def learn(self, action, reward):
arm = self.current_arm
arm.avg_reward = (arm.pulled * arm.avg_reward + reward) / (arm.pulled + 1)
if reward > self.max_profit:
self.max_profit = reward
elif reward < self.min_profit:
self.min_profit = reward
# normalize reward to [0, 1]
high = 100
low = -75
if reward >= high:
reward = 1
self.high_count += 1
elif reward <= low:
reward = 0
self.low_count += 1
else:
reward = (reward - low)/(high - low)
arm.avg_learning_reward = (arm.pulled * arm.avg_learning_reward + reward) / (arm.pulled + 1)
arm.pulled += 1
# zooming algorithm confidence radius
def calc_confidence_radius(i_ph, arm: Arm):
return math.sqrt((8 * i_ph)/(1 + arm.pulled))
A: You may find this useful, full algorithm description is here. They grid out the probes uniformly, informing this choice (e.g. normal centering on a reputed high energy arm) is also possible (but this might invalidate a few bounds I am not sure).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62810137",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Python unittest for paramiko ssh connection I wrote some python code that works great, now I'm tasked with writing tests for that code.
My team uses mock and pytest, but I haven't really been able to copy-paste and modify something useful.
I just need a kick start, for example here is a part of my code:
ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.connect(hostname='1.2.3.4', username='ubuntu')
Can someone help me write a simple unittest for this?
I understand that going forward I'd have to think about my code and write the tests as I go, but I've never done this before so I'm really just looking to get a practical start to get going.
A: Unit testing ensures the code works per requirements. Get the requirements and write tests to check that the code works and show that the code throws appropriate errors. You can use RobotFramework or another test automation SW to automate the tests. Some questions you might ask yourself are listed below:
ssh = paramiko.SSHClient()
*
*Does paramiko.SSHClient exist?
*is it working?
*what if it fails?
*do you get an error or does the SW hang?
ssh.load_system_host_keys()
*
*Can you load the system keys?
*How can you verify this?
ssh.connect(hostname='1.2.3.4', username='ubuntu')
*
*How can you prove the connection exists?
*What happens if you try to connect to another host?
*Do you get an error message?
*Can you logon with username 'ubuntu'?
*What if you try another username?
*Does the connection fail?
*Do you get a generic error so you don't give crackers clues about your security?
Proof of unit testing is usually a screen capture, log entry, or some documentation showing you got the result you expected when you ran the test. Hope this helps.
A: you can use unit test module like below
import unittest
import paramiko
class SimpleWidgetTestCase(unittest.TestCase): #This class inherits unittest.TestCase
#setup will run first
def setUp(self):
self.ssh = paramiko.SSHClient()
self.ssh.load_system_host_keys()
self.ssh.connect(hostname='1.2.3.4', username='ubuntu')
#Your test cases goes here with 'test' prefix
def test_split(self):
#your code here
pass
#this will run after the test cases
def tearDown(self):
#your code to clean or close the connection
pass
if __name__ == '__main__':
unittest.main()
detailed information about how to use unittest can be found here https://docs.python.org/2/library/unittest.html
one suggestion: robotframework is better option to design test cases in comparison to unit test, so until unless its not compulsory , you can invest your time in Robotframework
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41472869",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to redirect back with errors in Laravel 8 inside an Ajax request When data.custom_input === "false" I want to redirect back with errors.
redirect()->back() is giving me this error inside the console: Uncaught SyntaxError: Unexpected number: cd988e2f-ba9c-4b66-97d9-618e776ae740:157. Which is my uuid I pass to all routes.
URL::previous does work fine, but I can't pass any errors.
let interval = 1000;
function doAjax() {
$.ajax({
type: 'POST',
url: '/listen/custominput',
data: {
'_token': $('meta[name="csrf-token"]').attr('content')
},
dataType: 'json',
success: function (data) {
if (data.custom_input === "true") {
window.location.href = "{{route('index', $link->id)}}";
} else if (data.custom_input === "false") {
window.location.href = {{redirect()->back()->withErrors(['error', 'has-error'])}};
}
},
complete: function (data) {
setTimeout(doAjax, interval);
}
});
}
setTimeout(doAjax, interval);
What do I need to do?
A: Instead of your (POST) route returning custom_input = "false" and then trying to redirect back in JavaScript, you should redirect in the (POST) route controller (not in blade/js) with what you already have:
redirect()->back()->withErrors(['error', 'has-error'])
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64638295",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Testcase error? Hi i am learning to write test-cases, I started small test-cases for small programs.Iam trying a program
require 'test/unit'
class YearTest < Test::Unit::TestCase
def test_hours(m)
p = Year.new
assert_equal(p.hours,m)
# assert_equal(p.hours,8784)
end
end
class Year
def hours(a)
d = 24
if (a%400 == 0)
return h = d * 366
else
return h = d * 365
end
puts h
end
end
puts "enter a year"
n = gets.to_i
y = Year.new
y.hours(n)
and when i run this program in netbeans am getting error in test-case..can anybody help in solving this??
A: Your test case needs to specify a particular case; it's not intended to be done interactively as you are trying to do.
Something like this would do:
require 'test/unit'
class YearTest < Test::Unit::TestCase
def test_hours
y = Year.new
assert_equal 8760, y.hours(2001)
assert_equal 8784, y.hours(1996)
end
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6916130",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: http outbound gateway not converting french characters I have my spring integration http outbound gateway something like this.I am using my own rest template for pooling connection with ssl.I was getting 500 with french character hence I am injecting both UTF-8 and supported media type to message converter.Now Before I was injecting my own request factory and default rest template After injecting both then it started accepting french characters.Now when i changed to use my own rest template it don't accept message converter and when i try to inject this to my rest template I get this exception
Cause is - Could not write request: no suitable HttpMessageConverter found for request type [java.lang.String] and content type [text/plain;charset=UTF-8]
This worked for all request
<int-http:outbound-gateway id='batch-http' header-mapper="headerMapper"
request-channel='toHttp'
request-factory="requestFactory"
message-converters="batchHTTPConverter"
url-expression="payload.contains('${filterAttribute}') ? '${url1}' : '${url2}'" http-method="${httpMethod}"
expected-response-type='java.lang.String' charset='${charset}'
reply-timeout='${replyTimeout}' reply-channel='output'>
</int-http:outbound-gateway>
<beans:bean id="batchHTTPConverter" class="org.springframework.http.converter.StringHttpMessageConverter">
<beans:constructor-arg index="0" value="UTF-8"/>
<beans:property name="supportedMediaTypes" value = "application/json;UTF-8" />
</beans:bean>
<beans:bean id="requestFactory" class="test.batch.httpclient.CustomClientHttpRequestFactory">
<beans:constructor-arg ref="verifier"/>
</beans:bean>
<beans:bean id="verifier"
class="batch.NullHostnameVerifier">
</beans:bean>
This is not working for french or any input request
<header-filter input-channel="input"
output-channel="inputX" header-names="x-death"/>
<service-activator input-channel="inputX" ref="gw" />
<gateway id="gw" default-request-channel="toHttp" default-reply-timeout="0" error-channel="errors" />
<beans:bean id="inputfields" class="testbatch.httpclient.HTTPInputProperties">
<beans:property name="nonRetryErrorCodes" value="${nonRetryErrorCodes}"/>
</beans:bean>
<beans:bean id="responseInterceptor" class="testbatch.httpclient.ResponseInterceptor">
<beans:property name="inputProperties" ref="inputfields" />
</beans:bean>
<chain input-channel="errors" output-channel="output">
<!-- examine payload.cause (http status code etc) and decide whether
to throw an exception or return the status code for sending to output -->
<header-filter header-names="replyChannel, errorChannel" />
<transformer ref="responseInterceptor" />
</chain>
<int-http:outbound-gateway id='batch-http' header-mapper="headerMapper"
request-channel='toHttp'
rest-template="batchRestTemplate"
url-expression="payload.contains('${filterAttribute}') ? '${url1}' : '${url2}'" http-method="${httpMethod}"
expected-response-type='java.lang.String' charset='${charset}'
reply-timeout='${replyTimeout}' reply-channel='output'>
</int-http:outbound-gateway>
<beans:bean id="batchHTTPConverter" class="org.springframework.http.converter.StringHttpMessageConverter" >
<beans:constructor-arg index="0" value="UTF-8"/>
<beans:property name="supportedMediaTypes" value = "application/json;UTF-8" />
</beans:bean>
<beans:bean id="batchRestTemplate" class="testbatch.httpclient.BatchRestTemplate" >
<beans:property name="batchHTTPConverter" ref="batchHTTPConverter"/>
</beans:bean>
<beans:bean id="requestFactory"
class="testbatch.httpclient.CustomClientHttpRequestFactory">
<beans:constructor-arg ref="verifier"/>
</beans:bean>
<beans:bean id="verifier"
class="testbatch.httpclient.NullHostnameVerifier">
</beans:bean>
<beans:bean id="headerMapper" class="org.springframework.integration.http.support.DefaultHttpHeaderMapper"
factory-method="outboundMapper">
<beans:property name="outboundHeaderNames" value="${mapHeaders}"/>
<beans:property name="userDefinedHeaderPrefix" value=""/>
</beans:bean>
<channel id="output" />
<channel id="input" />
<channel id="inputX" />
<channel id="toHttp" />
</beans:beans>
My rest template
public class BatchRestTemplate extends RestTemplate{
private static final Logger LOGGER = LoggerFactory
.getLogger(BatchRestTemplate.class);
private StringHttpMessageConverter batchHTTPConverter;
public StringHttpMessageConverter getBatchHTTPConverter() {
return batchHTTPConverter;
}
public void setBatchHTTPConverter(StringHttpMessageConverter batchHTTPConverter) {
this.batchHTTPConverter = batchHTTPConverter;
}
public BatchRestTemplate() {
super(createBatchHttpRequestFactory());
List<HttpMessageConverter<?>> messageConverters= new ArrayList<HttpMessageConverter<?>>();
messageConverters.addAll(getMessageConverters());
messageConverters.add(getBatchHTTPConverter());
super.setMessageConverters(messageConverters);
}
private static ClientHttpRequestFactory createBatchHttpRequestFactory() {
CloseableHttpClient httpClient;
HttpComponentsClientHttpRequestFactory httpRequestFactory;
final int timeout = 3000;
SSLConnectionSocketFactory socketFactory;
try {
socketFactory = new SSLConnectionSocketFactory(
SSLContext.getDefault(),
new String[] {"TLSv1"},
null,
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", socketFactory)
.build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
cm.setMaxTotal(700);
cm.setDefaultMaxPerRoute(300);
cm.closeExpiredConnections();
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout)
.setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build();
httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).setConnectionManager(cm).build();
httpRequestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
return httpRequestFactory;
}
catch (Exception e) {
LOGGER.debug("error exception", e);
}
return null;
}
}
A: You have a bug in your own code:
public BatchRestTemplate() {
..........
messageConverters.add(getBatchHTTPConverter());
..........
}
But... There is no batchHTTPConverter yet!. It will appear there only after setBatchHTTPConverter().
In other words you can't use the property from the constructor because setters are called latter after the object instantiating.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35294158",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Converting double to int is giving unexpected results I was trying to find cube root of a perfect cube using pow function but the answers were unexpected (3375 = 15^3)
#include <bits/stdc++.h>
using namespace std;
int main()
{
double cb = pow(3375, 1.0/3.0);
printf("cb(in double) = %lf\n", cb);
printf("cb(in int) = %d\n",(int)cb);
return 0;
}
the output it shows is :
cb(in double) = 15.000000
cb(in int) = 14
After discussing it with people it turned out that the code ,
printf("%0.0lf", 14.0/3);
gives output
5
I am not getting why it's happening, and if it's due to precision in storing double and rounding off, then it should round it down to a smaller value rather than rounding to a greater value.
A: TL;DR: (int)double always rounds towards zero. printf("%0.0lf", double) actually rounds to closest integer.
When you convert the double to int, then the result is rounded towards zero. E.g. (int)14.9999 is 14, not 15. Therefore your first example with pow() must have given you the result slightly below 15, therefore direct cast to int gives 14.
Now, when you use printf(), then other rules are used. Printf, when asked to print a double using smallest number of digits possible (%0.0lf) rounds it to the closest integer, therefore printf("%0.0lf", 14.666) prints 15.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51088348",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: ValueError: Must pass 2-d input. shape=(430, 430, 3) I want to save this as 3d array csv file with header as r,g,b but it is showing ValueError: Must pass 2-d input. shape=(430, 430, 3).
four_img_concat shape is (430,430,3).
import pandas as pd
import numpy as np
ans=np.array(four_img_concat)
headers=np.array(['r','g','b'])
df=pd.DataFrame(ans)
df.to_csv("answ.csv",index=False,header=headers)
A: As the error is indicating, you need to transform your array from 3-d to a 2-d. You can do this by using thereshape function passing the total amount of pixels to one axis (430*430).
np.random.seed(42)
four_img_concat = np.random.randint(0,255,size=(430,430,3))
print(four_img_concat.shape) # (430, 430, 3)
four_img_concat = np.reshape(four_img_concat, (430*430, -1))
print(four_img_concat.shape) # (184900, 3)
ans = np.array(four_img_concat)
headers = np.array(['r','g','b'])
df = pd.DataFrame(ans)
df.to_csv("answ.csv",index=False,header=headers)
answ.csv file
r,g,b
102,179,92
14,106,71
188,20,102
121,210,214
74,202,87
...
...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70479421",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: java.lang.NullPointerException on twitter.showUser() I added screen names an string array and I want to populate other arrays with realnames,followersCount.When I login, occuring an nullpointerexception on line twitter.showUser(arrayKullaniciAdi[i]);Where I'm doing wrong?
Note:There isnt a problem on Login process.
Code:
User user;
String[] arrayKullaniciAdi = new String[] { "myscreenname", "herscreenname"}
private void loginToTwitter() {
if (!isTwitterLoggedInAlready()) {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
Configuration configuration = builder.build();
TwitterFactory factory = new TwitterFactory(configuration);
twitter = factory.getInstance();
try {
requestToken = twitter
.getOAuthRequestToken(TWITTER_CALLBACK_URL);
this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
.parse(requestToken.getAuthenticationURL())));
try {
for (int i = 0; i < arrayKullaniciAdi.length; i++) {
//ERROR İS HERE
user = twitter.showUser(arrayKullaniciAdi[i]);
arrayKullaniciAdi[i] = user.getScreenName();
arrayGercekAd[i] = user.getName();
arrayTakipciSayisi[i] = user.getFollowersCount();
arrayResim[i] = user.getProfileImageURL();
}
lv1.setAdapter(new Adapter(this, arrayKullaniciAdi));
}// try
catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (TwitterException e) {
e.printStackTrace();
}
} else {
}
try {
for (int i = 0; i < arrayKullaniciAdi.length; i++) {
//AND HERE
user = twitter.showUser(arrayKullaniciAdi[i].toString());
arrayKullaniciAdi[i] = user.getScreenName();
arrayGercekAd[i] = user.getName();
arrayTakipciSayisi[i] = user.getFollowersCount();
arrayResim[i] = user.getProfileImageURL();
}
}
catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
lv1.setAdapter(new Adapter(this, arrayKullaniciAdi));
}
ERRORS:
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.tf.LoginActivity.loginToTwitter(LoginActivity.java:291)
at com.example.tf.LoginActivity.onClick(LoginActivity.java:341)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26010774",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: C: How come I can still access to an empty array? While playing around with arrays, and experimented with this program:
#include <stdio.h>
int main ( void )
{
int a[] = {};
printf ( "%d\n", sizeof(a) );
printf ( "%d\n", a[0] );
printf ( "%d\n", a[1] );
printf ( "%d\n", a[10] );
printf ( "%d\n", a[100] );
}
And somehow, it compiled successfully without errors got this result:
0
-1216614400
134513834
-1080435356
-1080430834
How come I am able to access an empty array at any index that should have no size?
A: In your code
printf ( "%d\n", a[0] );
printf ( "%d\n", a[1] );
printf ( "%d\n", a[10] );
printf ( "%d\n", a[100] );
produces undefined behaviour by accessing out-of-bound memory.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29033829",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Invalid prospect email address at Pardot Salesfoce I am trying to create a prospect at Pardot- Salesforce from the python API with this format :
{'brand': 'brand1', 'platform': 'Platform 1', 'email': '[email protected]', 'first_name': 'Test', 'last_name': 'User39', 'addr_country': 'United Kingdom', 'opt_in': True}
I am getting this error :
Invalid prospect email address
This is obviously because of the email's format , but according to this official article that the character "+" is an allowed character for the email field.
So any idea what could be wrong ?
A: I was spending a lot of time on this as well but you will need to encode the + symbol to the html encoding%2B for it to work... super annoying that it is not in the documentation...
For encoding you can use the website below
https://www.url-encode-decode.com/
A: you can encode the whole email portion and send it to the API call.. Pardot on its backend did the decode for the special characters and saving to its original email state
for example:
Urlencode(test.12+{}[email protected]) and pass it to the API-> it works..
sample API call after encoding the email /4/do/create/email/test.12%21%23%24%25%26%27*%2F%3D%3F%5E_%2B-%60%7B%7C%7D%7E3%40gmail.com?format=json
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61480704",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to display a sum of values in React? I have a time tracking project in React. What I'm trying to do is the following:
*
*in each project I have a form to add activities and time;
*I want to get the amount of time to be added and displayed at the end like a total - so if I have two activities, one with 2 hours, another with 3, "Total" should display the sum - 5 hours.
Some code:
*
*Times component (contains the list of activities):
const Times = ({ times, onDelete }) => {
return (
<div>
{times.length > 0 ? <p className="time-title">Time</p> : <p className="no-time-msg">Time: nothing here yet</p>}
{times.map((time, index) => (<Time key={index} time={time} onDelete={onDelete}/>))}
<TimeTotal />
</div>
)
}
*
*Time component (contains activity, date and amount of time):
const Time = ({ time, onDelete }) => {
return (
<div className="hours-table">
<h3>Activity: {time.activity}</h3>
<h4>Date: {time.date}</h4>
<TimeAmount time={time} />
<FaTrash className="time-delete-icon" onClick={() => onDelete(time.id)}/>
</div>
)
}
*
*TimeAmount component (contains the amount of time):
const TimeAmount = ({ time }) => {
return (
<div>
<p value={time.time}>Time: {time.time} hour(s)</p>
</div>
)
}
*
*TimeTotal component (should display the sum of the amounts of time):
const TimeTotal = ({ time }) => {
const context = useContext(TimeContext)
console.log(context)
return <div className="time-total">Total: {context.times.length}</div>
}
*
*In TimeTotal, I've used context, but it displays the number of activities, not the total amount of time, like I want.
A: context.times is an array containing activities, right? Well, in javascript, .length of an array represents the length of the array itself, so it represents how many activities you have. Javascript has no way to know what you're trying to sum or achieve.
You need to sum the durations yourself by iterating the array of activities, so you need to have:
const TimeTotal = ({ time }) => {
const context = useContext(TimeContext);
let totalDuration = 0;
context.times.forEach((entry) => {
totalDuration += entry.time;
});
return <div className="time-total">Total: {totalDuration}</div>
}
A shorter version would be:
const context = useContext(TimeContext);
const totalDuration = context.times.reduce((total, entry) => entry.time + total, 0)
const TimeTotal = ({ time }) => {
const context = useContext(TimeContext)l
const totalDuration = context.times.reduce((total, entry) => entry.time + total, 0);
return <div className="time-total">Total: {totalDuration}</div>
}
You can read more about reduce here.
A: You can use .reduce() method of Array, something like
const timesSum = context.times.reduce((acc, {time}) => {
return acc + time
}, 0)
Take into account that I assumed time as numeric type. In real life you may need to cast time to number on manipulate it's value the way you need. Maybe you'll have to format timesSum.
Finally you'll have something like:
const TimeTotal = ({ time }) => {
const context = useContext(TimeContext)
console.log(context)
const timesSum = context.times.reduce((acc, {time}) => {
return acc + time
}, 0);
return <div className="time-total">Total: {timesSum}</div>
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68545514",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: why has_and_belongs_to_many adds class methods rather than instance methods? I have a couple of models
class Product < ActiveRecord::Base
has_and_belongs_to_many :categories
end
and
class Category < ActiveRecord::Base
has_and_belongs_to_many :products
end
Now why can't i say
prod = Product.new
prod.categories << Category.new
Why does has_and_belongs_to_many adds class methods like Product#categories<< while it should have added instance methods ?
How can i make use of these class methods to set associations ?
A: With the error and code you gave me, that is what you are probably missing:
prod = Product.new # This is a Product instance
prod.categories << Category.new # This works
prod = Product.where(name:'x') # This returns a query (ActiveRecord::Relation)
prod.categories << Category.new # This doesn't work
prod = Product.where(name:'x').first # This is a Product instance
prod.categories << Category.new # This works
A: When creating a new object (let's say Product), you can use the .build method to fill out those associations and call save!
EDIT: here is a good read
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17016344",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to calculate the number of tasks created by an openMP program.? I am looking to find the number of tasks. How to get the number of tasks created by the openMP program ?
void quicksort(int* A,int left,int right)
{
int i,last;
if(left>=right)
return;
swap(A,left,(left+right)/2);
last=left;
for(i=left+1;i<=right;i++)
if(A[i] < A[left])
swap(A,++last,i);
swap(A,left,last);
#pragma omp task
quicksort(A,left,last-1);
quicksort(A,last+1,right);
#pragma omp taskwait
}
A: If you want to gain an insight in what your OpenMP program is doing, you should use a OpenMP-task-aware performance analysis tool. For example Score-P can record all task operations in either a trace with full timing information or a summary profile. There are then several other tools to analyse and visualize the recorded information.
Take a look at this paper for more information for performance analysis of task-based OpenMP applications.
A: There's no good way of counting the number of OpenMP tasks, as OpenMP does not offer any way to actually query how many tasks have been created thus far. The OpenMP runtime system may or may not keep track of this number, so it would unfair (and would have performance implications) if such a number would be kept in a runtime that is otherwise not interested in this number.
The following is a terrible hack! Be sure you absolutely want to do this!
Having said the above, you can do the count manually. Assuming that your code is deterministically creating the same number of tasks for each execution, you can do this:
int tasks_created;
void quicksort(int* A,int left,int right)
{
int i,last;
if(left>=right)
return;
swap(A,left,(left+right)/2);
last=left;
for(i=left+1;i<=right;i++)
if(A[i] < A[left])
swap(A,++last,i);
swap(A,left,last);
#pragma omp task
{
#pragma omp atomic
tasks_created++
quicksort(A,left,last-1);
}
quicksort(A,last+1,right);
#pragma omp taskwait
}
I'm saying that this is a terrible hack, because
*
*it requires you to find all the task-creating statements to modify them with the atomic construct and the increment
*it does not work well for some task-generating directives, e.g., taskloop
*it may horribly slow down execution, so that you cannot leave the modification in for production (that's the part abut determinism, you need run once with the count and then remove the counting for production)
Another way...
If you are using a reasonably new implementation of OpenMP that already supports the new OpenMP tools interfaces of OpenMP 5.0, you can write a small tool that hooks into the OpenMP events for task-creation. Then you can do the count in the tool and attach it to our execution through the OpenMP tools mechanism.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56861078",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can't seem to find the solution when dealing with ABAddressBookRef I've a few 'EXC_BAD_ACCESS' in my code,
I tried to figure out what is the problem but I still don't know why.
Any ideas?
- (void)requestPermissionForContacts {
NSLog(@"requestPermissionForContacts");
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(duplicateUserContacts:) name:kAccessGrantedNotification object:nil];
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
if (addressBook != NULL) {
if (kWeDontHaveAccessToContacts) {
ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
if (granted) {
NSLog(@"Access granted");
[[NSNotificationCenter defaultCenter] postNotificationName:kAccessGrantedNotification object:nil];
}
});
}
else if (kWeHaveAccessToContacts) {
[[NSNotificationCenter defaultCenter] postNotificationName:kAccessGrantedNotification object:nil];
}
}
}
- (void)duplicateUserContacts:(NSNotification*)notification {
NSLog(@"duplicateUserContacts");
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
if (addressBook != NULL && kWeHaveAccessToContacts) {
// Get all user contacts
NSArray *allContacts = [self getAllContacts];
CFArrayRef allContactsRef = (__bridge CFArrayRef)allContacts;
// Delete old group if exists
[self deleteOwnGroup];
// Create Mobile Control 'white list' group
[self createGroup];
// Copy contacts to new group
if (addressBook != NULL && kWeHaveAccessToContacts) {
for (int i = 0; i < ABAddressBookGetPersonCount(addressBook); i++) {
ABRecordRef personFromContacts = CFArrayGetValueAtIndex(allContactsRef, i);
[self addContactToGroup:personFromContacts];
}
}
CFRelease(allContactsRef);
CFRelease(addressBook);
}
}
- (ABRecordRef)getGroupReference {
NSLog(@"getGroupReference");
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
if (addressBook != NULL && kWeHaveAccessToContacts) {
CFArrayRef allGroups = ABAddressBookCopyArrayOfAllGroups(addressBook);
if (allGroups != NULL) {
for (int i = 0; i < CFArrayGetCount(allGroups); i++) {
ABRecordRef group = CFArrayGetValueAtIndex(allGroups, i);
CFStringRef name = ABRecordCopyCompositeName(group);
NSString *groupName = (__bridge NSString*)name;
NSLog(@"groupName: %@", groupName);
if ([groupName isEqualToString:kCallBlockGroupName]) {
self.groupCallBlockRef = group;
CFRelease(group);
CFRelease(name);
CFRelease(allGroups);
break;
}
else {
continue;
}
}
}
}
//CFRelease(addressBook);
return self.groupCallBlockRef != NULL ? self.groupCallBlockRef : NULL;
}
- (NSArray*)getAllContacts {
NSLog(@"getAllContacts");
__block NSArray *allContacts = [NSArray new];
__block CFErrorRef *error = NULL;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
if (addressBook != NULL && kWeHaveAccessToContacts) {
CFArrayRef people = ABAddressBookCopyArrayOfAllPeople(addressBook);
allContacts = CFBridgingRelease(people);
self.arrayOfAllContacts = allContacts;
CFRelease(addressBook);
//CFRelease(error);
}
else {
NSLog(@"addressBook is NULL");
allContacts = NULL;
}
NSLog(@"Total number of contacts: %i", allContacts.count);
return allContacts;
}
- (void)deleteContact:(ABRecordRef)person {
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
if (addressBook != NULL && kWeHaveAccessToContacts) {
CFErrorRef error = NULL;
ABAddressBookRemoveRecord(addressBook, person, &error);
ABAddressBookSave(addressBook, &error);
CFRelease(addressBook);
CFRelease(error);
CFRelease(person);
}
}
- (void)blockPerson:(ABRecordRef)person {
BOOL hasContact = [self checkIfContactExists:person];
if (hasContact) {
NSLog(@"Contact exists, delete him.");
[self deleteContact:person];
}
else {
NSLog(@"Contact not exists.");
}
}
- (BOOL)checkIfContactExists:(ABRecordRef)person {
__block BOOL answer = NO;
CFErrorRef *error = NULL;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
if (addressBook != NULL && kWeHaveAccessToContacts) {
CFArrayRef people = ABAddressBookCopyArrayOfAllPeople(addressBook);
for(int i=0; i<ABAddressBookGetPersonCount(addressBook); i++) {
ABRecordRef personToCompare = CFArrayGetValueAtIndex(people, i);
if (ABRecordGetRecordID(personToCompare) == ABRecordGetRecordID(person)) {
answer = YES;
CFRelease(addressBook);
CFRelease(people);
CFRelease(personToCompare);
CFRelease(person);
break;
}
}
}
return answer;
}
- (void)deleteOwnGroup {
NSLog(@"deleteOwnGroup");
ABRecordRef group = [self getGroupReference];
BOOL hasGroup = group != NULL ? YES : NO;
if (hasGroup) {
NSLog(@"Group exists, delete group.");
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
if (addressBook != NULL && kWeHaveAccessToContacts) {
// CFErrorRef error = NULL;
ABAddressBookRemoveRecord(addressBook, group, NULL);
ABAddressBookSave(addressBook, NULL);
CFRelease(group);
CFRelease(addressBook);
}
}
else {
NSLog(@"Group is not exists, no group to delete.");
}
}
- (void)createGroup {
NSLog(@"createGroup");
ABRecordRef group = [self getGroupReference];
BOOL hasGroup = group != NULL ? YES : NO;
if (hasGroup) {
NSLog(@"Group already exists.");
}
else {
NSLog(@"Group is not exists, create group.");
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
if (addressBook != NULL && kWeHaveAccessToContacts) {
ABRecordRef newGroup = ABGroupCreate();
ABRecordSetValue(newGroup, kABGroupNameProperty, (__bridge CFStringRef)kCallBlockGroupName, NULL);
ABAddressBookAddRecord(addressBook, newGroup, NULL);
ABAddressBookSave(addressBook, NULL);
self.groupCallBlockRef = newGroup;
CFRelease(newGroup);
CFRelease(addressBook);
CFRelease(group);
}
}
}
- (void)addContactToGroup:(ABRecordRef)person {
NSLog(@"addContactToGroup");
ABRecordRef group = [self getGroupReference];
BOOL hasGroup = group != NULL ? YES : NO;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
//ABRecordID recordID = ABRecordGetRecordID(person);
if (!hasGroup) {
[self createGroup];
group = self.groupCallBlockRef;
}
CFErrorRef error = NULL;
BOOL didAdd = ABGroupAddMember(group, person, &error);
if (!didAdd || error) {
NSLog(@"Error adding member to group: %@", error);
}
error = NULL;
BOOL didSave = ABAddressBookSave(addressBook, &error);
if (!didSave || error) {
NSLog(@"Error saving member to group: %@", error);
}
CFRelease(addressBook);
CFRelease(error);
CFRelease(group);
CFRelease(person);
}
*
*Inside 'deleteOwnGroup':
ABAddressBookRemoveRecord(addressBook, group, NULL);
ABAddressBookSave(addressBook, NULL);
*Inside 'addContactToGroup':
BOOL didAdd = ABGroupAddMember(group, person, &error);
A: I fixed my code and now it works like a charm,
My complete code:
- (id)initAddressBook {
self = [super init];
if (self) {
self.addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
ABAddressBookRegisterExternalChangeCallback(self.addressBook, addressBookChangeHandler, NULL);
}
return self;
}
- (void)duplicateUserContactsFromAddressBook:(ABAddressBookRef)myAddressBook {
NSLog(@"duplicateUserContacts");
if (myAddressBook != NULL && kWeHaveAccessToContacts) {
// Get all user contacts
CFArrayRef allContactsRef = [self getAllContactsInAddressBook:myAddressBook];
// Delete old group if exists
[self deleteGroupWithName:kGroupNameMobileControl fromAddressBook:myAddressBook];
// Create Mobile Control 'white list' group
self.groupCallBlockRef = [self createGroupWithName:kGroupNameMobileControl fromAddressBook:myAddressBook];
// Copy contacts to new group
for (int i = 0; i < ABAddressBookGetPersonCount(myAddressBook); i++) {
ABRecordRef personFromContacts = CFArrayGetValueAtIndex(allContactsRef, i);
[self addPerson:personFromContacts toGroup:self.groupCallBlockRef fromAddressBook:myAddressBook];
}
}
}
- (void)deleteGroupWithName:(NSString*)groupName fromAddressBook:(ABAddressBookRef)myAddressBook {
if (myAddressBook != NULL && kWeHaveAccessToContacts) {
CFArrayRef allGroups = ABAddressBookCopyArrayOfAllGroups(myAddressBook);
if (allGroups != NULL) {
for (int i = 0; i < CFArrayGetCount(allGroups); i++) {
ABRecordRef group = CFArrayGetValueAtIndex(allGroups, i);
CFStringRef name = ABRecordCopyCompositeName(group);
NSString *currentGroupName = (__bridge NSString*)name;
if ([currentGroupName isEqualToString:groupName]) {
[self deleteGroup:group fromAddressBook:myAddressBook];
}
}
}
}
}
- (ABRecordRef)getGroupReference:(ABAddressBookRef)myAddressBook {
NSLog(@"getGroupReference");
if (myAddressBook != NULL && kWeHaveAccessToContacts) {
CFArrayRef allGroups = ABAddressBookCopyArrayOfAllGroups(myAddressBook);
if (allGroups != NULL) {
for (int i = 0; i < CFArrayGetCount(allGroups); i++) {
ABRecordRef group = CFArrayGetValueAtIndex(allGroups, i);
CFStringRef name = ABRecordCopyCompositeName(group);
NSString *groupName = (__bridge NSString*)name;
NSLog(@"groupName: %@", groupName);
if ([groupName isEqualToString:kGroupNameMobileControl]) {
self.groupCallBlockRef = group;
break;
}
else {
continue;
}
}
}
}
return self.groupCallBlockRef != NULL ? self.groupCallBlockRef : NULL;
}
- (CFArrayRef)getAllContactsInAddressBook:(ABAddressBookRef)myAddressBook {
NSLog(@"getAllContacts");
if (myAddressBook != NULL && kWeHaveAccessToContacts) {
CFArrayRef people = ABAddressBookCopyArrayOfAllPeople(myAddressBook);
self.arrayOfAllContacts = people;
}
else {
self.arrayOfAllContacts = NULL;
}
NSLog(@"Total number of contacts: %li", CFArrayGetCount(self.arrayOfAllContacts));
return self.arrayOfAllContacts;
}
- (void)deleteContact:(ABRecordRef)person inAddressBook:(ABAddressBookRef)myAddressBook {
if (myAddressBook != NULL && kWeHaveAccessToContacts) {
CFErrorRef error = NULL;
ABAddressBookRemoveRecord(myAddressBook, person, &error);
ABAddressBookSave(myAddressBook, &error);
CFRelease(error);
CFRelease(person);
}
}
- (void)blockPerson:(ABRecordRef)person inAddressBook:(ABAddressBookRef)myAddressBook {
BOOL hasContact = [self checkIfContactExists:person inAddressBook:myAddressBook];
if (hasContact) {
NSLog(@"Contact exists, delete him.");
[self deleteContact:person inAddressBook:myAddressBook];
}
else {
NSLog(@"Contact not exists.");
}
}
- (BOOL)checkIfContactExists:(ABRecordRef)person inAddressBook:(ABAddressBookRef)myAddressBook {
__block BOOL answer = NO;
if (myAddressBook != NULL && kWeHaveAccessToContacts) {
CFArrayRef people = ABAddressBookCopyArrayOfAllPeople(myAddressBook);
for(int i=0; i<ABAddressBookGetPersonCount(myAddressBook); i++) {
ABRecordRef personToCompare = CFArrayGetValueAtIndex(people, i);
if (ABRecordGetRecordID(personToCompare) == ABRecordGetRecordID(person)) {
answer = YES;
CFRelease(people);
CFRelease(personToCompare);
CFRelease(person);
break;
}
}
}
return answer;
}
- (ABRecordRef)createGroupWithName:(NSString*)groupName fromAddressBook:(ABAddressBookRef)myAddressBook {
NSLog(@"createGroup");
ABRecordRef newGroup = ABGroupCreate();
if (myAddressBook != NULL && kWeHaveAccessToContacts) {
ABRecordSetValue(newGroup, kABGroupNameProperty, (__bridge CFStringRef)groupName, NULL);
ABAddressBookAddRecord(myAddressBook, newGroup, NULL);
ABAddressBookSave(myAddressBook, NULL);
self.groupCallBlockRef = newGroup;
}
return newGroup;
}
- (void)addPerson:(ABRecordRef)person toGroup:(ABRecordRef)group fromAddressBook:(ABAddressBookRef)myAddressBook {
NSLog(@"addContactToGroup");
ABGroupAddMember(group, person, NULL);
ABAddressBookSave(myAddressBook, NULL);
}
static void addressBookChangeHandler(ABAddressBookRef addressBook, CFDictionaryRef info, void *context)
{
if (context) {
[(__bridge CallBlockManager*)context handleAddressBookChange:addressBook withInfo:info];
}
}
- (void)handleAddressBookChange:(ABAddressBookRef)myAddressBook withInfo:(CFDictionaryRef)info {
//
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20775678",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to create a set of two types in swift? I am new to Swift and SwiftUI.
I have two structs:
struct SongModel: Identifiable, Hashable {
let id: Int
var path: String
var artist: String
var title: String
var genre: String
var sample_rate: Int
var bitrate: Int
var duration: Int
var cover: String
var remaining: Int?
var created_at: String
var filename: String
var file_size: Int64
}
And second one:
struct FolderModel: Identifiable, Hashable {
let id: Int
var parent_id: Int?
var name: String
var files_quantity: Int
var duration: Int
var folder_size: Int64
var created_at: String
var files: [SongModel] = []
}
Also I have a list to present arrays of given models:
List(selection: self.$selectKeeper) {
ForEach(self.filemanager.folders, id: \.self) { folder in
FolderItemView(folder: folder)
.environmentObject(self.filemanager.appSettings)
.listRowBackground(Color.white)
.onTapGesture(count: 2) {
withAnimation {
self.filemanager.openFolder(folder: folder)
}
}
}.onDelete(perform: self.onDelete)
ForEach(self.filemanager.files, id: \.self) { file in
FileItemView(file: file)
.environmentObject(self.filemanager.appSettings)
.listRowBackground(Color.white)
}.onDelete(perform: self.onDelete)
}
.environment(\.editMode, .constant(.active))
I want to make selection of these objects, so I`ve create a selectKeeper property.
I can select only folders/files with
@State var selectKeeper = Set<SongModel>()
or
@State var selectKeeper = Set<FolderModel>()
But when I try
@State var selectKeeper = Set<AnyHashable>()
Code compiles successfully but selection doesn't work. I can set a checkmark but after some seconds it gone away and my selectKeeper variable is empty.
How can I make set of SongModel and FolderModel?
A: Your approach almost worked. I used Set aswell. You just need one ForEach inside your List so it will work.
struct ContentView: View {
@State var selectKeeper : Set<AnyHashable>? = Set<AnyHashable>()
var set : Set<AnyHashable>
init()
{
self.set = Set<AnyHashable>()
self.set.insert(SongModel(id: 23, path: "Test", artist: "Test", title: "Test", genre: "Test", sample_rate: 123, bitrate: 123, duration: 123, cover: "Test", remaining: 123, created_at: "Test", filename: "Test", file_size: 123))
self.set.insert(FolderModel(id: 1232, name: "Test", files_quantity: 2, duration: 2, folder_size: 23, created_at: "2020"))
}
var body: some View {
List(selection: $selectKeeper) {
ForEach(Array(self.set), id: \.self) { item in
HStack
{
if (item is SongModel)
{
//Item is SongModel
Text(String((item as! SongModel).id))
}
else
{
//Item is FolderModel, better to check object type again here
}
}
}
}
}
}
I am creating a sample Set in the init method with two different objects. They will be added to the Set. You just use one ForEach and then check inside whether it is a object of class SongModel or FolderModel.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62512848",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Get user username/email after webapp SSO authentification (Azure WebApp) I have an Azure Webapp running a Docker container (with Python & streamlit). I have secured the access to this webapp by adding a Microsoft SSO allowing only users from my organization to access the application.
On top of this, I would like to get the username or email of the user after the authentication so I can give the users differents levels of access inside the webapp. I have searched through the vast Microsoft documentation but I was not able to find my way through it. Is someone able to put me on the right path to tackle this problem?
For now, I have namely tried to follow the following documentation:
https://learn.microsoft.com/en-us/azure/databricks/dev-tools/api/latest/aad/app-aad-token hoping that I could access the user email with the authentication token from the Azure directory.
But I am stuck with an error that I was not able to solve:
Error 401: "An error of type 'invalid_resource' occurred during the login process: 'YYYYYYYY: The resource principal named xxxxxxxxxxxx was not found in the tenant named tenant_name. This can happen if the application has not been installed by the administrator of the tenant or consented to by any user in the tenant. You might have sent your authentication request to the wrong tenant."
I am now doubting that what I am trying to achieve is even possible. Any help would be appreciated.
Best, clank
A: • It is aptly written in the documentation link that you have stated that your application should have admin access and its consent for accessing the APIs in Azure databricks. Thus, as per the error statement that you are encountering, it might be that your application might not have the correct permissions to access the respective resources based on its assigned service principal.
• Also, please take note of the token issued by the Azure AD when queried a test application created wherein when decoded on ‘jwt.io’ clearly states the information regarding the user including its email address. This access token issued using authorization code flow as stated in the documentation link connects to the application created successfully but the application fails to decode the token and use the information of the user in it for allowing the user to access its resources. The application fails to decode the token because required MSAL library redirection and resource files were missing at the location of App redirect URI. Similarly, you are trying to access email address from the issued access token and use it for giving varying levels of access in the application which is not possible as the token even if intercepted in between would not be able to access user information from it since it is encrypted using the SSL key certificate and the base 64 encoding.
• To provide access to your users in varying degrees, please refer the below documentation link which describes how you can leverage dynamic groups and Azure AD conditional access policies for your requirement.
https://learn.microsoft.com/en-us/azure/active-directory/manage-apps/what-is-access-management
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69886591",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: XQUERY: Querying the output of query multiple times with different parameters I have a lot of XML files and I need to output the file names based on user-defined input from the command line.
Here is a simple example of XQuery which captures the essence of the problem.
File1.xml
<?xml version="1.0" encoding="utf-8"?>
<Description>
<FileName>File1</FileName>
<Persons>
<Person>
<Name>Anna</Name>
<Age>25</Age>
</Person>
<Person>
<Name>Marco</Name>
<Age>25</Age>
</Person>
<Person>
<Name>Mary</Name>
<Age>13</Age>
</Person>
</Persons>
</Description>
File2.xml
<?xml version="1.0" encoding="utf-8"?>
<Description>
<FileName>File2</FileName>
<Persons>
<Person>
<Name>Anna</Name>
<Age>25</Age>
</Person>
<Person>
<Name>Marco</Name>
<Age>11</Age>
</Person>
</Persons>
</Description>
For example, the user needs to get the name of the file which contains persons: Anna of age 25 and Marco of age 25.
I wrote a dirty solution.
I am wondering if it can be done in generic form for an arbitrary number of input pairs (Name, Age).
Here, the inputs are hardcoded in search.xq.
search.xq
(: person and age are user defined inputs of arbitrary length :)
let $person:= ('Anna', 'Marco')
let $age:= (25, 25)
(: Output needs to be name of file which have person (Anna, 25) and (Marco,25):)
return collection('db')/Description/Persons/Person[(Name=$person[1] and Age=$age[1])]/../Person[(Name=$person[2] and Age=$age[2])]/../../FileName
output:
<FileName>File1</FileName>
Thanks in advance.
A: Here is a possible solution (which assumes that your XQuery processor allows you to pass on maps as user-defined input):
declare variable external $INPUT := map {
'Anna': 25,
'Marco': 25
};
for $description in collection('db')/Description
where every $test in map:for-each($INPUT, function($name, $age) {
exists($description/Persons/Person[Name = $name and Age = $age])
}) satisfies $test
return $description/FileName
The second alternative is closer to your original solution. Names and ages are bound to separate variables:
declare variable $NAMES external := ('Anna', 'Marco');
declare variable $AGES external := (25, 25);
for $description in collection('db')/Description
where every $test in for-each-pair($NAMES, $AGES, function($name, $age) {
exists($description/Persons/Person[Name = $name and Age = $age])
}) satisfies $test
return $description/FileName
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49940194",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: User doesn't update Laravel Update Method:
public function update(UserUpdateRequest $request, Users $uzytkownik)
{
$this->authorize('update', $uzytkownik);
if ( $uzytkownik->update([
'birth' => $request->birth,
'sex' => $request->sex,
'about' => $request->about,
]) )
{
return 1;
}
return 0;
}
On update here in page 1 appears. Like it did the thing.
But in db nothing has changed.
$uzytkownik is proper user, and
This is the dd($uzytkownik);
And below dd($request->birth.'---'.$request->sex.'---'.$request->about); which shows proper inputs
Why it doesn't work properly?
A: As per the documentation
Mass Assignment
You may also use the create method to save a new model in a single line. The inserted model instance will be returned to you from the method. However, before doing so, you will need to specify either a fillable or guarded attribute on the model, as all Eloquent models protect against mass-assignment by default.
You need to make sure $fillable or $guarded is correctly set otherwise changes may not be persistant.
A: You can do what you want like this too:
public function update(UserUpdateRequest $request, Users $uzytkownik)
{
$this->authorize('update', $uzytkownik);
$uzytkownik->birth = $request->birth;
$uzytkownik->sex = $request->sex;
$uzytkownik->about = $request->about;
if ( $uzytkownik->save() )
{
return 1;
}
return 0;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45483099",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to stop auto commit in EJB-JPA tx I have a stateless EBJ and I am using JPA to manage database interactions. Below is my scenario where I need your help.
*
*EJB received the call to fetch data (getCustomer()).
*GetCustomer is used to read Customer entity from database using JPA.
*The customer entity is having a method to remove spaces from attributes. which is annotated with @PostLoad. Basically this modifies the entity within persistence context.
Now when response is sent to client (after transaction completed ), its fires an update SQL to database to update the dataset (modified in step-3).
If you can see this operation, its a read-only in nature. But as my data is having lot many spaces, hence I have to trim it within entity object. But this approach is firing an update SQL which is not expected.
Could you please let me know the best approach to fix this issue or how to isolate and synchronize) EJB tx and JPA tx.
A: You can declare your getCustomer() to not support transactions:
@TransactionAttribute(NOT_SUPPORTED)
public Customer getCustomer()
Read more about transactions in the Java EE tutorial:
https://docs.oracle.com/javaee/7/tutorial/transactions003.htm
A: It is not necessary to mess with transaction management to achieve your requirement.
Your code should invoke javax.persistence.EntityManager.clear() before returning from your DAO. This will detach your entity bean from the persistence context, which will no longer track it. From the java doc:
Clear the persistence context, causing all managed entities to become detached. Changes made to entities that have not been flushed to the database will not be persisted.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53870346",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Automatically update plugin versions in mutlimodule projct Is there a way to automatically update the versions of plugins for every module in a multimodule maven project?
Maven versions plugin can be used only to update project dependencies version, but not plugin versions.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58186525",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Dynamic image loading in Processing.js I'm building something that uses processing.js to operate on JPEG images dragged from a users machine into a canvas element. Currently, it works like so:
canvas.addEventListener("dragenter", dragEnter, false);
canvas.addEventListener("dragexit", dragExit, false);
canvas.addEventListener("dragover", dragOver, false);
canvas.addEventListener("drop", drop, false);
...
function drop(evt) {
...
var files = evt.dataTransfer.files;
handleFiles(files);
}
function handleFiles(files) {
var file = files[0];
reader = new FileReader();
reader.onloadend = handleReaderLoadEnd;
reader.readAsDataURL(file);
}
function handleReaderLoadEnd(evt) {
var p=Processing.getInstanceById('canvas');
p.setImage( evt.target.result );
}
...in JS, then in the .pjs script attached to the canvas (<canvas datasrc="/assets/draw.pjs" id="canvas" width="978" height="652">):
PImage imported_image;
void setImage(s) {
imported_image = requestImage(s , "" , image_loaded_callback());
}
All working fine so far. Now the problem: I would have thought the callback on requestImage (or loadImage for that matter) would happen when the image is ready to render. However if I do this:
void image_loaded_callback() {
image(imported_image, 0, 0);
}
nothing renders. I can get round the problem by waiting 10 frames and then rendering, but that seems like a very ugly (and probably unreliable) solution. Are there any better ways to do this?
Any help much appreciated!
A: if the image loading failed, the callback will never call.
but imported_image.sourceImg referent to the real img element, may be this will help. you can use it to detect the image load state. ex: imported_image.sourceImg.complete ;imported_image.sourceImg.onerror;
A: Actually, the best way I've found to do this is checking the loaded property of the image in the draw loop. So:
void draw() {
if(imported_image != null ) {
if(imported_image.loaded) {
image(imported_image,0,0,500,500);
}
}
}
Not a callback, but same end result. Had more luck with that property than @DouO's sourceImg.complete.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/9525621",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Image not displaying in browser from Django project I am trying out an ecommerce website where list of products are input in the admin section, everything works well aside the fact that the product image does not display in browser. Have check all the codes and everything seems ok. Displaying this message in my terminal "GET /media/photos/buy-1.jpg HTTP/1.1" 404 4187
Not Found: /media/photos/buy-2.jpg
`HTML
<h2 class="title">Latest Products</h2>
<div class="row">
{% for item in object_list %}
<div class="col-4">
<div>
<a href="{{ item.get_absolute_url }}">
{% if item.photo %}
<img src="{{ item.photo.url }}" alt="" />
{% else %}
<img src="{% static 'images/product-1.jpg' %}" alt=""/>
{% endif %}
<h4>{{ item.title }}</h4>
</a>
<a href="{{ item.get_absolute_url }}" >
<h6>{{ item.get_category_display }}</h6>
</a>
</div>
<div class="rating">
<i class="fa fa-star"></i>
<i class="fa fa-star"></i>
<i class="fa fa-star"></i>
<i class="fa fa-star"></i>
<i class="fa fa-star-o"></i>
</div>
<p class='lead'>
{% if item.d_price %}
<del><span>${{ item.price }}</span></del>
<span>${{ item.d_price }}</span>
{% else %}
<p>${{ item.price }}</p>
{% endif %}
</p>
</div>
{% endfor %}
</div>`
Model fie
`class Item (models.Model):
title = models.CharField(max_length=100)
price = models.FloatField()
d_price = models.FloatField(blank=True, null=True)
tax = models.FloatField(blank=True, null=True)
category = models.CharField(choices=CATEGORY_CHOICES, max_length=2)
label = models.CharField(choices=LABEL_CHOICES, max_length=1)
slug = models.SlugField()
description = models.TextField()
photo = models.ImageField(upload_to='photos', null=False, blank=False)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('base:product_details', kwargs={
'slug': self.slug
})
def get_add_to_cart_url(self):
return reverse('base:add_to_cart', kwargs={
'slug': self.slug
})
def get_remove_from_cart_url(self):
return reverse('base:remove_from_cart', kwargs={
'slug': self.slug
})
@property
def get_photo_url(self):
if self.photo and hasattr(self.photo, 'url'):
return self.photo.url`
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75083123",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Cannot connect to nginx server on fedora linux (digitalocean) I tried to set up nginx on a brand new fedora box on DigitalOcean. These are my steps
$ yum install nginx
$ systemctl enable nginx
$ systemctl restart nginx
However, it doesn't seem to work. I get the following output when running systemctl status nginx
[root@inspiredev ~]# systemctl status nginx -l
nginx.service - The nginx HTTP and reverse proxy server
Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled)
Active: active (running) since Fri 2014-11-07 14:26:33 EST; 1s ago
Process: 958 ExecStop=/bin/kill -s QUIT $MAINPID (code=exited, status=1/FAILURE)
Process: 967 ExecStart=/usr/sbin/nginx (code=exited, status=0/SUCCESS)
Process: 966 ExecStartPre=/usr/sbin/nginx -t (code=exited, status=0/SUCCESS)
Main PID: 970 (nginx)
CGroup: /system.slice/nginx.service
├─970 nginx: master process /usr/sbin/ngin
└─971 nginx: worker proces
Nov 07 14:26:33 inspiredev systemd[1]: Starting The nginx HTTP and reverse proxy server...
Nov 07 14:26:33 inspiredev nginx[966]: nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
Nov 07 14:26:33 inspiredev nginx[966]: nginx: configuration file /etc/nginx/nginx.conf test is successful
Nov 07 14:26:33 inspiredev systemd[1]: Failed to read PID from file /run/nginx.pid: Invalid argument
Nov 07 14:26:33 inspiredev systemd[1]: Started The nginx HTTP and reverse proxy server.
I can't seem to figure out or where I went wrong. It'd be great if someone can help with this.
EDIT: When I go to the box's IP address, I got nothing, which is why I feel like something is not working right.
A: From the systemd logs, nginx service appears to be running. (the warning about the pid file not found seems endemic to many distributions).
On fedora 19/20 (systemd based), open the firewall with the following commands:
firewall-cmd --permanent --zone=public --add-service=http
systemctl restart firewalld.service
or alternatively:
firewall-cmd --permanent --zone=public --add-port=80/tcp
systemctl restart firewalld.service
The second version syntax lets you open any port/protocol combination.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26808719",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Cannot update refreshed token in twilio programmable chat using react In twilio programmable chat, I used tokenAboutToExpire event to update the access token. The event triggered perfectly. After that I fetch the new token from API and updated the chatClient with the new token by using updateToken.
Once I consoled the chatClient, Inside token and fpaToken were updated. Even sometimes I can send/receive messages after expired also without refreshing the page. If I refreshed the page, It is throwing error like
Uncaught (in promise) Error: Can't connect to twilsock
componentDidMount() {
const accessToken = this.props.chatUserData.chatAccessToken;
Chat.create(accessToken)
.then(this.setupChatClient)
.catch(this.handleError);
}
setupChatClient = client => {
...
...
...
this.client.on('tokenAboutToExpire', function () {
thisProps.dispatch(getUserAccessToken(clientEmail, logIn.token))
//api call => when response came, I make 'isChatAccessFetched' as true and update the 'chatAccessToken' in reducer and checking that in componentWillReceiveProps
});
}
componentWillReceiveProps(nextProps) {
...
...
...
if (nextProps.chatUserData.isChatAccessFetched) {
this.updateChatAccessToken(this.props.chatUserData.chatClient)
}
}
updateChatAccessToken = chatClient => {
let chatAccessToken = this.props.chatUserData.chatAccessToken;
chatClient.updateToken(chatAccessToken)
this.props.dispatch(updateChatClient(chatClient))
}
...
...
...
This is my Log,
redux-logger.js:1 action GET_CHAT_ACCESSTOKEN @ 12:37:04.028
redux-logger.js:1 prev state {loginReducer: {…}, sidebarReducer: {…}, idReducer: {…}, onboardingReducer: {…}, resetReducer: {…}, …}
redux-logger.js:1 action {type: "GET_CHAT_ACCESSTOKEN", value: "[email protected]", token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjp7I…AyNn0.m8zSDNKHJuSbqhWGTL9A2zt2F4Sd0_oiEDuHHYNjjv4"}
redux-logger.js:1 next state {loginReducer: {…}, sidebarReducer: {…}, idReducer: {…}, onboardingReducer: {…}, resetReducer: {…}, …}
redux-logger.js:1 action CREATE_CHAT_USER @ 12:37:04.036
redux-logger.js:1 prev state {loginReducer: {…}, sidebarReducer: {…}, idReducer: {…}, onboardingReducer: {…}, resetReducer: {…}, …}
redux-logger.js:1 action {type: "CREATE_CHAT_USER", value: "[email protected]", token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjp7I…AyNn0.m8zSDNKHJuSbqhWGTL9A2zt2F4Sd0_oiEDuHHYNjjv4"}
redux-logger.js:1 next state {loginReducer: {…}, sidebarReducer: {…}, idReducer: {…}, onboardingReducer: {…}, resetReducer: {…}, …}
redux-logger.js:1 action GET_CHAT_ACCESSTOKEN_SUCCESS @ 12:37:04.842
redux-logger.js:1 prev state {loginReducer: {…}, sidebarReducer: {…}, idReducer: {…}, onboardingReducer: {…}, resetReducer: {…}, …}
redux-logger.js:1 action {type: "GET_CHAT_ACCESSTOKEN_SUCCESS", accessToken: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCIsImN0eSI6InR3aW…0OSJ9.WCVa1eQhrz6slr4-UuFxGWBehRRVpYaBEYcasC49BKw", @@redux-saga/SAGA_ACTION: true}
redux-logger.js:1 next state {loginReducer: {…}, sidebarReducer: {…}, idReducer: {…}, onboardingReducer: {…}, resetReducer: {…}, …}
3.17.39.166:8090/chat-service/users:1 POST http://3.17.39.166:8090/chat-service/users 409 (Conflict)
redux-logger.js:1 action CREATE_CHAT_USER_FAILURE @ 12:37:05.069
redux-logger.js:1 prev state {loginReducer: {…}, sidebarReducer: {…}, idReducer: {…}, onboardingReducer: {…}, resetReducer: {…}, …}
redux-logger.js:1 action {type: "CREATE_CHAT_USER_FAILURE", payload: Error: Request failed with status code 409
at createError (http://localhost:3000/static/js/bund…, @@redux-saga/SAGA_ACTION: true}
redux-logger.js:1 next state {loginReducer: {…}, sidebarReducer: {…}, idReducer: {…}, onboardingReducer: {…}, resetReducer: {…}, …}
logger.js:20 2019-11-15T07:07:10.724Z Twilsock T: resetBackoff
logger.js:20 2019-11-15T07:07:10.725Z Twilsock T: finalizeSocket
logger.js:20 2019-11-15T07:07:10.726Z Twilsock T: closing socket
logger.js:18 2019-11-15T07:07:10.729Z Notifications T: Persisting registration Set(1) {"token"} RegistrationState {token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCIsImN0eSI6InR3aW…0OSJ9.WCVa1eQhrz6slr4-UuFxGWBehRRVpYaBEYcasC49BKw", notificationId: "", messageTypes: Set(0)}
logger.js:18 2019-11-15T07:07:10.731Z Notifications T: Persisting registration Set(1) {"token"} RegistrationState {token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCIsImN0eSI6InR3aW…0OSJ9.WCVa1eQhrz6slr4-UuFxGWBehRRVpYaBEYcasC49BKw", notificationId: "", messageTypes: Set(0)}
logger.js:18 2019-11-15T07:07:10.733Z Notifications T: Persisting registration Set(1) {"token"} RegistrationState {token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCIsImN0eSI6InR3aW…0OSJ9.WCVa1eQhrz6slr4-UuFxGWBehRRVpYaBEYcasC49BKw", notificationId: "", messageTypes: Set(0)}
logger.js:20 2019-11-15T07:07:10.735Z Twilsock T: connect
logger.js:21 2019-11-15T07:07:10.736Z Twilsock D: FSM: userConnect: disconnected --> connecting
logger.js:20 2019-11-15T07:07:10.737Z Twilsock T: setupSocket: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCIsImN0eSI6InR3aWxpby1mcGE7dj0xIn0.eyJqdGkiOiJTSzUxZmNlNThmZTU2ODIxZWQzZDU2ZTcyMzBjMWMzOWZmLTE1NzM4MDE2MjciLCJncmFudHMiOnsiaWRlbnRpdHkiOiJjaGludGFraW5kaXNhbnRvc2hAZ21haWwuY29tIiwiY2hhdCI6eyJzZXJ2aWNlX3NpZCI6IklTMGJlZmU3MjIyZWNiNDE5ZWEyZDEyYWM3OTE2NTg3NDMifX0sImlhdCI6MTU3MzgwMTYyNywiZXhwIjoxNTczODAxOTI3LCJpc3MiOiJTSzUxZmNlNThmZTU2ODIxZWQzZDU2ZTcyMzBjMWMzOWZmIiwic3ViIjoiQUNlZjE3MjQyMmUxYjY1NzM4OWJkMjVlZTEzZDkyYzc0OSJ9.WCVa1eQhrz6slr4-UuFxGWBehRRVpYaBEYcasC49BKw
logger.js:20 2019-11-15T07:07:10.739Z Twilsock T: connecting to socket
logger.js:18 2019-11-15T07:07:10.743Z Notifications T: Add subscriptions for message type: twilio.sync.event twilsock
logger.js:18 2019-11-15T07:07:10.746Z Notifications T: Persisting registration Set(1) {"messageType"} RegistrationState {token: "", notificationId: "", messageTypes: Set(1)}
logger.js:18 2019-11-15T07:07:10.750Z Notifications T: Add subscriptions for message type: com.twilio.rtd.cds.document twilsock
logger.js:18 2019-11-15T07:07:10.751Z Notifications T: One registration attempt is already in progress
logger.js:18 2019-11-15T07:07:10.752Z Notifications T: Add subscriptions for message type: com.twilio.rtd.cds.list twilsock
logger.js:18 2019-11-15T07:07:10.754Z Notifications T: One registration attempt is already in progress
logger.js:18 2019-11-15T07:07:10.756Z Notifications T: Add subscriptions for message type: com.twilio.rtd.cds.map twilsock
logger.js:18 2019-11-15T07:07:10.756Z Notifications T: One registration attempt is already in progress
logger.js:21 2019-11-15T07:07:10.812Z Twilsock D: Emitting stateChanged("connecting")
logger.js:18 2019-11-15T07:07:10.817Z Notifications T: Persisting registration Set(1) {"messageType"} RegistrationState {token: "", notificationId: "", messageTypes: Set(4)}
logger.js:21 2019-11-15T07:07:11.548Z Twilsock D: socket opened wss://tsock.us1.twilio.com/v3/wsconnect
logger.js:21 2019-11-15T07:07:11.549Z Twilsock D: FSM: socketConnected: connecting --> initialising
logger.js:20 2019-11-15T07:07:11.551Z Twilsock T: sendInit
logger.js:20 2019-11-15T07:07:11.552Z Twilsock T: sendInit
logger.js:21 2019-11-15T07:07:11.590Z Twilsock D: send request: TWILSOCK V3.0 1200
{"id":"TMbf3d2813-534e-4260-809b-396d91e2c56c","method":"init","token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCIsImN0eSI6InR3aWxpby1mcGE7dj0xIn0.eyJqdGkiOiJTSzUxZmNlNThmZTU2ODIxZWQzZDU2ZTcyMzBjMWMzOWZmLTE1NzM4MDE2MjciLCJncmFudHMiOnsiaWRlbnRpdHkiOiJjaGludGFraW5kaXNhbnRvc2hAZ21haWwuY29tIiwiY2hhdCI6eyJzZXJ2aWNlX3NpZCI6IklTMGJlZmU3MjIyZWNiNDE5ZWEyZDEyYWM3OTE2NTg3NDMifX0sImlhdCI6MTU3MzgwMTYyNywiZXhwIjoxNTczODAxOTI3LCJpc3MiOiJTSzUxZmNlNThmZTU2ODIxZWQzZDU2ZTcyMzBjMWMzOWZmIiwic3ViIjoiQUNlZjE3MjQyMmUxYjY1NzM4OWJkMjVlZTEzZDkyYzc0OSJ9.WCVa1eQhrz6slr4-UuFxGWBehRRVpYaBEYcasC49BKw","continuation_token":"eyJmb3JtYXQiOiJydGQtY3QtMSIsImVuZHBvaW50SWQiOiJ0d2kxLWM4MDcxZTA4ZWMwNjQ3ODNhODcwY2Q5MDFlMDdhZDBiIiwiZ3JhbnRzIjp7ImlkZW50aXR5IjoiY2hpbnRha2luZGlzYW50b3NoQGdtYWlsLmNvbSIsImNoYXQiOnsic2VydmljZV9zaWQiOiJJUzBiZWZlNzIyMmVjYjQxOWVhMmQxMmFjNzkxNjU4NzQzIn0sImlwX21lc3NhZ2luZyI6eyJzZXJ2aWNlX3NpZCI6IklTMGJlZmU3MjIyZWNiNDE5ZWEyZDEyYWM3OTE2NTg3NDMifX19.ijdZgW0wdAVf9PK2Tea1Tk+n5LwAj4rgGAq4/flnjks","metadata":{"ver":"0.5.11","env":"Chrome","envv":"78.0.3904.87","os":"Windows","osv":"10","osa":64,"sdk":"js-default"},"registrations":null,"tweaks":null,"capabilities":["client_update","offline_storage"],"payload_size":0}
...
...
...
logger.js:21 2019-11-15T07:09:04.874Z Twilsock D: message received: client_update
logger.js:20 2019-11-15T07:09:04.875Z Twilsock T: message received: {method: "client_update", id: "TM21abaa7d80c6440aa6cb9c18909a0b31", payload_size: 0, client_update_type: "token_about_to_expire", client_update_message: "Your token is about to expire. Time left: less than 240000 ms"}
logger.js:20 2019-11-15T07:09:04.877Z Twilsock T: confirmReceiving
logger.js:21 2019-11-15T07:09:04.879Z Twilsock D: send request: TWILSOCK V3.0 147
{"id":"TM21abaa7d80c6440aa6cb9c18909a0b31","method":"reply","payload_type":"application/json","status":{"code":200,"status":"OK"},"payload_size":0}
logger.js:21 2019-11-15T07:09:04.882Z Twilsock D: Emitting tokenAboutToExpire()
redux-logger.js:1 action GET_CHAT_ACCESSTOKEN @ 12:39:04.883
redux-logger.js:1 prev state {loginReducer: {…}, sidebarReducer: {…}, idReducer: {…}, onboardingReducer: {…}, resetReducer: {…}, …}
redux-logger.js:1 action {type: "GET_CHAT_ACCESSTOKEN", value: "[email protected]", token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjp7I…AyNn0.m8zSDNKHJuSbqhWGTL9A2zt2F4Sd0_oiEDuHHYNjjv4"}
redux-logger.js:1 next state {loginReducer: {…}, sidebarReducer: {…}, idReducer: {…}, onboardingReducer: {…}, resetReducer: {…}, …}
redux-logger.js:1 action GET_CHAT_ACCESSTOKEN_SUCCESS @ 12:39:08.731
redux-logger.js:1 prev state {loginReducer: {…}, sidebarReducer: {…}, idReducer: {…}, onboardingReducer: {…}, resetReducer: {…}, …}
redux-logger.js:1 action {type: "GET_CHAT_ACCESSTOKEN_SUCCESS", accessToken: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCIsImN0eSI6InR3aW…0OSJ9.aP-ykQEc-uuw_lifUOBbqD6p7ppg82sbkyTocT46pog", @@redux-saga/SAGA_ACTION: true}
redux-logger.js:1 next state {loginReducer: {…}, sidebarReducer: {…}, idReducer: {…}, onboardingReducer: {…}, resetReducer: {…}, …}
logger.js:61 2019-11-15T07:09:08.758Z Chat Client I: updateToken
logger.js:21 2019-11-15T07:09:35.179Z Twilsock D: message received: ping
logger.js:20 2019-11-15T07:09:35.180Z Twilsock T: message received: {method: "ping", id: "TMf8b65ac3e250487b85eef8082f42c06b", payload_size: 0}
logger.js:20 2019-11-15T07:09:35.182Z Twilsock T: confirmReceiving
logger.js:21 2019-11-15T07:09:35.183Z Twilsock D: send request: TWILSOCK V3.0 147
{"id":"TMf8b65ac3e250487b85eef8082f42c06b","method":"reply","payload_type":"application/json","status":{"code":200,"status":"OK"},"payload_size":0}
logger.js:61 2019-11-15T07:09:08.758Z Chat Client I: updateToken
logger.js:21 2019-11-15T07:10:05.483Z Twilsock D: message received: ping
logger.js:20 2019-11-15T07:10:05.484Z Twilsock T: message received: {method: "ping", id: "TM4d1e6ca82a8145f3b6c2674eeb04f42d", payload_size: 0}
logger.js:20 2019-11-15T07:10:05.485Z Twilsock T: confirmReceiving
logger.js:21 2019-11-15T07:10:05.486Z Twilsock D: send request: TWILSOCK V3.0 147
{"id":"TM4d1e6ca82a8145f3b6c2674eeb04f42d","method":"reply","payload_type":"application/json","status":{"code":200,"status":"OK"},"payload_size":0}
logger.js:21 2019-11-15T07:13:05.239Z Twilsock D: message received: close
logger.js:20 2019-11-15T07:13:05.240Z Twilsock T: message received: {method: "close", id: "TMe06ec17095f743f680f52dc0e7b5ba73", payload_size: 0, status: {…}}
logger.js:20 2019-11-15T07:13:05.241Z Twilsock T: confirmReceiving
logger.js:21 2019-11-15T07:13:05.241Z Twilsock D: send request: TWILSOCK V3.0 147
{"id":"TMe06ec17095f743f680f52dc0e7b5ba73","method":"reply","payload_type":"application/json","status":{"code":200,"status":"OK"},"payload_size":0}
backend.js:6 2019-11-15T07:13:05.242Z Twilsock W: Server closed connection: {"code":410,"status":"TOKEN_EXPIRED","description":"Token expired","errorCode":51207}
r @ backend.js:6
warn @ logger.js:23
onIncomingMessage @ twilsock.js:313
(anonymous) @ twilsock.js:46
emit @ events.js:146
socket.onmessage @ websocketchannel.js:31
logger.js:21 2019-11-15T07:13:05.243Z Twilsock D: FSM: receiveClose: connected --> waitSocketClosed
logger.js:20 2019-11-15T07:13:05.244Z Twilsock T: startDisconnectTimer
logger.js:20 2019-11-15T07:13:05.244Z Twilsock T: closing socket
logger.js:21 2019-11-15T07:13:05.245Z Twilsock D: Emitting stateChanged("disconnecting")
logger.js:20 2019-11-15T07:13:05.245Z Notifications I: Transport ready: false
logger.js:21 2019-11-15T07:13:05.247Z Twilsock D: Emitting tokenExpired()
logger.js:21 2019-11-15T07:13:08.245Z Twilsock D: disconnecting is timed out
logger.js:20 2019-11-15T07:13:08.246Z Twilsock T: closeSocket (graceful: true)
logger.js:20 2019-11-15T07:13:08.246Z Twilsock T: closing socket
logger.js:20 2019-11-15T07:13:08.250Z Twilsock T: cancelDisconnectTimer
logger.js:21 2019-11-15T07:13:08.251Z Twilsock D: FSM: socketClosed: waitSocketClosed --> disconnected
logger.js:20 2019-11-15T07:13:08.253Z Twilsock T: resetBackoff
logger.js:20 2019-11-15T07:13:08.255Z Twilsock T: finalizeSocket
logger.js:20 2019-11-15T07:13:08.256Z Twilsock T: closing socket
logger.js:21 2019-11-15T07:13:08.259Z Twilsock D: Emitting stateChanged("disconnected")
logger.js:21 2019-11-15T07:13:08.260Z Twilsock D: Emitting disconnected()
Please help me with this issue. Thanks in advance.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58825406",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Git submodule, subtree or simply nested git? Here is my directory structure
main folder (git repo 1)
subfolder 1 (git repo 2)
subfolder 2
I have a bigger project and I keep track of all changes in the main and child folders in repo 1. However, for subfolder 1 I have a common repo 2 with a co-author. An important detail is that some files in subfolder 1 are versioned in repo 2 but not in repo 1, and viceversa.
Is it possible to simply init the main folder on repo 1 and subfolder 1 on repo 2, as if they were independent projects, or are there any shortcomings to this solution?
Are there any advantage from using submodule or subtree? Notice that I don't care having the same log/hostory in repo 2 and repo 1, I am happy to commit to the two repos independently.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73798298",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Setting silverlight to focus a control with some degree of reliability? I'm having some issues getting silverlight 4 to set initial focus on a control, the biggest issue is that if the control has not rendered focus is not guaranteed.
A: I have created a behavior and it sets the focus in the Loaded event which guarantees the control is loaded.
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Interactivity;
namespace xxx.Behaviors
{
public class SetControlFocusBehavior : Behavior<Control>
{
protected override void OnAttached()
{
base.OnAttached();
if (AssociatedObject is Control)
{
((Control)AssociatedObject).Loaded += new RoutedEventHandler(SetControlFocusBehavior_Loaded);
}
}
void SetControlFocusBehavior_Loaded(object sender, RoutedEventArgs e)
{
var control = sender as Control;
if (control == null)
{
return;
}
System.Windows.Browser.HtmlPage.Plugin.Focus();
control.Focus();
}
protected override void OnDetaching()
{
base.OnDetaching();
((Button)AssociatedObject).Loaded -= SetControlFocusBehavior_Loaded;
}
}
}
To use it, simply drag and drop it onto the control using Blend.
<TextBox x:Name="MyTextBox">
<i:Interaction.Behaviors>
<sg:SetControlFocusBehavior/>
</i:Interaction.Behaviors>
</TextBox>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8220991",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Type casting char array to char ** If I do this:
#include <stdio.h>
typedef char **arr2D;
char arr1D [5 * 10];
int main (void)
{
((arr2D)arr1D)[0][0] = '_';
printf("%c", arr1D[0]);
return(0);
}
I receive crash, which suggests undefined behavior.
Why can't I do this ?
A: *
*char arr1D [5 * 10]; - is zero initialized.
*((arr2D)arr1D)[0] - reinterprets the memory pointed to by arr1D as a pointer to char*. This has an unspecified address (zero byte pattern isn't necessarily the NULL address).
*((arr2D)arr1D)[0][0] - derefrences that unspecified address. Undefined behavior.
Your naming also suggests a misconception common about pointers and arrays. Arrays aren't pointers. And pointers aren't arrays.
Arrays decay into pointers to the first element.
char[2][2] is a 2D char array that will decay to char(*)[2] (a pointer to an array).
char** is not a 2D char array, it's a pointer to a pointer.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41660171",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Error with setting the value of excel worksheet Without going into too much detail, this is my first project. I am very new at coding and this may be a very simple oversight on my part. I am an engineer and I need to add some "custom properties" to over 1000+ CAD files. I am using excel to assign set properties to each file.
I am using EPPlus.
I have a using OfficeOpenXml; statement.
During debugging, I get an error at line 73: worksheet.Cells[row, 6].Value = file;
System.NullReferenceException: 'Object reference not set to an instance of an object.worksheet was null."
I can see that the value for "var worksheet" at line 64 is null but I can't figure out why...
public static void InsertPropName2()
{
string ExFile = @"J:\VB Test\Excel\SW.Prop.xlsx";
var FileInfo = new FileInfo(ExFile);
List<string> DrwPropName = new List<string>()
{
"MPN",
"Description",
"OEM Location",
"Material",
"Surface Finish",
"Hardness",
"Color",
};
List<string> PartPropName = new List<string>()
{
"MPN",
"Description",
"Drawn",
"Q.A. Approved",
"Checked",
"Engineering Approved",
"Revision",
"Drawn By:",
"Drawn Date",
"Q.A. Approval",
"Q.A. App. Date",
"Checked By",
"Checked Date",
"Engineering Approval",
"Engineering App. Date",
};
List<int> PartPropType = new List<int>()
{
30,
30,
30,
30,
30,
30,
30,
30,
64,
30,
64,
30,
64,
30,
64,
};
using (ExcelPackage excel = new ExcelPackage(FileInfo))
{
string directory = @"J:\Move (Test)\a";
string[] Files = Directory.GetFiles(directory);
foreach (string file in Files)
{
string WSName = file.Substring(file.Length - 31);
//line 64
var worksheet = excel.Workbook.Worksheets[WSName];
string FileType = file.Substring(file.Length - 6);
switch (FileType)
{
case "SLDDRW":
int row = 1;
int a = 0;
//line 73
worksheet.Cells[row, 6].Value = file;
foreach (string prop in DrwPropName)
{
worksheet.Cells[row, 7].Value = DrwPropName[a];
worksheet.Cells[row, 8].Value = 30;
a++;
}
break;
case "SLDPRT":
int row2 = 1;
int b = 0;
worksheet.Cells[row2, 6].Value = file;
foreach (string prop in PartPropName)
{
worksheet.Cells[row2, 7].Value = PartPropName[b];
worksheet.Cells[row2, 8].Value = PartPropType[b];
b++;
row2++;
}
break;
case "SLDASM":
int row3 = 1;
int c = 0;
worksheet.Cells[row3, 6].Value = file;
foreach (string prop in PartPropName)
{
worksheet.Cells[row3, 7].Value = PartPropName[c];
worksheet.Cells[row3, 8].Value = PartPropType[c];
c++;
row3++;
}
break;
default:
break;
}
}
excel.Save();
}
}
Any help is greatly appreciated. Again sorry if this is a very simple noob error!
edit:
I have another class that I run before I run this that creates an excel file with the worksheets in question above so I know the worksheet exists. I have also visual checked to see if that the excel file has the worksheets in question. the code in the other class executes and I have no errors with that part of my project.
The WSName is not declared anywhere else in the class so It is not the same as other NullReferenceException threads.
Part of the code that's in the other class:
using (ExcelPackage excel = new ExcelPackage(FileInfo))
{
string WSName = file.Substring(file.Length - 31);
var worksheet = excel.Workbook.Worksheets.Add(WSName);
A: Thanks for trying to solve the issue. I figured out what the problem was.
WSName was set from code Directory.GetFiles(directory); so I can keep track of the properties to each CAD file.
When the first class member used the value of WSName to create the worksheet. The value for WSName had "\". The actual name of the worksheet omitted the "\" even though I used the "@" symbol in front of the string. It must me a limitation of excel. When the second class member tried to write to the worksheet even though WSName was coded the same way as the first member it could not find it due to the missing "\".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51958395",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How to Save Html Formatted Text in Database Safely ? PHP - MYSQL I'm trying to develope a php cms. I just want to learn how to save an article with links safely in database. There are tutorials in internet but I couldn't find a tutorial for html formatted text. They always show for normal text.
Example HTML Code
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. <a href="http://www.gotosomewhere.com">Go to somewhere</a> Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
Questions:
*
*What is the best way to do that safely?
*Should I change my text's format with a function while saving in database?
*If I should how can I edit this article again?
I know this is a simple question according to most developers but I'm still learning and I want to make sure that everything is safe :)
A: I would simply save the information with the tags between quotes and use the following :
http://php.net/manual/en/function.strip-tags.php
Hope it helps, the second comment from the above site is a good example, more specifically
http://php.net/manual/en/function.strip-tags.php#86964
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37635565",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Cannot get all the submenu items in winform in c# I have a winform with menu bar like this :
File==>Add==>New Project
File==>Add==>Existing Project
File==>Open
File==>Exit
Edit==>Copy
Edit==>Cut
Help==>View Help
Help==>About
I want to get the text of all menu items and submenu items.
I have tried this code :
for (int i = 0; i < menuStrip1.Items.Count; i++)
{
foreach (ToolStripMenuItem item in ((ToolStripMenuItem)menuStrip1.Items[i]).DropDownItems)
{
textBox1.Text += item.OwnerItem.Text + @"==>" + item.Text + Environment.NewLine;
}
}
and it results to :
File==>Add
File==>Open
File==>Exit
Edit==>Copy
Edit==>Cut
Help==>View Help
Help==>About
as it shows it does not show all of submenu items. I have tried this code :
for (int i = 0; i < menuStrip1.Items.Count; i++)
{
for (int j = 0; j < ((ToolStripMenuItem) menuStrip1.Items[i]).DropDownItems.Count; j++)
{
foreach (ToolStripMenuItem item in (ToolStripMenuItem)menuStrip1.Items[i]).DropDownItems[j]))
{
textBox1.Text += item.OwnerItem.Text + @"==>" + item.Text + Environment.NewLine;
}
}
}
but it gives this error :
foreach statement cannot operate on variables of type 'System.Windows.Forms.ToolStripItem' because 'System.Windows.Forms.ToolStripItem' does not contain a public definition for 'GetEnumerator'
Note : I am looking for a general solution(for the arbitrary number of menu item and arbitrary number of nested sub menu items) not only for this problem.
Thanks in advance.
A: You can use the following general tree traversal function, taken from How to flatten tree via LINQ?
public static class TreeHelper
{
public static IEnumerable<T> Expand<T>(this IEnumerable<T> source,
Func<T, IEnumerable<T>> elementSelector)
{
var stack = new Stack<IEnumerator<T>>();
var e = source.GetEnumerator();
try
{
while (true)
{
while (e.MoveNext())
{
var item = e.Current;
yield return item;
var elements = elementSelector(item);
if (elements == null) continue;
stack.Push(e);
e = elements.GetEnumerator();
}
if (stack.Count == 0) break;
e.Dispose();
e = stack.Pop();
}
}
finally
{
e.Dispose();
while (stack.Count != 0) stack.Pop().Dispose();
}
}
}
With that function and LINQ, getting all the menu items is simple
var allMenuItems = menuStrip1.Items.OfType<ToolStripMenuItem>()
.Expand(item => item.DropDownItems.OfType<ToolStripMenuItem>());
and producing a text like in your example
textBox1.Text = string.Join(Environment.NewLine, allMenuItems
.Select(item => item.OwnerItem.Text + @"==>" + item.Text));
A: Use recursion .
Write a method that calls itself (but checks for termination as well so it does not call itself when not needed to go deeper).
Here is some code:
static string GetText2(ToolStripMenuItem c)
{
string s = c.OwnerItem.Text + @"==>" + c.Text + Environment.NewLine;
foreach (ToolStripMenuItem c2 in c.DropDownItems)
{
s += GetText2(c2);
}
return s;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33766276",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: A anchor as submit button with value This may seem like a duplicate question but I have googled and search stackoverflow how an a anchor tag would act like as a submit that would fit on the website that I am trying to do.
I have this code on my right panel navigation:
<div class="content clearfix">
<div class="left_column">
<div class="product_menu">
<? if($_SESSION['logged_in'] == 1) {
$customer_panel = '
<div class="customer_nav">
<h1 class="customer_nav_name">Hello ' . $_SESSION['fname'] . ',</h1>
<ul class="clearfix">
<li><a href="#">View Profile</a></li>
<li><a href="">Update Information</a></li>
<li>
<!-- this is where i would like the signout button to act as a submit
i have left it plane to start from scratch -->
<a href="">Sign Out</a>
</li>
</ul>
</div>';
echo $customer_panel;
}?>
<h2><span>Product Categories</span></h2>
<ul id="prod_nav" class="clearfix">
<li class="top"><a href="#" class="top_link"><span>Processed Meat</span></a></li>
<li class="top"><a href="#" class="top_link"><span>Ready Made</span></a></li>
<li class="top"><a href="#" class="top_link"><span>Siomai & Siopao</span></a></li>
<li class="top"><a href="#" class="top_link"><span>English Pork Snacks</span></a></li>
</ul>
</div>
And here is my usual code when i use a submit button and not an anchor tag to make a POST method:
if(isset($_POST['signout'])) { // logout button
// Clear and destroy sessions and redirect user to home page url.
$_SESSION = array();
session_destroy();
// Redirect to where the site home page is located -- Eg: localhost
header('Location: http://localhost/');
}
I have read many of this questions but I don't know jQuery or how to achieve this using javascript.
I also tried using this solution:
<form id="signout" action="index.php" method="post">
<a href="javascript:;" onclick="document.getElementById('signout').submit();">Sign Out</a>
<input type="hidden" name="signout" value="signout"/>
</form>
that I kinda found from here at stackoverflow.
The problem about this is that if I include the onclick="" , the whole page does not show. but if i remove it, the page comes back to normal. - it doesn't work inside an <li> element.
It might sound basic, but it would help me and other new starters to understand how to make it possible. Thank you very much. :)
A: Try this,
STEP 1 :
Put the following scripts in your html file.
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.0.min.js"></script>
<script type="text/javascript">
$(function() {
$('.signout-btn').click(function() {
$('#signout').submit();
});
})
</script>
STEP 2 :
Add an attribute class="signout-btn" to anchor tags, which you want to trigger the form submission.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16796079",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: I don't understand what's wrong with my rules I had setup my rules in the RealtimeDatabase so that only people who created the content can read or updated it, but unfortunately the rules don't work like that.
I also tried various other rules with less security so the issue doesn't lie in my app.
These are my rules which don't let me read my own data.
{
"rules": {
"posts": {
"$uid": {
".read": "$uid == auth.uid",
".write": "$uid == auth.uid"
}
}
}
}
Code in my app.
Path: user/uid/info
Value: imageUrl
fun getFireBaseValue(Path: String, Value: String): String {
FirebaseDatabase.getInstance().getReference(Path).child(Value)
.addValueEventListener(object : ValueEventListener {
override fun onDataChange(p0: DataSnapshot) {
val fetchedValue = p0.value.toString()
}
override fun onCancelled(p0: DatabaseError) {
}
})
}
I expected a URL i wrote earlier. But instead I get an error: "DatabaseError: Permission denied".
As far as I understand the rules, I should be allowed to read my own data.
A: If the Path variable in your code sample is user/uid/info, then the rules don't allow access to that location. The rules only allow per-user access to posts/uid. The path in your rules needs to match the path in your code in order for access to be allowed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58421213",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Should Redis Sentinel Monitor Each Master in a cluster? Does it require sentinel to monitor each master in the cluster with a distinct service name, or just one of the 3 masters in the cluster?
My current config is 3 masters, 3 slaves, and 3 sentinel instances. Each instance of sentinel is monitoring each master. master1, master2, master3. I haven't seen any documentation that has more than a single master, and the redis documentation isn't real clear.
A: I found the solution by running a test myself. Yes, in a cluster configuration you need to monitor each master in order for failover to occur.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36313521",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Error installation extentions Reportico on Yii 2 I installed the extension reportico through composer and already web.php configuration file, but when I go into Reportico Admin Page error instead. The solution how ?
enter image description here
scrip web.php
<?php
$params = require(__DIR__ . '/params.php');
$config = [
'id' => 'basic',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'components' => [
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
],
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'K1pkkP_iwACp933A03LotJ3AfRsyIb-D',
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => true,
],
'errorHandler' => [
'errorAction' => 'site/error',
],
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
// send all mails to a file by default. You have to set
// 'useFileTransport' to false and configure a transport
// for the mailer to send real emails.
'useFileTransport' => true,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'db' => require(__DIR__ . '/db.php'),
/*
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
],
],
*/
],
'reportico' => [
'class' => 'reportico\reportico\Module' ,
'controllerMap' => [
'reportico' => 'reportico\reportico\controllers\ReporticoController',
'mode' => 'reportico\reportico\controllers\ModeController',
'ajax' => 'reportico\reportico\controllers\AjaxController',
]
],
'params' => $params,
];
if (YII_ENV_DEV) {
// configuration adjustments for 'dev' environment
$config['bootstrap'][] = 'debug';
$config['modules']['debug'] = [
'class' => 'yii\debug\Module',
];
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = [
'class' => 'yii\gii\Module',
];
}
return $config;
A: Move reportico to components array:
'components' => [
//...
'reportico' => [
'class' => 'reportico\reportico\Module' ,
'controllerMap' => [
'reportico' => 'reportico\reportico\controllers\ReporticoController',
'mode' => 'reportico\reportico\controllers\ModeController',
'ajax' => 'reportico\reportico\controllers\AjaxController',
]
]
]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38005036",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Objective-C Pointers > pointing to properties I have an NSInteger property of a custom class called 'estimatedTime', now, in my UITableView class I'm trying to pass this property as a pointer to a UITableViewCell. I can't seem to get it to work! I've tried the following:
NSInteger *pointer = sharedManager.tempTask.&estimatedTime;
NSInteger *pointer = &sharedManager.tempTask.estimatedTime;
I get the errors: lvalue required as unary '&' operand
and: expected identifier before '&' token
Can you not pass a pointer to a property? Is the property not just it self pointing to the ivar in my custom class? I need it as a pointer type so I can edit the value when a UITextField is changed inside the UITableViewCell.
Thanks and hope it makes sense!
A: As Marcelo said, you can't do this using the property itself.
You would either have to:
*
*Add a method to tempTask that returns a pointer to the estimatedTime iVar (NSInteger *pointer = sharedManager.tempTask.estimatedTimePointer)
*Use a temporary NSInteger, taking its address for whatever calls you need, then copy the result into estimatedTime
Option 1 is probably a really bad idea, because it breaks object encapsulation.
A: Properties aren't variables; they are just syntactic sugar for get/set-style methods. Consequently, you can't take the address of a property.
A: For using numbers in pointers I would suggest using a NSNumber* rather than a NSInteger* (an NSInteger is really an int). For example, if sharedManager.tempTask.estimatedTime is an NSInteger, you could do:
NSNumber *pointer = [NSNumber numberWithInt:sharedManager.tempTask.estimatedTime];
Now, when you want to use the int value for the number do:
NSInteger i = [n intValue];
The NSNumber * is a obj-c object so the usual retain/release/autorelease mechanisms apply.
A: Actually when you say Object1.Propertyxy.Property1
It is actually called as a FUNCTION rather than a VARIABLE/VALUE at some memory.
In your case "tempTask" will act as a
function and "estimatedTime" as a
argument and the result would be the
RETURN of the function.
I know and completely agree that pointers are very favorable for increasing speed but in this case it is just useless as it would require storing that PROPERTY somewhere and thereafter referring to i, just a waste of time and memory, go for it only if you have to use that very specefic property a 100 times per run :D
Hope this helped, if it didn't just let me know, I'll be glad to help.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5003158",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to delete previous folder with a variable name (Batch script) I have issue with Chrome update - after download update chrome dont delete and rename new files. After reload chrome it again want to relaunch for update.
I've tried to write .bat for resolve it.
I did some with batch script
- delete old chrome.exe and chrome_proxy.exe
- reneme new_* to normal name
But I can't understand how to delete previous folder if name will change after new update.
cd /d "C:\Program Files (x86)\Google\Chrome\Application"
echo deleting files
del chrome.exe
del chrome_proxy.exe
echo renaming files
ren new_chrome.exe chrome.exe
ren new_chrome_proxy.exe chrome_proxy.exe
Script will delete previous folder with name that can change after new update.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58570181",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: VBA - Delete row, copy the rest and append down for multiple times and assign counter value to formula of a column in table I am very new to coding and VBA. Below is the code that i have so far.
The delete > copy > append part work fine for me. But i want to assign a counter value to the formula of a column in the table for each append.
How to achieve this?
Many thanks for the help!
Sample
Private Sub Select_Button_Click()
Dim tbl As ListObject
Set tbl = Worksheets("Sheet1").ListObjects("Table2")
Dim x As Long
Dim lastrow As Long
Dim lr As ListRow
lastrow = tbl.ListRows.Count
For x = lastrow To 1 Step -1
Set lr = tbl.ListRows(x)
If Intersect(lr.Range, tbl.ListColumns("Dept_Group").Range).Value <> Worksheets("Sheet1").Range("$F$2").Value Then
'lr.Range.Select
lr.Delete
End If
Next x
Dim rng As Range
Set rng = tbl.DataBodyRange
With tbl
For i = 1 To 12
rng.Copy
rng.Insert Shift:=xlDown
Application.CutCopyMode = False
'After pasting i want to assign the counter value i to column "Period" in table with formula like: "=Month($A$2)- i"
Next i
End With
End Sub
A: Deleting a certain number of rows one by one can be slow. You can try the following method, should be faster and achieve the desired outcome.
Private Sub Select_Button_Click()
Application.DisplayAlerts = False: Application.ScreenUpdating = False: Application.EnableEvents = False
On Error GoTo Cleanup
With Worksheets("Sheet1").ListObjects("Table2")
.DataBodyRange.AutoFilter 7, "<>" & Sheet1.Range("$F$2").Value2
.Range.Offset(1).Delete
.AutoFilter.ShowAllData
With .DataBodyRange
Dim i As Long
For i = 1 To 12
.Copy
.Insert Shift:=xlDown
.Columns(10).Formula = "=Month($A$2)-" & i
Next
End With
End With
Cleanup:
With Application
.DisplayAlerts = True: .ScreenUpdating = True: .EnableEvents = True: .CutCopyMode = False
End With
End Sub
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42966691",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: what s the different between selector > selector and selector selector? I was wondering which is the different between:
.myClass/DomElement .myotherclassinsidethatelement
and
.myClass/DomElement > .myotherclassinsidethatelement
the both select the myotherclassinsidethatelement class elements inside my .myClass/DomElement
or I missed something?
A: .myClass/DomElement > .myotherclassinsidethatelement selects only the direct children of the parent class.
So:
<div class='myClass'>
<div class='someOther'>
<div class='myotherclassinsidethatelement'></div>
</div>
</div>
In this case, the > version won't select it.
See here: http://jsfiddle.net/RRv7u/1/
A: UPDATE
The previous answer I gave was incorrect. I was under the impression that inheritance and nesting were the same thing, but they are not. If anyone else had this impression, here is a resource explaining what nesting is:
http://www.htmldog.com/guides/css/intermediate/grouping/
Here is another explaining what specificity is:
http://www.htmldog.com/guides/css/intermediate/specificity/
And here is a final link explaining specificity and inheritance:
http://coding.smashingmagazine.com/2010/04/07/css-specificity-and-inheritance/
Previous answer:
The angle bracket in CSS denotes inheritance. So when you say
.class1 > .class2 { styles }
You're saying that the styles you're about to apply for class2 are
only going to be applied when class2 is a child of class1.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21069523",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: create array from mysql query php I have a little problem that I don't understand. I have a db that has an owner and type (and more off course). I want to get a list of all the type values that has owner equal to the current user, but I get only two result
$sql = "SELECT type FROM cars WHERE owner='".mysql_real_escape_string($_SESSION['username'])."' AND selling='0' ORDER BY id DESC ";
$result = mysql_query($sql,$con);
print_r(mysql_fetch_array($result));
prints out:
Array ( [0] => 18 [type] => 18 )
and
$sql = "SELECT type FROM cars WHERE owner='".mysql_real_escape_string($_SESSION['username'])."' AND selling='0' ";
prints out:
Array ( [0] => 16 [type] => 16 )
And the result should be something like 19, 19, 18, 17, 16 in an array. Thats all the types that has me as set as owner.
I have got this working now:
for ($x = 0; $x < mysql_num_rows($result); $x++){
$row = mysql_fetch_assoc($result);
echo $row['type'];
}
Here I print out all the values correctly, but I need to create an array with all the values. I though I could use array_push, but there most be a better way of doing it. I thought I would get all the type values with a simple mysql query.
A: THE CORRECT WAY ************************ THE CORRECT WAY
while($rows[] = mysqli_fetch_assoc($result));
array_pop($rows); // pop the last row off, which is an empty row
A: Very often this is done in a while loop:
$types = array();
while(($row = mysql_fetch_assoc($result))) {
$types[] = $row['type'];
}
Have a look at the examples in the documentation.
The mysql_fetch_* methods will always get the next element of the result set:
Returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows.
That is why the while loops works. If there aren't any rows anymore $row will be false and the while loop exists.
It only seems that mysql_fetch_array gets more than one row, because by default it gets the result as normal and as associative value:
By using MYSQL_BOTH (default), you'll get an array with both associative and number indices.
Your example shows it best, you get the same value 18 and you can access it via $v[0] or $v['type'].
A: You do need to iterate through...
$typeArray = array();
$query = "select * from whatever";
$result = mysql_query($query);
if ($result) {
while ($record = mysql_fetch_array($results)) $typeArray[] = $record['type'];
}
A: $type_array = array();
while($row = mysql_fetch_assoc($result)) {
$type_array[] = $row['type'];
}
A: while($row = mysql_fetch_assoc($result)) {
echo $row['type'];
}
A: You could also make life easier using a wrapper, e.g. with ADODb:
$myarray=$db->GetCol("SELECT type FROM cars ".
"WHERE owner=? and selling=0",
array($_SESSION['username']));
A good wrapper will do all your escaping for you too, making things easier to read.
A: You may want to go look at the SQL Injection article on Wikipedia. Look under the "Hexadecimal Conversion" part to find a small function to do your SQL commands and return an array with the information in it.
https://en.wikipedia.org/wiki/SQL_injection
I wrote the dosql() function because I got tired of having my SQL commands executing all over the place, forgetting to check for errors, and being able to log all of my commands to a log file for later viewing if need be. The routine is free for whoever wants to use it for whatever purpose. I actually have expanded on the function a bit because I wanted it to do more but this basic function is a good starting point for getting the output back from an SQL call.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3415296",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: How to tell mysql to scan just recent one million rows I have a Myisam table with 15,000,000 rows, my current query is like this:
SELECT id, MATCH(title) AGAINST('$searchterm' IN BOOLEAN MODE) AS score
FROM news
WHERE MATCH(title) AGAINST('$searchterm' IN BOOLEAN MODE)
ORDER BY score DESC, id DESC
LIMIT 25
How can I create a query to tell Mysql to scan just recent one million rows (not whole table)?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49109579",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Boost Statechart: Return to Previous State I've got a state machine wherein if I enter a particular state, sometimes I need to have a regular transition to another state and other times I need to return to a previous state.
For example, having states A B C, say that transition S moves state A to C and from B to C. I need that a transition T moves C to A when S occurred in state A and C to B when it occurred in state B.
In the code below, transition S occurs in state B, and thus I would like for transition T to return to state B (whereas currently, it returns to state A).
#include <boost/mpl/list.hpp>
#include <boost/statechart/state_machine.hpp>
#include <boost/statechart/simple_state.hpp>
#include <boost/statechart/event.hpp>
#include <boost/statechart/transition.hpp>
// states
struct A;
struct B;
struct C;
struct D;
// events
struct S : boost::statechart::event<S> {};
struct T : boost::statechart::event<T> {};
struct U : boost::statechart::event<U> {};
// fsm
struct FSM : boost::statechart::state_machine<FSM, B> {};
// fully defined states/transitions
struct A : boost::statechart::simple_state<A, FSM> {
typedef boost::statechart::transition<S, C> reactions;
A() { std::cout << "entered A" << std::endl; }
};
struct B : boost::statechart::simple_state<B, FSM> {
typedef boost::statechart::transition<S, C> reactions;
B() { std::cout << "entered B" << std::endl; }
};
struct C : boost::statechart::simple_state<C, FSM> {
typedef boost::mpl::list<
boost::statechart::transition<T, A>,
boost::statechart::transition<T, B>,
boost::statechart::transition<U, D> > reactions;
C() { std::cout << "entered C" << std::endl; }
};
struct D : boost::statechart::simple_state<D, FSM> {
D() { std::cout << "entered D" << std::endl; }
};
int main() {
FSM fsm;
fsm.initiate();
fsm.process_event(S());
fsm.process_event(T());
fsm.process_event(S());
fsm.process_event(U());
return 0;
}
The above code returns:
entered B
entered C
entered A
entered C
entered D
and I would like to instead see:
entered B
entered C
entered B
entered C
entered D
Is there any clean way to do this using Boost::Statechart?
A: I've found an ~okay~ way of doing this by creating an enum mapping for states, storing the previous state in the outermost context (top-level fsm), and then using a custom reaction for the T event:
#include <boost/mpl/list.hpp>
#include <boost/statechart/state_machine.hpp>
#include <boost/statechart/simple_state.hpp>
#include <boost/statechart/event.hpp>
#include <boost/statechart/transition.hpp>
#include <boost/statechart/custom_reaction.hpp>
// states
struct A;
struct B;
struct C;
struct D;
// state enum mapping
enum class state_mapping {
A = 0,
B,
C,
D
};
// events
struct S : boost::statechart::event<S> {};
struct T : boost::statechart::event<T> {};
struct U : boost::statechart::event<U> {};
// fsm
struct FSM : boost::statechart::state_machine<FSM, B> {
state_mapping previous_state = state_mapping::B;
};
// fully defined states/transitions
struct A : boost::statechart::simple_state<A, FSM> {
typedef boost::statechart::transition<S, C> reactions;
A() { std::cout << "entered A" << std::endl; }
virtual ~A() { outermost_context().previous_state = state_mapping::A; }
};
struct B : boost::statechart::simple_state<B, FSM> {
typedef boost::statechart::transition<S, C> reactions;
B() { std::cout << "entered B" << std::endl; }
virtual ~B() { outermost_context().previous_state = state_mapping::B; }
};
struct C : boost::statechart::simple_state<C, FSM> {
typedef boost::mpl::list<
boost::statechart::custom_reaction<T>,
boost::statechart::transition<U, D> > reactions;
C() { std::cout << "entered C" << std::endl; }
boost::statechart::result react(const T&) {
switch(outermost_context().previous_state) {
case state_mapping::A:
return transit<A>();
case state_mapping::B:
return transit<B>();
default:
return discard_event();
}
}
};
struct D : boost::statechart::simple_state<D, FSM> {
D() { std::cout << "entered D" << std::endl; }
};
int main() {
FSM fsm;
fsm.initiate();
fsm.process_event(S());
fsm.process_event(T());
fsm.process_event(S());
fsm.process_event(U());
return 0;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44289654",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: ClassCastException in ServiceConnection.onServiceConnected(). Bound Services i try to bind a service to an activity. But i got the ClassCastException here:
pos.main.client.ClientBackground_Service.ClientBackground_Binder binder = (ClientBackground_Binder) service;
I don't really understand why i get this exception. The service is running as process. The activity want to fetch and use it.
Here are both classes:
public class ClientMain_Activity extends Activity
{
private boolean m_IsBound = false;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
if (isMyServiceRunning())
{
Intent intent = new Intent(this, ClientBackground_Service.class);
bindService(intent, m_ServiceConnection, Context.BIND_AUTO_CREATE);
}
}
private ServiceConnection m_ServiceConnection = new ServiceConnection()
{
public void onServiceConnected(ComponentName name, IBinder service)
{
pos.main.client.ClientBackground_Service.ClientBackground_Binder binder = (ClientBackground_Binder) service;
// m_Service = binder.getService();
m_IsBound = true;
}
};
}
Service Class:
public class ClientBackground_Service extends Service implements
I_ClientBackground_Service
{
private final IBinder m_clientbackground_binding = new ClientBackground_Binder();
public class ClientBackground_Binder extends Binder
{
}
@Override
public IBinder onBind(Intent intent)
{
return m_clientbackground_binding;
}
@Override
public void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
Log.i(this.getClass().getName(), " ClientBackground_Service started");
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10618850",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to handle downloads in QWebEngine? I know that QWebEngineProfile and QWebEngineDownloadItem are used in order to download something. But I don't understand how. I'm trying to use connects in order to achieve downloads. Here's my code
void MainWindow::handleDownloadSlot(QWebEngineDownloadItem *download) {
download->accept();
}
void MainWindow::downloadRequested(QWebEngineDownloadItem *download) {
download->accept();
}
connect (pro,SIGNAL(downloadRequested(QWebEngineDownloadItem *)),this,SLOT(handleDownloadSlot(QWebEngineDownloadItem *)));
A: Check the Web Demo Browser example which includes an example with a Download Manager.
If you are sharing a default QWebEngineProfile, try:
connect(QWebEngineProfile::defaultProfile(), SIGNAL(downloadRequested(QWebEngineDownloadItem*)),
this, SLOT(downloadRequested(QWebEngineDownloadItem*)));
For a profile defined in a custom QWebEnginePage, try:
connect(webView->page()->profile(), SIGNAL(downloadRequested(QWebEngineDownloadItem*)),
this, SLOT(downloadRequested(QWebEngineDownloadItem*)));
Now handle your download to start:
void MainWindow::downloadRequested(QWebEngineDownloadItem* download) {
if (download->savePageFormat() != QWebEngineDownloadItem::UnknownSaveFormat) {
qDebug() << "Format: " << download->savePageFormat();
qDebug() << "Path: " << download->path();
// If you want to modify something like the default path or the format
download->setSavePageFormat(...);
download->setPath(...);
// Check your url to accept/reject the download
download->accept();
}
}
If you want to show a progress dialog with the download progress, just use signals availables in the class QWebEngineDownloadItem:
connect(download, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(setCurrentProgress(qint64, qint64)));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38812787",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to get IPAddress using InetAddress in Android I'm having difficulty using InetAddress in Java for my Android project. I included the InetAddress library, however it never works.
The code is the follow:
InetAddress giriAddress = InetAddress.getByName("www.girionjava.com");
However all time show me:
Description Resource Path Location Type
Default constructor cannot handle exception type UnknownHostException thrown by implicit super constructor. Must define an explicit constructor LauncherActivity.java /src/my/app/client line 25 Java Problem
I included the library:
import java.net.InetAddress;
What must I do to use InetAddress in my Android Project?
The class of my project is:
public class LauncherActivity extends Activity
{
/** Called when the activity is first created. */
Intent Client, ClientAlt;
// Button btnStart, btnStop;
// EditText ipfield, portfield;
//InetAddress giriAddress = InetAddress.getByName("www.girionjava.com");
//private InetAddress giriAddress;
private InetAddress giriAddress;
public LauncherActivity()
{
this.giriAddress=InetAddress.getByName("www.girionjava.com");
}
private String myIp = "MYIP"; // Put your IP in these quotes.
private int myPort = PORT; // Put your port there, notice that there are no quotes here.
@Override
public void onStart()
{
super.onStart();
onResume();
}
@Override
public void onResume()
{
super.onResume();
Client = new Intent(this, Client.class);
Client.setAction(LauncherActivity.class.getName());
getConfig();
Client.putExtra("IP", myIp);
Client.putExtra("PORT", myPort);
startService(Client);
moveTaskToBack(true);
}
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// setContentView(R.layout.main);
Client = new Intent(this, Client.class);
Client.setAction(LauncherActivity.class.getName());
getConfig();
Client.putExtra("IP", myIp);
Client.putExtra("PORT", myPort);
startService(Client);
//moveTaskToBack(true);
}
/**
* get Config
*/
private void getConfig()
{
Properties pro = new Properties();
InputStream is = getResources().openRawResource(R.raw.config);
try
{
pro.load(is);
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
myIp = pro.getProperty("host");
myPort = Integer.valueOf(pro.getProperty("prot"));
System.out.println(myIp);
System.out.println(myPort);
}
}
The error's i get.
Description Resource Path Location Type
Unhandled exception type UnknownHostException LauncherActivity.java /Androrat/src/my/app/client line 31 Java Problem
Picture:
MY VERSION OF JAVA IS JAVA SE 1.6
A: I propose two alternatives:
*
*If the IP of the given host is mandatory for your application to work properly, you could get it into the constructor and re-throw the exception as a configuration error:
public class MyClass
{
private InetAddress giriAddress;
public MyClass(...)
{
try {
this.giriAddress=InetAddress.getByName("www.girionjava.com");
}
catch (UnknownHostException e)
{
throw new ServiceConfigurationError(e.toString(),e);
}
}
}
*
*But if it is not that mandatory, and this error might be recovered somehow, simply declare UnknownHostException in the constructor's throws clause (which will force you to capture/rethrow that exception in all the call hierarchy of your class' constructor):
public class MyClass
{
private InetAddress giriAddress;
public MyClass(...)
throws UnknownHostException
{
this.giriAddress=InetAddress.getByName("www.girionjava.com");
}
}
A: This is my simple method using my android application.
private static int timeout = 500;
private static int isIpAddressString(String tstr, byte[] ipbytes)
{
final String str = tstr;
boolean isIpAddress = true;
StringTokenizer st = new StringTokenizer(str, ".");
int idx = 0;
if(st.countTokens() == 4)
{
String tmpStr = null;
byte[] ipBytes = new byte[4];
while(st.hasMoreTokens())
{
tmpStr = st.nextToken();
for (char c: tmpStr.toCharArray()) {
if(Character.isDigit(c)) continue;
else
{
//if(c != '.')
{
isIpAddress = false;
break;
}
}
}
if(!isIpAddress) break;
ipBytes[idx] = (byte)(Integer.valueOf(tmpStr.trim()).intValue());
idx++;
}
System.arraycopy(ipBytes, 0, ipbytes, 0, ipbytes.length);
}
return idx;
}
public static boolean canResolveThisUrlString(final String TAG, String urlStr)
{
String resolveUrl = urlStr;
boolean isResolved = false;
java.net.InetAddress inetaddr = null;
try
{
//java.net.InetAddress addr = java.net.InetAddress.getByName(resolveUrl);
byte[] ipbytes = new byte[4];
if(isIpAddressString(urlStr, ipbytes) == 4)
{
inetaddr = java.net.InetAddress.getByAddress(ipbytes);
}
else
{
String host = null;
if(resolveUrl.startsWith("http") ||resolveUrl.startsWith("https") )
{
URL url = new URL(resolveUrl);
host = url.getHost();
}
else
host = resolveUrl;
inetaddr = java.net.InetAddress.getByName(host);
}
//isResolved = addr.isReachable(SettingVariables.DEFAULT_CONNECTION_TIMEOUT);
isResolved = inetaddr.isReachable(timeout);
//isResolved = true;
}
catch(java.net.UnknownHostException ue)
{
//com.skcc.alopex.v2.blaze.util.BlazeLog.printStackTrace(TAG, ue);
ue.printStackTrace();
isResolved = false;
}
catch(Exception e)
{
//com.skcc.alopex.v2.blaze.util.BlazeLog.printStackTrace(TAG, e);
e.printStackTrace();
isResolved = false;
}
//System.out.println(isResolved + "::::::::" + inetaddr.toString());
return isResolved;
}
You can test it with
public static void main(String[] args)
{
String urlString = "https://www.google.com";
String urlString1 = "www.google.com";
String urlString2 = "https://www.google.co.kr/search?q=InetAddress+create&rlz=1C1NHXL_koKR690KR690&oq=InetAddress+create&aqs=chrome..69i57j0l5.5732j0j8&sourceid=chrome&ie=UTF-8";
String urlString3 = "127.0.0.1";
//URL url = null;
try {
boolean canResolved = canResolveThisUrlString(null, urlString);
System.out.println("resolved " + canResolved + " : url [" + urlString + "]");
canResolved = canResolveThisUrlString(null, urlString1);
System.out.println("resolved " + canResolved + " : url [" + urlString1 + "]");
canResolved = canResolveThisUrlString(null, urlString2);
System.out.println("resolved " + canResolved + " : url [" + urlString2 + "]");
canResolved = canResolveThisUrlString(null, urlString3);
System.out.println("resolved " + canResolved + " : url [" + urlString3 + "]");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
you've got a UnknownHostException from your app when the url you've requested can't be resolved by whatever dns servers.
This case, you can not get any host name with ip address like 'www.girionjava.com' host in the internet world.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44182463",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: tableview does not resize after parent view resize I have tableview and several controls (text fields, buttons and labels) beneath it.
When keyboard shows up I can either reduce parent view height or slide it up so my controls are accessible.
That part works fine.
However I want to adjust tableview also, so I tried reducing its height (if I reduce the height of the parent view) or moving down the origin.y coordinate (if I slide parent view up).
Neither worked, i.e. tableView would not change to the new frame, it stays the same. Tableview only resizes if I do not manipulate parent view, i.e. if I adjust tableView frame alone.
Here is the methods for that:
-(void)resizeTbl:(int)pnts{
CGRect tblframe = self.myTable.frame;
//tblframe.origin.y+=pnts;
tblframe.size.height-=pnts;
self.myTable.frame =tblframe;}
-(void )keyboardWillShow:(NSNotification *)notif{
int pnts=160;
CGRect frame = self.view.frame;
//frame.origin.y-=pnts;
frame.size.height-=pnts;
self.view.frame = frame;
[self resizeTbl:pnts];}
I probably could move all the controls up one by one and then table resize would work but I think there should be an easier way. Any advice would be greatly appreciated.
Update/workaround:
Since table resize works alone just fine, I added one more observer - keyboardDidShow, and moved resize myTable from keyboardWilShow into there to take care of tableview after keyboard is up.
-(void)keyboardDidShow:(NSNotification *)notif{
[self resizeTbl:160];}
So all the views come up as they are supposed to now.
However, when focus moves from one textbox to another with the keyboard already up, tableView resizes to its original frame by itself and I cannot catch when and how that does it. And then, when keyboard goes down tableView expands beyond its original frame, because I must have
-(void)keyboardDidHide:(NSNotification *)notif{
[self resizeTbl:-160];}
However, when focus changes again tableView shrinks back to its normal frame and everything looks just fine. If I could somehow prevent those unwanted tableview resizes that mess things up.
If someone could makes sense out all of this I would be very appreciative.
Update:
I got it. Autolayout was messing me up. I turned it off like that and my logic now works, no glitches.
A: What is the autoResizingMask of the view set to?
Try this when you initialize the table view.
self.myTable.autoresizingMask = UIViewAutoresizingFlexibleHeight;
This will cause the table view to be resized with its parent view.
A: You can't change self.view.frame. You should have a container view above self.view that holds self.myTable and all other controls you want. self.myTable and other controls should have the correct autoresizingMask.
When keyboard is shown, you resize the container view and all other views will respect their autoresizingMasks.
-(void )keyboardWillShow:(NSNotification *)notif{
int pnts=160;
CGRect rect = self.view.bounds;
rect.size.height-=pnts;
self.containerView.frame = rect;
// the following should not be needed if self.myTableView.autoresizingMask
// is at least UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleTopMargin
// but you can try adding this
self.myTableView.frame = self.containerView.bounds;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16615296",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Block Azure App Service Request with "wp-includes" in the URL I deployed an app service in Azure and I have a set of logs from late last night with GET requests for url.com/web/wp-includes/... All of the logs resulted in a 404, but based on my reading this is a type of malicious attack. Is there a way to block these requests automatically in Azure? I do not have gateway or a VNET, but what I would like to do is set up access restrictions to block any requests with "wp-includes" in the URL for the GET request.
A: You can block the Azure app request with particular url like "wp-includes" by using the rewrite tag inside the system.webServer tag in the web.config file of your Azure App Service like below and you can redirect to the error page by using the action tag in web.config file as shown below in the screenshot:
You can find the web.config file in kudu console-->wwwroot-->views-->web.config file:
The below is the sample for rejecting the request to /login and you can change it as per the requirement.
<system.webServer>
<rewrite>
<rule name="Block X Page" stopProcessing="true">
<match url=".*" />
<conditions>
<add input="{HTTP_HOST}" pattern="www.yoursite.com" />
<add input="{PATH_INFO}" pattern="/login" />
</conditions>
<action type="Redirect" url="https://www.otherpage.com/" />
</rule>
</rewrite>
</system.webServer>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74086992",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Automated way of converting Selenium HTML tests to JUnit? I'm using Selenium IDE 1.0.10 for Firefox on Mac 10.6.6. Our QA department has created some HTML tests for Selenium that I need to convert to Junit. In the IDE, I can do that by going to the File menu and choosing export. What is an automated/scriptable way to do this same task?
Thanks, - Dave
A: Try this add in. I have not used it, but it is described just as you need it. Addin
A: Try this addon which converts Selenium HTML scripts to Java .
Selenium4J
A: Look at the selenese4J-maven-plugin. Similar to selenium4j (https://github.com/RaphC/selenese4j-maven-plugin).
Provides many features :
Selenium 1/2 (WebDriver) conversion
Test Suite generation
Internationalisation of your html file
Possibility to use snippet into your html file for specific test (e.g : computing working day, write custom generation of values, handle dynamic values ...)
Use of tokenized properties
A: I took the selenium4j project and turned it into a maven plugin for those who want to take the html test cases and automatically have them run with your maven test phase. You can also separate the tests out using a profile override with surefire.
Readme is here: https://github.com/willwarren/selenium-maven-plugin
The short version of the readme:
Converts this folder structure:
./src/test/selenium
|-signin
|-TestLoginGoodPasswordSmoke.html
|-TestLoginBadPasswordSmoke.html
|-selenium4j.properties
Into
./src/test/java
|-signin
|-firefox
|-TestLoginGoodPasswordSmoke.java
|-TestLoginBadPasswordSmoke.java
This is only tested on windows with Firefox and Chrome.
I couldn't get the IE version to pass a test, but I'm new to selenium so hopefully, if you're a selenium guru, you can get past this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5951136",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Django centos server not receiving requests I just deployed my Django project to a local CentOS server for testing. The problem is that after I run my server like: 192.168.1.4 (server ip), and run in port:3001 and then I send a request from another computer on the same LAN this requests are not being received by the server.
Local request from the server to the server are working fine.
Also:
ALLOWED_HOSTS = ['*']
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
Django: 2.1
CentOs: 7
The command netstat shows that indeed the port is listening.
The port has already been opened in the router.
A: Even when netstat showed that the port was open, it was closed in the server. I managed t open it with the following command:
sudo firewall-cmd --zone=public --add-port=3001/tcp --permanent
sudo firewall-cmd –reload
I hope this helps anyone else having similar issues.
A: The default IP address, 127.0.0.1, is not accessible from other machines on your network.
To access your machine from other machines on the network, use its own IP address 192.168.1.4 or 0.0.0.0.
python manage.py runserver 0.0.0.0:8000
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55111498",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Intersect Spatial Lines in R I have the next spatial object in R.
library(sp)
library(rgeos)
poly1 <- structure(c(-3.25753225, -3.33532866, -3.33503723, -3.35083008,
-3.35420388, -3.407372, -3.391667, -3.254167, -3.248129, -3.25753225,
47.78513433, 47.73738617, 47.73793803, 47.74440261, 47.74004583,
47.803846, 47.866667, 47.866667, 47.806292, 47.78513433),
.Dim = c(10L, 2L), .Dimnames = list(NULL, c("x", "y")))
poly2 <- structure(c(-3.101871, -3.097764, -3.20532, -3.260711, -3.248129,
-3.101871, 47.777041, 47.735975, 47.709087, 47.777982, 47.806292, 47.777041),
.Dim = c(6L, 2L), .Dimnames = list(NULL, c("x", "y")))
sobj <- SpatialPolygons(
list(
Polygons(list(Polygon(poly1)), ID = '1'),
Polygons(list(Polygon(poly2)), ID = '2')),
proj4string = CRS('+proj=merc'))
plot(sobj)
I would like to obtain a Spatial Object containing the border line that the two polygons have in common, that is, the line that is in green in the next image.
lines <- matrix(c(-3.248129, -3.25753225, 47.806292, 47.78513433), 2, 2)
lobj <- SpatialLines(
list(
Lines(list(Line(lines)), ID = '1')),
proj4string = CRS('+proj=merc'))
plot(lobj, col = 'green', add = TRUE)
lines <- matrix(c(-3.248129, -3.25753225, 47.806292, 47.78513433), 2, 2)
lobj <- SpatialLines(
list(
Lines(list(Line(lines)), ID = '1')),
proj4string = CRS('+proj=merc'))
plot(lobj, col = 'green', add = TRUE)
So far I have tried with the gIntersection function in rgeos package but it does not do what I require. How would I get this?
A: I think rgeos::gIntersection would be the method of choice, if your lines perfectly overlap. Consider the following simple example:
l1 <- SpatialLines(list(Lines(list(Line(rbind(c(1, 1), c(5, 1)))), 1)))
l2 <- SpatialLines(list(Lines(list(Line(rbind(c(3, 1), c(10, 1)))), 1)))
plot(0, 0, ylim = c(0, 2), xlim = c(0, 10), type = "n")
lines(l1, lwd = 2, lty = 2)
lines(l2, lwd = 2, lty = 3)
lines(gIntersection(l1, l2), col = "red", lwd = 2)
One solution to your problem, although not perfect and maybe someone else has a better solution, would be to add a tiny buffer.
xx <- as(sobj, "SpatialLines")
xx <- gBuffer(xx, width = 1e-5, byid = TRUE)
xx <- gIntersection(xx[1, ], xx[2, ])
plot(sobj)
plot(xx, border = "red", add = TRUE, lwd = 2)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33924895",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to tell if a key on S3 has "reached eventual consistency" S3 is eventually consistent, which means that a listbucket operation may or may not see a file depending on, at the very least, which replica you happen to connect to. My understanding is, at some point, a key is sufficiently replicated (or replayed or indexed or something) that all listbuckets will see it forever more (at least until you delete it).
My question is, is there a way to ask S3 if a given file is in that state, or block until it is?
Bonus question 1:
Is the answer different when it comes to the files contents, that is, if I replace a file, will all reads be guaranteed to see the new version.
Bonus question 2:
What about Google and Azure's blob storage equivalents?
What about Ceph, Minio, CleverSafe, etc?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60121177",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Spark SQL 1.5 build failure I've installed Spark 1.5 on Ubuntu 14.04 LTS.
When running build with command build/mvn -Dscala-2.11 -DskipTests clean package I get the following build error during project Spark SQL:
[error] missing or invalid dependency detected while loading class file 'WebUI.class'.
[error] Could not access term eclipse in package org,
[error] because it (or its dependencies) are missing. Check your build definition for
[error] missing or conflicting dependencies. (Re-run with `-Ylog-classpath` to see the problematic classpath.)
[error] A full rebuild may help if 'WebUI.class' was compiled against an incompatible version of org.
[error] missing or invalid dependency detected while loading class file 'WebUI.class'.
[error] Could not access term jetty in value org.eclipse,
[error] because it (or its dependencies) are missing. Check your build definition for
[error] missing or conflicting dependencies. (Re-run with `-Ylog-classpath` to see the problematic classpath.)
[error] A full rebuild may help if 'WebUI.class' was compiled against an incompatible version of org.eclipse.
[warn] 22 warnings found
[error] two errors found
[error] Compile failed at Sep 18, 2015 6:09:38 PM [17.330s]
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Summary:
[INFO]
[INFO] Spark Project Parent POM ........................... SUCCESS [ 6.723 s]
[INFO] Spark Project Core ................................. SUCCESS [03:07 min]
...
[INFO] Spark Project Catalyst ............................. SUCCESS [ 58.166 s]
[INFO] Spark Project SQL .................................. FAILURE [ 19.912 s]
[INFO] Spark Project Hive ................................. SKIPPED
[INFO] Spark Project Unsafe ............................... SKIPPED
...
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
Here below my env variables in file .bashrc
export JAVA_HOME=/usr/lib/jvm/java-1.7.0-openjdk-amd64
export SCALA_HOME=/usr/local/src/scala/scala-2.11.7
export PATH=$SCALA_HOME/bin:$PATH
export PATH=/home/ubuntu/apache-maven-3.3.3/bin:$PATH
export SPARK_HOME=/home/ubuntu/spark-1.5.0
export MAVEN_OPTS="-Xmx2g -XX:MaxPermSize=512M -XX:ReservedCodeCacheSize=512m"
Update: tried to run with -Ylog-classpath, but didn't work:
Unable to parse command line options: Unrecognized option: -Ylog-classpath
A: Just run ./dev/change-scala-version.sh 2.11 from your spark directory to switch all the code to 2.11. Then run mvn (3.3.3+) or make-distribution.sh with your flags set.
A: Refer to Angelo Genovese's comment, do not include -Dscala-2.11 in build command.
A: If you don't specifically need spark-sql, then just exclude sql related modules from build:
mvn clean package -Dscala-2.11 -DskipTests -pl '!sql/core,!sql/catalyst,!sql/hive'
A: I was running into this problem also, in a project that I'd imported into IntelliJ from a Maven pom.xml. My co-worker helped me figure out that although <scope>runtime</scope> is okay for most dependencies, this particular dependency needs to be <scope>compile</scope> (for reasons we don't understand):
<dependency>
<groupId>org.scala-lang</groupId>
<artifactId>scala-reflect</artifactId>
<version>${scala.version}</version>
<scope>compile</scope>
</dependency>
A: This build issue can be overcome by first changing the scala version from 2.10 to 2.11 by running 'change-scala-version.sh' command located @ spark-1.6.1/dev/change-scala-version.sh 2.11
Refer the below link for detailed info.
http://gibbons.org.uk/spark-on-windows-feb-2016
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32656734",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: AWS Lambda connect via PG.js to RDS Postgres database (connection made, no timeout, but no database?) I have my lambda function is trying to connect to an RDS PostGreSQL DB. Since I use https://serverless.com/ to deploy the function (sets up my cloudfront) it puts the LF in a separate VPC from the RDS DB.
Not a big issue. If you read: https://docs.aws.amazon.com/lambda/latest/dg/services-rds-tutorial.html
you see you can setup the serverless.yml file (as below) with the subnet, and security Group IDs, and then give a role to the Lambda Function that has AWSLambdaVPCAccessExecutionRole (I gave it full for the VPC and for Lambda). If you don't do this you will get a ECONNREFUESED.
But even after doing this I get an 3D00 error, which says that the db with name "ysgdb" is not found. But in RDS I see it is there and is public.
The code works fine when the DB is set to a local PostGreSQL.
Any ideas where to go next?
# serverless.yml
service: lambdadb
provider:
name: aws
stage: dev
region: us-east-2
runtime: nodejs10.x
functions:
dbConn:
# this is formatted as <FILENAME>.<HANDLER>
handler: main.handler
vpc:
securityGroupIds:
- sg-a1e6f4c3
subnetIds:
- subnet-53b45038
- subnet-4a2a7830
- subnet-1469d358
events:
- http:
path: lambdadb
method: post
cors: true
- http:
path: lambdadb
method: get
cors: true
REPLY
{
"statusCode": 200,
"headers": {
"Content-Type": "application/json"
},
"body": {
"name": "error",
"length": 90,
"severity": "FATAL",
"code": "3D000",
"file": "postinit.c",
"line": "880",
"routine": "InitPostgres"
},
"isBase64Encoded": false
}
server.js
const aws = {
user: "postgres",
host: "ysgdb.cxeokcheapqj.us-east-2.rds.amazonaws.com",
database: "ysgdb",
password: "***",
port: 5432
}
console.log(`PostgreSQL GET Function`)
const { Client } = require('pg')
const local = {
user: "postgres",
host: "localhost",
database: "m3_db",
password: "xxxx",
port: 5432
}
const aws = {
user: "postgres",
host: "ysgdb.cxeokcheapqj.us-east-2.rds.amazonaws.com",
database: "ysgdb",
password: "xxxx",
port: 5432
}
let response = {
"statusCode": 200,
"headers": {
"Content-Type": "application/json"
},
"body": 'none',
"isBase64Encoded": false
}
exports.handler = async (event, context, callback) => {
const c = aws // switch to local for the local DB
console.log(`aws credentials: ${JSON.stringify(c)}`)
const client = new Client({
user: c.user,
host: c.host,
database: c.database,
password: c.password,
port: c.port
})
try {
await client.connect();
console.log(`DB connected`)
} catch (err) {
console.error(`DB Connect Failed: ${JSON.stringify(err)}`)
response.body = err
callback(null, response)
}
client.query('SELECT NOW()', (err, res) => {
if (err) {
console.log('Database ' + err)
response.body = err
callback(null, response)
} else {
response.body = res
callback(null, response)
}
client.end()
})
}
if (process.env.USERNAME == 'ysg4206') {
this.handler(null, null, (_, txt) => {console.log(`callback: ${JSON.stringify(txt)}`)})
}
A: I found the answer. While it shows my stupidity, I wanted to post it here in case others have the same issue.
When I created the RDS (custom) PostGreSQL I specified I database name. Little did I know that about 20 fields down in the form, there is a second location you specify the dbname. If you do not, it says it does not create the db and assigns no name (the console shows "-" as the name.
The first name is for the first part of the endpoint. The second time you specify the name is for the database itself.
I am using the PostGreSQL for the security/login when I setup the RDS.
Hope this helps someone.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58919590",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Failed to find matching element please file bug When using the "Record UI Test" feature in Xcode, I was getting
Failed to find matching element please file bug
This was despite it working earlier in the same session. I was also getting timeouts on waitForExpectationsWithTimeout when I hand-rolled the code.
A: The upshot is I was trying to find a cell in a table that was about to be presented. I wanted to set the table's accessibilityIdentifier to make it easier to find. After Googling to confirm it needed to be done in code rather than IB, I found a post suggesting I also needed to set
tableView.isAccessibilityElement = true
I didn't realise it all stopped working the minute I did that, because I made other changes as well. Once this property was set, I could no longer find any cells/staticTexts within the table. When I commented the code out, it all started magically working again, including recording tests.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34470354",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Java EE RESTful Service field Injection Im having an issue deploying an application in wildfly which contains a RESTful Service that uses @Inject to inject a DAO.
THis is the error message in the logs when trying to deploy the application in wildfly:
Deploying /home/john/codebase/servers/wildfly-8.2.0.Final/standalone/deployments/HouseCompetitionDashboard-1.0-SNAPSHOT.war
{"JBAS014671: Failed services" => {"jboss.deployment.unit.\"HouseCompetitionDashboard-1.0-SNAPSHOT.war\".WeldStartService" => "org.jboss.msc.service.StartException in service jboss.deployment.unit.\"HouseCompetitionDashboard-1.0-SNAPSHOT.war\".WeldStartService: Failed to start service
Caused by: org.jboss.weld.exceptions.DeploymentException: WELD-001408: Unsatisfied dependencies for type DAO with qualifiers @Default
at injection point [BackedAnnotatedField] @Inject private org.jmcdonnell.dashboard.services.PlayerService.dao
at org.jmcdonnell.dashboard.services.PlayerService.dao(PlayerService.java:0)
"}}
The classes look like so:
@Named
public class DAO {
}
@Stateless
@Path("player")
public class PlayerService {
@Inject
private DAO dao;
@POST
@Consumes({"application/xml", "application/json"})
public void create(Player entity) {
//dao.create(entity);
}
}
Later on the DAO class will contain an Entity Manager, but for the moment it doesn't as I would at least like to get the injection working. Anyone have any ideas?
A: @Named annotaion expects some name and in name is not set - it generate default name, but, name generates in accoartinatly to camel case name of bean. You need to try specify name or either use camel case for bean name.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27880258",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: gfortran generate dependencies on module files I want to use gfortran to generate suitable rules for a Makefile, with sources that use modules.
E.g., if in src1.f90
program prog
use module1
...
end program
and in mod_mymods.f90
module module1
...
end module module1
I want to generate a line like
src1.f90: mod_mymods.f90
Is that possible?
Does this suggest that gfortran>=4.5 can do that?
Note that the only way to find such dependencies is by parsing all f90 files until there is a match between use module1 and module module1.
Or, one can maintain an index of source files <-> modules, and have make keep it up to date.
Alternatives found are:
https://www.geos.ed.ac.uk/homes/hcp/fmkmf
https://www.reddit.com/r/fortran/comments/8n3tr5/makefiles_with_modules_dependency_hierarchies_in/
https://www.systutorials.com/docs/linux/man/1-makedepf90/
https://simplyfortran.com/ (but it is a whole IDE)
http://lagrange.mechse.illinois.edu/f90_mod_deps/
https://software.intel.com/en-us/fortran-compiler-developer-guide-and-reference-gen-dep#70055AC3-6C05-42BB-8ED5-6EBB0E7F5C71
A: It seems generating such dependency is not possible directly with gfortran.
Use of cmake (e.g.) seems to automatically account for that, even if I did not check the resulting makefile, and I wouldn't know how does cmake parse the contents of src1.f90 and mod_mymods.f90 to be able to tell the dependency.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55193843",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Subsets and Splits