qid int64 10 74.7M | question stringlengths 15 26.2k | date stringlengths 10 10 | metadata list | response_j stringlengths 27 28.1k | response_k stringlengths 23 26.8k |
|---|---|---|---|---|---|
52,765,098 | I have a List of a person object. Now I want to remove an object and all I know is the instance variables of the object.
I mean I don't have the object, all I can do is create another object with same field values.
Obviously the new object can't be used to remove the original, since both are different.
A very silly question indeed. | 2018/10/11 | [
"https://Stackoverflow.com/questions/52765098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7382577/"
] | The [`Array.filter()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) method passes the index (`i`) to the callback function, and you can use it to get the previous value from the array. To take the 1st item as well, I use the condition `!i`, which evaluated to `true` when `i` is 0.
```js
const data = [{ timestamp: 1 }, { timestamp: 3 }, { timestamp: 250 }, { timestamp: 1000 }];
const final = data.filter((o, i) =>
!i || (o.timestamp - data[i-1].timestamp > 240)
);
console.log(final);
``` | ```
let prevTs = -Infinity;
const result = data.filter((d) => {
const localResult = (d.timestamp - prevTs) > 240;
prevTs = d.timestamp;
return localResult;
});
```
Or you can use index arg in your filter callback:
```
data.filter((d, i) => {
if (!i) {
return true;
}
return (d.timestamp - data[i - 1].timestamp) > 240
});
``` |
50,558,470 | I have to problem when build. i add build firebase core 16.0.0, but when build, this is build firebase core 17.0.0. why it build 17.0.0.I check android
<https://firebase.google.com/docs/android/setup#available_libraries>, now version 16.0.0, i have to remove build project, but this is not success.
Can you help me? Thanks.
when i increase version build
```
classpath 'com.google.gms:google-services:4.0.1' // google-services plugin
```
and
```
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support.constraint:constraint-layout:1.1.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
//them multiDexEnabled = true
implementation 'com.android.support:multidex:1.0.3'
implementation 'com.android.support:recyclerview-v7:27.1.1'
implementation 'com.android.support:design:27.1.1'
// butter knife.
implementation 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
// gson.
implementation 'com.google.code.gson:gson:2.8.2'
// image loading.
implementation 'com.github.bumptech.glide:glide:4.7.1'
annotationProcessor 'com.github.bumptech.glide:compiler:4.7.1'
implementation "com.github.bumptech.glide:okhttp3-integration:4.7.1"
implementation 'com.github.bumptech.glide:annotations:4.7.1'
//com.squareup.retrofit2
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.4.0'
//com.squareup.okhttp3
implementation 'com.squareup.okhttp3:logging-interceptor:3.10.0'
implementation 'com.squareup.okhttp3:okhttp:3.10.0'
//io.reactivex.rxjava2
implementation 'io.reactivex.rxjava2:rxandroid:2.0.2'
implementation 'io.reactivex.rxjava2:rxjava:2.1.13'
// keyboard keyboardvisibilityevent
implementation 'net.yslibrary.keyboardvisibilityevent:keyboardvisibilityevent:2.1.0'
// Cloud Messaging
implementation 'com.google.firebase:firebase-messaging:17.0.0'
//Analytics
implementation 'com.google.firebase:firebase-core:16.0.0'
//Invites and Dynamic Links
implementation 'com.google.firebase:firebase-invites:16.0.0'
//AdMob
implementation 'com.google.firebase:firebase-ads:16.0.0'
implementation 'com.firebaseui:firebase-ui-database:3.1.1' // No trouble in compiling
implementation 'com.google.firebase:firebase-auth:16.0.1'
// ViewModel and LiveData
implementation 'android.arch.lifecycle:extensions:1.1.1'
//room Save data in a local database using Room
implementation 'android.arch.persistence.room:runtime:1.1.0'
annotationProcessor "android.arch.persistence.room:compiler:1.1.0"
//push OneSignal
implementation 'com.onesignal:OneSignal:3.8.3'
//gmc
implementation 'com.google.android.gms:play-services-gcm:15.0.1'
//palette
implementation 'com.android.support:palette-v7:27.1.1'
//loading
implementation 'com.wang.avi:library:2.1.3'
//crop image
implementation 'com.isseiaoki:simplecropview:1.1.7'
//exoplayer-textureview
implementation 'com.google.android.exoplayer:exoplayer:2.7.3'
implementation 'com.google.android.exoplayer:extension-ima:2.7.3'
//facebook .
implementation 'com.facebook.android:facebook-android-sdk:4.29.0'
//facebook ads
implementation 'com.facebook.android:audience-network-sdk:4.28.1'
//no name :)
implementation 'com.android.support:support-v4:27.1.1'
implementation 'com.android.support:customtabs:27.1.1'
}
``` | 2018/05/28 | [
"https://Stackoverflow.com/questions/50558470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3584419/"
] | I have fix problem : import onesignal
```
buildscript {
repositories {
maven { url 'https://plugins.gradle.org/m2/'}
}
dependencies {
classpath 'gradle.plugin.com.onesignal:onesignal-gradle-plugin:0.10.1'
}
}
apply plugin: 'com.onesignal.androidsdk.onesignal-gradle-plugin'
repositories {
maven { url 'https://maven.google.com' }
}
``` | Remove `implementation 'com.google.firebase:firebase-core:16.0.0'`
and use`implementation 'com.google.firebase:firebase-database:10.0.0'` for firebase database, it will solve your problem. |
10,404,276 | I have a situation where lets say i'm trying to get the information about some food. Then I need to display all the information plus all the ingredients in that food.
With my query, i'm getting all the information in an array but only the first ingredient...
```
myFoodsArr =
[0]
foodDescription = "the description text will be here"
ratingAverage = 0
foodId = 4
ingredient = 1
ingAmount = 2
foodName = "Awesome Food name"
typeOfFood = 6
votes = 0
```
I would like to get something back like this...
```
myFoodsArr =
[0]
foodDescription = "the description text will be here"
ratingAverage = 0
foodId = 4
ingArr = {ingredient: 1, ingAmount: 4}, {ingredient: 3, ingAmount: 2}, {ingredient: 5, ingAmount: 1}
foodName = "Awesome Food name"
typeOfFood = 6
votes = 0
```
This is the query im working with right now. How can I adjust this to return the food ID 4 and then also get ALL the ingredients for that food? All while at the same time doing other things like getting the average rating of that food?
Thanks!
```
SELECT a.foodId, a.foodName, a.foodDescription, a.typeOfFood, c.ingredient, c.ingAmount, AVG(b.foodRating) AS ratingAverage, COUNT(b.foodId) as tvotes
FROM `foods` a
LEFT JOIN `foods_ratings` b
ON a.foodId = b.foodId
LEFT JOIN `foods_ing` c
ON a.foodId=c.foodId
WHERE a.foodId=4
```
**EDIT:**
Catcall introduced this concept of "sub queries" I never heard of, so I'm trying to make that work to see if i can do this in 1 query easily. But i just keep getting a return false. This is what I was trying with no luck..
```
//I changed some of the column names to help them be more distinct in this example
SELECT a.foodId, a.foodName, a.foodDescription, a.typeOfFood, AVG(b.foodRating) AS ratingAverage, COUNT(b.foodId) as tvotes
FROM foods a
LEFT JOIN foods_ratings b ON a.foodId = b.foodId
LEFT JOIN (SELECT fId, ingredientId, ingAmount
FROM foods_ing
WHERE fId = 4
GROUP BY fId) c ON a.foodId = c.fId
WHERE a.foodId = 4";
```
**EDIT 1 more thing related to ROLANDS GROUP\_CONCAT/JSON Idea as a solution 4 this**
I'm trying to make sure the JSON string im sending back to my Flash project is ready to be properly parsed `Invalid JSON parse input.` keeps popping up..
so im thinking i need to properly have all the double quotes in the right places.
But in my MySQL query string, im trying to escape the double quotes, but then it makes my mySQL vars not work, for example...
If i do this..
```
GROUP_CONCAT('{\"ingredient\":', \"c.ingredient\", ',\"ingAmount\":', \"c.ingAmount\", '}')`
```
I get this...
`{"ingredient":c.ingredient,"ingAmount":c.ingAmount},{"ingredient":c.ingredient,"ingAmount":c.ingAmount},{"ingredient":c.ingredient,"ingAmount":c.ingAmount}`
How can i use all the double quotes to make the JSON properly formed without breaking the mysql? | 2012/05/01 | [
"https://Stackoverflow.com/questions/10404276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/393373/"
] | One obvious solution is to actually perform two queries:
1) get the food
```
SELECT a.foodId, a.foodName, a.foodDescription, a.typeOfFood
FROM `foods` a
WHERE a.foodsId=4
```
2) get all of its ingredients
```
SELECT c.ingredient, c.ingAmount
FROM `foods_ing` c
WHERE c.foodsId=4
```
This approach has the advantage that you don't duplicate data from the "foods" table into the result. The disadvantage is that you have to perform two queries. Actually you have to perform one extra query for each "food", so if you want to have a listing of foods with all their ingredients, you would have to do a query for each of the food record.
Other solutions usually have many disadvantages, one of them is using [GROUP\_CONCAT](http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat) function, but it has a tough limit on the length of the returned string. | When you compare MySQL's aggregate functions and GROUP BY behavior to SQL standards, you have to conclude that they're simply broken. You can do what you want in a single query, but instead of joining directly to the table of ratings, you need to join on a query that returns the results of the aggregate functions. Something along these lines should work.
```
select a.foodId, a.foodName, a.foodDescription, a.typeOfFood,
c.ingredient, c.ingAmount,
b.numRatings, b.avgRating
from foods a
left join (select foodId, count(foodId) numRatings, avg(foodRating) avgRating
from foods_ratings
group by foodId) b on a.foodId = b.foodId
left join foods_ing c on a.foodId = c.foodId
order by a.foodId
``` |
30,006,889 | I made a father class:
```
function MouseController(m,v) {
this.model = m;
this.view = v;
}
MouseController.prototype.mouseClick = function(x, y) {}
```
with two variables inside `this.model` and `this.view`.
Now I have a child class of this father:
```
DragController.prototype = new MouseController();
function DragController() {
MouseController.call(this);
}
```
How can I access to father variable `this.model` and `this.view` from child class ? | 2015/05/02 | [
"https://Stackoverflow.com/questions/30006889",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1501582/"
] | Ensure MouseController inherits from DragController properly.
```
DragController.prototype = MouseController.prototype;
```
Then use:
```
this.model
this.view
```
The properties are inherited :-)
Make sure the arguments are passed to the base class:
```
function DragController(m, v) {
MouseController.call(this, m, v);
}
```
Fiddle: <http://jsfiddle.net/GarryPas/ku4p4332/3/> | When you make the call `MouseController.call(this)` inside the `DragController`'s constructor, you are setting the newly instantiated `DragController` object's (`this`) properties `model` and `view`.
So these properties are directly accessible through the current instance i.e. as `this.model` and `this.view`.
Of course since (A) you don't pass anything to the `new MouseController()` when you create the `DragController.prototype` and (B) you don't pass anything to the `MouseController.call(this)` call, both `this.model` and `this.view` end up being `undefined`.
You have two options to assign values to `model` and `view` upon instantiation.
Option 1
--------
Pass values to `MouseController` when you create the `DragController.prototype`:
```
DragController.prototype = new MouseController(<default model value for all objects>, <default view value for all objects>);
```
With Option 1, all newly create `DragController` objects will have the same initial values for the `model` and `view` properties and there is no need to call `MouseController.call()` in the `DragController` constructor function.
Option 2
--------
Pass parameters to the `DragController` constructor and handle them as:
SubOption 2.1: use them directly to assign the corresponding properties of the newly instantiated object
OR
SubOption 2.2: pass them to the call `MouseController.call()`:
```
function DragController(m,v) {
// Suboption 2.1
MouseController.call(this,m,v);
--OR--
// Suboption 2.2
MouseController.call(this);
this.model = m;
this.view = v;
}
```
Either way, methods inherited from the parent `MouseController` through the prototype chain, will have access just fine to `this.model` and `this.view`.
Minor detail
------------
No matter which way you go, you might want to also fix the results of getting the property `.constructor` of your `DragController` instances. Now for example if you create a new `DragController`:
```
dc = new DragController('foo', 'bar');
dc.constructor; // returns 'MouseController' instead of `DragController`
```
To fix this, you should add a statement:
```
DragController.prototype.constructor=DragController;
``` |
32,504,097 | I've installed OpenShift Version 3 on CentOS7.
I followed the official documentation:
<https://docs.openshift.org/latest/admin_guide/install/prerequisites.html#configuring-docker-storage>
method 1 (Docker):
<https://docs.openshift.org/latest/getting_started/administrators.html#installation-methods>
I chose to install OpenShift in a Docker Container.
The last commmand I had to do was this one:
I'm launching the server in a Docker container using images from Docker Hub.:
```
$ docker run -d --name "openshift-origin" --net=host --privileged \
-v /var/run/docker.sock:/var/run/docker.sock \
-v /tmp/openshift:/tmp/openshift \
openshift/origin start
```
This command:
* starts OpenShift listening on all interfaces (0.0.0.0:8443),
* **starts the web console listening on all interfaces (0.0.0.0:8443),**
* launches an etcd server to store persistent data, and
* launches the Kubernetes system components.
```
$ sudo docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
d3f023085328 openshift/origin "/usr/bin/openshift 2 days ago Up 2 days openshift-origin
```
Now I was able to do:
```
$ sudo docker exec -it openshift-origin bash
```
So I can access openshift in my container. I can create projects and apps but the building-state is always pending.
I'm not able to visit `https://publicip:8443/console`. Someone who can help me? The OpenShift-page loads for a second (when i'm going <http://publicip:8443>) but than I get a redirect\_url to 10.0.0.x:8443. My master-config looks like this: <https://github.com/openshift/origin/blob/master/test/old-start-configs/v1.0.0/config/openshift.local.config/master/master-config.yaml>. What do I have to change?
url: `https://10.0.0.x:8443/oauth/authorize?client_id=openshift-web-console&response_type=token&state=%2F&redirect_uri=https%3A%2F%2F10.0.0.x%3A8443%2Fconsole%2Foauth`
EDIT:
```
docker run -d --name "origin" \
--privileged --pid=host --net=host \
-v /:/rootfs:ro -v /var/run:/var/run:rw -v /sys:/sys -v /var/lib/docker:/var/lib/docker:rw \
-v /var/lib/origin/openshift.local.volumes:/var/lib/origin/openshift.local.volumes \
openshift/origin start
``` | 2015/09/10 | [
"https://Stackoverflow.com/questions/32504097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4525448/"
] | You should store your states unique identifiers in a dictionary. Then, access the values of that object for each line of `csv_file.csv`.
```
import csv
reader_csv = csv.reader(open('csv_file.csv', 'r')) # no b flag for python3
file_write = open('output.csv', 'a')
writer = csv.writer(file_write)
# Dictionary construction
with open('states.csv', mode='r') as infile:
reader = csv.reader(infile)
states_dict = {rows[0]:rows[1] for rows in reader}
# File writing
for line in reader_csv:
writer.writerow([states_dict[line[0]]]+[line[1]]+[line[2]])
file_write.close()
``` | ```
import csv
with open('state.csv') as csvfile:
reader = csv.DictReader(csvfile)
states = {row.get('state_id'): row.get('state_name') for row in reader}
with open('csv_file.csv') as csvfile:
reader = csv.DictReader(csvfile)
with open('output.csv', 'wb') as outfile:
fieldnames = ['state_name', 'year', 'value']
writer = csv.DictWriter(outfile, fieldnames=fieldnames)
writer.writeheader()
for row in reader:
writer.writerow({'state_name': states.get(row.get('state_id')), 'year': row.get('year'), 'value': row.get('value')})
``` |
16,267,053 | So, basically I have a very large array that I need to read data from. I want to be able to do this in parallel; however, when I tried, I failed miserably. For the sake of simplicity, let's say I have an array with 100 elements in it. My idea was to partition the array into 10 equals parts and try to read them in parallel (10 is arbitrary, but I don't know how many processes I could run at once and 10 seemed low enough). I need to return a computation (new data structure) based off of my readings from each partition, but I am NOT modifying anything in the original array.
Instead of trying the above exactly, I tried something simpler, but I did it incorrectly, because it didn't work in any capacity. So, then I tried to simply use child processes to push to a an array. The code below is using `Time::HiRes` to see how much faster I can get this to run using forking as opposed to not, but I'm not at that point yet (I'm going to be testing that when I have closer to a few million entries in my array):
```
use strict;
use warnings;
use Time::HiRes;
print "Starting main program\n";
my %child;
my @array=();
my $counter=0;
my $start = Time::HiRes::time();
for (my $count = 1; $count <= 10; $count++)
{
my $pid = fork();
if ($pid)
{
$child{$pid}++;
}
elsif ($pid == 0)
{
addToArray(\$counter,\@array);
exit 0;
}
else
{
die "couldnt fork: $!\n";
}
}
while (keys %child)
{
my $pid = waitpid(-1,0);
delete $child{$pid};
}
my $stop = Time::HiRes::time();
my $duration = $stop-$start;
print "Time spent: $duration\n";
print "Size of array: ".scalar(@array)."\n";
print "End of main program\n";
sub addToArray
{
my $start=shift;
my $count=${$start};
${$start}+=10;
my $array=shift;
for (my $i=$count; $i<$count +10; $i++)
{
push @{$array}, $i;
}
print scalar(@{$array})."\n";
}
```
NB: I used push in lieu of `${$array}[$i]=$i`, because I realized that my `$counter` wasn't actually updating, so that would never work with this code.
I assume that this doesn't work because the children are all copies of the original program and I'm never actually adding anything to the array in my "original program". On that note, I'm very stuck. Again, the actual problem that I'm actually trying to solve is how to partition my array (with data in it) and try to read them in parallel and return a computation based off of my readings (NOTE: I'm not going to modify the original array), but I'm never going to be able to do that if I can't figure out how to actually get my `$counter` to update. I'd also like to know how to get the code above to do what I want it to do, but that's a secondary goal.
Once I can get my counter to update correctly, is there any chance that another process would start before it updates and I wouldn't actually be reading in the entire array? If so, how do I account for this?
Please, any help would be much appreciated. I'm very frustrated/stuck. I hope there is an easy fix. Thanks in advance.
EDIT: I attempted to use Parallel::ForkManager, but to no avail:
```
#!/usr/local/roadm/bin/perl
use strict;
use warnings;
use Time::HiRes;
use Parallel::ForkManager;
my $pm = Parallel::ForkManager->new(10);
for (my $count = 1; $count <= 10; $count++)
{
my $pid = $pm->start and next;
sub1(\$counter,\@array);
$pm->finish; # Terminates the child process
}
$pm->wait_all_children;
```
I didn't include the other extraneous stuff, see above for missing code/sub... Again, help would be much appreciated. I'm very new to this and kind of need someone to hold my hand. I also tried to do something with `run_on_start` and `run_on_finish`, but they didn't work either. | 2013/04/28 | [
"https://Stackoverflow.com/questions/16267053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2073001/"
] | Your code has two issues: Your child processes share no data, and you would have a race condition if forked processes would share data. The solution is to `use threads`. Any possibility for race conditions can be eliminated by partitioning the data in the parent thread, and of course, by not using shared data.
### Threads
Threads in Perl behave similar to `fork`ing: by default, there is no shared memory. This makes using threads quite easy. However, each thread runs it own perl interpreter, which makes threads quite costly. Use sparingly.
First, we have to activate threading support via `use threads`. To start a thread, we do `threads->create(\&code, @args)`, which returns a thread object. The code will then run in a separate thread, and will be invoked with the given arguments. After the thread has finished execution, we can collect the return value by calling `$thread->join`. Note: The context of the threaded code is determined by the `create` method, not by `join`.
We could mark variables with the `:shared` attribute. Your `$counter` and `@array` would be examples for this, but it is generally better to pass explicit copies of data around than to use shared state (disclaimer: from a theoretical standpoint, that is). To avoid race conditions with the shared data, you'd actually have to protect your `$counter` with a semaphore, but again, there is no need for shared state.
Here is a toy program showing how you could use threads to parallelize a calculation:
```
use strict;
use warnings;
use threads;
use 5.010; # for `say`, and sane threads
use Test::More;
# This program calculates differences between elements of an array
my @threads;
my @array = (1, 4, 3, 5, 5, 10, 7, 8);
my @delta = ( 3, -1, 2, 0, 5, -3, 1 );
my $number_of_threads = 3;
my @partitions = partition( $#array, $number_of_threads );
say "partitions: @partitions";
for (my $lower_bound = 0; @partitions; $lower_bound += shift @partitions) {
my $upper_bound = $lower_bound + $partitions[0];
say "spawning thread with [@array[$lower_bound .. $upper_bound]]";
# pass copies of the values in the array slice to new thread:
push @threads, threads->create(\&differences, @array[$lower_bound .. $upper_bound]);
# note that threads->create was called in list context
}
my @received;
push @received, $_->join for @threads; # will block until all are finished
is_deeply \@received, \@delta;
done_testing;
# calculates the differences. This doesn't need shared memory.
# note that @array could have been safely accessed, as it is never written to
# If I had written to a (unshared) variable, these changes would have been thread-local
sub differences {
say "Hi from a worker thread, I have ", 0+@_, " elements to work on";
return map $_[$_] - $_[$_-1], 1 .. $#_;
# or more readable:
# my @d;
# for my $i (1 .. $#_) {
# push @d, $_[$i] - $_[$i-1];
# }
# return @d;
}
# divide workload into somewhat fair parts, giving earlier threads more work
sub partition {
my ($total, $parts) = @_;
my $base_size = int($total / $parts);
my @partitions = ($base_size) x $parts;
$partitions[$_-1]++ for 1 .. $total - $base_size*$parts;
return @partitions;
}
```
A note on the number of threads: This should depend on the number of processors of your system. If you have four cores, more than four threads don't make much sense. | So, after my struggle, here's the fix:
EDIT: THIS DOES NOT ACCOMPLISH WHAT I WANTED TO DO
```
#!/usr/local/roadm/bin/perl
use strict;
use warnings;
use Time::HiRes;
use Parallel::ForkManager;
print "Starting main program\n";
my @array=();
my $counter=0;
my $start = Time::HiRes::time();
my $max_processes=20;
my $partition=10;
my $max_elements=100;
my $pm = Parallel::ForkManager->new($max_processes);
$pm->run_on_start( sub {
my ($pid, $exit_code, $ident) = @_;
sub1(\$counter,\@array);
});
while ($counter < $max_elements)
{
my $pid = $pm->start and next;
$pm->finish; # Terminates the child process
}
$pm->wait_all_children;
my $stop = Time::HiRes::time();
my $duration = $stop-$start;
print "Time spent: $duration\n";
print "Size of array: ".scalar(@array)."\n";
print "\nEnd of main program\n";
sub sub1 {
my $start=shift;
my $count=${$start};
${$start}+=$partition;
my $array=shift;
for (my $i=$count; $i<$count + $partition; $i++)
{
push @{$array}, $i;
}
return @{$array};
}
``` |
5,892,912 | I have a MVC 3 project in which I use \_Layout.cshtml as master page in all web pages. Now I want to remove this master page (layout) from one of the page (progress.cshtml). So I removed the removed the top portion of the page which was
```
@{
ViewBag.Title = "Progress";
Layout = "~/Views/Shared/_Layout.cshtml";
}
```
I thought this will work but when I browse progress page it still shows the content from layout file. How I can remove this binding? | 2011/05/05 | [
"https://Stackoverflow.com/questions/5892912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/287100/"
] | Set the layout= null to remove the default layout inheritance in that view | ```
@{
ViewBag.Title = "Progress";
Layout = null;
}
``` |
29,350,634 | This is perhaps a naive question from iOS newbie.
I see that typical iOS application main.m has following code:
```
int main(int argc, char * argv[]) {
@autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}
```
What is the point of having autoreleasepool around UIApplicationMain in iOS application? UIApplicationMain doesn't return till the application actually exits so why have UIApplicationMain() in autoreleasepool, which triggers 'free' for all the objects allocated during application's execution. | 2015/03/30 | [
"https://Stackoverflow.com/questions/29350634",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1223747/"
] | Currently, with LLVM compiler every thread has an autorelease pool by default and this is not needed. If you use a different compiler with a different implementation for autorelease pools (they are now a language feature), you are required to set up an autorelease pool for every thread. It doesn't matter that the call never returns, the pool has to be set up (and it can be drained thanks to it).
I can't find the duplicate question but I am sure it's there. | From [Using Autorelease Pool Blocks](https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmAutoreleasePools.html):
>
> Cocoa always expects code to be executed within an autorelease pool block, otherwise autoreleased objects do not get released and your application leaks memory. (If you send an `autorelease` message outside of an autorelease pool block, Cocoa logs a suitable error message.) The AppKit and UIKit frameworks process each event-loop iteration (such as a mouse down event or a tap) within an autorelease pool block.
>
>
>
TLDR: Running Cocoa code outside of an autorelease block is an error because it may leak memory. |
6,370,737 | Im trying to get my head around javascript inheritance and this code doesnt work cant see why:
```
function Animal(){
this.hasfur = true;
}
function Cat(){
this.sound = "Meow";
}
$(document).ready(function(){
Cat.protptype = new Animal();
var myCat = new Cat();
console.log(myCat.hasfur);
}
```
The console comes out with undefined. But I thought that when I access myCat.hasfur it should look at the prototype of cat which is vehicle and then look at that property...? | 2011/06/16 | [
"https://Stackoverflow.com/questions/6370737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/223863/"
] | You can change it using the cursor class programtically, like this,
```
this.Cursor = Cursors.WaitCursor;
```
To change it back to normal,
```
this.Cursor = Cursors.Default;
``` | how about using Cursor property of the form?
```
this.Cursor = System.Windows.Forms.Cursors.No;
``` |
45,430,067 | I am new in angular 4 and i am getting `[ts] Cannot find name 'model'` error in
my angular 4 project. kindly help to me where is my mistake.
Thanks in advance.
```
import { Component, OnInit } from '@angular/core';
import { Customer } from './customer';
@Component({
selector: 'app-customer-profile',
templateUrl: './customer-profile.component.html',
styleUrls: ['./customer-profile.component.css']
})
export class CustomerProfileComponent implements OnInit {
constructor() {
}
ngOnInit() {
model = new Customer(1,'vikram','R',25);
}
}
``` | 2017/08/01 | [
"https://Stackoverflow.com/questions/45430067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You should not use `Task.Run` or `Task.Factory.StartNew`. It seems you don't actually understand what async is. Namely, it's *not* parallel processing. All async does is allow the running thread to be returned to the pool if it enters a wait-state. Threads are generally a limited commodity; they have overhead and consume system resources. In something like a web server, the thread pool is usually capped at 1000, which means you can have 1000 active threads at any given time. Async simply allows threads which are idle to be returned to the pool, so that they can be used to do additional work, rather than just sitting there idle.
In the context of a web server, each request is assigned a thread. This is why the thread-cap on the server is usually referred to as the "max requests". One request *always* equals at least one thread. Doing something like creating a new thread, takes *another* thread from the pool, so now your single request is sitting on two threads (effectively halving your server's potential throughput). Now, if the action is async, the first thread will be returned to the pool, because the new thread is now active and the original is now idle. However, that means you've bought yourself nothing: you've simply traded one thread for another and added a bunch of unnecessary overhead. Creating a new thread is *not* the same as background processing; that's a common and *dangerous* misconception.
Plain and simple, the server cannot return a response until *all* work has completed on the action. Whether you use one thread or a thousand to get there, makes no difference in terms of response time (except that using more than one thread actually *increases* your response time, causing *more* delays, not less). Even async done properly will actually increase your response time, even if only by microseconds. This is because async has inherent overhead. Sync is *always* quicker. The benefit from async is that you can utilize resources more efficiently, *not* that anything happens "faster". | You should not mix `Task.Factory.StartNew` with `async-await`. Use `Task.Run` instead.
* [Task.Run vs Task.Factory.StartNew](https://blogs.msdn.microsoft.com/pfxteam/2011/10/24/task-run-vs-task-factory-startnew/)
But, since it's an ASP.NET application, by doing async over sync, you're just switching from one thread pool thread to another and then to another which will make the overall system slower. |
20,513,680 | How to insert today date in mysql using php.date format is like `Dec-10-2013`.i tried
```
$sql="insert into tbl_name (colm1,colm2) values (1,now())";
```
Here value inserted in colm2 is 2013-12-11. | 2013/12/11 | [
"https://Stackoverflow.com/questions/20513680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | What you want to do is save your dates as TIMESTAMP or something similar. When you retrieve it, you can format it. You can insert your dates with 'NOW()' or a given format if they are different.
If you want to display the time, you can do: `new DateTime($row['my_date']);`
For inserting you can use the same method: `(new DateTime($date))->getTimestamp()`
***Why DateTime?***
- Because it works with timezones.
***Why not store it as Dec-10-2013?***
- Because you cannot do anything with a varchar pretending to be a date. You have a TIMESTAMP field type for that | I can see in your question that your db timezone format is `YYYY-MM-DD`
```
$date = date("Y-m-d", strtotime($yourDate));
$sql="insert into tbl_name (colm1,colm2) values (1,{$date})";
```
EDIT:
'Dec-10-2013' is known format for php, so you can do this `$yourDate = 'Dec-10-2013'`; |
34,842,211 | I have a repetitive task of calculating the average price of a product for each country. Price and country code (e.g., ES = Spain , TR = Turkey) are located in two different columns in my dataframe. How can I use a for-loop to iterate over the different countries?
```
# get price for ES only
ES = subset(training.data.raw$priceusd, training.data.raw$destinationcountry== "ES")
# sum all prices of ES
summyES = sum(ES)
# Freq of ES
FES = 5223
# avg price of ES
(avgES = summy/FES)
# AVG price for TR
TR = subset(training.data.raw$priceusd, training.data.raw$destinationcountry=="TR")
summyTR = sum(TR)
FTR = 3201
avgTR = summy/FTR
print(avgTR)
``` | 2016/01/17 | [
"https://Stackoverflow.com/questions/34842211",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You have a split-apply-combine problem. Try something like:
```
aggregate(priceusd ~ destinationcountry, data = training.data.raw, FUN = mean)
```
As an example, from reproducible data:
```
> aggregate(Sepal.Length ~ Species, data = iris, FUN = mean)
Species Sepal.Length
1 setosa 5.006
2 versicolor 5.936
3 virginica 6.588
```
There are dozens of ways to do this, using base R functions as well as add-on packages. Searching "split-apply-combine" should lead you to all of them. | You can use `dplyr` to do this.
```
library(dplyr)
training.data.raw %>%
group_by(destinationcountry) %>%
summary(avg = mean(priceusd)) # Avg computed for each group in destinationcountry
```
This will calculate the average for each group. |
60,606 | I am struggling to find a philosophical reason for believing in the axiom of power set, and I was hoping you can give me some justifications.
I am not looking for answers of the form "it's convenient to use power set axiom" or "why wouldn't it be true?", as my view of the mathematical world tends to be platonist. Just for pure philosophical and logical arguments for this axiom.
Thank you very much for your answers. | 2019/02/23 | [
"https://philosophy.stackexchange.com/questions/60606",
"https://philosophy.stackexchange.com",
"https://philosophy.stackexchange.com/users/31204/"
] | The power set axiom postulates: For any set X exists a set P(X) which comprises as elements exactly the subsets of X.
Hence the power set axiom acts as a tool to form new sets from existing ones, by fixing a certain defining property.
As one knows, not any defining property is admissible for defining new sets, see the Russell antinomy. Compared to unrestricted use of defining properties the power set axiom is a mild version. It does not introduce new inconsistencies. Hence power sets exist in the context of Zermelo Fraenkel set theory.
But IMO this kind of existence does not follow neither from logical reasons nor from philosophical argumentation.
A deep consequence of the power set axiom is the result: For any set X the cardinality of P(X) is stricly bigger than the cardinality of X. Moreover 2ℵ0, the cardinality of the power set of the naturals, equals the cardinality of the reals.
Hence accepting the set of reals implies at least the existence of the power set of the naturals.
Whether power sets exist in the Platonic world of forms is a question I cannot answer. Unfortunately, I do not remember, contrary to Platonic anamnesis :-) | After Russell's paradox (and others) the idea of "what a set is?" has changed! from the very broad idea of a set being an extension of a predicate (Frege), to a an entity that is constructed in a controlled step-wise manner in stages, beginning from some particular lower level objects, call them Ur-elements, then construct sets of those, then we go to the next level of constructing sets of those and the ones prior to them and so on... It is this image of a hierarchy that justifies the power set axioms and other axioms of Zermelo set theory.
Now it is obvious that the next level must be at least some subset of the power class of the prior level, like for example the set of all definable subsets of the prior level, so the real question would turn to be about:
How much width we accept per stage of the Hierarchy?
An argument towards full width would definitely motivate the power set axiom. The main problem of the other direction is when we must stop? which appears to be ad-hoc most of the times, if we want to adhere to strict constructibility criterion then we'd end up with thin stages, but this appears to be a rather strict restriction rather than a kind of reality about the matter. If one opt for maximality, then definitely the power set axiom would be the maximal next stage. I don' know why in some sense maximals appears less ad-hoc than particular restrictions.
All in all, of all axioms of ZFC, the power set axiom seem to be the most doubtful, and no easy line of justification, especially of the natural sort you are calling for, is available.
However, there are many technical reasons for its development, like the study of reals, having easier notation, etc.., but that would be pragmatic.
In a mereological foundation of set theory, like that of [David Lewis](http://www.andrewmbailey.com/dkl/Mathematics_is_Megethology.pdf), sets appear as labeling bodies, catalogs, but this is only to make them achieve a hierarchical buildup, so it would be expected for the next stage in the hierarchy to unravel the part-hood of the prior level, and to the full spectrum of it as well! Since this is just part of capturing its mereological properties in the hierarchical buildup, it would be strange to think of hidden parts not been visualized in the hierarchy, since part-hood (which is equivalent to subclass-hood by Lewis's definitions and premises) is already the MAIN primitive in that setting. With Lewis he stresses, through his premises, that *subclass* is exactly equivalent to *part of class*, and that this is a basic mereological property of classes! Now going hierarchical through the Epsilon membership relation, it would be expected from the *set* principle to un-ravel this *essential* nature of classes in set language; i.e., *subset* is exactly equivalent to *part of set*, and so the full girth of powering is to be exposed! |
25,682 | I spent a fair bit of time riding in the lane, in traffic. In this situation, it seems that a brake light would be very useful: It's not always obvious when the vehicle ahead of you is slowing down, and I don't want to be rear-ended by someone who doesn't notice me slowing.
This intuition does not match reality. I was not able to find any bicycle brake lights that seem really ready for prime time. This is what I was able to find:
* [Q-Lite Multi](http://smile.amazon.com/Q-Lite-Multi-Function-Tail-Light/dp/B00I53W5YS) — Apparently available from just one vendor (TerraTrike). Not mentioned on manufacturer (Q-Lite) website.
* [Maxxon](http://www.sungoinc.com/light/products.html) — Available on Amazon, but poor reviews suggest it does not detect deceleration well.
* [Revolights](http://revolights.com/pages/howitworks) — Complicated spoke mounting system; unclear drivers will interpret it properly.
* [Velodroom](http://vd.ee/) — Not yet available (pre-order only).
* [LucidBrake](http://lucidbrake.com/) — Perhaps the most promising of the bunch. Apparently available only direct from a not-so-great website.
The first uses a brake handle-mounted switch. The others use accelerometers to detect slowing.
None of the major bike light manufacturers seem to offer a brake light.
My question is, what's the disconnect? Am I misjudging the value of brake lights? Is there some challenge that makes them hard to offer for bicycles? | 2014/11/15 | [
"https://bicycles.stackexchange.com/questions/25682",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/4175/"
] | I ride my bike to work every day and also ride mountainbikes in my free time. I never had the feeling that cars might crash into my rear end, right turning cars (we're driving on the right side) and opening doors are a larger problem that cannot be fixed by tail lights.
However, there a another light missing from the list above - from German manufacturer Lupine. It charges via Micro-USB, which I like. It's called Rotlicht and has an acceleration sensor to see whether you're braking: [Rotlicht](http://www.lupine.de/eng/products/rear-tail-lights/rotlicht/introduction)
Here's a [review on mtb-news.de](http://www.mtb-news.de/news/2014/10/28/lupine-rotlicht-ruecklicht-im-test/) (in German though). | Maybe not too visible to cars, but I think the following brake light is ideal if riding in a pace line on a group ride, for the price and weight it can't be beat. If something comes up you might need both hands on the brake levers and can't signal to riders behind.
<http://gizmodo.com/a-cheap-10-bike-brake-light-that-only-glows-when-youre-1723097375>
It is triggered by the back brake squeezing its lever when the back brake is applied. |
47,435,066 | I'm using CodeIgniter, and I'm new at it, as I'm in web development.
I'm having a problem with the `base_url` from CI: it leads to `404 Page not found`.
Here is the referrence for the page:
```
<li><a href="<?=base_url('Usual/novo_usual')?>">Cadastrar</a></li>
```
The controller's function:
```
function novo_usual(){
$this->load->view('html-header');
$this->load->view('html-footer');
$this->load->view('cadastro_usual');
}
```
My controller's name file starts in capital, like Usual.php, and it extends `CI_Controller`.
My altoloado.php:
```
$autoload['helper'] = array('url','html','form','funcoes');
```
My routes.php:
```
$route['default_controller'] = 'Home';
```
Finally the .htaccess file
```
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond $1 !^(index\.php|images|css|js|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?$1 [L]
</IfModule>
``` | 2017/11/22 | [
"https://Stackoverflow.com/questions/47435066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8989826/"
] | Following @Szarik recommendations, I follow [this link](https://github.com/angular/in-memory-web-api), which has the answer. Actually, it's the official specification of the Library I am using: in-memory-web-api
Diving a little in the README.md, we reach this:
>
> You can override the default parser by implementing a parseRequestUrl method in your InMemoryDbService.
>
>
> The service calls your method with two arguments.
>
>
> 1. url - the request URL string
> 2. requestInfoUtils - utility methods in a RequestInfoUtilities object, including the default parser. Note that some values have not yet been set as they depend on the outcome of parsing.
>
>
> Your method must either return a ParsedRequestUrl object or null|undefined, in which case the service uses the default parser. In this way you can intercept and parse some URLs and leave the others to the default parser.
>
>
>
So that was it! | To examplify the answer above:
The 'forRoot' takes optional settings, and among these an 'apiBase'. To match an endpoint of
`private url = '/some/endpoint/responseExample';`
set the corresponding 'apiBase' without prefix and suffix slashes:
```
HttpClientInMemoryWebApiModule.forRoot(InMemoryDbItemService, { apiBase: 'some/endpoint'})
```
The 'responseExample' is the actual data.
```
createDb() {
const responseExample = {[some:'structure']}
return { responseExample };
}
``` |
1,671,314 | I live in a rural area with only two choices for Internet connection, 1.2 Mbit/s [DSL](https://en.wikipedia.org/wiki/Digital_subscriber_line) from AT&T or 15 Mbit/s from old-style satellites with 700 ms ping time and fast only in averages.
The fast connection is OK for web access, but the shorter lag time is necessary for interactive work. I have the DSL on a wired Ethernet connection and the long-lag higher bandwidth on Wi-Fi.
I have two routers, one for each ISP. My laptop can support both connections at same time. Can Windows 10 manage to utilize both depending on some internal metrics? At same time I have local storage on only one network and a printer on only one. Can the OS act as a bridge between the two local subnets? | 2021/08/24 | [
"https://superuser.com/questions/1671314",
"https://superuser.com",
"https://superuser.com/users/1500023/"
] | I would opt for a multi-WAN router instead.
I've seen that these offer load-balancing support, but I'm not sure if that is customizable to send certain traffic across one network versus the other; you'll have to read into the router's documentation before buying one.
[This one](https://docs.netgate.com/pfsense/en/latest/multiwan/policy-route.html) seems to allow you to alternate WANs based on port number being used. [US$179](https://shop.netgate.com/products/1100-pfsense) isn't terribly expensive given the functionality.
I suggest this because even if you succeed in getting Windows 10 to do smart network switching then you'll have to repeat the process if you desire another machine to behave similarly. Also, such changes could present huge headaches if you have to use someone else's network or if your router breaks and you get a new one.
The multi-WAN router would be much more robust and reliable solution.
Getting a purpose-built networking device to achieve your goals is going to be far easier than coercing a user-oriented operating system to do something unnatural.
---
The other option for your "interactive" work ([RDP](https://en.wikipedia.org/wiki/Remote_Desktop_Protocol) right?) is to just get an el cheapo laptop connected to the DSL which can handle your desired monitor resolution and alternate machines as needed. | buy a load balance router (TL-R470T) and configure it for BINDING of two VLAN ports on the box. I am rural with hardly any phone signal, just 1 bar on phone 4G+ in some places outside.
Putting two sims in each 4G device and bonding them, I can get 93 mega bits per second down load and 19 upload.
I have 1 external passive ariel for a domestic router (Class 6) and another externally mounted ZYXEL router MIMO etc - POE supply so can be placed up to 100m away from the WAN router.
Much cheaper faster and better than previous SAT system.
No more glitch streaming - 4k
costs a little for the setup but repaid in a few months by the savings. |
73,265,368 | I have been using the following UIView extension for quite a while to fade text in and out. I have been trying to figure out how to implement this with SwiftUI but so far haven't found anything that exactly addresses this for me. Any help would be greatly appreciated.
```
extension UIView {
func fadeKey() {
// Move our fade out code from earlier
UIView.animate(withDuration: 3.0, delay: 2.0, options: UIView.AnimationOptions.curveEaseIn, animations: {
self.alpha = 1.0 // Instead of a specific instance of, say, birdTypeLabel, we simply set [thisInstance] (ie, self)'s alpha
}, completion: nil)
}
func fadeIn1() {
// Move our fade out code from earlier
UIView.animate(withDuration: 1.5, delay: 0.5, options: UIView.AnimationOptions.curveEaseIn, animations: {
self.alpha = 1.0 // Instead of a specific instance of, say, birdTypeLabel, we simply set [thisInstance] (ie, self)'s alpha
}, completion: nil)
}
``` | 2022/08/07 | [
"https://Stackoverflow.com/questions/73265368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12323191/"
] | Please, remove CSS:
```
.MuiDrawer-paper {
width: 10% !important;
}
```
And update this line:
```
const drawerWidth = 240;
```
It can be "200px" or "10%", whatever you need. | If you inspect elements, you will see
```
<div class="MuiDrawer-root MuiDrawer-docked css-1f2xuhi-MuiDrawer-docked">
<div class="MuiPaper-root MuiPaper-elevation MuiPaper-elevation0 MuiDrawer-paper MuiDrawer-paperAnchorLeft MuiDrawer-paperAnchorDockedLeft css-12i7wg6-MuiPaper-root-MuiDrawer-paper">
```
`.MuiDrawer-paper` does not change the width of the parent element, which is `240px`
```
.css-1f2xuhi-MuiDrawer-docked {
-webkit-flex: 0 0 auto;
-ms-flex: 0 0 auto;
flex: 0 0 auto;
width: 240px;
-webkit-flex-shrink: 0;
-ms-flex-negative: 0;
flex-shrink: 0;
}
``` |
67,715,506 | I have a long list of functions that needs to be executed based on user input
I want a way to do this **without a long if else statement**
Thanks in advance this will save a lot of time
```
def function1(a,b):
return a+b
def function2(a,b):
return a-b
.
.
.
there a are many functions like this
.
.
.
class marks:
def __init__(self,w,b):
self.w=w
self.b=b
def execute(self,function):
I WANT TO KNOW THIS PART
m=marks(50,30)
m.execute("function2") should perform function2 and print
m.execute("function45") should perform function45 and print
``` | 2021/05/27 | [
"https://Stackoverflow.com/questions/67715506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14561199/"
] | Set up a dictionary in the style `action = {'keyword1':function1,'keyword2':function2...}` then for user input `entry` you can check the input with `entry in action` and activate with `action[entry]()`. | Try using the [eval](https://www.programiz.com/python-programming/methods/built-in/eval) function:
```
names = {"function1": function1, "function2": function2 ...}
func = input('which function do you want to call')
print(eval(func, names))
``` |
126 | I'm a novice user, I've been playing with the RPi a lot lately but I haven't seen any questions that I can answer.
My only contribution so far is to up vote questions and comments I think are useful.
Is this helpful to a site in beta?
I will of course be asking questions when they crop up as well!
Am I helping the site at all? | 2012/06/16 | [
"https://raspberrypi.meta.stackexchange.com/questions/126",
"https://raspberrypi.meta.stackexchange.com",
"https://raspberrypi.meta.stackexchange.com/users/175/"
] | Yes!
====
Don't worry if you can't answer questions, just providing questions to be answered, when you have them, is often the thing a lot of betas struggle with most.
A lot of betas have an initial rush then a bit of a slump, especially on questions - so people who can post a steady stream of good, relevant questions are much appreciated, and very much needed. It's not all about just rushing to provide the best answers. If there were no questions, there wouldn't be any!
Another point worth mentioning, I think most people here are very aware of the fact that the Raspberry Pi will probably attract beginners in a number of areas, so even very basic questions would still be welcome as I see it. | Yes.
Other things you can do:
* Suggest edits to existing questions & answers.
You gain +2 rep for each edit that is approved by the author.
* Flag spam and "me too" answers for moderation (you don't get rep for this, but you can get the [deputy](https://raspberrypi.meta.stackexchange.com/badges/70/deputy) and [marshal](https://raspberrypi.meta.stackexchange.com/badges/76/marshal) badges.) |
3,386,897 | Strings that match /^\w+$/ are quite common. For example many authentication systems use that pattern to validate usernames. I'm wondering if a term exists that identifies this kind of strings.
I've been thinking of the term "alphanumeric" but is a string alphanumeric if it contains an underscore? | 2010/08/02 | [
"https://Stackoverflow.com/questions/3386897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/200145/"
] | I do not think that it is a good idea to give it a potentially confusing name. Alphanumeric could be misunderstood. If you need to refer to it, for example in your documentation, define it with an unique name like 'username\_pattern', and refer to that definition of yours whenever you talk about it. | Personally, I’d call it “a string that matches `^\w+$`” if my audience knows what this means. That is probably the most succint “name” that doesn’t significantly sacrifice accuracy. If I had to *say* it, I might call it “a non-empty string containing only word characters”, but once again I need to assume that my listener(s) know the technical meaning of *word character*.
If you want to come up with an English name for it, you are necessarily going to sacrifice a lot of accuracy and end up with something much more vague than the hard and well-defined regular expression — especially if your audience is not technical and/or does not recognise the term as a *technical* term with this precise meaning. |
38,008,354 | I wrote a form where its fields need to be reset after successful submission. The entire flow happens through `ajax` and `php`. Here is the code:
**`HTML`**
```
<form role="form" class="contact-form" id="contact-fm" method="post">
<div class="form-group">
<div class="controls">
<input type="text" placeholder="Name" class="requiredField" name="name" required>
</div>
</div>
<div class="form-group">
<div class="controls">
<input type="email" class="email" class="requiredField" placeholder="Email" name="email" required>
</div>
</div>
<div class="form-group">
<div class="controls">
<input type="text" class="requiredField" placeholder="Subject" name="subject" required>
</div>
</div>
<div class="form-group">
<div class="controls">
<textarea rows="7" placeholder="Message" name="message" class="requiredField" required></textarea>
</div>
</div>
<button type="submit" id="submit" class="btn-system btn-large">Send</button>
<div id="success" style="color:#34495e;"></div>
</form>
```
**`AJAX`**
```
$(function() {
$("input,textarea").jqBootstrapValidation({
preventSubmit: true,
submitError: function($form, event, errors) {
// additional error messages or events
},
submitSuccess: function($form, event) {
event.preventDefault(); // prevent default submit behaviour
// get values from FORM
var name = $("input#name").val();
var email = $("input#email").val();
var sub = $("input#subject").val();
var message = $("textarea#message").val();
$.ajax({
url: "php/send.php",
type: "POST",
data: {
name: name,
email: email,
sub: subject,
message: message
},
cache: false,
})
document.getElementById('contact-fm').reset();
},
});
});
```
**`PHP`**
```
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$subject = $_POST['subject'];
$to = 'ajay.k@enexl.com';
if (filter_var($email, FILTER_VALIDATE_EMAIL)) { // this line checks that we have a valid email address
$mailSubject = "Contact request from " .$name;
$txt = "name : ".$name.".\n\nSubject : ".$subject.".\n\nMail id : ".$email."\n\nMessage : ".$message;
$headers = "From: ".$email ;
mail($to,$mailSubject,$txt,$headers);
$data = array();
$data['status'] = 'success';
//echo json_encode($data);
echo "<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js'></script>";
echo "<p id='text'>Your email was sent! One of our team members would contact you shortly!</p>"; // success message
echo "<script type='text/javascript'>";
echo "$(function(){";
echo "$('#text').fadeOut(5000);";
echo "});";
echo "</script>";
}
else{
echo "<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js'></script>";
echo "<p id='textOne'>Mail was not sent, make sure that all fields are filled in!</p>"; // success message
echo "<script type='text/javascript'>";
echo "$(function(){";
echo "$('#textOne').fadeOut(5000);";
echo "});";
echo "</script>";
}
?>
```
When I use `document.getElementById('contact-fm').reset();`, form doesn't get reset. How can I make it reset? | 2016/06/24 | [
"https://Stackoverflow.com/questions/38008354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4185813/"
] | You don't need to have bunch of subscriptions and unsubscribe manually. Use [Subject](https://github.com/ReactiveX/rxjs/blob/6.x/doc/subject.md) and [takeUntil](http://xgrommx.github.io/rx-book/content/observable/observable_instance_methods/takeuntil.html) combo to handle subscriptions like a boss:
```js
import { Subject } from "rxjs"
import { takeUntil } from "rxjs/operators"
@Component({
moduleId: __moduleName,
selector: "my-view",
templateUrl: "../views/view-route.view.html"
})
export class ViewRouteComponent implements OnInit, OnDestroy {
componentDestroyed$: Subject<boolean> = new Subject()
constructor(private titleService: TitleService) {}
ngOnInit() {
this.titleService.emitter1$
.pipe(takeUntil(this.componentDestroyed$))
.subscribe((data: any) => { /* ... do something 1 */ })
this.titleService.emitter2$
.pipe(takeUntil(this.componentDestroyed$))
.subscribe((data: any) => { /* ... do something 2 */ })
//...
this.titleService.emitterN$
.pipe(takeUntil(this.componentDestroyed$))
.subscribe((data: any) => { /* ... do something N */ })
}
ngOnDestroy() {
this.componentDestroyed$.next(true)
this.componentDestroyed$.complete()
}
}
```
---
**Alternative approach**, which was proposed [by @acumartini in comments](https://stackoverflow.com/questions/38008334/angular-rxjs-when-should-i-unsubscribe-from-subscription/41177163?#comment77901337_42695571), uses [takeWhile](http://xgrommx.github.io/rx-book/content/observable/observable_instance_methods/takewhile.html) instead of [takeUntil](http://xgrommx.github.io/rx-book/content/observable/observable_instance_methods/takeuntil.html). You may prefer it, but mind that this way your Observable execution will not be cancelled on ngDestroy of your component (e.g. when you make time consuming calculations or wait for data from server). Method, which is based on [takeUntil](http://xgrommx.github.io/rx-book/content/observable/observable_instance_methods/takeuntil.html), doesn't have this drawback and leads to immediate cancellation of request. [Thanks to @AlexChe for detailed explanation in comments](https://stackoverflow.com/questions/38008334/angular-rxjs-when-should-i-unsubscribe-from-subscription/41177163?#comment78927120_42695571).
So here is the code:
```js
@Component({
moduleId: __moduleName,
selector: "my-view",
templateUrl: "../views/view-route.view.html"
})
export class ViewRouteComponent implements OnInit, OnDestroy {
alive: boolean = true
constructor(private titleService: TitleService) {}
ngOnInit() {
this.titleService.emitter1$
.pipe(takeWhile(() => this.alive))
.subscribe((data: any) => { /* ... do something 1 */ })
this.titleService.emitter2$
.pipe(takeWhile(() => this.alive))
.subscribe((data: any) => { /* ... do something 2 */ })
// ...
this.titleService.emitterN$
.pipe(takeWhile(() => this.alive))
.subscribe((data: any) => { /* ... do something N */ })
}
ngOnDestroy() {
this.alive = false
}
}
``` | **A Subscription essentially just has an unsubscribe() function to release resources or cancel Observable executions.**
In Angular, we have to unsubscribe from the Observable when the component is being destroyed. Luckily, Angular has a ngOnDestroy hook that is called before a component is destroyed, this enables devs to provide the cleanup crew here to avoid hanging subscriptions, open portals, and what nots that may come in the future to bite us in the back
```
@Component({...})
export class AppComponent implements OnInit, OnDestroy {
subscription: Subscription
ngOnInit () {
var observable = Rx.Observable.interval(1000);
this.subscription = observable.subscribe(x => console.log(x));
}
ngOnDestroy() {
this.subscription.unsubscribe()
}
}
```
We added ngOnDestroy to our AppCompoennt and called unsubscribe method on the this.subscription Observable
**If there are multiple subscriptions:**
```
@Component({...})
export class AppComponent implements OnInit, OnDestroy {
subscription1$: Subscription
subscription2$: Subscription
ngOnInit () {
var observable1$ = Rx.Observable.interval(1000);
var observable2$ = Rx.Observable.interval(400);
this.subscription1$ = observable.subscribe(x => console.log("From interval 1000" x));
this.subscription2$ = observable.subscribe(x => console.log("From interval 400" x));
}
ngOnDestroy() {
this.subscription1$.unsubscribe()
this.subscription2$.unsubscribe()
}
}
``` |
18,326,398 | How can I retrieve data from OpenStreetMap (OSM) using the OSM API (<http://wiki.openstreetmap.org/wiki/API>) and Ruby? Is there any ruby gem available which serves my purpose? I have been searching for a good solution for my purpose but nothing served me exactly what I need.
As for example : Given the country name as input, I need to get the list of all streets of that country etc.
Any kind of link/code sample or starting point is fine. I can then explore more to find out what I need exactly. Thanks! | 2013/08/20 | [
"https://Stackoverflow.com/questions/18326398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/981183/"
] | Unfortunately, there's no concise syntax for constructing populated maps in Java. You'll have to write it out long-hand. A separate helper method can make it a little simpler:
```
HashMap<String, String> makeMap(String name, String desc, String keys) {
HashMap<String, String> map = new HashMap<>();
// Before Java 7, above must be: new HashMap<String, String>();
map.put("name", name);
map.put("desc", desc);
map.put("keys", keys);
}
```
Then:
```
HashMap<String, HashMap<String, String>> myArray = new HashMap<>();
myArray.put("en",
makeMap("english name", "english description", "english keywords"));
// etc.
```
You would retrieve it with:
```
english_name = myArray.get("en").get("name");
``` | I really liked the example by "dAv dEv", though he didn't really fill his double array of keys (I added a loop within a loop). I also like TreeMaps better than HashMaps because they aren't as random.
```
import java.util.Map;
import java.util.TreeMap;
TreeMap<String, TreeMap<String, String>> myArray =
new TreeMap<String, TreeMap<String, String>>();
String[] roles = { "Help Desk", "Administrator", "Super Use", ... };
String[] elements = { "Hydrogen", "Helium", "Lithium", "Beryllium", ... };
// Setting values TODO: read data values from Excel spreadsheet (or wherever)
for(String role : roles) {
myArray.put(role, new TreeMap<String, String>());
for (String elementName : elements) {
String value = Utils.getHumanName("first", true);
myArray.get(role).put(elementName, value);
}
}
// Getting values
for (Map.Entry<String,TreeMap<String,String>> entry1 : myArray.entrySet()) {
String key1 = entry1.getKey();
TreeMap<String,String> value1 = entry1.getValue();
for (Map.Entry<String,String> entry2 : value1.entrySet()) {
String key2 = entry2.getKey();
String value2 = entry2.getValue();
System.out.println("(" + key1 + ", " + key2 + ") = " +
myArray.get(key1).get(key2));
}
}
```
P.S. I used Utils.getHumanName() as my data generator. You will need to use your own. |
2,014,915 | I've come across laplace transforms as a method to solve differential/integral equations by diagonalizing the derivative operator. I've also seen generating functions as a similar way to transform a recurrence relation into an algebraic problem by diagonalizing the shift operator. The laplace transform of a convolution is a product of the laplace transforms for each function and similarly the generating function of a convolution is a product of generating function. A different application of transforms would be how the dirichlet convolution can become a product when using Dirichlet generating functions. Yesterday I was reading about multiplication algorithms and discovered one fast way to multiply numbers is based on doing a discrete fourier transform because a product of two numbers can be viewed as a convolution of two polynomials where the x in the polynomials would be the base you use to represent the numbers.
These examples of using transforms to simplify a problem I've seen from various courses in math, but I've never really studied the transforms for there own sake. What would be a good textbook/other source on transform theory that deals with things like the similarities of various integral transforms and generating functions?
Edit: My current math background is essentially a standard undergraduate math courses (introductory algebra, analysis, topology, discrete math, etc). | 2016/11/15 | [
"https://math.stackexchange.com/questions/2014915",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/261268/"
] | The choice of the appropriate book depends on whether you are looking for basic or advanced references. For a basic approach, I would suggest you the following two books:
* "[An introduction to Transform Theory](http://store.elsevier.com/An-Introduction-to-Transform-Theory/isbn-9780080873558/)" (1971) by David V. Widder, if you want a general introduction on the topic. Albeit rather old, this book provides a very good description of the basic theory and main applications of the integral transforms, dealing primarily with the Laplace transform and its utility for the solution of ordinary differential equations, but also with several other issues, including the general convolution transform;
* "[An Introduction to Laplace Transforms and Fourier Series](http://www.springer.com/la/book/9781447163947)" (2014) by Phil Dyke, if you want a more recent nice book giving a general introduction to this topic. It also contains a number of well-explained examples and solutions, which make it easy to read.
For an advanced approach, specific references for single types of transform might be preferrable. I would suggest you the following ones:
* "[The Laplace Transform: Theory and Applications](https://www.google.it/url?sa=t&source=web&rct=j&url=http://www.javaquant.net/papers/laplacetransform.pdf&ved=0ahUKEwiu_NmDnsHQAhUIxxQKHWc8CvsQFggiMAE&usg=AFQjCNEauXnju-yg-owNgZK1-4OQoOFD3w&sig2=X0dheBpyIwogZsiHNIAfBQ)" (1999) by Joel Schiff (already cited in the previous answer), if you search a deep and complete assessment of the applications of the Laplace transform. The link above is a pdf version;
* "[The Fourier Transform and its Applications](https://www.google.it/url?sa=t&source=web&rct=j&url=https://see.stanford.edu/materials/lsoftaee261/book-fall-07.pdf&ved=0ahUKEwjypszunsHQAhWIxxQKHe-KCGUQFggfMAA&usg=AFQjCNE9y-gisMrw4qnCIGW1kLU8F63dQg&sig2=iSwROxm0M9iHUMUgwr4KqQ)" (2007) by Brad Osgood, if you want an updated, advanced book on the theory and applications of the Fourier transform. The link above is a pdf version;
* "[Hilbert transforms](https://books.google.it/books/about/Hilbert_Transforms.html?id=spGVZqZk-L4C&redir_esc=y)" (2009) by Frederick W. King, a very comprehensive book on this topic, that also deals with many practical applications in physical sciences. | If you would like to study Laplace transform in depth, there is no better book than **Joel Schiff's book on Laplace Transform**: <http://www.springer.com/gp/book/9780387986982>
If you would like to study a large variety of transforms and see how they relate to each other I highly recommend
**Advanced Engineering Mathematics with MATLAB, Third Edition By Dean G. Duffy**
<https://www.amazon.ca/Advanced-Engineering-Mathematics-MATLAB-Third/dp/1439816247>
In this book they talk about Hilbert Transform, Z-transform, Fourier, Laplace, everything you can think of. |
8,024,529 | I am trying to scrape a website. I have been able to get the contents on the website into a string/file.
Now, I would like to search for a specific line that has something like:
```
<li><span class="abc">Key 1:</span> <span class="aom_pb">Value 1</span></li>
```
There is gauranteed to be only one Key 1: in the website and I need to get the Value 1.
What the best way to do this.
If its through regular expression, can you help me with how it should look. I havent used Regex much.
Regards,
AMM | 2011/11/06 | [
"https://Stackoverflow.com/questions/8024529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11212/"
] | You should use a parser such as [`lxml`](http://lxml.de/) to extract data from HTML. Using regular expressions for such a task is [A Bad Ideatm](http://www.codinghorror.com/blog/2009/11/parsing-html-the-cthulhu-way.html).
Lxml allows you to use XPath expressions to select elements, and in this case, the relevant "key" span can be selected using the expression `//span[@class='abc' and text()='Key 1:']`. This expression just searches the whole tree for `span` elements with classes of `abc` and containing the exact text `Key 1:`.
You can then use `.getnext()` on the element to get the following element that contains the data you want.
Here's how one would do it in full:
```here
import lxml.html as lh
html = """
<html>
<head>
<title>Test</title>
</head>
<body>
<ul>
<li><span class="abc">Key 3:</span> <span class="aom_pb">Mango</span></li>
<li><span class="abc">Key 1:</span> <span class="aom_pb">Pineapple</span></li>
<li><span class="abc">Key 2:</span> <span class="aom_pb">Apple</span></li>
<li><span class="abc">Key 7:</span> <span class="aom_pb">Peach</span></li>
</ul>
</body>
</html>
"""
tree = lh.fromstring(html)
for key_span in tree.xpath("//span[@class='abc' and text()='Key 1:']"):
print key_span.getnext().text
```
**Result:**
`Pineapple` | Another approach using BeautifulSoup: loop over the <li> elements, and check the <span>s inside them.
```
import BeautifulSoup
downloaded_str='''
<li><span class="abc">Key 0:</span> <span class="aom_pb">Value 1</span></li>
<li><span class="abc">Key 1:</span> <span class="aom_pb">Value 1</span></li>
<li><span class="abc">Key 2:</span> <span class="aom_pb">Value 1</span></li>
'''
soup = BeautifulSoup.BeautifulSoup(downloaded_str)
for li in soup.findAll('li'):
span = li.find('span', {'class': 'abc'}, recursive=False)
if span and span.text == 'Key 1:':
return li.find('span', {'class': 'aom_pb'}, recursive=False).text
``` |
24,239,497 | I'm trying to set a header for a webpage that looks like this:

and here's the code I'm trying so far:
**HTML**
```
<header id="top-section">
<div class="content-wrapper">
<div class="float-left">
<a href="../Home/Index"><img src="http://upload.wikimedia.org/wikipedia/commons/a/ac/Approve_icon.svg" alt="SustIMS" width="50%" height="50%" /></a>
</div>
<p class="user-info">
<div class="user-info">
Welcome Jon
</div>
<div class="float-right">
<a href="Index">
<img class="toolbar-icons" alt="Home" src="http://htiins.com/wp-content/uploads/2012/10/home-icon.png" /></a>
</div>
</p>
</div>
</header>
```
**CSS**
```
body {
font: 13px/20px 'Lucida Grande', Tahoma, Verdana, sans-serif;
color: #404040;
background: rgba(240, 240, 240, 1);
border: 2px solid red;
}
.float-left {
float: left;
width: 200px;
border: 2px solid cyan;
}
.float-right {
float: right;
}
#top-section
{
border: 4px solid blue;
height: 120px;
}
.user-info
{
float: right;
font-family: Rockwell, Consolas, "Courier New", Courier, monospace;
font-size: 1.25em;
border: 2px solid green;
}
.toolbar-icons
{
float: right;
width: 100px;
height: 100px;
clear: both;
border: 2px solid orange;
}
```
Here's the [Fiddle](http://jsfiddle.net/7VR85/).
I've set borders in different colors to better understand the divs positioning.
How can I achieve something like the image above?
Thanks
\*EDIT\*\*
Maybe this explains better what I'm looking for: here's how it should look like:

Thanks for some great answers so far! | 2014/06/16 | [
"https://Stackoverflow.com/questions/24239497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2398715/"
] | Move
```
<p class="user-info">
<div class="user-info">
Welcome Jon
</div>
```
into our float-right div and give header the css style of
```
header{
overflow:hidden;
padding:10px;
}
```
to end up with this result.
<http://jsfiddle.net/P9Zjx/> | I'm not sure what dimensions you want to work with and whether this is supposed to be responsive, e.g. stacked on mobile devices, but this should help you get closer to what you want. I cleaned up the `code` a bit ...
**<http://jsfiddle.net/7VR85/2/>** |
34,095 | This is related to a question I asked earlier - <https://softwareengineering.stackexchange.com/questions/34023/how-to-end-a-relationship-with-a-client-without-pissing-them-off>
What are your obligations when charging by the hour vs charging by project? If you agree to take on a project, give a rough estimate that it might take 10 days for you to work on and charge £X per hour - are you obligated to work for free after those 10 days are up and you have still not managed to complete your project due to unanticipated issues? What if you have delivered the project but bugs are found - should you fix these bugs for free if the 10 days are up or should you charge your client?
Also, for the above project, what should be the result when you start on the project, but after the 10 days for whatever reason you have to give up and tell your client that you cannot do it anymore? I realise that this does nothing to build your reputation and relationship with the client but are you obligated to pay back the money paid to you or do you just deliver the half/nearly completed source code and help them find someone else to complete it?
The reason I am asking the above questions is because I am very new to freelancing and would like to know how to deal with the above situations if they ever crop up.
Thanks! | 2011/01/06 | [
"https://softwareengineering.stackexchange.com/questions/34095",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/12490/"
] | >
> If you agree to take on a project... work on and charge £X per hour - are you obligated to work for free after those 10 days are up and you have still not managed to complete your project due to unanticipated issues?
>
>
>
No. £X per hour is £X per hour. Clearly, you've never had complex jobs done on your home or boat.
Inability to estimate means nothing. Nothing.
£X per hour is £X per hour. Until the job is done or the client says "you're fired." (or "you're sacked". I'm a Yank, so I don't know what they say in the UK.)
>
> What if you have delivered the project but bugs are found - should you fix these bugs for free if the 10 days are up or should you charge your client?
>
>
>
Depends on the bug. You **must** do root cause analysis. Bad (or incomplete) specification is mostly their problem. Unanticipated technical wrinkles is par for the course -- they pay. Dumb coding mistakes is your problem.
>
> you have to give up and tell your client that you cannot do it anymore?
>
>
>
Ooops. That's unprofessional. If you have to give up, you've really made a terrible, terrible mistake.
>
> I realise that this does nothing to build your reputation and relationship with the client but are you obligated to pay back the money paid to you or do you just deliver the half/nearly completed source code and help them find someone else to complete it?
>
>
>
Sigh. At this point, you've behaved so poorly that nothing much matters. You should really find another career if you can't follow through on your contracts. Seriously. Rethink your life.
Half-completed software is worthless. No one will "complete it". They'll explain that you're an idiot (because you are) throw your code away and start again from scratch.
You need to do the following.
1. Cut the requirements back to something final, deliverable, and usable.
2. Create that final, deliverable, usable thing. Even if it's not the original grand scheme.
3. Charge for that deliverable, usable thing.
4. Transition the backlog of undeliverable stuff to someone else.
Code that cannot be used is useless. Indeed, it's a cost.
You and your customer will waste time trying to "transition" the half-completed code to someone else. Emphasis on **waste**. It's easier for most people to start from scratch than to start from half-finished. | Legal reasons aside, this is a service business after all and you live and you die by references. It can only take one bad one to give you a bad rep. I can only take one really satisfied customer to give you lot's of other work. So apply the golden rule, treat your customer as you'd like to be treated, within reason. People remember and value people who go a little above and beyond their "duty". |
94,615 | I have only one VPS with Windows Server 2008 R2 x64 and want to buy an Antivirus. I tried NOD32 but they do not give less than 5 users in business edition (I have only one server). Kaspersky may be another solution but whether should i go for Internet Security or Anti-virus?
I have few website hosted on this server and user have ability to upload .jpg, .gif, .zip files in few of the folders.
Apart from above two any other suggestions on Antivirus that works well on above configuration and available for only one user?
Thanks | 2009/12/15 | [
"https://serverfault.com/questions/94615",
"https://serverfault.com",
"https://serverfault.com/users/-1/"
] | I always liked ClamWin. May or may not meet your requirements though. It doesn't scan everything all the time, so performance is better, but that might be something you need. Interestingly enough, I see it performed horribly on an AV "roundup" test a few months ago, but the previous year it was a top performer. Not sure about the status at this time though. I'm pretty suspicious of those tests though. | Personally I like AVG, and you can buy it on a per machine basis. The only downside is that from time to time when they update their scanner it requires a machine reboot so you have to schedule those for convenient times. |
145,231 | I've recently heard somebody answered "Yes, perhapsy."
Or could it be "perhapsee"?
Could this be used as a slang term for "perhaps"?
It happened in NYC area a few weeks ago. | 2014/01/09 | [
"https://english.stackexchange.com/questions/145231",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/22953/"
] | It sounds like a contraction of *perhaps so*
>
> A: Did they know where she was?
>
> B: Perhaps so --> Perhapsy
>
>
> A: Will he pass?
>
> B: Perhaps so --> Perhapsy
>
>
>
A possible spelling variation might be: *perhapsi* rather than *perhapsee*. It also reminds me of *pepsi*. Words ending in double e are rare in English although not unheard of, *committee* being one that springs to mind. | I would say it's most likely to be a personal or family idiom rather than slang. Some people like to play with language and come up with their own variants. For example, my own family calls milk "bookum bookum" (long story).
Yes, sometimes a term like that will catch on and become slang for a community (whether large or small). I'd say the "perhapsie" won't catch on fast, but you never know. |
259,639 | I have noticed that when riding in a train travelling at over 100 kmh$^{-1}$, a loud 'slap' can be heard when another train travelling at a similar speed passes in the opposite direction, followed by 'whooshing' as air is sheared between the two trains.
I was wondering what the source of this initial 'slapping' sound is, and whether it is emitted when the fronts of the trains level with each other, or when the front of the opposing train levels with your window?
Since the sound (in my experience) is never heard when watching two trains pass each other from the platform, I would guess that it is due to the sudden compression of air outside the window, generating a sound wave which can only be heard by people travelling with the trains. However I am still not sure about what the presence of **two trains** has to do with this: it cannot be heard when one just stands on a platform and watches a single train come past, even when the relative speed is similar to that which could be observed between two trains? What actually causes this sound? | 2016/06/03 | [
"https://physics.stackexchange.com/questions/259639",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/105680/"
] | I hear this regularly. I think its a combination of the effects above. The first effect is a front of compressed air being forced ahead of each of the trains. But then, as the fronts of the trains meet and pass, the Bernoulli effect leads to *lower* pressure between the trains. But this isn't uniform, each carriage has its own mini air front, and the carriages have numerous windows and doors, giving numerous ins and outs.
The result is that intermingled high and low pressure air waves are being forced into and between carriages where the cross section of the space also varies rapidly, and this causes peak and trough air pressures which impact less-than-solid sides and the windows and doors which can move in and out.
So what you hear is a large bang as the train fronts meet; lesser bangs at each carriage; doors and windows thumped in and out in a rhythmic pattern related to the passage of very similar carriages in sequence by varying air pressure; and so on. | It is worth to mention two things.
1. Sound is pressure wave traveling in air.
2. When train is in motion, it brings motion to the air by the train. And when air velocity increases, the air pressure decreases based (can be seen in Bernoulli equation).
When two trains move opposite to each other, the air flow is enough stronger if it is not doubled. The pressure is lower. The flow is turbulent and the pressure is not evenly distributed in space between two trains. So that you can hear slapping. |
50,306,020 | I want to replace a string by removing the s in the end
Example
```
Sticks -> Stick
STiCKs -> STiCK
StICks -> StICK
sticks -> stick
```
while using the
```
string.replace("sticks", "stick");
```
doesn't maintain case as it is case sensitive, so I'm seeking for a better option. | 2018/05/12 | [
"https://Stackoverflow.com/questions/50306020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8189364/"
] | You could use a very simple regex for this mission.
`(?i)` guarantees that your regex will be treated case insensitive
[**Demo : `(?i)(stick)s`**](https://regex101.com/r/SwTTCP/1/)
[**Ideone Java Demo**](https://ideone.com/SGFWdR)
```
string.replaceAll("(?i)(stick)s", "$1");
``` | I don't really get why all the answers so far are so complex. You can just check the last character and if it's a `s` (or `S`) you use `String#substring` ([documentation](https://docs.oracle.com/javase/10/docs/api/java/lang/String.html#substring(int,int))) and leave out the last character:
```
String text = "STiCks";
char lastCharacter = text.charAt(text.length() - 1);
if (lastCharacter == 'S' || lastCharacter == 's') {
text = text.substring(0, text.length() - 1);
}
```
---
If you want to apply that method to multiple words, for example in a sentence, tokenize the sentence first. Then apply the method to each word and rebuild the sentence.
```
String sentence = StiCks are nice, I like sticks"
String[] words = sentence.split(" ");
StringJoiner joiner = new StringJoiner(" ");
for (String word : words) {
joiner.add(removePluralSuffix(word));
}
String result = joiner.toString();
```
or the same with Streams:
```
String result = Arrays.stream(sentence.split(" "))
.map(this::removePluralSuffix)
.collect(Collectors.joining(" "));
``` |
4,633,053 | In the quadrilateral ABCD, side AD is equal to side BC, and lines AD and BC intersect at point E. Points M and N are the midpoints of sides AB and CD, respectively. Prove that the segment MN is parallel to the bisector of $\angle{AEB}$
This has a very "easy" synthetic solution which involves constructing the midpoint of lets say diagonal AC and doing further reasoning which will not be included in this post.
I personally don't like this solution as it is very hard to find without previously encountering such problems and not quite intuitive.
I have tried using polar coordinates to encode the angle bisector condition but I am not sure how to do so for the equal segments and further finish the problem.
I will be very grateful if someone provides me a hint or even a solution :D (any analytic approach would do I just figured out complex was the most suitable) | 2023/02/05 | [
"https://math.stackexchange.com/questions/4633053",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/1089102/"
] | Since $(1+x)^n = \sum\_{k=0}^n \binom{n}{k}x^k$, differentiate twice to get
$$n(n-1)(1+x)^{n-2} = \sum\_{k=2}^n k(k-1)\binom{n}{k}x^{k-2}$$
Substituting $n+1$ for $n$ we also get
$$(n+1)n(1+x)^{n-1} = \sum\_{k=2}^{n+1} k(k-1)\binom{n+1}{k}x^{k-2}.$$
Substitute $x=1$ in each of these, giving
\begin{align\*}
n(n-1)2^{n-2} &= \sum\_{k=2}^n k(k-1)\binom{n}{k} \\
n(n+1)2^{n-1} &= \sum\_{k=2}^{n+1} k(k-1)\binom{n+1}{k}.
\end{align\*}
Subtract the first of these from the second, giving
\begin{align\*}
\tag{\*}2^{n-2}n(2(n+1)-(n-1)) &= \sum\_{k=2}^{n+1}k(k-1)\left(\binom{n+1}{k}-\binom{n}{k}\right)\\
&= \sum\_{k=2}^{n+1}k(k-1)\binom{n}{k-1}.
\end{align\*}
Finally, this gives
$$\sum\_{k=1}^{n}k(k-1)\binom{n}{k-1} = n2^{n-2}(n+3) - n(n+1)$$
since the summand of (\*) is zero for $k=1$ and is $n(n+1)$ for $k=n+1$. The right-hand side indeed simplifies to
$$n((n-1)(2^{n-2}-1)+2^n-2).$$ | Start with
$$
(1+x)^n=\sum\_{k=0}^n \binom nk x^k
$$
First, multiply both sides by $x$:
$$
x(1+x)^n=\sum\_{k=0}^n \binom nk x^{k+1}=\sum\_{k=1}^{n+1}\binom{n}{k-1}x^k
$$
*Now* you can differentiate twice, then set $x=1$, to recover your sum.
$$
\frac{\mathrm d^2}{\mathrm dx^2}\,x(1+x)^n=\sum\_{k=1}^{n+1}\binom{n}{k-1}\cdot k\cdot (k-1)\cdot x^{k-2}
$$
$$
\frac{\mathrm d^2}{\mathrm dx^2}\,x(1+x)^n\Bigg|\_{x=1}=\sum\_{k=1}^{\color{red}{n+1}}k(k-1)\binom{n}{k-1}
$$
There is one slight problem; the upper limit for the sum we derived is $n+1$, but for the desired sum, the upper limit is $n$. This is fixed by pulling out the $k=n+1$ term from the sum.
$$
\frac{\mathrm d^2}{\mathrm dx^2}\,x(1+x)^n\Bigg|\_{x=1}=\binom{n}{n}\cdot (n+1)n+\sum\_{k=1}^{\color{blue}{n}}k(k-1)\binom{n}{k-1}
$$
Now the sum you want has appeared, so you can solve for it and are done (after you compute the second derivative and plug in one). |
31,013,807 | I have a working function implementation in `c` that requires a large locally allocated chunk of memory as a working space. This function gets called a lot in succession where it is guaranteed that the required amount of working space does not change. To optimize the function I have refactored it to allocate a static single continuous piece of memory the first time it is called, that is only released when it is asked to. It looks something like this
```
void worker(struct* ptr, size_t m) {
static double *stack;
static size_t sz_stack;
static double *alpha;
static double *delta;
if (!ptr) {
if (stack) {
free(stack);
}
stack = NULL;
sz_stack = 0;
return;
}
if (!stack) {
sz_stack = 2*m;
stack = calloc(sz_stack, sizeof(*stack));
if (stack==NULL)
// Error and cleanup
alpha = stack;
delta = alpha + m;
}
// Do work using alpha and delta as arrays
return;
}
```
The caller can call this function successively where `ptr` will hold the final result as long as the problem size given by `m` does not change. When the caller is done with the function, or the problem size changes, he calls `worker(NULL, 0);` and the allocated memory will be freed.
I am now working on rewriting this codebase to `c++` and as the best practices tell me I have used individual `std::vector` for `alpha` and `delta` instead of the contiguous `stack`. However, profiling revealed that there is a huge bottleneck as the `std::vector` containers are allocated and free'd each and every function call.
My question now is:
*What is the modern `c++` way to maintain a contiguous piece of working space for a function in between calls?* | 2015/06/23 | [
"https://Stackoverflow.com/questions/31013807",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1628893/"
] | If it is guaranteed that the required working space will not be changing during contiguous function calls (as you mentioned), to me it seems the simplest solution would be to use a static array (somewhat similar to your C code, but using 'new' and 'delete[]' instead of 'calloc' and 'free'). | static is a dreadful thing because it plays really badly with thread safety and is wholly unnecessary.
The modern way is one of the following:
Declare the memory further up on the stack. vector<> or array<> or even malloc if you like. Pass a pointer (or, equivalently, reference) to this memory into your function.
```
int main()
{
vector<double> storage;
while (1)
{
worker(&storage,0,0);
}
return 0;
}
```
Or, write your function as a member of a class. Declare the memory as a member of your class. Create one instance of your class, then call the function repeatedly:
```
struct oo_hack
{
void worker (struct* ptr, size_t m)
{
// Do some things using storage
}
vector<double> storage;
}
int main()
{
oo_hack myhack; // This is on the stack, but has a vector inside
while (1)
{
myhack.worker(0,0);
}
return 0;
} // memory gets freed here
```
I'd suggest declaring the memory further up on the stack and passing it into the functions, but you may prefer the second. |
21,362,257 | This is the code I am using within my html file
```
<? if (empty($_POST["name"]) || empty($_POST["gender"]) || empty($_POST["dorm"]): ?>
You must provide your name, gender, and dorm! Go <a href="froshims2.php">back</a>.
<? else: ?>
You are registered! (Well, not really.)
<? endif ?>
```
I get a error saying:
>
> Parse error: syntax error, unexpected ':' in
> /home/jharvard/vhosts/localhost/public/week2/register2.php on line 20
>
>
>
I don't understand why this form of if else is not working | 2014/01/26 | [
"https://Stackoverflow.com/questions/21362257",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1681338/"
] | Missing closing bracket on this line
```
<? if (empty($_POST["name"]) || empty($_POST["gender"]) || empty($_POST["dorm"]): ?>
```
Should be
```
<? if (empty($_POST["name"]) || empty($_POST["gender"]) || empty($_POST["dorm"])): ?>
```
note the last bracket after `$_POST['dorm']` | you are missing one `)` at the end of your if statement and a semicolon after `endif`:
```
<? if (empty($_POST["name"]) || empty($_POST["gender"]) || empty($_POST["dorm"])): ?>
You must provide your name, gender, and dorm! Go <a href="froshims2.php">back</a>.
<? else: ?>
You are registered! (Well, not really.)
<? endif; ?>
``` |
2,052,684 | Hey, my friends and I are trying to beat each other's runtimes for generating "[Self Numbers](http://en.wikipedia.org/wiki/Self_number)" between 1 and a million. I've written mine in c++ and I'm still trying to shave off precious time.
Here's what I have so far,
```
#include <iostream>
using namespace std;
bool v[1000000];
int main(void) {
long non_self = 0;
for(long i = 1; i < 1000000; ++i) {
if(!(v[i])) std::cout << i << '\n';
non_self = i + (i%10) + (i/10)%10 + (i/100)%10 + (i/1000)%10 + (i/10000)%10 +(i/100000)%10;
v[non_self] = 1;
}
std::cout << "1000000" << '\n';
return 0;
}
```
The code works fine now, I just want to optimize it.
Any tips? Thanks. | 2010/01/12 | [
"https://Stackoverflow.com/questions/2052684",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/131383/"
] | Generate the numbers once, copy the output into your code as a gigantic string. Print the string. | Since the range is limited (1 to 1000000) the maximum sum of the digits does not exceed 9\*6 = 54. This means that to implement the sieve a *circular buffer of 54 elements* should be perfectly sufficient (and the size of the sieve grows very slowly as the range increases).
You already have a sieve-based solution, but it is based on pre-building the full-length buffer (sieve of 1000000 elements), which is rather inelegant (if not completely unacceptable). The performance of your solution also suffers from non-locality of memory access.
For example, this is a possible very simple implementation
```
#define N 1000000U
void print_self_numbers(void)
{
#define NMARKS 64U /* make it 64 just in case (and to make division work faster :) */
unsigned char marks[NMARKS] = { 0 };
unsigned i, imark;
for (i = 1, imark = i; i <= N; ++i, imark = (imark + 1) % NMARKS)
{
unsigned digits, sum;
if (!marks[imark])
printf("%u ", i);
else
marks[imark] = 0;
sum = i;
for (digits = i; digits > 0; digits /= 10)
sum += digits % 10;
marks[sum % NMARKS] = 1;
}
}
```
(I'm not going for the best possible performance in terms of CPU clocks here, just illustrating the key idea with the circular buffer.)
Of course, the range can be easily turned into a parameter of the function, while the size of the curcular buffer can be easily calculated at run-time from the range.
As for "optimizations"... There's no point in trying to optimize the code that contains I/O operations. You won't achieve anything by such optimizations. If you want to analyze the performance of the algorithm itself, you'll have to put the generated numbers into an output array and print them later. |
28,958,973 | I have a little problem that I'd love to solve on my website.
Have a look at this JSFIDDLE — <https://jsfiddle.net/sm25t089/>
This is the javascript code:
```
$(document).ready(function () {
$(".bottoni").hide();
$(".reveal").click(function () {
$(this).toggleClass("active").next().slideToggle(200, "linear");
if ($.trim($(this).text()) === '(+)') {
$(this).text('(×)');
} else {
$(this).text('(+)');
}
return false;
});
$("a[href='" + window.location.hash + "']").parent(".reveal").click();
});
```
I'd love the menu to move from out-of-the-screen to the left, to the right, instead the actual bottom to top.
Thanks for the help.
F. | 2015/03/10 | [
"https://Stackoverflow.com/questions/28958973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2175150/"
] | here is one solution using css3
```
transition:0.3s;
```
<https://jsfiddle.net/sm25t089/1/>
if you prefer using only ccs2 then you can do the same with a jquery animate | You can use the jQuery method **[.animate()](http://api.jquery.com/animate/)**
```
(function($) {
$(document).off("click.slide").on("click.slide", ".reveal", function (e) {
var $self = $(this),
$menu = $(".bottoni"),
isActive;
e.preventDefault();
$self.toggleClass("active");
isActive = $self.hasClass("active");
$self.text(isActive ? "(x)" : "(+)");
$menu.animate({
"left": isActive ? "21px" : "-100px"
}, 200, "linear");
});
})(jQuery);
```
Here are a JSFiddle with the sample: **<https://jsfiddle.net/sm25t089/3/>** |
17,033,694 | Following a Microsoft hands-on lab for Dynamics CRM 2011, I am attempting to add a custom view to a form that responds 'onchange' to a particular property. Here is my function to add the custom view:
```
function HandleOnChangeDVMInformationLookup()
{
var locAttr = Xrm.Page.data.entity.attributes.get("new_referringdvm");
if (locAttr.getValue() != null)
{
var dvmId = locAttr.getValue()[0].id;
var viewDisplayName = "DVM Information";
var viewIsDefault = true;
var fetchXml = '<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false"><entity name="dvminformation"><attribute name="dvminformation_id"/><attribute name="dvminformation_name"/><attribute name="new_firstname"/><attribute name="new_lastname"/><filter type="and"><condition attribute="id" operator="eq" value="' +dvmId +'"/></filter></entity></fetch>';
var layoutXml = '<grid name="resultset" object="10001" jump="dvminformation_name" select="1" icon="1" preview="1"><row name="result" id="dvminformation_id"><cell name="dvminformation_name" width="300" /><cell name="new_firstname" width="125"/></row></grid>';
var control = Xrm.Page.ui.controls.get("new_dvm_information");
control.addCustomView("62e0ee43-ad05-407e-9b0b-bf1f821c710e", "dvminformation", viewDisplayName, fetchXml, layoutXml, viewIsDefault );
}
}
```
Upon changing the selected 'dvm' in the form and triggering this function I receive the following error:
>
> Unhandled Exception: System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]: The entity with a name = 'dvminformation' was not found in the MetadataCache.Detail:
>
> -2147217150
>
> The entity with a name = 'dvminformation' was not found in the MetadataCache.
> 2013-06-10T22:01:49.4392114Z
>
>
>
>
>
>
Is 'dvminformation' not the entity name I just defined in the XML? Am I missing a step?
Thanks. | 2013/06/10 | [
"https://Stackoverflow.com/questions/17033694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1144073/"
] | I had the same error message with the customerAddress entity.
Turns out I referenced the entity as `"customerAddress"` (note the camel case).
But CRM wants logical names of entities and attributes in all lower case. So `"customeraddress"` did work. | Check if you are connecting to correct org (web.config?)
[See](https://community.dynamics.com/crm/f/117/t/208316) |
632,854 | I wanted to calculate the inverse function of
$$
f(x) = \frac{1}{x} + \frac{1}{x-1}
$$
Quite simple I thought, put
$$
y = \frac{1}{x} + \frac{1}{x-1} = \frac{2x-1}{x(x-1)}
$$
rearrange and solve
$$
y(x(x-1)) - 2x + 1 = 0
$$
which give the quadratic equation
$$
yx^2 - (y + 2)x + 1 = 0
$$
Using the [Solution Formula](http://en.wikipedia.org/wiki/Quadratic_formula) we got
$$
x = \frac{(y+2) \pm \sqrt{y^2+4}}{2y}
$$
So the inverse function is
$$
f^{-1}(x) = \frac{(x+2) \pm \sqrt{x^2+4}}{2x}
$$
Just to confirm I put in [WolframAlpha](http://www.wolframalpha.com/input/?i=inverseFunction%281/x%20%2b%201/%28x-1%29%29) and it gives me
$$
\frac{-x-2}{2x} \pm \frac{\sqrt{x^2+4}}{2x}
$$
(just click on the link to start WolframAlpha with this parameter), which
is different up to a sign in the first summand, can not see an error, do you (or is WolframAlpha wrong...)?
*EDIT*: If the link is not working for you:
 | 2014/01/09 | [
"https://math.stackexchange.com/questions/632854",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/33817/"
] | Nothing wrong with your answer! Actually Wolfram's answer is wrong! Just check it by $x=3/2$ in wolfram's inverse. | Your error is in the solution formula. You have $(y+2)^2 - 4\cdot y\cdot 1 = y^2+4 \neq (y+2)(y-2)$. It would be $y^2-4 = (y+2)(y-2)$. |
11,856,036 | In an Android book I have it says that themes can be applied to and entire activity or an entire application. It doesn't show how but the Android docs say to simply put the theme statement into the androidmanifest.xml file like so....
```
<application android:icon="@drawable/ic_launcher">
<activity android:theme="@style/bigred" . . . .
```
but it doesn't work. Only the application bar is styled with the big red type and the text in other widgets is not styled at all. How is this supposed to be done?
Also the docs say that to see what styles are available from Android to read the code! Any better docs than this? | 2012/08/08 | [
"https://Stackoverflow.com/questions/11856036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1058647/"
] | See [this fiddle](http://jsfiddle.net/94RuA/2/)
You must do the job in the `change` event.
then calling `.trigger('change')` on the check boxes make the div show/hide on the initial page load.
The code :
```
$(document).ready(function(){
$('input#upload_yes').change(function(){
if($(this).is(':checked')) {
$("#upload_form").show();
} else {
$("#upload_form").hide();
}
});
$('input#new_info_yes').change(function(){
if($(this).is(':checked')) {
$("#new_info_form").slideDown(500);
} else {
$("#new_info_form").hide();
}
});
//Trigger the change event so the divs are initially shown or hidden.
$('input[type=checkbox]').trigger('change');
});
``` | You aren't binding this code to the proper event:
```
$(document).ready(function() {
$("#upload_yes").on('change', function() {
if ($(this).is(':checked')) {
$("#upload_form").show();
$("#new_info_form").slideDown(500);
} else {
$("#upload_form, #new_info_form").hide();
}
});
});
``` |
24,060,016 | We have a requirement where we need to crawl one particular set of URLs.
Say for example we have site abc.com. We need to crawl abc.com/test/needed -- all URL matching this pattern under "needed" folder. But we don't want to crawl rest of the URLs under abc.com/test/.
I guess this will be done using RegEx. Can anyone help me with respect to RegEx? | 2014/06/05 | [
"https://Stackoverflow.com/questions/24060016",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1085906/"
] | You need to call (P/Invoke) `WinVerifyTrust()` function from `wintrust.dll`. There is (as far as I know) no alternative in managed .NET.
You can find documentation of this method [here](http://msdn.microsoft.com/en-us/library/aa388208.aspx).
Someone already asked this question on SO. It was not accepted, but it should be correct (I only scrolled through). [Take a look.](https://stackoverflow.com/a/6597017/3245057)
You could also take a look at [this guide](http://www.pinvoke.net/default.aspx/wintrust.winverifytrust) but they really do the same. | To validate the integrity of the signed .exe file, we can use StrongNameSignatureVerificationEx method:
```
[DllImport("mscoree.dll", CharSet = CharSet.Unicode)]
public static extern bool StrongNameSignatureVerificationEx(
string wszFilePath, bool fForceVerification, ref bool pfWasVerified);
var assembly = Assembly.GetExecutingAssembly();
bool pfWasVerified = false;
if (!StrongNameSignatureVerificationEx(assembly.Location, true, ref pfWasVerified))
{
// it's a patched .exe file!
}
```
But it's not enough. It's possible to remove the signature and then apply/re-create it again! (there are a lot of tools to do that) In this case you need to store the public key of your signature somewhere (as a resource) and then compare it with the new/present public key. [more info here](http://blogs.msdn.com/b/shawnfa/archive/2004/06/07/150378.aspx) |
45,934,970 | My question is "Is there a way to avoid sending callbacks deep in the tree when I want to access/react upon child components data".
I have a component `Application` that contains a child component `Person` which in turn contains a child component `TraitCollection` which in turn contains a child component `Trait`.
When `Trait` is changed I want to send data back to `Application` to be forwarded to another child in `Application` named `PersonList`.
My current solution is to send callbacks as props to each child. Each callback function constructs and appends the data which finally reaches `Application` where I pass it down as a prop to `PersonList`.
I can imagine that "adding more levels", or splitting components up in more smaller parts will further complicate this callback chain.
Is there any other way to do this or is this the best way to handle passing data from children to parents in React? | 2017/08/29 | [
"https://Stackoverflow.com/questions/45934970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4958802/"
] | The way you are handling it is the **recommended** way and the most React-like. There is nothing wrong with that approach by itself other than the problem you have found. It looks like [Redux](http://redux.js.org/docs/introduction/) could help you solve that problem. Redux lets you unify the state of your React application with the usage of a common store and a good design pattern based on action creators, actions and reducers. | To avoid **Deep** `Callbacks`, according to [React](https://reactjs.org/docs/hooks-faq.html) documentation, [useReducer](https://reactjs.org/docs/hooks-reference.html#usereducer) via `context` as below:
**How to avoid passing callbacks down?**
We’ve found that most people don’t enjoy manually passing `callbacks` through every level of a component tree. Even though it is more explicit, it can feel like a lot of “`plumbing`”.
In large component trees, an alternative we recommend is to pass down a `dispatch` `function` from [useReducer](https://reactjs.org/docs/hooks-reference.html#usereducer) via `context`:
```
const TodosDispatch = React.createContext(null);
function TodosApp() {
// Note: `dispatch` won't change between re-renders
const [todos, dispatch] = useReducer(todosReducer);
return (
<TodosDispatch.Provider value={dispatch}>
<DeepTree todos={todos} />
</TodosDispatch.Provider>
);
}
```
Any `child` in the tree inside `TodosApp` can use the `dispatch` `function` to pass actions up to `TodosApp`:
```
function DeepChild(props) {
// If we want to perform an action, we can get dispatch from context.
const dispatch = useContext(TodosDispatch);
function handleClick() {
dispatch({ type: 'add', text: 'hello' });
}
return (
<button onClick={handleClick}>Add todo</button>
);
}
```
This is both more convenient from the maintenance perspective (no need to keep forwarding `callbacks`), and avoids the `callback` problem altogether. Passing `dispatch` **`down`** like this is the recommended pattern for **`deep`** **`updates`**. |
69,036,319 | I just started to learn python yesterday so complete noob. I have about 10 hours javascript experience to but had to switch since I'm learning Python in college. I decided to try make a program by myself since I learn a lot better doing that instead of countless videos.
The major problem I'm having is saving my variable of balance. When I win or lose the balance just restarts at 2000. I think that's probably because of the variable `balance = 2000` but if I don't define it, it doesn't work. I know it's not anything important but I want to learn where I'm going wrong.
If anyone can help me that would be much appreciated. Also I know the codes a mess but will try make it better later.
```
global balance
name = input ("Please Enter Your Name: ")
password = input ("Please Make A Password: ")
def playgame():
balance = 2000
yesOrNo = input("Would You Like To Put A Bet on Y/N?; ")
if yesOrNo == "y":
howBigABet = int(input("How Much Would You like to bet?: "))
if howBigABet <= balance:
pickNumber = int(input("Please PicK A Number: "))
from random import randint
value = randint(0, 1)
print(value)
if pickNumber == value:
print(value)
balance = balance + howBigABet * 2
print("you won " + str(howBigABet * 2))
print(balance)
playgame()
else:
print ("Sorry Wrong Number")
balance = balance - howBigABet
print("your new balance is: " + str(balance))
playgame()
if balance <= 200:
print("You Are Low on Cash Top up?")
elif balance <= 0:
print("You Are Out Of cash " + name + " Top Up ")
playgame()
else:
print("Sorry You Dont Have Enough Money")
print("Hello " + name)
passwordAttempted = input("Please Enter Your Password: ")
if passwordAttempted == password:
print("Welcome " + name)
playgame()
else:
print ("Wrong Password " + name + " !")
``` | 2021/09/02 | [
"https://Stackoverflow.com/questions/69036319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16817699/"
] | Since `balance` is local to the function `playgame()` every time the function is called, the variable will be reset. You can fix this problem a couple of ways. You can make `balance` a global variable, or you can add a loop where the function doesn't return after one execution. The second example I gave would look something like this:
```
global balance
name = input ("Please Enter Your Name: ")
password = input ("Please Make A Password: ")
def playgame():
balance = 2000
yesOrNo = input("Would You Like To Put A Bet on Y/N?; ")
while yesOrNo == "y":
howBigABet = int(input("How Much Would You like to bet?: "))
if howBigABet <= balance:
pickNumber = int(input("Please PicK A Number: "))
from random import randint
value = randint(0, 1)
print(value)
if pickNumber == value:
print(value)
balance = balance + howBigABet * 2
print("you won " + str(howBigABet * 2))
print(balance)
yesOrNo = input("Would You Like To Put A Bet on Y/N?; ")
continue
else:
print ("Sorry Wrong Number")
balance = balance - howBigABet
print("your new balance is: " + str(balance))
yesOrNo = input("Would You Like To Put A Bet on Y/N?; ")
continue
if balance <= 200:
print("You Are Low on Cash Top up?")
elif balance <= 0:
print("You Are Out Of cash " + name + " Top Up ")
yesOrNo = input("Would You Like To Put A Bet on Y/N?; ")
continue
else:
print("Sorry You Dont Have Enough Money")
print("Hello " + name)
passwordAttempted = input("Please Enter Your Password: ")
if passwordAttempted == password:
print("Welcome " + name)
playgame()
else:
print ("Wrong Password " + name + " !")
``` | The first thing `playgame` does is set your balance to 2000, so it's always going to be 2000 at the beginning of a game. This is happening because you restart a new game by calling `playgame()` *from within `playgame`.* This is called recursion. It's a powerful tool that has a lot of uses, but this is probably not the best use of it. Among other things, when a game ends, it's going to return to where it was in the previous game, and pick up executing the next statement after `playgame()`. (You don't have anything like that in your current code, but the moment you do, you'll get confused. In short, `playgame()` is not a simple "go back to the beginning" command.)
So one way to address this is to change the main structure of your function to a loop. After `balance = 2000` add:
```
while True:
```
and indent the rest of the function under that statement.
Wherever you have `playgame()` within the `playgame` function, change it to `continue`. This will cause the program to go back to the beginning of the `while` loop.
Since `balance = 2000` is not within the loop, it will be executed once and will not be re-executed for subsequent games.
Another way to solve the problem (keeping the recursion) is to move the initialization of `balance` outside the loop, say to right after you ask for the user's name and password. In the `playgame` function, replace `balance = 2000` with `global balance`. This way, the variable is not local to the function and will retain its value from call to call.
Finally, you could make the game a class rather than a standalone function. This way, `balance` can be an attribute of the object rather than a local variable to your function, but still not a global. (Global variables are generally a bad idea, especially as your code gets more complex, because they make it difficult to keep track of every piece of the data the function uses to do its job.) This is probably the best way to do it long-term, but you'll need to learn a bit more about programming before you tackle that. |
7,458,291 | I have an AutoCompleteTextView in my layout. I also have an alternative way to select the same items which are present in the AutoCompleteTextView. When the alternative way is selected, I populate the value in the AutoCompleteTextView via:
```
autoCompleteTextView.setText(valueFromAlternativeSource);
```
where `valueFromAlternativeSource` is one of the valid auto complete options. The trouble with this is that the autocomplete dropdown appears when setText is called. Putting the following line after the above doesn't work:
```
autoCompleteTextView.dismissDropDown(); //Doesn't work. Why?
```
Any ideas on why dismiss dropdown isn't working or other ways I could dismiss the dropdown? | 2011/09/17 | [
"https://Stackoverflow.com/questions/7458291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/296108/"
] | If you want to support API<17, Subclass AutoCompleteTextview and override `setText(text, filter)` method
```
@Override
public void setText(CharSequence text, boolean filter) {
if(Build.VERSION.SDK_INT>=17) {
super.setText(text, filter);
}else{
if(filter){
setText(text);
}else{
ListAdapter adapter = getAdapter();
setAdapter(null);
setText(text);
if(adapter instanceof ArrayAdapter)
setAdapter((ArrayAdapter) adapter);
else
setAdapter((CursorAdapter) adapter);
//if you use more types of Adapter you can list them here
}
}
}
```
Then whenever you want to set the text manually call `setText(text, false)` | ```
autoCompleteTextView.setText(valueFromOtherMeans, filter);
* @param filter If <code>false</code>, no filtering will be performed
* as a result of this call.
``` |
124,454 | The Gemmorah teaches us that we could learn basic morality from the animal kingdom ([Eruvin.100b.29, see also 28](https://www.sefaria.org.il/Eruvin.100b.29?vhe=William_Davidson_Edition_-_Vocalized_Aramaic&lang=bi&with=Rashi&lang2=en)):
>
> אָמַר רַבִּי יוֹחָנָן: אִילְמָלֵא לֹא נִיתְּנָה תּוֹרָה, הָיִינוּ לְמֵידִין צְנִיעוּת מֵחָתוּל, וְגָזֵל מִנְּמָלָה, וַעֲרָיוֹת מִיּוֹנָה. דֶּרֶךְ אֶרֶץ מִתַּרְנְגוֹל — שֶׁמְּפַיֵּיס וְאַחַר כָּךְ בּוֹעֵל.
>
>
>
>
> Similarly, Rabbi Yoḥanan said: Even if the Torah had not been given, we would nonetheless have learned modesty from the cat, which covers its excrement, and that stealing is objectionable from the ant, which does not take grain from another ant, and forbidden relations from the dove, which is faithful to its partner, and proper relations from the rooster, which first appeases the hen and then mates with it.
>
>
>
My basic question is - how do these manifestations of animal morality come about? Do the sages claim that animals possess basic morality, that they are subject to basic moral laws, maybe the 7 Noahide laws, or that their behavior is completely habitual, but we would interpret it as moral?
So here comes my second question:
In my understanding, we recognize that what cats do is moral only because the Torah teaches us so, and without such prior knowledge we couldn't differentiate between cats' and dogs' modesty.
In such situation, without divine guidance, how would we differentiate between moral and immoral animals? | 2021/07/28 | [
"https://judaism.stackexchange.com/questions/124454",
"https://judaism.stackexchange.com",
"https://judaism.stackexchange.com/users/15579/"
] | Note: The following is my opinion and is based primarily from the written Torah.
The Bible seems to take it for granted that animals naturally have some form of morality, wisdom/understanding, and holiness. In the story of Gan Eden the serpent is called the "most wise" of the animals, as if other animals are wise and the serpent simply happens to be the wisest. And when the snake sins, it is punished for its sin because *it should have known better*, just like Adam and Eve.
When we get to the flood story God beholds the whole earth and concludes that all flesh has become corrupt. Many commentaries limit this corruption to people, and limit it further to the corruption being the act of theft. This doesn't make sense on a peshat level because we know God is loathe to kill animals for no reason, for he says so very clearly in the book of Jonah.
Jonah 4:11
>
> יא וַאֲנִי לֹא אָחוּס, עַל-נִינְוֵה הָעִיר הַגְּדוֹלָה--אֲשֶׁר יֶשׁ-בָּהּ הַרְבֵּה מִשְׁתֵּים-עֶשְׂרֵה רִבּוֹ אָדָם, אֲשֶׁר לֹא-יָדַע בֵּין-יְמִינוֹ לִשְׂמֹאלוֹ, וּבְהֵמָה, רַבָּה. {ש} 11 11 And should I not have concern for the great city of Nineveh, in which there are more than a hundred and twenty thousand people who cannot tell their right hand from their left—**and also many animals?**
>
>
>
It seems to me that God has concluded that nearly the entire animal kingdom has become corrupt just like mankind, and therefore he will destroy people and animals who are guilty of the same sin. It's beyond the scope of this answer to discuss what this joint sin might be, but feel free to ask that question as a separate post if you wish.
To further the point that the Bible views morality and wisdom/understanding as intrinsic to animals is the fact that God not only feels compelled to destroy animal life with man, God also establishes a **covenant with animals** and men as *equal parties* which is something most commentaries gloss over. We know they are being treated as equal parties because covenants are agreed upon with words and then a physical representation is made. Think the big rock for the covenant with Jacob and Lavan, the copies of the stones of the ten commandments. Usually each party gets either their own copy or has access to the physical representation of the covenant. Both Laban and Jacob can go back to the stone pillar, we hold both copies of the 10 commandments (one set for us the other for God) but we place them in the holy of holies where God resides. In the case of this covenant the rainbow is given which is in heaven, but also visible to man and animals.
Genesis 6:11-13, 17-22
>
> יא וַתִּשָּׁחֵת הָאָרֶץ, לִפְנֵי הָאֱלֹהִים; וַתִּמָּלֵא הָאָרֶץ,
> חָמָס. 11 And the earth was corrupt before God, and the earth was
> filled with violence. יב וַיַּרְא אֱלֹהִים אֶת-הָאָרֶץ, וְהִנֵּה
> נִשְׁחָתָה: כִּי-הִשְׁחִית כָּל-בָּשָׂר אֶת-דַּרְכּוֹ, עַל-הָאָרֶץ.
> {ס} 12 And God saw the earth, and, behold, it was corrupt; for all
> flesh had corrupted their way upon the earth. {S} יג וַיֹּאמֶר
> אֱלֹהִים לְנֹחַ, קֵץ כָּל-בָּשָׂר בָּא לְפָנַי--כִּי-מָלְאָה הָאָרֶץ
> חָמָס, מִפְּנֵיהֶם; וְהִנְנִי מַשְׁחִיתָם, אֶת-הָאָרֶץ. 13 And God
> said unto Noah: 'The end of all flesh is come before Me; for the earth
> is filled with violence through them; and, behold, I will destroy them
> with the earth....... יז וַאֲנִי, הִנְנִי מֵבִיא אֶת-הַמַּבּוּל מַיִם
> עַל-הָאָרֶץ, לְשַׁחֵת כָּל-בָּשָׂר אֲשֶׁר-בּוֹ רוּחַ חַיִּים, מִתַּחַת
> הַשָּׁמָיִם: כֹּל אֲשֶׁר-בָּאָרֶץ, יִגְוָע. 17 And I, behold, I do
> bring the flood of waters upon the earth, to destroy all flesh,
> wherein is the breath of life, from under heaven; every thing that is
> in the earth shall perish. יח וַהֲקִמֹתִי אֶת-בְּרִיתִי, אִתָּךְ;
> וּבָאתָ, אֶל-הַתֵּבָה--אַתָּה, וּבָנֶיךָ וְאִשְׁתְּךָ וּנְשֵׁי-בָנֶיךָ
> אִתָּךְ. 18 But I will establish My covenant with thee; and thou
> shalt come into the ark, thou, and thy sons, and thy wife, and thy
> sons' wives with thee. יט וּמִכָּל-הָחַי מִכָּל-בָּשָׂר שְׁנַיִם
> מִכֹּל, תָּבִיא אֶל-הַתֵּבָה--לְהַחֲיֹת אִתָּךְ: זָכָר וּנְקֵבָה,
> יִהְיוּ. 19 And of every living thing of all flesh, two of every sort
> shalt thou bring into the ark, to keep them alive with thee; they
> shall be male and female. כ מֵהָעוֹף לְמִינֵהוּ, וּמִן-הַבְּהֵמָה
> לְמִינָהּ, מִכֹּל רֶמֶשׂ הָאֲדָמָה, לְמִינֵהוּ--שְׁנַיִם מִכֹּל
> יָבֹאוּ אֵלֶיךָ, לְהַחֲיוֹת. 20 Of the fowl after their kind, and of
> the cattle after their kind, of every creeping thing of the ground
> after its kind, two of every sort shall come unto thee, to keep them
> alive. כא וְאַתָּה קַח-לְךָ, מִכָּל-מַאֲכָל אֲשֶׁר יֵאָכֵל,
> וְאָסַפְתָּ, אֵלֶיךָ; וְהָיָה לְךָ וְלָהֶם, לְאָכְלָה. 21 And take
> thou unto thee of all food that is eaten, and gather it to thee; and
> it shall be for food for thee, and for them.' כב וַיַּעַשׂ, נֹחַ:
> כְּכֹל אֲשֶׁר צִוָּה אֹתוֹ, אֱלֹהִים--כֵּן עָשָׂה. 22 Thus did Noah;
> according to all that God commanded him, so did he.
>
>
>
Genesis 9:9-10
>
> ט וַאֲנִי, הִנְנִי מֵקִים אֶת-בְּרִיתִי אִתְּכֶם, וְאֶת-זַרְעֲכֶם,
> אַחֲרֵיכֶם. 9 'As for Me, behold, I establish My covenant with you,
> and with your seed after you; י וְאֵת כָּל-נֶפֶשׁ הַחַיָּה אֲשֶׁר
> אִתְּכֶם, בָּעוֹף בַּבְּהֵמָה וּבְכָל-חַיַּת הָאָרֶץ אִתְּכֶם; מִכֹּל
> יֹצְאֵי הַתֵּבָה, לְכֹל חַיַּת הָאָרֶץ. 10 and with every living
> creature that is with you, the fowl, the cattle, and every beast of
> the earth with you; of all that go out of the ark, even every beast of
> the earth.
>
>
>
So just to recap, God seems to want to destroy all flesh because all flesh is corrupt. And for those that haven't become corrupted (both man and animal), God is going to save them AND establish a covenant with both man and animal kind. So without getting into the detail of just how much morality or wisdom the animal kingdom has, the Bible takes for granted that both exist naturally in animals to such an extent that animals can be judged as sinners worthy of the death penalty, or redeemed and have covenants established with them. | In regards to the basic question, the Ben Yohada on that Gemara mentions in passing that these traits are natural to these species
>
> ונמצא דלמדין צניעות משני מדות טבעיות שבו
>
>
> |
21,239,137 | I've been breaking my head over the following problem.
I've got this array:
```
[596] => 2
[9] => 2
[358] => 2
[1579] => 1
[156] => 1
[576] => 1
[535] => 1
```
As you can see, the values are ordered in a descending way, but the keys are random. I would like to keys to be sorted DESC as well though. I've been playing with array\_multisort, but I haven't been able to fix the problem with it. The first problem that I encountered was the fact that array\_multisort reindexes numeric keys. I changed to keys to a non-numeric variant, namely k596 etc... That made me able to sort the keys, but not like I wanted it to.
```
[k9] => 2
[k596] => 2
[k358] => 2
[k576] => 1
[k535] => 1
[k1579] => 1
[k156] => 1
```
The result that I would like to see in the end is:
```
[k596] => 2
[k358] => 2
[k9] => 2
[k1579] => 1
[k576] => 1
[k535] => 1
[k156] => 1
```
Is anyone able to help me out here? There must be a simple way to do this, right? | 2014/01/20 | [
"https://Stackoverflow.com/questions/21239137",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1796440/"
] | place conditions touch down, touch up, and touch move in onTouchArea of sprite as follows:
```
public boolean onAreaTouched(TouchEvent event,float X,float Y){
if (event.getAction() == MotionEvent.ACTION_DOWN) {
spr.registerEntityModifier(new MoveXModifier(0.5f,spr.getX(),spr.getX()-10));
}
if (event.getAction() == MotionEvent.ACTION_UP) {
}
}
``` | It is better to use a PhysicsHandler to move the sprite with a velocity.Modifiers are not accessible until they finished, that is why your sprite wont again go further even you pressed the button.
Else if u want just simple continuous Movement u can simple increment the position of sprite.
```
@Override
public boolean onAreaTouched(TouchEvent event,float X,float Y)
{
if (event.getAction() == MotionEvent.ACTION_DOWN)
{
spr.setPosition(spr.getX()+1, spr.getY());
}
return true;
}
```
do same for left motion with spr.getX()-1 |
73,576 | If I select Radiance or Ambiance in the menu show in the following picture, my whole theme does not change. It only changes the title bar.
How can I resolve this problem? Or how can I reset the theme to default? | 2011/10/29 | [
"https://askubuntu.com/questions/73576",
"https://askubuntu.com",
"https://askubuntu.com/users/25456/"
] | Removing the file ~/.config/dconf/user solves the problem.
PS: To reconstruct the problem I made the following steps:
change in the file /etc/lightdm/unity-greeter.conf the line
```
font-name=Ubuntu 11
```
to
```
font-name=Ubuntu 10
```
and after saving run the command
```
lightdm --test-mode
```
That was all I modified yesterday. Now if you restart your session with CTRL+ALT+BACKSPACE and login again, your theme is ugly (like mine on the screen shot in my question). Can anyone verify this? | I had the same issue in Ubuntu 13.04. I just installed the [gnome-tweak-tool ](https://apps.ubuntu.com/cat/applications/gnome-tweak-tool) and changed the current theme under theme menu. It solved this. |
5,155,379 | I have a html snippet below which renders perfectly in all browsers. However in webkit on an iphone and ipad, when I pinch the page (so that its smaller), I see a black border which is the background color of the body shining through only on the right edge. This only happens when I specifiy the width of the .headerpic div. Since this is the only place in the document I specify the width, I was wondering why it stops short of rendering all the way to the right edge (since this is theoretically the widest part of the document?).
I've attached a photo of what it looks like from my ipad.
```
<!doctype html>
<html>
<head>
<style>
body {background-color:#000;color:#231f20;margin:0;}
#wrapper {background-color:#fff;min-height:1000px;}
#header .headerpic {height:102px;padding-top:80px;margin:0 auto;width:986px;}
#footer {color:#fff;}
</style>
</head>
<body>
<div id="wrapper">
<div id="header">
<div class="headerpic">
</div>
</div>
</div>
<div id="footer">
</div>
</body>
</html>
```
 | 2011/03/01 | [
"https://Stackoverflow.com/questions/5155379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/541744/"
] | In my case using:
```
<meta name="viewport" content="width=device-width, initial-scale=1.0">
```
Instead of:
```
<meta name="viewport" content="width=device-width">
```
Did the trick! | In my case this :
```
<meta name="viewport" content="width=device-width, initial-scale=1.0">
```
And :
```
html, body {min-width:980px; overflow-x: hidden;}
```
Fixes the problem. |
68,347,899 | I have got access token and expiry time as two columns in a JSON file after doing a POST request and stored the file in Blob storage.
Now I need to look inside the JSON file the I stored before and take the value of Access token and use it as a parameter to another REST request.
Please help... | 2021/07/12 | [
"https://Stackoverflow.com/questions/68347899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16431805/"
] | Using `awk`:
```
var=$(curl -v ...|awk -F ':' '/^X-Subject-Token/ {print $2}')
echo "$var"
``` | ```sh
# read the _lines_ of the header into an array
mapfile -t header < <(curl --head ...)
declare -A values
for h in "${header[@]}"; do
if [[ $h =~ ^([^:]+):" "(.*) ]]; then
values[${BASH_REMATCH[1]}]=${BASH_REMATCH[2]}
fi
done
declare -p values
echo "${values[X-Subject-Token]}"
```
Sometimes headers can span multiple lines or be encoded in a different charset, so this method is not infallible.
Also, header field names are case-insensitive, so you might want to do:
```sh
declare -l field # variable has lower-case attribute
for h in "${header[@]}"; do
if [[ $h =~ ^([^:]+):" "(.*) ]]; then
field=${BASH_REMATCH[1]}
value=${BASH_REMATCH[2]}
values[$field]=$value
fi
done
echo "${values[x-subject-token]}"
``` |
58,379,079 | I'm working on a homework set and I need some help. I have a list that looks like this:
```
list = [1, 2, [3, 4], 5]
```
The problem is asking me to use list slicing to extract the last element of the nested list. Can someone help me with this? | 2019/10/14 | [
"https://Stackoverflow.com/questions/58379079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12215024/"
] | ```
list_1 = [1, 2, [3, 4], 5]
new_list = [elem[-1] for elem in list_1 if isinstance(elem, list)]
print(new_list )
```
Output:
```
[4]
```
For getting the last element of a list please refer [here](https://www.geeksforgeeks.org/python-how-to-get-the-last-element-of-list/).
For list comprehension, see [here](https://www.geeksforgeeks.org/python-list-comprehension-and-slicing/) | If you're just trying to get one element, then you just need to get the index of that element. In this case the external list has 4 elements:
`Index 0 1 2 3`
`Value 1 2 [3,4] 5`
The internal list has 2 elements:
`Index 0 1`
`Value 3 4`
So what you need to do is get the index of the internal list, `2`, and the index of the last element in the internal list `1` or `-1` (index `-1` always gets the last element in a list):
`element = list[2][1]`
Note: `list` is a reserved keyword in python so do not use it for variable naming. |
31,318,333 | I am working on a project with directed graphs where the weight of the edges all depend on a variable x.
I'm trying to find the minimum value of x such that my graph does not contain any circuit of positive weight.
My question is -and it is probably pretty stupid but I don't see how- :
How can I use a modified Bellman-Ford to check for the presence of positive circuits instead of negative circuits ?
Thanks. | 2015/07/09 | [
"https://Stackoverflow.com/questions/31318333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5098619/"
] | thanks to everyone.my working answer is here
```
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
[login logInWithReadPermissions:@[@"email"] handler:^(FBSDKLoginManagerLoginResult *result, NSError *error)
{
if (error)
{
// Process error
}
else if (result.isCancelled)
{
// Handle cancellations
}
else
{
if ([result.grantedPermissions containsObject:@"email"])
{
NSLog(@"result is:%@",result);
if ([FBSDKAccessToken currentAccessToken])
{
NSLog(@"Token is available : %@",[[FBSDKAccessToken currentAccessToken]tokenString]);
[[[FBSDKGraphRequest alloc] initWithGraphPath:@"me" parameters:@{@"fields": @"id, name, link, first_name, last_name, picture.type(large), email, birthday, bio ,location ,friends ,hometown , friendlists"}]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error)
{
NSLog(@"resultis:%@",result);
}
else
{
NSLog(@"Error %@",error);
}
}];
}
//[login logOut];
}
}
}];
``` | Yes it is. You need to use `Facebook SDK` and it's `graph API`. You can take a look here:
[Getting started - Facebook SDK for iOS](https://developers.facebook.com/docs/ios)
Here is an example of code in Objective-C:
```
// For more complex open graph stories, use `FBSDKShareAPI`
// with `FBSDKShareOpenGraphContent`
/* make the API call */
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:@"/{friendlist-id}"
parameters:params
HTTPMethod:@"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
id result,
NSError *error) {
// Handle the result
}];
``` |
20,132,254 | I would like to create a select dropdown that contains all values from a column with each value only appearing once.
Is there a way to achieve this in JavaScript or jQuery assuming I have a basic HTML table and the column in question is columnA ? | 2013/11/21 | [
"https://Stackoverflow.com/questions/20132254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2571510/"
] | ```
function getNthColumn(n) {
var data = [],
i,
yourSelect,
unique;
$("#yourTable tr td:nth-child("+n+")").each(function () {
data.push($(this).text());
});
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
// Use this function if your table is not large as the time complexity is O(n^2)
unique = data.filter(function(item, i, arr) {
return i == arr.indexOf(item);
});
yourSelect = $('#yourSelect');
for (i = 0; i < unique.length; i += 1) {
yourSelect.append("<option>"+unique[i]+"</option>");
}
}
```
<http://jsfiddle.net/xaum3/2/> | Plain Javascript, ES6, easy:
```
const cells = [].slice.call(table.querySelectorAll('td.mycell')) //using slice to convert nodelist to array
const values = cells.map(cell => cell.textContent)
const distinct = [...new Set(values)]
``` |
7,189,803 | I have an index.php file in the top level with other files such as "login.php", "register.php" in a folder called includes. The folder hierarchy looks like this:
```
index.php
includes/
register.php
login.php
css/
style.css
images/
image.png
```
How can I set the url to something like <http://www.mydomain.com/register> which then from within the index.php page calls (includes) the register.php page?
Is this the best way to go about it?
Thanks
Mike | 2011/08/25 | [
"https://Stackoverflow.com/questions/7189803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/904570/"
] | using mod\_rewrite:
```
RewriteRule ^register index.php?page=register
RewriteRule ^login index.php?page=login
```
index.php:
```
<?php
include('includes/'.$_GET['pagename'].'.php');
?>
```
EDIT:
For security reasons, see also arnouds comment below. | You can write a .htaccess file with something like this:
```
RewriteEngine On
RewriteRule ^([a-z]+)/?$ /index.php?include=$1 [PT,QSA]
```
and the index.php file with:
```
include('includes/'.$_GET['include'].'.php');
```
Of course you can adapt this code to what you need. |
856,653 | I'm using ARM RealView debug 3.1 and I'm unable to watch variables inside functions defined in a C++ namespace, the code works well and is compiled with armcc. Do any of you know a solution for this? | 2009/05/13 | [
"https://Stackoverflow.com/questions/856653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/72784/"
] | In my case, the issue ending up being related to both using full IIS (not Express) and having a debug build where it included full debug symbols but also had project properties, `Build`, `Optimize code` checked.
Under Express, this works fine, but under full IIS this doesn't work. Visual Studio attaches to the w3wp process correctly, but it does not load symbols for the optimized dll. In Visual Studio you can go to `Debug`, `Windows`, `Modules` then scroll for the specific dll and see if under the `Symbol Status` column it shows `Skipped Loading Symbols.`. Right-click on it and select `Load Symbols` to make it work.
One additional setting that can affect this is if Visual Studio is set to only debug user code under `Debug`, `Options and Settings`, `Debugging`, `General`, `Enable Just My Code`. When optimized, the dlls will be marked as not user code when running under full IIS, so when Just My Code is enabled any breakpoints in them will be skipped. You can either set VS to debug non-user code or set the build to not optimize to allow breakpoints to be hit. | Sounds silly, but put a breakpoint earlier in the process: maybe the process doesn't reach the breakpoint. |
36,357,939 | Looks like time is automatically getting changed during conversion.
My input is `17:15:25`. However, it gets converted to `13:15:25`
What could be the reason?
```
string testDate = Convert.ToDateTime("2016-03-24T17:15:25.879Z")
.ToString("dd-MMM-yyyy HH:mm:ss", CultureInfo.InvariantCulture);
```
The result I get for `testDate` is : `24-Mar-2016 13:15:25` | 2016/04/01 | [
"https://Stackoverflow.com/questions/36357939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4379237/"
] | The `Z` in your input indicates a UTC time, but the default behaviour of `Convert.ToDateTime` is to convert the result to your local time. If you look at the result of `Convert.ToDateTime("2016-03-30T17:15:25.879Z").Kind` you'll see it's `Local`.
I would suggest using `DateTime.ParseExact`, where you can specify the *exact* behaviour you want, e.g. preserving the UTC time:
```
var dateTime = DateTime.ParseExact(
"2016-03-30T17:15:25.879Z",
"yyyy-MM-dd'T'HH:mm:ss.FFF'Z'",
CultureInfo.InvariantCulture,
DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal);
Console.WriteLine(dateTime); // March 30 2016 17:15 (...)
Console.WriteLine(dateTime.Kind); // Utc
```
You can then convert that value to a string however you want to.
Of course I'd *really* suggest using my [Noda Time](http://nodatime.org) project instead, where you'd parse to either an `Instant` or a `ZonedDateTime` which would know it's in UTC... IMO, [`DateTime` is simply broken](http://blog.nodatime.org/2011/08/what-wrong-with-datetime-anyway.html), precisely due to the kind of problems you've been seeing. | Because of the CultureInfo.InvariantCulture.
You are converting a date in your GMT
```
Convert.ToDateTime("2016-03-24T17:15:25.879Z")
```
And then you are converting it to string in an invariant culture
```
ToString("dd-MMM-yyyy HH:mm:ss",CultureInfo.InvariantCulture);
```
You should use DateTime.ParseExact, and then use the invariant culture in the conversion. |
7,681,543 | I am playing videos locally from sd card in listview in an android app. Now i want to hide those videos from user so that he can only play those videos but should not locate those videos to copy from sd card. Is there any way to hide videos on sd card? | 2011/10/06 | [
"https://Stackoverflow.com/questions/7681543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/967686/"
] | Use the [`ShouldSerialize`](http://james.newtonking.com/projects/json/help/?topic=html/ConditionalProperties.htm) feature provided by Json.Net. So basically, your class will look like:
```
public abstract class JsonDocument
{
/// <summary>
/// The document type that the concrete class expects to be deserialized from.
/// </summary>
//[JsonProperty(PropertyName = "DocumentType")] // We substitute the DocumentType property with this ExpectedDocumentType property when serializing derived types.
public abstract string ExpectedDocumentType { get; }
/// <summary>
/// The actual document type that was provided in the JSON that the concrete class was deserialized from.
/// </summary>
public string DocumentType { get; set; }
//Tells json.net to not serialize DocumentType, but allows DocumentType to be deserialized
public bool ShouldSerializeDocumentType()
{
return false;
}
}
``` | You can do this with an Enum, I don't know if DocumentType is a enum but it should.
```
enum DocumentType {
XML,
JSON,
PDF,
DOC
}
```
When deserializing the request it will give you an error if the client sends you an invalid enum. The "InvalidEnumArgumentException" which you can catch and tell the client that it's sending an non valid DocumentType. |
61,603,419 | I want to create a funtion that accepts two inputs (a dataframe and a string). Moreover, if the string is equal to `"cols"` this function need to return the number of columns, othwerwise it need to be return the number of rows.
My code is:
```
wl_df <- function(df,string) {
if(string == "cols")
return(ncol(df))
} else {
return(nrow(df))
}
```
However, I get the following errors:
```
Error: unexpected 'else' in:
" return(ncol(df))
} else"
```
,
```
Error: no function to return from, jumping to top level
```
and,
```
Error: unexpected '}' in " }"
```
Why do I get these errors, and how can I fix them?
Thanks in advance! | 2020/05/04 | [
"https://Stackoverflow.com/questions/61603419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Here is another approach, same function but in a more compact way:
```
wl_df <- function(df, string) ifelse(string == "cols", ncol(df), nrow(df))
``` | You can vectorize it, if you want to hit a whole list of data frames.
```
@library(tidyverse)
dfTests <- list(mtcars, iris, diamonds)
wl_df <- function(dfs,string) {
map_dbl(dfs,
~ case_when(
string == "cols" ~ ncol(.x),
string == "rows" ~ nrow(.x),
TRUE ~ NA))
}
# R > wl_df(dfTests, "cols")
# [1] 11 5 10
# R > wl_df(dfTests, "rows")
# [1] 32 150 53940
``` |
37,384,882 | Here is my code
```
Pattern pbold = Pattern.compile(".*\\* *(.*?) *\\*.*");
Matcher mbold = pbold.matcher(s);
mbold.find();
``` | 2016/05/23 | [
"https://Stackoverflow.com/questions/37384882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2567997/"
] | What you need is the metacharacter that matches whitespaces charaters: `(?s)`
This whitespace metacharacter matches:
* A space character
* A tab character
* A carriage return character
* A new line character
* A vertical tab character
For more info about this special characters, please consult [The Java Tutorials - Regular Expressions - Predefined Character Classes](https://docs.oracle.com/javase/tutorial/essential/regex/pre_char_classes.html).
The code belows matches the case you need:
```
String s = "abc021\n" +
"34-+\n" +
"*\n" +
"a\n" +
"p\n" +
"p\n" +
"l\n" +
"e\n" +
"*\n" +
"fga32\n" +
"49";
Pattern pbold = Pattern.compile(".*\\* *((?s).*?) *\\*.*");
Matcher mbold = pbold.matcher(s);
mbold.find();
```
There is also a similar question here:
[Regular expression does not match newline obtained from Formatter object](https://stackoverflow.com/questions/11644100/regular-expression-does-not-match-newline-obtained-from-formatter-object) | Use flags igm like below:
```
Pattern pbold = Pattern.compile(".*\\* *(.*?) *\\*.*");
Matcher mbold = pbold.matcher(s, Pattern.MULTILINE|Pattern.CASE_INSENSITIVE|Pattern.DOTALL);
mbold.find();
``` |
3,941 | Does mining a block mean that anyone else who was working on mining a block loses their progress and must restart? | 2012/06/13 | [
"https://bitcoin.stackexchange.com/questions/3941",
"https://bitcoin.stackexchange.com",
"https://bitcoin.stackexchange.com/users/277/"
] | Yes and no.
When a new block is created, everyone on the network must discard old work and use the new information provided (assuming they don't want to create forks). It does lead to some small performance loss.
On the other hand, creating a block is more or less like playing a lottery - there is no real "progress" per se, you are just trying more and more tickets until you win something. When a new block is created you don't have a situation of "10% left, I lost so much work", as there is no telling whether there actually IS a solution to the particular configuration of a block you were creating.
All in all, yes, everyone must start over when a new block is created, but they don't lose much (aside from some small performance drop due to stale shares). | No, because there's no progress in mining blocks. If you've mined for 5 minutes and didn't find a block, you aren't any closer to finding it than when you started - the [hazard function](http://en.wikipedia.org/wiki/Failure_rate#Failure_rate_in_the_continuous_sense) is constant. |
40,836,001 | I am trying to write a simple program in c++ where I have 2 classes, and both can access functions from each other. This is a simplification of what I am actually trying to do in the end, which is to create a game with board and piece classes. I was able to do this in java, but I am now running into problems trying to do the same in c++. My code is as follows:
```
#include <iostream>
class B;
class A {
public:
void sync(B obj){
b = obj;
}
void print(){
std::cout << "Hello from class A" << std::endl;
}
void printBoth(){
std::cout << "Hello from class A" << std::endl;
b.print();
}
private:
B b;
};
class B {
public:
B(A obj){
a = obj;
}
void print(){
std::cout << "Hello from class B" << std::endl;
}
void printBoth(){
std::cout << "Hello from class B" << std::endl;
a.print();
}
private:
A a;
};
int main(){
A a;
B b(a);
a.sync(b);
a.printBoth();
std::cout << std::endl;
b.printBoth();
return 0;
}
```
When I try to compile this with `g++ example.cpp`, I receive 5 errors:
```
example.cpp:20:5: error: field ‘b’ has incomplete type
B b;
^
example.cpp: In member function ‘void A::sync(B)’:
example.cpp:7:8: error: ‘obj’ has incomplete type
void sync(B obj){
^
example.cpp:3:7: error: forward declaration of ‘class B’
class B;
^
example.cpp:8:4: error: ‘b’ was not declared in this scope
b = obj;
^
example.cpp: In member function ‘void A::printBoth()’:
example.cpp:17:4: error: ‘b’ was not declared in this scope
b.print();
^
```
I have never used forward declaration with classes, so I apologize if I am missing something glaringly obvious. Any help is appreciated, and I thank you in advance. | 2016/11/28 | [
"https://Stackoverflow.com/questions/40836001",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7021841/"
] | If you want a pure regex solution then use lookarounds:
```
>>> s = "12.03 5.897 7.10.74 0.103 12.05 6.4.1 8.98"
>>> print re.findall(r'(?<!\.)\b\d+\.\d+\b(?!\.)', s)
['12.03', '5.897', '0.103', '12.05', '8.98']
```
[RegEx Demo](https://regex101.com/r/MFgPui/4)
* `(?<!\.)` is negative lookbehind to assert failure when previous char is DOT.
* `(?!\.)` is negative lookahead to assert failure when next char is DOT.
* `\b` is word boundary which is required on both sides to make sure we match full decimal number | Use `(?<=\s)\d*\.\d*(?=\s|$)|^\d*\.\d*(?=\s|$)`:
```
import re
re.findall(r'(?<=\s)\d*\.\d*(?=\s|$)|^\d*\.\d*(?=\s|$)', s)
# ['12.03', '5.897', '0.103', '12.05', '8.98']
```
* the patten matches either `(?<=\s)\d*\.\d*(?=\s|$)` or `^\d*\.\d*(?=\s|$)` depending on whether the number is at the beginning of the string;
* `\d*\.\d*(?=\s|$)` matches a number with one dot followed by a space or the end of the string;
Note: Can not use `(?<=\s|^)` to integrate both cases because the look-behind syntax does not support so; |
68,475,076 | I have a series of spreadsheets we use to load parameters into a database for a point and click style of order entry. Some of the spreadsheets have hundreds of sheets and keeping them up to date is constantly a problem. What I am trying to do is insert some code that will go sheet by sheet and compile some data from each tab on to a summary sheet.
I have tinkered with editing the code from [Excel VBA to insert sheet name on each row when combining data tables with variable columns](https://stackoverflow.com/questions/39707622/excel-vba-to-insert-sheet-name-on-each-row-when-combining-data-tables-with-varia) but I am a total hack and so far have been unsuccessful.
To be brief, I am needing the code to return the sheet name in column A and then scan the first row for the first unused column, then return the contents of that column to column C and the row# it came from to column B on the summary sheet.
[](https://i.stack.imgur.com/TDYTG.png)
This sample illustrates how the data is structured, a series of questions with an answer at the end. They are not static, but the questions have headers in Row 1 (sometimes just a space value) but the answers do not, Cell 1 of that column is always blank (null).
[](https://i.stack.imgur.com/xxRuy.png)
EDIT: Using several sources here on Stack Overflow, I have managed to piece this together which almost works. Instead of finding the last used column and row, I need to find the first column with a null header (row 1) and the last row before any breaks. This is due to there being notes added to most sheets on the right of the data and possibly below.
```
Sub CopyData()
Application.ScreenUpdating = False
Dim wsSummary As Worksheet
Dim LastRowWs As Long
Dim LastColWs As Long
Dim LastRowSummary As Long
Dim StartRowSummary As Long
Set wsSummary = ThisWorkbook.Worksheets("Summary") ' defines WsSummary
LastRowSummary = wsSummary.Cells(wsSummary.Rows.Count, "A").End(xlUp).Row + 1 ' identifys the last used row on target summary sheet
wsSummary.Range("A2:ZZ" & LastRowSummary).Clear 'clears a set range on target summary sheet
For Each Ws In ThisWorkbook.Worksheets
Select Case Ws.Name
Case "Summary", "Category", "TOC", "Index"
'If it's one of these sheets, do nothing
Case Else
LastRowWs = Ws.Cells(Ws.Rows.Count, "A").End(xlUp).Row ' Finds the last column in worksheet
LastColWs = Ws.Cells(LastRowWs, Columns.Count).End(xlToLeft).Column ' Finds the last used colun in Worksheet - ISSUE, I need first null cell column!
StartRowSummary = wsSummary.Cells(wsSummary.Rows.Count, "A").End(xlUp).Row + 1 'first empty row
Ws.Range(Split(Cells(, LastColWs).Address, "$")(1) & "2:" & Split(Cells(, LastColWs).Address, "$")(1) & LastRowWs).Copy Destination:=wsSummary.Range("A" & StartRowSummary)
LastRowSummary = wsSummary.Cells(wsSummary.Rows.Count, "A").End(xlUp).Row
wsSummary.Range("B" & StartRowSummary & ":B" & LastRowSummary) = Ws.Name ' returns sheet name
wsSummary.Range("C" & StartRowSummary & ":C" & LastRowSummary) = LastColWs 'returns column #
wsSummary.Range("D" & StartRowSummary & ":D" & LastRowSummary) = Split(Cells(, LastColWs).Address, "$")(1) 'returns Column letter
End Select
Next
Application.ScreenUpdating = True
End Sub
``` | 2021/07/21 | [
"https://Stackoverflow.com/questions/68475076",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16497544/"
] | [`GuildEmoji`](https://discord.js.org/#/docs/main/stable/class/GuildEmoji)'s [`author`](https://discord.js.org/#/docs/main/stable/class/GuildEmoji?scrollTo=author) property returns a [`User`](https://discord.js.org/#/docs/main/stable/class/User) object, so you can use either `emoji.author.tag` or `emoji.author.username`. | You might need to [fetch](https://discord.js.org/#/docs/main/stable/class/GuildEmoji?scrollTo=fetchAuthor) the author.
```js
const userTag = (await emoji.fetchAuthor()).tag;
```
Don't forget that you can only use `await` inside an [async function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function). |
4,337,220 | I've spent the last few days scouring the site looking for an answer to this problem,
i need to create a folder and then make it a shared networked folder, I've tried several different sample code snippets from different sites
<http://www.sarampalis.org/articles/dotnet/dotnet0002.shtml> (this link is dead)
but none seem to allow the folder to be shared
If anyone could be of help it'd be much aprriciated | 2010/12/02 | [
"https://Stackoverflow.com/questions/4337220",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/528259/"
] | I did follow the link that you have in your question.
I have a Win 7 Professional + VS.NET 2010 Professional as my dev environment on my laptop.
I took the code from the article and quickly fired up a devenv and executed the code. The code executed perfectly without any error. When i looked at the created directory you dont see a share icon on the folder but it is indeed shared. How can you check that:
open a command prompt
type "net share" and press enter
you will see that it will list the folder c:\MyTestShare with a share name "My Test Share"
One more way to find out whether it is shared or not is to right click on the folder and look at the sharing tab. Check the Network Path label. It will clearly show the shared path.
Hope this helps you.
Lohith | See
<http://www.sarampalis.org/articles/dotnet/dotnet0002.shtml>
<http://www.codeproject.com/KB/system/Share-Folder-c_.aspx> |
545,510 | I want to create a .pem file to connect to the server.
I know that I can use ssh-keygen, But I want to use it for a specific user, And I need a script that will do for me all process.
My need is to run the script one time on server X and so each time that I want to connect to X server I can use this the .pem file, in my computer to connect to the X server. | 2019/10/07 | [
"https://unix.stackexchange.com/questions/545510",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/332990/"
] | I found a way to do it, and I didn't find an answer about how to do it, so I post it.
```
#! /bin/bash
#Based on https://linuxaws.wordpress.com/2017/07/17/how-to-generate-pem-file-to-ssh-the-server-without-password-in-linux/
user=$(echo "$USER")
ssh-keygen << EOF
$user
EOF
mv $user $user.pem
sudo chmod 700 ~/.ssh
touch ~/.ssh/authorized_keys
sudo chmod 600 ~/.ssh/authorized_keys
cat $user.pub >> ~/.ssh/authorized_keys
echo "Copy the $user.pem to your computer."
```
After you run this script on a server or computer you can connect to it from another server/computer, with the command
```
ssh -i <pem_filename>.pem user@host
``` | I have created a script below for ec2 instances to create a Key based sudo user. Kindly try this.
Note: below script works for all linux OS like redhat, ubuntu, suse, kali, centos, fedora, amazon linux 1/2, debain......etc
```
#!/bin/bash
#author: bablish jaiswal
#purpos: a sudo pem based user creation
clear
#echo "Hi, I am a function to create a sudo user with pem file. Kindly share following information"
echo -e "\n\n\n"
printf "\e[6;33mHi, I am a function to create sudo user with pem file. Kindly share following information\e[0m";echo
read -p "user name:- " name #input your name
read -p "complete path for $name home directory:- " home #user home directory
sudo useradd -m -d $home $name -s /bin/bash #create user by given input
sudo -u $name cat /dev/zero | sudo -u $name ssh-keygen -q -N "" #generating pem
sudo -u $name mv $home/.ssh/id_rsa.pub $home/.ssh/authorized_keys #permission
sudo chmod 700 $home/.ssh #permission again
sudo chmod 600 $home/.ssh/authorized_keys #permission again and again
echo " "
#echo "-------Copy below pem file text---------"
printf "\e[6;33m-----------------------------Copy below text-------------------------\e[0m";echo
sudo cat $home/.ssh/id_rsa
echo " "
#echo "-------Copy above text---------"
#svalue=$(cat /etc/sudoers |grep -i root |grep -i all|tail -n1 |awk '{$1=""}1')
svalue=$(cat /etc/sudoers |grep -i root |grep -i all|tail -n1 |awk '{print $2}') #sudo creation
echo "${name} ${svalue} NOPASSWD:ALL" >> /etc/sudoers && echo “Remark:- User $name is a sudo user” #sudo confirmation message
``` |
2,761,934 | Is there any good control or plug-in for uploading multiple photos with preview? As far as I understand it is impossible to preview photo on local computer using just JavaScript. So it has to use Flash or Java.
Thanks, also, I use ASP.NET. | 2010/05/03 | [
"https://Stackoverflow.com/questions/2761934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/192727/"
] | I have often been annoyed by this problem myself, and unfortunately the solution suggested in [Aaronaught's answer](https://stackoverflow.com/a/2762169/3734747) quickly becomes messy when @parameters and 'strings' are involved. However, I have found a different workaround by exploiting the usage of synonyms:
```
IF(COL_LENGTH('MyTable', 'NewCol') IS NULL)
BEGIN
ALTER TABLE MyTable ADD NewCol VARCHAR(16) NULL;
CREATE SYNONYM hack FOR MyTable;
UPDATE hack SET NewCol = 'Hello ' + OldCol;
DROP SYNONYM hack;
ALTER TABLE MyTable ALTER COLUMN NewCol VARCHAR(16) NOT NULL;
END
``` | Try adding a "GO" statement after the ALTER TABLE.
It was news to me, but it says [here](http://msdn.microsoft.com/en-us/library/ms188037.aspx) that all statements in a batch (those preceeding the GO) are compiled into one query plan.) Withou no GO in the SQL, the entire plan is effectively one query.
EDIT: Since GO gives a syntax error (which seemed strange to me), I created something similar, and found this worked
```
declare @doUpdate bit;
SELECT @doUpdate = 0;
IF NOT EXISTS(SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'PurchaseOrder' AND COLUMN_NAME = 'IsDownloadable')
BEGIN
SELECT @doUpdate=1
END
IF @doUpdate<>0
ALTER TABLE [dbo].[PurchaseOrder] ADD [IsDownloadable] bit NOT NULL DEFAULT 0
IF @doUpdate<>0
UPDATE [dbo].[PurchaseOrder] SET [IsDownloadable] = 1 WHERE [Ref]=0
COMMIT TRAN
``` |
2,659 | I am doing a final year project which involves finding the position and orientation of a screw which has to be opened by a robot hand having a screw driver as an end effector.
I have developed a program in matlab that detects the screw and returns its centroid, I have also gone ahead to calibrate the camera and I have obtained both the intrinsic and the extrinsic parameters.
How do I obtain the rotation and translation matrix to enable me extract the eulers angles of a screw? | 2012/06/20 | [
"https://dsp.stackexchange.com/questions/2659",
"https://dsp.stackexchange.com",
"https://dsp.stackexchange.com/users/1537/"
] | I am trying to imagine how the detected screw is represented. Even if you have the centroid point and some representation of the shape, you need to estimate plane in which the screw lays. Such estimation would be very inaccurate given just the elliptic shape of the screw, which is usually small and its perspective and even affine deformation would be negligible in the image.
Furthermore, a small ambiguity came to my mind, see the picture (red dots are the centroids):

Although both screws may be represented by the same ellipses (up to centroid position), their rotations about vertical axis are different.
Maybe you are aware of that.
More information about detected screw representation and the scene would be helpful for a constructive answer.
I think pose estimation problems are covered in Hartley & Zisserman: "Multiple View Geometry". Of course it is much more accurate to estimate object pose when you have more views (e.g. stereo cameras). | My understanding is that you can not calculate homography from a single conic (conic is projection of a circle, in this case edge of the round screw). When camera calibration and homography between sensor and another plane (in you case the plane of the head of the screw) are known, you can calculate the orientation and location of the camera compared to the plane (or vice versa).
But, you can estimate homography from four known points. If you have [slot/flat head screw](http://en.wikipedia.org/wiki/Slot_drive#Slot), accurate estimation of the screw position and orientation can be very hard as the measurement error for the the corners of the slot will be relatively big compared to distance of the points. If you have [cross](http://en.wikipedia.org/wiki/Phillips_drive#Cross) type head, the four known points can be more spread apart and the homography estimation and therefore location/orientation estimation will be more accurate.
You can most likely combine the knowledge about the points of the slot corners and the edge of the screw (conic) to form even better estimation of the homography.
There is quite recent [paper](http://iic.cs.arizona.edu/static/resources/2010/07/01/planar_homography.pdf) on the topic of estimating homography with different techniques. Note that there are many cases in which particular method of homography estimation does not work. For example the [paper](http://iic.cs.arizona.edu/static/resources/2010/07/01/planar_homography.pdf) describes a method for computing homography from a point and a line, but it does not warn you that the point can not lie on the same line.
I have always recommended [master thesis of Liljequist](http://www.40noll.com/ar/exjobb.pdf) as good introduction paper about how to estimate camera location when camera calibration and homography are known. As Libor suggested, Multiple View Geometry by Hartley and Zisserman is good book about the camera geometry and algorithms related to it, but is also quite heavy compared to what you need for basic algorithms. |
9,944 | My question is with regards to booting a Linux system from a separate /boot partition. If most configuration files are located on a separate / partition, how does the kernel correctly mount it at boot time?
Any elaboration on this would be great. I feel as though I am missing something basic. I am mostly concerned with the process and order of operations.
Thanks!
EDIT: I think what I needed to ask was more along the lines of the dev file that is used in the root kernel parameter. For instance, say I give my root param as root=/dev/sda2. How does the kernel have a mapping of the /dev/sda2 file? | 2011/03/23 | [
"https://unix.stackexchange.com/questions/9944",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/4856/"
] | In ancient times, the kernel was hard coded to know the device major/minor number of the root fs and mounted that device after initializing all device drivers, which were built into the kernel. The `rdev` utility could be used to modify the root device number in the kernel image without having to recompile it.
Eventually boot loaders came along and could pass a command line to the kernel. If the `root=` argument was passed, that told the kernel where the root fs was instead of the built in value. The drivers needed to access that still had to be built into the kernel. While the argument looks like a normal device node in the `/dev` directory, there obviously is no `/dev` directory before the root fs is mounted, so the kernel can not look up a dev node there. Instead, certain well known device names are hard coded into the kernel so the string can be translated to the device number. Because of this, the kernel can recognize things like `/dev/sda1`, but not more exotic things like `/dev/mapper/vg0-root` or a volume UUID.
Later, the `initrd` came into the picture. Along with the kernel, the boot loader would load the `initrd` image, which was some kind of compressed filesystem image (gzipped ext2 image, gzipped romfs image, squashfs finally became dominant). The kernel would decompress this image into a ramdisk and mount the ramdisk as the root fs. This image contained some additional drivers and boot scripts instead of a real `init`. These boot scripts performed various tasks to recognize hardware, activate things like raid arrays and LVM, detect UUIDs, and parse the kernel command line to find the real root, which could now be specified by UUID, volume label and other advanced things. It then mounted the real root fs in `/initrd`, then executed the `pivot_root` system call to have the kernel swap `/` and `/initrd`, then exec `/sbin/init` on the real root, which would then unmount `/initrd` and free the ramdisk.
Finally, today we have the `initramfs`. This is similar to the `initrd`, but instead of being a compressed filesystem image that is loaded into a ramdisk, it is a compressed cpio archive. A tmpfs is mounted as the root, and the archive is extracted there. Instead of using `pivot_root`, which was regarded as a dirty hack, the `initramfs` boot scripts mount the real root in `/root`, delete all files in the tmpfs root, then `chroot` into `/root`, and exec `/sbin/init`. | Sounds like you're asking how does the kernel "know" which partition is the root partition, without access to configuration files on /etc.
The kernel can accept command line arguments like any other program. GRUB, or most other bootloaders can accept command line arguments as user input, or store them and make various combinations of command line arguments available via a menu. The bootloader passes the command line arguments to the kernel when it loads it (I don't know the name or mechanics of this convention but it's probably similar to how an application receives command line arguments from a calling process in a running kernel).
One of those command line options is `root`, where you can specify the root filesystem, i.e. `root=/dev/sda1`.
If the kernel uses an initrd, the bootloader is responsible for telling the kernel where it is, or putting the initrd in a standard memory location (I think) - that's at least the way it works on my Guruplug.
It's entirely possible to not specify one and then have your kernel panic immediately after starting complaining that it can't find a root filesystem.
There might be other ways of passing this option to the kernel. |
21,087,970 | What is the best way to write a method that given a type T and integer n, returns a list of n newly created objects of type T. Is it possible to pass a constructor as argument or will I have to accomplish this in some other way?
Was thinking something like this
```
public <T> ArrayList<Object> generate(T type, int amount){
ArrayList<Object> objects = new ArrayList();
for (int i = 0; i < amount; i ++){
objects.add(new bla bla)...
}
``` | 2014/01/13 | [
"https://Stackoverflow.com/questions/21087970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2938939/"
] | Use a generic method.
```
public <T> List<T> getList(Class<T> clazz, int size) throws InstantiationException, IllegalAccessException{
List<T> list = new ArrayList<T>();
for(int x = 0; x < size; x++){
list.add(clazz.newInstance());
}
return list;
}
```
**NOTE:** This will only work for objects with a default constructor. If you want to create a `List` of objects that do not contain a default constructor you must do so using reflection to pick the appropriate constructor. | ```
public static <T> List<T> generate(Class<T> clazz, int amount) {
ArrayList<Object> objects = new ArrayList();
for (int i = 0; i < amount; i ++){
objects.add(clazz.newInstance());
}
return list;
}
```
The code above actually tries to use default constructor. You can pass a reflection reference to an appropriate constructor of your choice if you want. A list of constructors can be obtained by calling `Class.getConstructors()`.
Then your code would look like this:
```
public static <T> List<T> generate(Constructor<T> constructor, int amount) {
ArrayList<Object> objects = new ArrayList();
for (int i = 0; i < amount; i ++){
objects.add(constructor.newInstance(param1, param2, ...)); // fill the arguments
}
return list;
}
``` |
21,153,433 | I'm having trouble understanding the result of using void when calling a method. Below is a `main()` that calls a `test()`. The `test()` has a return of `void`.
If I call `void test()` (use `void`) the execution seems to stop: no print from `test()`
If I call `test()` (no `void`) the execution works fine.
What is the logic of this? I'm thinking that the word `void` in the call is somehow waiting for a return from `test()` which never comes? But wouldn't that be after `test()` did its job of printing? In the call is it sending `void` and `test()` not handling it?
Note: This is from a C language for a Propeller microcontroller, perhaps the logic is different than C on a PC. Much thanks.
```
#include "simpletools.h";
void testerForVoid(); //forward declare
int main(void)
{
print("Begin main");
// option 1 - no void - works
testerForVoid();
// option 2 - with void - fails
void testerForVoid();
return 0;
}
void testerForVoid()
{
print("\nBegin testForVoid");
}
``` | 2014/01/16 | [
"https://Stackoverflow.com/questions/21153433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1432507/"
] | `void` is only used in the function declaration. When you call a function with `void` return type, just call it without using `void`.
* Use `void testerForVoid();` to declare a function that returns `void`, as the forward declared in your case.
* Use `testerForVoid();` to call the function.
In you example, for option#2, it tends to declare the function again, which has already been forward declared. No real function all is conducted. | option 1 is a call to function `testerForVoid()` which has already been declared.
option 2 is a declaration of function `testerForVoid()`. This fails because it has already been declared. |
12,717,112 | I use this code in PHP:
```
$idcat = 147;
$thumbnail_id = get_woocommerce_term_meta( $idcat, 'thumbnail_id', true );
$image = wp_get_attachment_url( $thumbnail_id );
echo '<img src="'.$image.'" alt="" width="762" height="365" />';
```
Where `147` is the current ID manually set, but i need to current id in other categories
Any suggest? | 2012/10/03 | [
"https://Stackoverflow.com/questions/12717112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1718405/"
] | This solution with few code. I think is better.
```
<?php echo wp_get_attachment_image( get_term_meta( get_queried_object_id(), 'thumbnail_id', 1 ), 'thumbnail' ); ?>
``` | Add code in `/wp-content/plugins/woocommerce/templates/` loop path
```
<?php
if ( is_product_category() ){
global $wp_query;
$cat = $wp_query->get_queried_object();
$thumbnail_id = get_woocommerce_term_meta( $cat->term_id, 'thumbnail_id', true );
$image = wp_get_attachment_url( $thumbnail_id );
echo "<img src='{$image}' alt='' />";
}
?>
``` |
55,359,176 | I'm learning react and it's great, but i've ran into an issue and i'm not sure what the best practice is to solve it.
I'm fetching data from an API in my componentDidMount(), then i'm setting some states with SetState().
Now the problem is that because the first render happens before my states have been set, im sending the initial state values into my components. Right now i'm setting them to empty arrays or empty Objects ({ type: Object, default: () => ({}) }).
Then i'm using ternary operator to check the .length or if the property has a value.
Is this the best practice or is there some other way that i'm unaware of?
I would love to get some help with this, so that i do the basics correctly right from the start.
Thanks! | 2019/03/26 | [
"https://Stackoverflow.com/questions/55359176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10296538/"
] | It Depends.
suppose you are fetching books data from server.
here is how to do that.
```js
state = {
books: null,
}
```
if, your backend api is correctly setup.
You will get either empty array for no books or array with some length
```js
componentDidMount(){
getBooksFromServer().then(res => {
this.setState({
books: res.data
})
})
}
```
Now In Your render method
```js
render() {
const { books } = this.state;
let renderData;
if(!books) {
renderData = <Spinner />
} else
if(books.length === 0) {
renderData = <EmptyScreen />
}
else {
renderData = <Books data = { books } />
}
return renderData;
}
```
If you are using offline data persistence In that case initially you won't have empty array.So This way of handling won't work.
To show the spinner you have to keep a variable **loader** in state.
and set it true before calling api and make it false when promise resolves or rejects.
finally read upon to state.
```js
const {loader} = this.state;
if(loader) {
renderData = <Spinner />
}
``` | I set initial state in constructor. You can of course set initial state of component as static value - empty array or object. I think better way is to set it using props. Therefore you can use you component like so `<App items={[1,2,3]} />` or `<App />` (which takes value of items from `defaultProps` object because you not pass it as prop).
Example:
```
import React, { Component } from 'react';
import PropTypes from 'prop-types';
class App extends Component {
constructor(props) {
super(props);
this.state = {
items: [], // or items: {...props.items}
};
}
async componentDidMount() {
const res = await this.props.getItems();
this.setState({items: res.data.items})
}
render() {
return <div></div>
}
};
App.defaultProps = {
items: []
}
``` |
7,933,598 | In one of my tables (sellers), all the fields requires permission from the user for others (registered or non-registered) to see. I could go through and create an associated column for each column, ex. (column1, column1\_privacy, column2, column2\_privacy). However, this seems redundant and bad design.
Is there a more elegant solution for this in Rails? Thanks in advance. | 2011/10/28 | [
"https://Stackoverflow.com/questions/7933598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/610408/"
] | ***As of today, there are four available approaches, two of them requiring a certain storage backend:***
1. **[Django-eav](https://github.com/mvpdev/django-eav)** (the original package is no longer mantained but has some **[thriving forks](https://github.com/mvpdev/django-eav/network)**)
This solution is based on [Entity Attribute Value](https://en.wikipedia.org/wiki/Entity-attribute-value_model) data model, essentially, it uses several tables to store dynamic attributes of objects. Great parts about this solution is that it:
* uses several pure and simple Django models to represent dynamic fields, which makes it simple to understand and database-agnostic;
* allows you to effectively attach/detach dynamic attribute storage to Django model with simple commands like:
```
eav.unregister(Encounter)
eav.register(Patient)
```
* **[Nicely integrates with Django admin](https://github.com/mvpdev/django-eav/blob/master/eav/admin.py)**;
* At the same time being really powerful.Downsides:
* Not very efficient. This is more of a criticism of the EAV pattern itself, which requires manually merging the data from a column format to a set of key-value pairs in the model.
* Harder to maintain. Maintaining data integrity requires a multi-column unique key constraint, which may be inefficient on some databases.
* You will need to select [one of the forks](https://github.com/mvpdev/django-eav/network), since the official package is no longer maintained and there is no clear leader.The usage is pretty straightforward:
```
import eav
from app.models import Patient, Encounter
eav.register(Encounter)
eav.register(Patient)
Attribute.objects.create(name='age', datatype=Attribute.TYPE_INT)
Attribute.objects.create(name='height', datatype=Attribute.TYPE_FLOAT)
Attribute.objects.create(name='weight', datatype=Attribute.TYPE_FLOAT)
Attribute.objects.create(name='city', datatype=Attribute.TYPE_TEXT)
Attribute.objects.create(name='country', datatype=Attribute.TYPE_TEXT)
self.yes = EnumValue.objects.create(value='yes')
self.no = EnumValue.objects.create(value='no')
self.unkown = EnumValue.objects.create(value='unkown')
ynu = EnumGroup.objects.create(name='Yes / No / Unknown')
ynu.enums.add(self.yes)
ynu.enums.add(self.no)
ynu.enums.add(self.unkown)
Attribute.objects.create(name='fever', datatype=Attribute.TYPE_ENUM,\
enum_group=ynu)
# When you register a model within EAV,
# you can access all of EAV attributes:
Patient.objects.create(name='Bob', eav__age=12,
eav__fever=no, eav__city='New York',
eav__country='USA')
# You can filter queries based on their EAV fields:
query1 = Patient.objects.filter(Q(eav__city__contains='Y'))
query2 = Q(eav__city__contains='Y') | Q(eav__fever=no)
```
2. **Hstore, JSON or JSONB fields in PostgreSQL**
PostgreSQL supports several more complex data types. Most are supported via third-party packages, but in recent years Django has adopted them into django.contrib.postgres.fields.
**HStoreField**:
[Django-hstore](https://github.com/jordanm/django-hstore) was originally a third-party package, but Django 1.8 added **[HStoreField](https://docs.djangoproject.com/en/1.8/ref/contrib/postgres/fields/#hstorefield)** as a built-in, along with several other PostgreSQL-supported field types.
This approach is good in a sense that it lets you have the best of both worlds: dynamic fields and relational database. However, hstore is [not ideal performance-wise](http://archives.postgresql.org/pgsql-performance/2011-05/msg00263.php), especially if you are going to end up storing thousands of items in one field. It also only supports strings for values.
```
#app/models.py
from django.contrib.postgres.fields import HStoreField
class Something(models.Model):
name = models.CharField(max_length=32)
data = models.HStoreField(db_index=True)
```
In Django's shell you can use it like this:
```
>>> instance = Something.objects.create(
name='something',
data={'a': '1', 'b': '2'}
)
>>> instance.data['a']
'1'
>>> empty = Something.objects.create(name='empty')
>>> empty.data
{}
>>> empty.data['a'] = '1'
>>> empty.save()
>>> Something.objects.get(name='something').data['a']
'1'
```
You can issue indexed queries against hstore fields:
```
# equivalence
Something.objects.filter(data={'a': '1', 'b': '2'})
# subset by key/value mapping
Something.objects.filter(data__a='1')
# subset by list of keys
Something.objects.filter(data__has_keys=['a', 'b'])
# subset by single key
Something.objects.filter(data__has_key='a')
```
**JSONField**:
JSON/JSONB fields support any JSON-encodable data type, not just key/value pairs, but also tend to be faster and (for JSONB) more compact than Hstore.
Several packages implement JSON/JSONB fields including **[django-pgfields](https://django-pgfields.readthedocs.org/en/latest/fields.html)**, but as of Django 1.9, **[JSONField](https://docs.djangoproject.com/en/1.9/ref/contrib/postgres/fields/#jsonfield)** is a built-in using JSONB for storage.
**JSONField** is similar to HStoreField, and may perform better with large dictionaries. It also supports types other than strings, such as integers, booleans and nested dictionaries.
```
#app/models.py
from django.contrib.postgres.fields import JSONField
class Something(models.Model):
name = models.CharField(max_length=32)
data = JSONField(db_index=True)
```
Creating in the shell:
```
>>> instance = Something.objects.create(
name='something',
data={'a': 1, 'b': 2, 'nested': {'c':3}}
)
```
Indexed queries are nearly identical to HStoreField, except nesting is possible. Complex indexes may require manually creation (or a scripted migration).
```
>>> Something.objects.filter(data__a=1)
>>> Something.objects.filter(data__nested__c=3)
>>> Something.objects.filter(data__has_key='a')
```
3. **[Django MongoDB](http://django-mongodb-engine.readthedocs.org/en/latest/)**
Or other NoSQL Django adaptations -- with them you can have fully dynamic models.
NoSQL Django libraries are great, but keep in mind that they are not 100% the Django-compatible, for example, to migrate to [Django-nonrel](http://www.allbuttonspressed.com/projects/django-nonrel) from standard Django you will need to replace ManyToMany with [ListField](https://stackoverflow.com/questions/3877246/django-nonrel-on-google-app-engine-implications-of-using-listfield-for-manytom) among other things.
Checkout this Django MongoDB example:
```
from djangotoolbox.fields import DictField
class Image(models.Model):
exif = DictField()
...
>>> image = Image.objects.create(exif=get_exif_data(...))
>>> image.exif
{u'camera_model' : 'Spamcams 4242', 'exposure_time' : 0.3, ...}
```
You can even create [embedded lists](http://django-mongodb.org/topics/embedded-models.html) of any Django models:
```
class Container(models.Model):
stuff = ListField(EmbeddedModelField())
class FooModel(models.Model):
foo = models.IntegerField()
class BarModel(models.Model):
bar = models.CharField()
...
>>> Container.objects.create(
stuff=[FooModel(foo=42), BarModel(bar='spam')]
)
```
4. **[Django-mutant: Dynamic models based on syncdb and South-hooks](https://github.com/charettes/django-mutant)**
[Django-mutant](https://github.com/charettes/django-mutant) implements fully dynamic Foreign Key and m2m fields. And is inspired by incredible but somewhat hackish solutions by [Will Hardy](http://dynamic-models.readthedocs.org/en/latest/index.html) and Michael Hall.
All of these are based on Django South hooks, which, according to [Will Hardy's talk at DjangoCon 2011](http://blip.tv/djangocon-europe-2011/wednesday-1415-will-hardy-5311186) **(watch it!)** are nevertheless robust and tested in production ([relevant source code](http://dynamic-models.readthedocs.org/en/latest/)).
First to [implement this](https://bitbucket.org/mhall119/dynamo/overview) was [Michael Hall](http://mhall119.com/2011/02/fun-with-django-meta-classes-and-dynamic-models/).
Yes, this is magic, with these approaches you can achieve **fully dynamic Django apps, models and fields** with any relational database backend. But at what cost? Will stability of application suffer upon heavy use? These are the questions to be considered. You need to be sure to maintain a proper [lock](https://stackoverflow.com/questions/1123200/how-to-lock-a-critical-section-in-django) in order to allow simultaneous database altering requests.
If you are using Michael Halls lib, your code will look like this:
```
from dynamo import models
test_app, created = models.DynamicApp.objects.get_or_create(
name='dynamo'
)
test, created = models.DynamicModel.objects.get_or_create(
name='Test',
verbose_name='Test Model',
app=test_app
)
foo, created = models.DynamicModelField.objects.get_or_create(
name = 'foo',
verbose_name = 'Foo Field',
model = test,
field_type = 'dynamiccharfield',
null = True,
blank = True,
unique = False,
help_text = 'Test field for Foo',
)
bar, created = models.DynamicModelField.objects.get_or_create(
name = 'bar',
verbose_name = 'Bar Field',
model = test,
field_type = 'dynamicintegerfield',
null = True,
blank = True,
unique = False,
help_text = 'Test field for Bar',
)
``` | I've been working on pushing the django-dynamo idea further. The project is still undocumented but you can read the code at <https://github.com/charettes/django-mutant>.
Actually FK and M2M fields (see contrib.related) also work and it's even possible to define wrapper for your own custom fields.
There's also support for model options such as unique\_together and ordering plus Model bases so you can subclass model proxy, abstract or mixins.
I'm actually working on a not in-memory lock mechanism to make sure model definitions can be shared accross multiple django running instances while preventing them using obsolete definition.
The project is still very alpha but it's a cornerstone technology for one of my project so I'll have to take it to production ready. The big plan is supporting django-nonrel also so we can leverage the mongodb driver. |
91,071 | [](https://i.stack.imgur.com/8GRAZ.png)
How to add a custom button to sales order view in magento2, since some of the events was remove in-favor of plugins.
* Removed some events (plugins must be used instead):
+ adminhtml\_widget\_container\_html\_before ([use in magento 1.x](https://stackoverflow.com/questions/6642599/how-to-add-new-button-to-order-view-in-magento-admin-panel))
+ admin\_session\_user\_logout
+ model\_config\_data\_save\_before
+ ...
See [Magento2 Change Log](https://github.com/magento/magento2/blob/develop/CHANGELOG.md) | 2015/11/21 | [
"https://magento.stackexchange.com/questions/91071",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/519/"
] | Create DI file: `app/code/YourVendor/YourModule/etc/di.xml`:
```
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<virtualType name="SalesOrderViewWidgetContext" type="\Magento\Backend\Block\Widget\Context">
<arguments>
<argument name="buttonList" xsi:type="object">YourVendor\YourModule\Block\Adminhtml\Order\View\ButtonList
</argument>
</arguments>
</virtualType>
<type name="Magento\Sales\Block\Adminhtml\Order\View">
<arguments>
<argument name="context" xsi:type="object">SalesOrderViewWidgetContext</argument>
</arguments>
</type>
</config>
```
What we do here is:
1. Set custom `context` argument into the `Order\View` block. This
context is defined as a virtual type.
2. Define virtual type for a
widget context. We set custom `buttonList` argument with our own
button list class.
Implement your button list class:
```
<?php
namespace YourVendor\YourModule\Block\Adminhtml\Order\View;
class ButtonList extends \Magento\Backend\Block\Widget\Button\ButtonList
{
public function __construct(\Magento\Backend\Block\Widget\Button\ItemFactory $itemFactory)
{
parent::__construct($itemFactory);
$this->add('mybutton', [
'label' => __('My button label')
]);
}
}
``` | Create di.xml following location
```
app/code/Learning/RewriteSales/etc/di.xml
```
Content should be
```
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Backend\Block\Widget\Context">
<plugin name="add_custom_button_sales_veiw" type="Learning\RewriteSales\Plugin\Widget\Context" sortOrder="1"/>
</type>
</config>
```
Create Context.php following loaction
```
app/code/Learning/RewriteSales/Plugin/Widget/Context.php
```
Content should be
```
namespace Learning\RewriteSales\Plugin\Widget;
class Context
{
public function afterGetButtonList(
\Magento\Backend\Block\Widget\Context $subject,
$buttonList
)
{
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$request = $objectManager->get('Magento\Framework\App\Action\Context')->getRequest();
if($request->getFullActionName() == 'sales_order_view'){
$buttonList->add(
'custom_button',
[
'label' => __('Custom Button'),
'onclick' => 'setLocation(\'' . $this->getCustomUrl() . '\')',
'class' => 'ship'
]
);
}
return $buttonList;
}
public function getCustomUrl()
{
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$urlManager = $objectManager->get('Magento\Framework\Url');
return $urlManager->getUrl('sales/*/custom');
}
}
```
Clear Magento cache and run update command
```
php bin/magento setup:upgrade
``` |
37,704,404 | So I've been wanting to bind the items of two pickers in Xamarin.Forms to my ViewModel. I have mainly used binding for textfields, where I just write something like:
```
<Label Text="{Binding CurrentDate}" />
```
and simply by setting the binding context, defining a property in the viewmodel
```
public System.DateTime CurrentDate{
get { return currentDate; }
set { currentDate = value; PropertyChanged(this, new PropertyChangedEventArgs("CurrentDate")); }
}
```
I am done binding. Now I have two pickers. The pickers represent a map/dictionary. Dictionary>. "A" is mapped to {"1","2"} and "B" is mapped to {"4","5"}. The first picker should show "A" and "B" as options. The second one should display the values associated with the chosen value from the first picker.
So there are two questions. 1) How do I bind a picker? 2) How do I bind a picker that has data that depends on another pickers selection?
I tried
```
<Picker Items="{Binding ItemsA}"></Picker>
```
With a matching property
```
public List<string> ItemsA
{
get { return itemsA;}
set { itemsA = value;PropertyChanged(this, new PropertyChangedEventArgs("ItemsA")); }
}
```
Am I missing out on something here? Help would be appreciated. | 2016/06/08 | [
"https://Stackoverflow.com/questions/37704404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/750565/"
] | Using [Zakaria's answer](https://stackoverflow.com/questions/37704393/how-to-create-a-link-that-actives-a-bootstrap-tab/37704861#37704637) I actually figured out a better solution.
Set an ID on each tab link like so:
```
<li><a data-toggle="tab" href="#tab-second" id="tab-second-link">Second Tab</a></li>
```
Then add an onclick event to any link:
```
<a class="btn btn-lg btn-primary" href="#" onclick="javascript: $('#tab-second-link').tab('show');";>Next</a>
``` | try this code (add bootstrap.js and jquery.js)
```
<div class="row">
<div class="tab-content">
<div class="tab-pane active" id="tab1">
//CONTENT OF TAB1
<div style="float: left;">
<a style="margin-left:5px;" class="btn btn-set btn-default" href="#tab2" data-toggle="tab"> MOVE TO TAB2</a>
</div>
</div>
<div class="tab-pane" id="tab2">
//CONTENT OF TAB2
<div style="float: left;">
<a class="btn btn-set btn-primary" href="#tab1" data-toggle="tab">MOVE TO TAB1</a></div>
</div>
</div>
```
example of using it to move between login and (s'inscrire) :
[](https://i.stack.imgur.com/IC1Zi.png) |
2,785,252 | Is it possible to find a retract $r:K \to M$ where the domain $K \subseteq \mathbb{R}^2$ is compact and convex and the codomain is given by
$M = [-1,1] \times \{0\} \ \cup \{0\} \times [-1,1] \subseteq K$ | 2018/05/17 | [
"https://math.stackexchange.com/questions/2785252",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/-1/"
] | I know this is a zombie response to a two-year-old question, but it seems to me that the OP here reinvented/rediscovered the concepts of [cardinality](https://en.wikipedia.org/wiki/Cardinality) **and** [equivalence classes](https://en.wikipedia.org/wiki/Equivalence_class), restricted to the set of natural numbers $\Bbb{N}\_0 := \{0, 1, 2, 3, ...\}$. From OP's comments:
>
> as I see it a subset that contains 3 members is exactly the same as every other member that contains 3 members, which means there's only 1 subset for each number of members, and only 1 infinite subset.
>
>
>
In other words, OP is really suggesting that 2 subsets of the "Unnatural Numbers" are to be considered "the same" if they can be [paired off in a 1-1 correspondence](https://en.wikipedia.org/wiki/Bijection). This is functionally equivalent to taking the subsets of the regular natural numbers $\Bbb{N}\_0$ and [forgetting](https://en.wikipedia.org/wiki/Forgetful_functor) the (labels/values/numerical properties) on the elements of any subset.
If we do this, then the only way to tell two subsets of $\Bbb{N}\_0$ apart is if they have different numbers of elements. Contrapositively, this is the same as saying two subsets of $\Bbb{N}\_0$ are "the same" if they have the same number of elements (i.e. there's a bijection between them). "Indistinguishability", in this sense, turns out to define what is usually referred to as an *equivalence relation* $\sim$ on the subsets of $\Bbb{N}\_0$. Although OP specifies "fuzziness" to mean non-symmetric in their post, their example of "fuzziness" is more like the "forgetfulness" one gets from an equivalence relation--we can indeed check that "indistinguishability" is an equivalence relation on subsets of $\Bbb{N}\_0$, which actually means it's symmetric (as well as reflexive and transitive). And the names of these equivalence classes are exactly the finite and countable cardinalities, because "cardinal numbers" are *exactly* what one gets by "forgetting" the labels, or interpretations, or relationships, between the elements of a set, and just keeping its "size".
*(The process of "forgetting" some or all irrelevant aspects of the structure on a highly structured set is very common in math and plays a role in foundations: see, for instance, [forgetful functors](https://en.wikipedia.org/wiki/Forgetful_functor). I suppose this could be considered another topic the OP 'discovered' for themselves, in a particular context.)* | You're really ignoring the following thing:
>
> If $f\colon A\to B$ is a bijection, then $F(X)=\{f(x)\mid x\in X\}$ defines a bijection between $\mathcal P(A)$ and $\mathcal P(B)$. In other words, equinumerous sets have equinumerous power sets.
>
>
>
What you sort of alleging here is that because your set lacks structure, it only has "a few subsets". But just because it lacks structure doesn't mean that it can be endowed with structure.
For example $\Bbb N$ lacks the structure of a field, but it can be endowed with one by pulling it from a different countable set. For example the rational numbers.
Of course, this ignores a more serious problem, that not all subsets are necessarily definable in a fixed structure. Even in the case of the natural numbers, not all subsets are definable. **Most** subsets are not definable.
What you might be looking for is the collection of definable subsets of a given structure. Then on a fixed countable set there can be many ways to structure it, and ask what sort of sets are definable in a fixed structure. This acts *a bit* like a power set, but not quite exactly that.
---
Let's leave, for a second, the land of countable sets. And leave the axiom of choice behind. Without the axiom of choice you get sets which can have actual limitations on what kind of structures can be put on them. You can find sets that cannot be endowed with a structure of a field, or a linear order, and so on and so forth.
In some cases this in fact leads to this sort of "intuitive" thought that the only subsets you can have are finite or complement of finite sets. Such sets are called *amorphous sets* and they are a rich source for counterexamples in failures related to choice. |
13,814,763 | Ok. Not sure this is a good idea. I'm building a template which passes a JSON config to a Javascript file assembling the template.
For links I need to include some logic how to build them in my JSON config. I would have to call this:
```
path.href.replace( /.*view=/, "" ) + ".cfm?id="+content.vcard.adresses[1]["iln/gln"]
```
Which in my config JSON:
```
<ul data-template="true" data-config='{
"type":"listview",
"link":"path.href.replace( /.*view=/, '' ) + '.cfm?id='+content.vcard.adresses[1]['iln/gln']",
"iconpos":"right"
}'></ul>
```
Will not work because of quotation-mark-mess, so the JSON is valid, but wrapping it in single quotes messes the HTML up.
**Question**:
Is there any way to pass this without breaking the HTML? Since it's a template I would like to keep the javascript logic as clean as possible = not put in custom methods for every template instance. So I would like to keep the method call here.
Thanks! | 2012/12/11 | [
"https://Stackoverflow.com/questions/13814763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/536768/"
] | In fact it is [preflight request](https://developer.mozilla.org/en-US/docs/HTTP_access_control#Preflighted_requests), because Prototype adds custom headers [X-Requested-With, X-Prototype-Version](http://api.prototypejs.org/ajax/) to the request. Because of these headers browser sends first `OPTIONS` request. [XHR spec](http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader%28%29-method) says:
>
> For non same origin requests using the HTTP GET method a preflight request is made when headers other than Accept and Accept-Language are set.
>
>
>
How to solve this problem? I can see only one possibility to solve this ASAP: completely overwrite method `Ajax.Request#setRequestHeaders()`, e.g. insert this script right after Prototype.js:
```
Ajax.Request.prototype.setRequestHeaders = function() {
var headers = {
// These two custom headers cause preflight request:
//'X-Requested-With': 'XMLHttpRequest',
//'X-Prototype-Version': Prototype.Version,
'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
};
if (this.method == 'post') {
headers['Content-Type'] = this.options.contentType +
(this.options.encoding ? '; charset=' + this.options.encoding : '');
/* Force "Connection: close" for older Mozilla browsers to work
* around a bug where XMLHttpRequest sends an incorrect
* Content-length header. See Mozilla Bugzilla #246651.
*/
if (this.transport.overrideMimeType &&
(navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005)
headers['Connection'] = 'close';
}
if (typeof this.options.requestHeaders == 'object') {
var extras = this.options.requestHeaders;
if (Object.isFunction(extras.push))
for (var i = 0, length = extras.length; i < length; i += 2)
headers[extras[i]] = extras[i+1];
else
$H(extras).each(function(pair) { headers[pair.key] = pair.value; });
}
for (var name in headers)
this.transport.setRequestHeader(name, headers[name]);
}
```
This patch removes custom headers from any AJAX request. In case when you still need these headers for non-CORS requests, more logic may be added which will give possibility to disable these headers in options for `new Ajax.Request()` (I'll skip this variant here to make answer shorter). | I've never used Prototype and i'm not sure how much use i'll be. But I had a quick look at the docs and I didn't see any support for method and parameters.
So try:
```
new Ajax.Request(REQUEST_ADDRESS+"?stationString="+station_id, {
onSuccess: displayMetar,
onFailure: function() {
$("errors").update("an error occurred");
}
});
```
Also I just noticed that stationString in your example should be in quotes assuming it isn't a variable. |
18,794,943 | I'm trying to write a program that decides whether a circle is inside/touching a rectangle. The user puts in the center point for the circle and the radius, and two diagonal points for the rectangle.
I'm not sure how to include all points of the circumference of the circle, to tell that there is at least one point in/touching the rectangle. Anyone sure how to do this?
When I run my current program, I'll purposely enter points of a circle being inside of a rectangle, and should work with the if statements I put, but it prints out the wrong answer.
```
import java.util.Scanner;
public class lab4 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double cx, cy, x, y, r, p1x, p1y, p2x, p2y, max;//input
String a;
System.out.print("Enter cx: ");
cx = in.nextDouble();
System.out.print("Enter cy: ");
cy = in.nextDouble();
System.out.print("Enter r: ");
r = in.nextDouble();
System.out.println("Enter x value of point 1:");
p1x = in.nextDouble();
System.out.println("Enter y value of point 1:");
p1y = in.nextDouble();
System.out.println("Enter x value of point 2:");
p2x = in.nextDouble();
System.out.println("Enter y value of point 2:");
p2y = in.nextDouble();
max = p2x;
if (p1x > max)
max = p1x;
max = p2y;
if (p1y > max)
max = p1y;
if (cx >= p1x && cx <= p2x)
a = "Circle is inside of Rectangle";
if (cx >= p1x && cx <= p2x)
a = "Circle is inside of Rectangle";
if (cx+r >= p1x && cx+r <= p2x)
a = "Circle is inside of Rectangle";
if (cx-r >= p1x && cx-r <= p2x)
a = "Circle is inside of Rectangle";
if (cy >= p1y && cy <= p2y)
a = "Circle is inside of Rectangle";
if (cy >= p1y && cy <= p2y)
a = "Circle is inside of Rectangle";
if (cy+r >= p1y && cy+r <= p2y)
a = "Circle is inside of Rectangle";
if (cy-r >= p1y && cy-r <= p2y)
a = "Circle is inside of Rectangle";
else
a = "Circle is outside of Rectangle";
System.out.println(a);
``` | 2013/09/13 | [
"https://Stackoverflow.com/questions/18794943",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2770679/"
] | As others have said, you need a chain of `if ... else if ... else if ... else` for your logic to work properly.
However, there's an easier approach. To test whether any part of a circle touches or is inside a rectangle, just expand the rectangle by the circle radius and then test whether the center of the circle is inside or on the expanded rectangle. Since you are using double coordinates, you can use a [`Rectangle.Double`](http://docs.oracle.com/javase/7/docs/api/java/awt/geom/Rectangle2D.Double.html) to do all the heavy lifting:
```
public static void main(String[] args) {
double cx, cy, r, p1x, p1y, p2x, p2y;
// first input cx, cy, r, p1x, p1y, p2x, and p2y
// construct a zero-width/height rectangle at p1
Rectangle2D.Double p1 = new Rectangle2D.Double(p1x, p1y, 0, 0);
// construct another one at p1
Rectangle2D.Double p2 = new Rectangle2D.Double(p2x, p2y, 0, 0);
// construct the union of the two
Rectangle2D.Double rect = p1.createUnion(p2);
// expand the rectangle
rect.setBounds(rect.x - r, rect.y - r, rect.w + 2 * r, rect.h + 2 * r);
// test for containment
if (rect.contains(cx, cy) {
a = "Circle is inside of Rectangle";
} else {
a = "Circle is outside of Rectangle";
}
System.out.println(a);
}
``` | because you treat every case separately without `else if` ,so if condition is you override value of a if the if condition is true ,your else if is related to the last if statement , not for all .
I suggest to concatenate every result to variable `a` like this to see which conditions are valid:
```
if (cx >= p1x && cx <= p2x)
a += "Circle is inside of Rectangle \n";
if (cx >= p1x && cx <= p2x)
a += "Circle is inside of Rectangle\n";
if (cx+r >= p1x && cx+r <= p2x)
a += "Circle is inside of Rectangle\n";
if (cx-r >= p1x && cx-r <= p2x)
a += "Circle is inside of Rectangle\n";
if (cy >= p1y && cy <= p2y)
a += "Circle is inside of Rectangle\n";
if (cy >= p1y && cy <= p2y)
a += "Circle is inside of Rectangle\n";
if (cy+r >= p1y && cy+r <= p2y)
a += "Circle is inside of Rectangle\n";
if (cy-r >= p1y && cy-r <= p2y)
a += "Circle is inside of Rectangle\n";
else
a += "Circle is outside of Rectangle\n";
```
Or if that's not what you want add else if to all your if statements like this :
```
if (cx >= p1x && cx <= p2x)
a = "Circle is inside of Rectangle";
else if (cx >= p1x && cx <= p2x)
a = "Circle is inside of Rectangle";
else if (cx+r >= p1x && cx+r <= p2x)
a = "Circle is inside of Rectangle";
else if (cx-r >= p1x && cx-r <= p2x)
a = "Circle is inside of Rectangle";
else if (cy >= p1y && cy <= p2y)
a = "Circle is inside of Rectangle";
else if (cy >= p1y && cy <= p2y)
a = "Circle is inside of Rectangle";
else if (cy+r >= p1y && cy+r <= p2y)
a = "Circle is inside of Rectangle";
else if (cy-r >= p1y && cy-r <= p2y)
a = "Circle is inside of Rectangle";
else
a = "Circle is outside of Rectangle";
``` |
180,590 | I have installed Magento 2.1.7, and theme Luma.
I then created a custom theme to inherit from Luma.
I was wondering if the content (blocks and widgets) are also inherited from the parent theme. In my case it does not see to happen. Is it the correct behavior or I am missing something?
See the screenshots.
Thanks
[](https://i.stack.imgur.com/zOlie.png)
[](https://i.stack.imgur.com/zFAhH.png) | 2017/06/24 | [
"https://magento.stackexchange.com/questions/180590",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/55595/"
] | Static blocks and widget are not showing in your custom theme because of luma theme blocks and widget are them specific define.
You can see below attached screen shot.
[](https://i.stack.imgur.com/XZj7X.png)
If you want to show all Luma theme static blocks and widget then you need to create it and assign to your theme. | because this content of luma theme show by widget. Widget only apply to specific theme design. So in your theme doesn't define any widget related to content block so it empty |
26,819,963 | I'm attempting to store persistent public data on an xmpp server using. Ideally, a user would be able to store a node on the server, and then retrieve that specific node later. This is all implemented on an openfire server, using strophe for the front end.
When I create the node, I use something like this:
```
$iq({
type: 'set',
to: 'pubsub.ubuntu',
id: 'pubsubecreatenode1'
}).c('pubsub', {xmlns: Strophe.NS.PUBSUB})
.c('create', {
node: "princely_musings";
});
```
which returns a result stanza with a create node, unless I've already created the node, in which case it returns:
```
<iq id="pubsubecreatenode1" xmlns="jabber:client" type="error"
from="pubsub.ubuntu"
to="admin@ubuntu">
<pubsub xmlns="http://jabber.org/protocol/pubsub">
<create node="princely_musings"></create>
</pubsub>
<error code="409" type="cancel">
<conflict xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"></conflict>
</error>
</iq>
```
I also publish to it using this:
```
$iq({
type: "set",
to: 'pubsub.ubuntu',
id: 'pub1'
}).c("pubsub", {
xmlns: Strophe.NS.PUBSUB
}).c("publish", {
node: "princely_musings"
}).c("item")
.c("object", {xmlns: "http://www.w3.org/2005/Atom"})
.h("somedata");
```
Which *also* returns a successful IQ result stanza.
However, when I go to discover the nodes, I get an item-not-found error when requesting a specific node (`princely_musings`), or an empty list when not specifying a node.
```
$iq({
type: "get",
to: 'pubsub.ubuntu',
id: "disco1"
}).c("query", {
xmlns: Strophe.NS.DISCO_ITEMS
});
```
and alternatively for a specific node:
```
.c("query", {
xmlns: Strophe.NS.DISCO_ITEMS,
node: "princely_musings"
});
```
These return:
```
<iq id="disco1" xmlns="jabber:client" type="result"
from="pubsub.ubuntu"
to="admin@ubuntu">
<query xmlns="http://jabber.org/protocol/disco#items"></query>
</iq>
```
and
```
<iq id="disco1" xmlns="jabber:client" type="error"
from="pubsub.ubuntu"
to="admin@ubuntu">
<query xmlns="http://jabber.org/protocol/disco#items"
node="princely_musings">
</query>
<error code="404" type="cancel">
<item-not-found xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"></item-not-found>
</error>
</iq>
```
The conflict errors that I arise when I try to create an existing node lead me to believe that I *am* appropriately storing the nodes on the server, however I can't determine why my discovery iq stanzas are failing to find anything. Is there something I'm missing or have misconfigured in these calls, or is there another protocol I should be using for this operation? | 2014/11/08 | [
"https://Stackoverflow.com/questions/26819963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2595638/"
] | Try this:
```vb
<%
Dim Views : Views ="Two" 'Change this to check
Response.write "Initial View =" & Views & "<br/>"
'But "One" will always be printed
If InStr(Views,"One")=0 Then
'add if there is no "One" already
Views = Views & ",One"
End If
Response.write "New View =" & Views & "<br/>"
Dim ArrValues : ArrValues =Array("One","Two","Three")
Dim Counter
For Counter=0 to UBound(ArrValues)
If InStr(Views,ArrValues(Counter))<>0 Then
%>
<table>
<tr>
<td>Table For View <%=ArrValues(Counter)%></td>
</tr>
</table>
<%
'Response.write ArrValues(Counter) & "<br/>"
End If
Next
%>
``` | There are multiple ways to approach this but without changing your code to much, it can be done by splitting your `Views` variable into an Array using the comma `,` as a delimiter. Once you have the Array use a `For` loop to iterate through the Views and use a `Select` statement to return the correct view.
As you specified that Table One will always be included it has been left outside of the loop.
Something like this (not tested);
```vb
<%
Dim item, items
'Build the array from the Views comma separated string
Views = Split(Views, ",")
'Always include Table One
%>
<table>
<tr>
<td>Table For View One</td>
</tr>
</table>
<%
'Check we have an Array built from the Split().
If IsArray(Views) Then
'How many views have we requested?
items = UBound(Views)
For item = 0 To items
'What view are we current looking at in the loop?
Select Case LCase(Trim(Views(item) & ""))
Case "two"
%>
<table>
<tr>
<td>Table For View Two</td>
</tr>
</table>
<%
Case "three"
%>
<table>
<tr>
<td>Table For View Three</td>
</tr>
</table>
<%
End Select
Next
End If
%>
```
Depending on the complexity of your views you could break each table into it's own Sub procedure or one Sub procedure and call in place of the in-line table definitions. Something like below;
```vb
Sub ShowTable(view)
'Keep all in-line table definitions together.
Select Case Trim(LCase(view & ""))
Case "one"
%>
<table>
<tr>
<td>Table For View One</td>
</tr>
</table>
<%
Case "two"
%>
<table>
<tr>
<td>Table For View Two</td>
</tr>
</table>
<%
Case "three"
%>
<table>
<tr>
<td>Table For View Three</td>
</tr>
</table>
<%
End Select
End Sub
```
In the main loop you would added `ShowTable()` calls in place of any in-line table code, for example;
```vb
<%
Dim item, items
'Build the array from the Views comma separated string
Views = Split(Views, ",")
'Always include Table One
Call ShowTable("one")
'Check we have an Array built from the Split().
If IsArray(Views) Then
'How many views have we requested?
items = UBound(Views)
For item = 0 To items
'What view are we current looking at in the loop?
Call ShowTable(views(item))
Next
End If
%>
```
Your output will then look something like this (*if you pass `"Two, Three"`*) for example;
```html
<table>
<tr>
<td>Table For View One</td>
</tr>
</table>
<table>
<tr>
<td>Table For View Two</td>
</tr>
</table>
<table>
<tr>
<td>Table For View Three</td>
</tr>
</table>
```
---
>
> **Update based on OP feedback**
>
>
> If [you don't want multiple tables](https://stackoverflow.com/questions/26819941/loop-based-in-variable-value-in-asp-classic#comment42249645_26842020) (*which is not clear from your question*) then just remove the `<table>` and `</table>` in-line definitions (*in the `ShowTable()` procedure*), this will create the "guts" of your table (*a series of table rows*).
> Then in the example code above just add `<table>` at the start and after the code `</table>`, which will encapsulate your dynamically generated table rows into one table.
>
>
>
> ```vb
> <table>
> <%
> Dim item, items
> 'Build the array from the Views comma separated string
> Views = Split(Views, ",")
>
> 'Always include Table One
> Call ShowTable("one")
> 'Check we have an Array built from the Split().
> If IsArray(Views) Then
> 'How many views have we requested?
> items = UBound(Views)
> For item = 0 To items
> 'What view are we current looking at in the loop?
> Call ShowTable(views(item))
> Next
> End If
> %>
> </table>
>
> ```
>
> Your output will then look something like this (*if you pass `"Two, Three"`*) for example;
>
>
>
> ```html
> <table>
> <tr>
> <td>Table For View One</td>
> </tr>
> <tr>
> <td>Table For View Two</td>
> </tr>
> <tr>
> <td>Table For View Three</td>
> </tr>
> </table>
>
> ```
>
> |
24,022,988 | I am trying to get my master changes into my local branch by doing
```
git checkout MyPersonalBranch
git rebase master
```
then I get the error
```
Patch failed at ..blah blah
When you have resolved this problem, run "git rebase --continue".
If you prefer to skip this patch, run "git rebase --skip" instead.
To check out the original branch and stop rebasing, run "git rebase --abort".
```
When I try `git rebase --continue` I get the error
```
xxx.client.jar: needs merge
You must edit all merge conflicts and then
mark them as resolved using git add
```
I want it to keep the xxx.jar in MyPersonalBranch. How do I tell git not to try to merge this one file? | 2014/06/03 | [
"https://Stackoverflow.com/questions/24022988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1110437/"
] | In general, you can use the `--strategy` option to specify how conflicts should be handled. The strategy `theirs` blindly replaces files.
However, in your case, you've only got a single file. You really won't want to use the `theirs` strategy for all files. Instead, after you get the message to resolve the conflict, you can checkout that one specific file from the branch:
```
git checkout <branch> yourfile
```
(At that point, `<branch>` still refers to the branch as it was before the rebase started.) | * check `git status` to see what conflicts exist as some must
* edit the files to resolve said conflicts
* `git add` the files you modifed
* `git status` should no longer show any 'both modified' files
* `git rebase --continue`
Depending upon how many times you made changes to the jar you mentioned, you will have to take different actions to put it into the desired state at the right time. Hopefully all your edits occured in a single commit, in which case you simply need to adjust its contents to be correct while rebasing. You can manually put the right file in place during the conflict or at the stop you could try checking out using the file and commit-id from when you made the first change to it.
But if you have already pushed your branch you really shouldn't be rebasing at all. You should probably just merge origin/master into your branch. |
13,625 | I recently tiled a bathroom myself for the first time, only to discover afterward that I was not as successful at cleaning the excess grout off as I had initially thought. As a result, there are now a few patches of set grout on the tiles. What is the best way to clean this off now?
Thanks! | 2016/07/22 | [
"https://lifehacks.stackexchange.com/questions/13625",
"https://lifehacks.stackexchange.com",
"https://lifehacks.stackexchange.com/users/12305/"
] | Use a razor blade scraper to remove set grout from tile. For stubborn areas, use a Pumie Scouring Sick. Cheap, works great, doesn’t mar surface.[](https://i.stack.imgur.com/ZifP5.jpg) | microfibre cloth are scratchy to help scrape the excess grout but not mark the tile if this doesnt work try in a small area a steel wool cloth lightly see if it works better |
47,402,460 | I have a basic table in javascript and a few lines of code where I compare the first values from each of the two tables. It skips the 'else if' statement and just goes straight to the 'else' at the end, when the 'else if' condition is true. I'm pretty new to all this so I won't be surprised if I messed up somewhere obvious. Any help is much appreciated.
```
var firstEquation = ['2', 'x', '+', '1', 'y', '=', '8'];
var secondEquation = ['3', 'x', '-', '1', 'y', '=', '7'];
if ( firstEquation[1] > secondEquation[1] ) {
print("Outcome 1");
} else if ( firstEquation[1] < secondEquation[1] ) {
print("Outcome 2");
} else {
print("Else");
}
``` | 2017/11/20 | [
"https://Stackoverflow.com/questions/47402460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8974577/"
] | JavaScript starts counting array indexes at 0. You've essentially said:
```
if ( "x" > "x" ) {
print("Outcome 1");
} else if ( "x" < "x" ) {
print("Outcome 2");
} else {
print("Else");
}
```
Since `"x"` is the second element in each array, and `"x" = "x"`, you will always hit the else statement. Change your array indexes to `firstEquation[0]` and `secondEquation[0]` to compare the first elements of the arrays. | You are comparing the second value, to compare first value use [0].
It goes straight to the last else because 'x' is not less nor greater than 'x' |
7,573,067 | I'm using different books to learn rails and they're all using different versions of ruby and rails. I've got instructions on how to load/use different versions of rails, but I don't know how to do it with ruby.
Can anyone tell me if this is possible and how to indicate which ruby I am using for each app?
i'm using mac os snow leopard. ruby 1.87 is installed currently in usr/bin | 2011/09/27 | [
"https://Stackoverflow.com/questions/7573067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/588498/"
] | Use [rvm](http://beginrescueend.com/rvm/install/). It manages different ruby versions and even different gemsets (e.g. per application). | The combination of [rbenv](https://github.com/sstephenson/rbenv) and [ruby-build](https://github.com/sstephenson/ruby-build) are a lighter weight alternative to the aforementioned RVM, though I prefer RVM personally. |
24,417,712 | I have a table of values with decimals and whole numbers. Some of the decimals have zeros two places after the decimal point (e.g. `0.60`) or the two places after the decimal point are both zeros (e.g. `4.00`).
How do I make sure any zeros are removed from after the decimal point? (So the aforementioned numbers would be `0.6` and `4`.) | 2014/06/25 | [
"https://Stackoverflow.com/questions/24417712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3676776/"
] | The `General` format will not show any trailing decimal zeros. Regardless of whether the number is entered manually or calculated, if the cell format is `General`, Excel will only show the decimals required to represent the number. | Please try:
```
=INT(A1*100)/100
```
and copy down to suit, assuming your data is in ColumnA and that formatting is 'General'.
---
A comparison of various possibilities:
[](https://i.stack.imgur.com/sFl42.jpg)
[It seems that for the accepted A to be correct the Q may be off topic (since @teylyn's solution would work also, is much simpler and requires no programming) - unless the objective is to convert to strings, which is not mentioned as a requirement.] |
24,015,948 | I am doing a web service in php to encode data to json. My php code is:
```
function getProgramDay($day)
{
global $DDBB_SERVER, $DDBB_USER, $DDBB_PASSWORD, $DDBB;
$sql = "SELECT program.id, programa.name FROM `mybd` WHERE program.day = '" . $day . "'";
$con = mysqli_connect($DDBB_SERVER, $DDBB_USER, $DDBB_PASSWORD, $DDBB);
if (!$con) {
die('Error de Conexión (' . mysqli_connect_errno() . '): ' . mysqli_connect_error());
}
if (!mysqli_set_charset($con, "utf8")) {
die("Error loading character set utf8:" . mysqli_error($con));
}
$result = mysqli_query($con, $sql);
$res = array();
// Prepare data
while ($row = mysqli_fetch_assoc($result)) {
$res[] = $row;
}
// Free resultset
mysqli_free_result($result);
// Close connection
mysqli_close($con);
// Return data
return $res;
}
```
And the result of this function in json is:
```
[{"id":"1","nombre":"Hello"}]
```
I would like that the result will be:
```
{"results":[{"id":"1","nombre":"Hello"}]}
```
How can I do this? I have tried but not works:
```
return "{'results':" .$res . "}";
```
Thank you so much :-) | 2014/06/03 | [
"https://Stackoverflow.com/questions/24015948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/752254/"
] | ```
return json_encode(array("results"=>$res));
```
As said in the comment, if you want to return an array and create the json in the calling code, do it like this:
```
return array("results"=>$res);
``` | Your output
```
[{"id":"1","nombre":"Hello"}]
```
is an array (witch you build with) `// Prepare data
while ($row = mysqli_fetch_assoc($result)) {
$res[] = $row;
}`
What you want to have is an an object
`object(stdClass)#6 (1) {
["results"] => array(1) {
[0] => object(stdClass)#7 (2) {
["id"] => string(1) "1"
["nombre"] => string(5) "Hello"
}
}
}`
so change your Prepare data with [mysqli\_fetch\_object](http://us3.php.net/manual/en/mysqli-result.fetch-object.php) and use json\_encode |
7,235,269 | I've got a dynamic html table and I want to retrieve the data from that table using the POST method. Is it possible to do this? What other ways would you recommend to achieve this.
Here's a simple example from what I got:
```
<html>
<form id="form1" method="post" action="process.php">
<table id="tblSample" name="tblSample">
<tbody>
<tr>
<td>
John Appleseed
</td>
<td>
Australia
</td>
</tr>
<tr>
<td>
Mary Poppins
</td>
<td>
USA
</td>
<tr>
</tbody>
</table>
</form>
</html>
```
Maybe it's possible to store the info in a javascript array or variable in order to post it to the action file, I'm not sure.
I don't know if this has anything to do, but the table is generated dynamically. The rows and cells are added by the user using javascript.
I'd appreciate your answers very much. | 2011/08/29 | [
"https://Stackoverflow.com/questions/7235269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/663593/"
] | A table cannot be accessed as such, unless you use form elements (`input`, `textarea`, etc.) and add `name` attribute to them; then, you can access your elements with `$_POST`.
If you have your data in a table, the best way to retrieve our data is by JavaScript, using `innerHTML`. | You can assign the `innerHTML` of the form to a variable and use AJAX to post it back to the server as a string, or store it in a `textarea` and do the same. Regardless, you need to parse the string to extract the data. |
56,291,781 | i want to export data from my json to csv file but i get this error Cannot use object of type stdClass as array
i want to know please how i can use it as array
```html
public function exportUsers()
{
$users = ServicePoint::all()->where("nature", "SP")->toArray();
$users = ServicePoint::all()->where('statut','<>', 2);
$arrayCsv = [];
foreach ($users as $key => $line){
$arrayCsv[$key][] = $line['name'];
$arrayCsv[$key][] = $line['lastname'];
$arrayCsv[$key][] = $line['email'];
}
```
anything can help please | 2019/05/24 | [
"https://Stackoverflow.com/questions/56291781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8183519/"
] | The reason that I had strange errors was, that in the second builder function I didn't add the following code:
```
if (!snapshot.hasData) return const Text("Loading...");
```
Once I added it, it worked. Seems the data was just not ready yet, hence it couldn't be read and hence the error. | Be careful to also test for `snap.hasData()` in your nested `StreamBuilder`. |
5,525,289 | I am working on a very basic robotics project, and wish to implement voice recognition in it.
i know its a complex thing but i wish to do it for only 3 or 4 commands(or words).
i know that using wavin i can record audio. but i wish to do real-time amplitude analysis on the audio signal, how can that be done, the wave will be inputed as 8-bit, mono.
i have thought of divinding the signal into a set of some specific time, further diving it into smaller subsets, getting the average rms value over the subset and then summing them up and then see how much different they are from the actual stored signal.If the error is below accepted value for all(or most) of the sets, then print the word.
How can this be implemented?
if you can provide me any other suggestion also, it would be great.
Thanks, in advance. | 2011/04/02 | [
"https://Stackoverflow.com/questions/5525289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/688927/"
] | There is no simple way to recognize words, because they are basically a sequence of phonemes which can vary in time and frequency.
Classical isolated word recognition systems use signal [MFCC](http://en.wikipedia.org/wiki/Mel-frequency_cepstral_coefficient) (cepstral coefficients) as input data, and try to recognize patterns using HMM (hidden markov models) or DTW (dynamic time warping) algorithms.
You will also need a silence detection module if you don't want a record button.
For instance [Edimburgh University toolkit](http://www.cstr.ed.ac.uk/projects/speech_tools/) provides some of these tools (with good documentation).
If you don't want to build it "from scratch" or have a source of inspiration, [here](http://www.isip.piconepress.com/projects/speech/index.html) is an (old but free) implementation of such a system (which uses its own toolkit) with a [full explanation and practical examples](http://www.isip.piconepress.com/projects/speech/software/tutorials/production/fundamentals/current/) on how it works.
This system is a LVCSR (Large-Vocabulary Continuous Speech Recognition) and you only need a subset of it. If someone know an open source reduced vocabulary system (like a simple IVR) it would be welcome.
If you want to make a basic system from your own, I recommend you to use MFCC and DTW:
* For each target word to modelize:
+ record some instances of the word
+ compute some (eg each 10ms) delta-MFCC through the word to have a model
* When you want to recognize a signal:
+ compute some delta-MFCC of this signal
+ use DTW to compare these delta-MFCC to each modelized word's delta-MFCC
+ output the word that fits the best (use a threshold to drop garbage) | If you just want to recognize a few commands, there are many commercial and free products you can use. See [Need text to speech and speech recognition tools for Linux](https://stackoverflow.com/questions/877508/need-text-to-speech-and-speech-recognition-tools-for-linux) or [What is the difference between System.Speech.Recognition and Microsoft.Speech.Recognition?](https://stackoverflow.com/questions/2977338/what-is-the-difference-between-system-speech-recognition-and-microsoft-speech-rec) or [Speech Recognition on iPhone](https://stackoverflow.com/questions/1118400/speech-recognition). The answers to these questions link to many available products and tools. Speech recognition and understanding of a list of commands is a very common problem solved commercially. Many of the voice automated phone systems you call uses this type of technology. The same technology is available for developers.
From watching these questions for few months, I've seen most developer choices break down like this:
* Windows folks - use the System.Speech features of .Net or Microsoft.Speech and install the free recognizers Microsoft provides. Windows 7 includes a full speech engine. Others are downloadable for free. There is a C++ API to the same engines known as SAPI. See at <http://msdn.microsoft.com/en-us/magazine/cc163663.aspx>. or <http://msdn.microsoft.com/en-us/library/ms723627(v=vs.85).aspx>
* Linux folks - Sphinx seems to have a good following. See <http://cmusphinx.sourceforge.net/> and <http://cmusphinx.sourceforge.net/wiki/>
* Commercial products - Nuance, Loquendo, AT&T, others
* Online service - Nuance, Yapme, others
Of course this may also be helpful - <http://en.wikipedia.org/wiki/List_of_speech_recognition_software> |
18,643,642 | Building thrift 0.9.1 (support C, C++, java, C#, perl, python) on Ubuntu 13.04 I am getting this error.
./configure run without any options, make run without any options...
```
Making all in test
make[2]: Entering directory `/home/dvb/sw/thrift-0.9.1/test'
Making all in nodejs
make[3]: Entering directory `/home/dvb/sw/thrift-0.9.1/test/nodejs'
make[3]: Nothing to be done for `all'.
make[3]: Leaving directory `/home/dvb/sw/thrift-0.9.1/test/nodejs'
Making all in cpp
make[3]: Entering directory `/home/dvb/sw/thrift-0.9.1/test/cpp'
Makefile:832: warning: overriding commands for target `gen-cpp/ThriftTest.cpp'
Makefile:829: warning: ignoring old commands for target `gen-cpp/ThriftTest.cpp'
/bin/bash ../../libtool --tag=CXX --mode=link g++ -Wall -g -O2 -L/usr/lib -o libtestgencpp.la ThriftTest_constants.lo ThriftTest_types.lo ../../lib/cpp/libthrift.la -lssl -lcrypto -lrt -lpthread
libtool: link: ar cru .libs/libtestgencpp.a .libs/ThriftTest_constants.o .libs/ThriftTest_types.o
ar: .libs/ThriftTest_constants.o: No such file or directory
make[3]: *** [libtestgencpp.la] Error 1
make[3]: Leaving directory `/home/dvb/sw/thrift-0.9.1/test/cpp'
make[2]: *** [all-recursive] Error 1
make[2]: Leaving directory `/home/dvb/sw/thrift-0.9.1/test'
make[1]: *** [all-recursive] Error 1
make[1]: Leaving directory `/home/dvb/sw/thrift-0.9.1'
make: *** [all] Error 2
dvb@dvb-u13:~/sw/thrift-0.9.1$
``` | 2013/09/05 | [
"https://Stackoverflow.com/questions/18643642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1874268/"
] | I ran into this problem tonight and "fixed" it. The problem is that ar(1) can't find the .o files in the directory test/cpp/.libs. I'm sure that there's some missing magic in the Makefile.am in test/cpp, but I've neither the patience or automake-fu to fix that.
Instead, I just symlinked the .o files from test/cpp to test/cpp/.libs/. That fixes the build of the C++ tests.
```
cd thrift-0.9.1/test/cpp/.libs
for i in ../*.o; do echo $i; ln -s $i .; done
``` | David V is right that 0.9.1 is broken but 0.9.2 works. The build instructions seem to be a broken link as well. So here are the commands that worked for me, from a fresh Ubuntu install:
```
# Install java if you don't have it
sudo apt-get install default-jre
# install build dependencies
sudo apt-get install libboost-dev libboost-test-dev libboost-program-options-dev libboost-system-dev libboost-filesystem-dev libevent-dev automake libtool flex bison pkg-config g++ libssl-dev
cd /tmp
curl http://archive.apache.org/dist/thrift/0.9.2/thrift-0.9.2.tar.gz | tar zx
cd thrift-0.9.2/
./configure
make
sudo make install
#test that it can run
thrift --help
```
(credit goes to [these](http://www.saltycrane.com/blog/2011/06/install-thrift-ubuntu-1010-maverick/) helpful instructions; I just replaced 0.9.1 with 0.9.2) |
37,318,719 | Laravel ajax returns 500 (Internal Server Error). Could you tell me what is the problem?
**sample.brade.php**
```
<script type="text/javascript">
$("input.dog_check").click(function(){
var amount = 10000;
var dataString = 'amount='+amount;
console.log(dataString);
$.ajax({
type:'POST',
data:dataString,
url: 'save_temporary_data',
success:function(data) {
alert(data);
}
});
});
</script>
```
**routes.php**
```
Route::post('/save_temporary_data', 'PaymentsController@saveTemporaryData');
```
**PaymentsController.php**
```
~~~
public function saveTemporaryData(){
if (Request::ajax()){
$amount = $_POST['amount'];
$insert = "insert into temporary_data values('$amount')";// Do Your Insert Query
if(mysql_query($insert)) {
echo "Success";
} else {
echo "Cannot Insert";
}
}
}
~~~
```
**update**
I added `<meta name="csrf-token" content="{{ csrf_token() }}">` and the following into `sample.blade.php`. However it cannot solve the problem.
```
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
```
**sample.blade.php**
```
<head>
<link rel="stylesheet" href="/css/header.css">
<link rel="stylesheet" href="/css/common.css">
<link rel="stylesheet" href="/css/reset.css">
<link rel="stylesheet" href="/css/edit_profile.css">
<link rel="stylesheet" href="/css/footer.css">
<link rel="stylesheet" href="/css/host_profile.css">
<link rel="stylesheet" href="/css/validationEngine.jquery.css">
<meta name="csrf-token" content="{{ csrf_token() }}">
</head>
~~~
$("input.dog_check").click(function(){
var amount = 10000;
var dataString = 'amount='+amount;
console.log(dataString);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type:'POST',
data:dataString,
url: 'save_temporary_data',
success:function(data) {
alert(data);
}
});
});
``` | 2016/05/19 | [
"https://Stackoverflow.com/questions/37318719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3575850/"
] | ```
<meta name="csrf-token" content="{{ csrf_token() }}" />
<script>
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
jQuery.ajax({
type:'POST',
url :"{{url('save_temporary_data')}}",
data:{_token: CSRF_TOKEN,amount:amount},
success:function(data){
alert(data);
}
});
</script>
```
in route file
```
Route::post('/save_temporary_data','PaymentsController@saveTemporaryData');
```
in controller
```
public function saveTemporaryData(Request $request){
echo $request['amount'];
}
``` | It is solved by referencing the following page. Thank [ajax post in laravel 5 return error 500 (Internal Server Error)](https://stackoverflow.com/questions/30154489/ajax-post-in-laravel-5-return-error)-500-internal-server-error?rq=1 |
95 | What's your top trick for getting a new employee set up quickly? Do you use images, scripts, something else? | 2009/04/30 | [
"https://serverfault.com/questions/95",
"https://serverfault.com",
"https://serverfault.com/users/32/"
] | I have found that the best to way optimize a new user setup is to start before they are hired. Get with the manager and find out what the employee will need. Have the hiring manager let you know the minute they accept the position. Have the manager give you all their info so you can do things like set up their login credentials.
In my last job, the most important thing for us was knowing WHERE the new employee was going to sit. It's so much easier to set up a computer if there is a desk to put it on. | As has been mentioned, setting up the machine with any productivity applications, corporate software, and a proper web browser (Firefox) are important basics. Shared space is another good point, though you should also make sure to map that properly on the user's machine and probably provide links to it so that the user knows it is available. In the same vein, bookmarks in the web browser to helpful intranet sites are a definite plus for users new to the company. |
14,628,101 | I am trying to enter `MPMediaItemArtwork` Image into `UITableView's` cell's ImageView with following code.
```
MPMediaItemArtwork *artwork = [[[self.arrayOfAlbums objectAtIndex:indexPath.row] representativeItem]valueForProperty:MPMediaItemPropertyArtwork];
UIImage *artworkImage = [artwork imageWithSize: cell.imageView.bounds.size];
if (artworkImage)
{
cell.imageView.image = artworkImage;
}
else
{
cell.imageView.image = [UIImage imageNamed: @"noArtwork.png"];
}
```
It's okay when i insert Artwork image in `UITableView's` cell `ImageView`.
But when my artwork image is too small or big , it's happened like following pic.
Not in completely fill in cell's ImageView.

You see that? I want to set Fill with `Stretch` like iOS Music App
Here is Build-in App Artwork Image that set Completely fill with `Stretch`

I want to do like that.
So i used `cell.imageView.contentMode = UIViewContentModeScaleAspectFill;` however it's not effect.
So how can i do that?
Thanks you for your work. | 2013/01/31 | [
"https://Stackoverflow.com/questions/14628101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/973477/"
] | Try this for calculating a new and fitting image;
Adjust `newRect` to the rect of your cell.
```
// scale and center the image
CGSize sourceImageSize = [artworkImage size];
// The rectangle of the new image
CGRect newRect;
newRect = CGRectMake(0, 0, 40, 33);
// Figure out a scaling ratio to make sure we maintain the same aspect ratio
float ratio = MAX(newRect.size.width / sourceImageSize.width, newRect.size.height / sourceImageSize.height);
UIGraphicsBeginImageContextWithOptions(newRect.size, NO, 1.0);
// Center the image in the thumbnail rectangle
CGRect projectRect;
projectRect.size.width = ratio * sourceImageSize.width;
projectRect.size.height = ratio * sourceImageSize.height;
projectRect.origin.x = (newRect.size.width - projectRect.size.width) / 2.0;
projectRect.origin.y = (newRect.size.height - projectRect.size.height) / 2.0;
[sourceImage drawInRect:projectRect];
UIImage *sizedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
cell.imageView.image = sizedImage;
``` | The line
```
UIImage *artworkImage = [artwork imageWithSize: cell.imageView.bounds.size];
```
creates an image with the size of the cell. So, it's scaled in this line and the image won't be bigger than the cell and therefore it will not scale afterwards.
I would leave the image at it's original size or at a size 2x the cell size and leave the scaling up to `contentMode`.
```
CGSize newSize = CGSizeMake(artwork.bounds.size.width, artwork.bounds.size.height)
UIImage *artworkImage = [artwork imageWithSize: newSize];
``` |
6,666,060 | Having created a java web service client using wsimport on a wsdl, I need to set the Authorization header for each soap message embedded in an http request. Having generated a subclass of javax.xml.ws.Service, how can I append an http header to each outgoing request??? | 2011/07/12 | [
"https://Stackoverflow.com/questions/6666060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/349913/"
] | Here is the code, based on Femi's answer.
It can be a little tricky to figure out. Works beautifully!
```
Service jaxwsService = Service.create(wsdlURL, serviceName);
Dispatch<SOAPMessage> disp = jaxwsService.createDispatch(portName, SOAPMessage.class, Service.Mode.MESSAGE);
//Add HTTP request Headers
Map<String, List<String>> requestHeaders = new HashMap<>();
requestHeaders.put("Auth-User", Arrays.asList("BILL_GATES"));
disp.getRequestContext().put(MessageContext.HTTP_REQUEST_HEADERS, requestHeaders);
``` | For the sake of completeness and to help others in similar situations, I'd like to illustrate the IMHO cleanest solution using the JAX-WS-handler-chain:
1) Sub-class your service-class (not the port-class) in a different (non-generated) package. Because the service-class (and its entire package) was likely generated from a WSDL, your changes to the sub-class are not lost, when you update your service-class after a WSDL change.
2) Annotate your service-sub-class like this (import `javax.jws.HandlerChain`):
```
@HandlerChain(file="HandlerChain.xml")
public class MyService extends GeneratedService {
```
3) Create a file called `HandlerChain.xml` in the same package as your service-sub-class, i.e. next to `MyService` with the following content:
```
<?xml version="1.0" encoding="UTF-8"?>
<handler-chains xmlns="http://java.sun.com/xml/ns/javaee">
<handler-chain>
<handler>
<handler-name>co.codewizards.example.HttpHeaderExtensionSOAPHandler</handler-name>
<handler-class>co.codewizards.example.HttpHeaderExtensionSOAPHandler</handler-class>
</handler>
</handler-chain>
</handler-chains>
```
You may add multiple `<handler>` elements, btw.
And make sure that this file really ends up in your JAR! For example, when using Maven, you have to place it either in `${project}/src/main/resources/` (instead of `${project}/src/main/java/`) or you have to change your build-configuration to include resources from the `java`-folder! I recommend the latter, because it's cumbersome to have a parallel package-structure in the `resources`-folder, which is often forgotten during refactorings.
4) Implement your `HttpHeaderExtensionSOAPHandler` -- similar to this:
```
import static com.google.common.base.Preconditions.*;
import java.util.*;
import javax.xml.namespace.QName;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;
import co.codewizards.webservice.WebserviceContext;
public class HttpHeaderExtensionSOAPHandler implements SOAPHandler<SOAPMessageContext> {
@Override
public boolean handleMessage(SOAPMessageContext context) {
checkNotNull(context, "context");
Boolean outboundProperty = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
checkNotNull(outboundProperty, "outboundProperty");
if (outboundProperty.booleanValue()) {
WebserviceContext<?, ?> webserviceContext = WebserviceContext.getThreadWebserviceContextOrFail();
String something = (String) webserviceContext.___(); // my API method ;-)
@SuppressWarnings("unchecked")
Map<String, List<String>> requestHeaders = (Map<String, List<String>>) context.get(MessageContext.HTTP_REQUEST_HEADERS);
if (requestHeaders == null) {
requestHeaders = new HashMap<String, List<String>>();
context.put(MessageContext.HTTP_REQUEST_HEADERS, requestHeaders);
}
requestHeaders.put(MyService.MY_CONSTANT, Collections.singletonList(something));
}
return true;
}
@Override
public boolean handleFault(SOAPMessageContext context) { return true; }
@Override
public void close(MessageContext context) { }
@Override
public Set<QName> getHeaders() { return Collections.emptySet(); }
}
```
In my example above (and in my productive code) I obtain the data to be passed into the HTTP request headers from a `ThreadLocale`, i.e. my current thread's context. Since this `WebserviceContext` is my custom class, you'll need to implement your own way to access your data. |
41,886,181 | I am attempting to obtain a result of row information coming from tables named book\_info and copy\_info, and then (if they exist) results from a table named publisher(whose foreign key is in copy\_info), and (if they exist) result from a table name genre via a junction table called books\_genres. Below, $safe\_copy\_id is defined in a php statement, I left it in for the sake of the example.
This works:
```
SELECT * FROM book_info, copy_info
LEFT OUTER JOIN publisher ON copy_info.publisher_id = publisher.publisher_id
WHERE book_info.book_id = copy_info.book_id
AND copy_info.copy_id = $safe_copy_id LIMIT 1
```
and this works:
```
SELECT * FROM book_info, copy_info, books_genres
LEFT OUTER JOIN genre ON books_genres.genre_id = genre.genre_id
WHERE book_info.book_id = copy_info.book_id
AND copy_info.copy_id = $safe_copy_id LIMIT 1
```
But what I would really like to work is this:
```
SELECT * FROM book_info, copy_info, books_genres
LEFT OUTER JOIN publisher ON copy_info.publisher_id = publisher.publisher_id
LEFT OUTER JOIN genre ON books_genres.genre_id = genre.genre_id
WHERE book_info.book_id = copy_info.book_id
AND copy_info.copy_id = $safe_copy_id LIMIT 1
```
Is it that I should be nesting something here? Not sure how to move forward and would appreciate any insight. | 2017/01/27 | [
"https://Stackoverflow.com/questions/41886181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7038718/"
] | You need to use the second parameter of the callback - it should contain the raw response.
```
request.execute(function(jsonResp, rawResp) {
console.log('rawResp: ', rawResp);
var respObject = JSON.parse(rawResp); // rawResp is encoded JSON string with header, body, etc.
var respBody = respObject.gapiRequest.data.body; // in my case here it outputs the text of my txt file
});
```
>
> The callback function which executes when the request succeeds or fails. jsonResp contains the response parsed as JSON. If the response is not JSON, this field will be false. rawResp is the HTTP response. It is JSON, and can be parsed to an object which includes body, headers, status, and statusText fields.
>
>
>
src: <https://developers.google.com/api-client-library/javascript/reference/referencedocs#gapiclientrequest>
P.S. Nice find with docs about "not JSON-parseable"! It helped me to solve this! | I believe this is the link you are looking for : )
<https://developers.google.com/drive/v3/web/manage-downloads>
>
> Downloading the file requires the user to have at least read access. Additionally, your app must be authorized with a scope that allows reading of file content. For example, an app using the drive.readonly.metadata scope would not be authorized to download the file contents. Users with edit permission may restrict downloading by read-only users by setting the viewersCanCopyContent field to true.
>
>
> |
15,625,850 | When I try to add column names and row data to table model, I get null pointer exception. Column names come from list and i add them to table model as array. But in there I get the exception: `tableModel.addColumn(columnNames.toArray());
tableModel.addRow(rowData);`
My full code:
```
public class DBC extends JFrame{
static String tablo;
static JTextField tf = new JTextField(20);
static int columnCount;
static JPanel tfPanel = new JPanel();
static String[] sutunlar;
static JLabel sutunLabel;
static JPanel sutunPanel = new JPanel(new BorderLayout());
static JTable table;
static JScrollPane scrollPane;
static DefaultTableModel tableModel;
static Object[] columnNames;
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/project"
,"root","123456789");
final Statement statement = connect.createStatement();
JLabel tabloSec = new JLabel("Tablo Seçin:");
final JComboBox<String> tablolar = new JComboBox<String>();
final DatabaseMetaData md = connect.getMetaData();
final ResultSet rs = md.getTables(null, null, "%", null);
while (rs.next()) {
tablolar.addItem(rs.getString(3));
}
tablolar.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
tablo = tablolar.getSelectedItem().toString();
try {
ResultSet rs2 = statement.executeQuery("SELECT * FROM "+tablo);
ResultSetMetaData rsmd = rs2.getMetaData();
columnCount = rsmd.getColumnCount();
List<String> columnNames = new ArrayList<String>();
sutunlar = new String[columnCount];
Object rowData[][] = {{""}};
for(int i=0;i<columnCount;i++){
sutunlar[i] = rsmd.getColumnLabel(i+1);
columnNames.add(sutunlar[i]);
tableModel.addColumn(columnNames.toArray());
tableModel.addRow(rowData);
}
tableModel = new DefaultTableModel(rowData, columnNames.toArray());
table = new JTable();
table.setModel(tableModel);
table.repaint();
scrollPane = new JScrollPane(table);
sutunPanel.add(scrollPane);
sutunPanel.revalidate();
sutunPanel.repaint();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
JButton ekle = new JButton("Ekle");
ekle.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
try {
switch(tablo){
case "department":
statement.executeUpdate("INSERT INTO department(Name,Location) VALUES('"+tf.getText()+"')");
case "employee":
statement.executeUpdate("INSERT INTO employee(Id,FirstName,LastName,Sex,Address,Email,Salary,BirthDate,JoinDate) VALUES('"+tf.getText()+"')");
case "engineer":
statement.executeUpdate("INSERT INTO engineer(EngineerType) VALUES('"+tf.getText()+"')");
case "manager":
statement.executeUpdate("INSERT INTO manager(Department) VALUES('"+tf.getText()+"')");
case "project":
statement.executeUpdate("INSERT INTO project(Name,Number,Value) VALUES('"+tf.getText()+"')");
case "secretary":
statement.executeUpdate("INSERT INTO secretary(TypingSpeed) VALUES('"+tf.getText()+"')");
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
JButton cik = new JButton("Çık");
cik.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
JPanel panel = new JPanel(new FlowLayout());
panel.add(tabloSec);
panel.add(tablolar);
panel.add(sutunPanel);
panel.revalidate();
panel.add(ekle);
panel.add(cik);
JFrame frame = new JFrame("Deneme");
frame.setSize(600,600);
frame.setLocationRelativeTo(null);
frame.add(panel);
frame.setVisible(true);
}
}
``` | 2013/03/25 | [
"https://Stackoverflow.com/questions/15625850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1831187/"
] | What you're looking for is this:
```
$triggerOn = '04/01/2013 03:08 PM';
$user_tz = 'America/Los_Angeles';
echo $triggerOn; // echoes 04/01/2013 03:08 PM
$schedule_date = new DateTime($triggerOn, new DateTimeZone($user_tz) );
$schedule_date->setTimeZone(new DateTimeZone('UTC'));
$triggerOn = $schedule_date->format('Y-m-d H:i:s');
echo $triggerOn; // echoes 2013-04-01 22:08:00
``` | Create the date using the local timezone, then call `DateTime::setTimeZone()` to change it. |
46,012,144 | I am trying to get customer\_id of a stripe customer from the response of of charge entity. But response is not providing the customer id in return.
```
&stripe.Charge JSON: {
"id": "ch_1AxWbTFytruJp2FXW6iuRd1X",
"object": "charge",
"amount": 100,
"amount_refunded": 0,
"application": null,
"application_fee": null,
"balance_transaction": "txn_17JOXKFytruJp2FXS4XNisQd",
"captured": false,
"created": 1504339423,
"currency": "usd",
"customer": null,
"description": "My First Test Charge (created for API docs)",
"destination": null,
"dispute": null,
"failure_code": null,
"failure_message": null,
"fraud_details": {
},
"invoice": null,
"livemode": false,
"metadata": {
},
"on_behalf_of": null,
"order": null,
"outcome": null,
"paid": true,
"receipt_email": null,
"receipt_number": null,
"refunded": false,
"refunds": {
"object": "list",
"data": [
],
"has_more": false,
"total_count": 0,
"url": "/v1/charges/ch_1AxWbTFytruJp2FXW6iuRd1X/refunds"
},
"review": null,
"shipping": null,
"source": {
"id": "card_1AxWPmFytruJp2FXw4m0V0fN",
"object": "card",
"address_city": null,
"address_country": null,
"address_line1": null,
"address_line1_check": null,
"address_line2": null,
"address_state": null,
"address_zip": "10001",
"address_zip_check": "unchecked",
"brand": "Visa",
"country": "US",
"customer": null,
"cvc_check": "unchecked",
"dynamic_last4": null,
"exp_month": 4,
"exp_year": 2024,
"fingerprint": "sNtyd9sZ2vA6o4IM",
"funding": "credit",
"last4": "4242",
"metadata": {
},
"name": "Mandeep",
"tokenization_method": null
},
"source_transfer": null,
"statement_descriptor": null,
"status": "succeeded",
"transfer_group": null
}
```
But it has a customer field inside the object which is null. Can anyone please tell me why am I getting this null?
What I am trying to do is to make a system where customer can book anonymously on site and while creating the booking the customer gets registered and charged for the total amount of the booking. I need to keep track of the customer's stripe account id and card id. So the problem is if I am creating a customer then I am not able to get its card id but when I am charging the customer then I am not able to get the customer id.
Customer Response:
```
&stripe.Customer JSON: {
"id": "cus_BKAxGZre2HCNIU",
"object": "customer",
"account_balance": 0,
"created": 1504339424,
"currency": "usd",
"default_source": null,
"delinquent": false,
"description": null,
"discount": null,
"email": null,
"livemode": false,
"metadata": {
},
"shipping": null,
"sources": {
"object": "list",
"data": [
],
"has_more": false,
"total_count": 0,
"url": "/v1/customers/cus_BKAxGZre2HCNIU/sources"
},
"subscriptions": {
"object": "list",
"data": [
],
"has_more": false,
"total_count": 0,
"url": "/v1/customers/cus_BKAxGZre2HCNIU/subscriptions"
}
}
``` | 2017/09/02 | [
"https://Stackoverflow.com/questions/46012144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6443951/"
] | When you create a `charge` using only the credit card token, no Stripe customer is created, you only create a payment with no associated customer.
So it's normal that you the API returns `customer: null`.
Instead of charging a credit card, I think you should **charge a new customer**.
In your backend code, you could handle the payment in 2 steps:
* STEP 1: create a new customer, passing the credit card token to store
the customer's card
* STEP 2: charge the customer, using the customer ID returned by
STEP 1 API call.
Doing this, you charge the customer with the credit card that is stored in customer's data.
For more details, check here: <https://stripe.com/docs/quickstart#saving-card-information>
Does it make sense? | You can access card\_id while creating new customer using following code (in Golang):
```
for _, data := range customer.Sources.Values{
card_id = data.ID
}
fmt.Println(card_id)
```
I spend almost 1 day to figure it out. Actually in customer structure(under stripe package) there are some fields which are having embedded types and such fields are further connected to some other structure in different files. So there is hierarchy to access structure fields like above.
Hope this will solve your problem.
Thanks! |
68,373,918 | The following code produces the following output and ends up in kind of an endless loop with 100% cpu load.
```cpp
#include <iostream>
#include <set>
class Foo{};
void delete_object_from_set(std::set<Foo *>& my_set, Foo* ob)
{
std::set< Foo *>::iterator setIt;
std::cout << "Try to delete object '" << ob << "'..." << std::endl;
for(setIt = my_set.begin(); setIt != my_set.end(); ++setIt)
{
Foo * tmp_ob = *setIt;
std::cout << "Check object '" << tmp_ob << "'..." << std::endl;
// compare the objects
//
if(ob == tmp_ob)
{
// if the objects are equal, delete this object from the set
//
std::cout << "Delete object '" << tmp_ob << " from set..." << std::endl;
setIt = my_set.erase(setIt);
std::cout << "Deleted object '" << tmp_ob << " from set..." << std::endl;
}
}
std::cout << "loop finished." << std::endl;
};
int main()
{
Foo* ob = new Foo();
std::set< Foo * > my_set;
my_set.insert(ob);
delete_object_from_set(my_set, ob);
std::cout << "finished" << std::endl;
return 0;
}
```
The output:
```
Try to delete object '0x563811ffce70'...
Check object '0x563811ffce70'...
Delete object '0x563811ffce70 from set...
Deleted object '0x563811ffce70 from set...
```
so it does not finish, having 100% cpu load.
I know how to do it correctly (see below), but I cannot understand what is going on here. It's not an endless loop, since then it should output something continuously, but it just keeps doing *something*. Any idea what?
How to do it the right way: [Deleting elements from std::set while iterating](https://stackoverflow.com/questions/2874441/deleting-elements-from-stdset-while-iterating) and [How to remove elements from an std::set while iterating over it](https://stackoverflow.com/questions/20627458/how-to-remove-elements-from-an-stdset-while-iterating-over-it) | 2021/07/14 | [
"https://Stackoverflow.com/questions/68373918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4270676/"
] | Hokay, so you asked how this could loop infinitely without continuously triggering the "Check object" print.
The quick answer (that you already got from others) is that calling `operator++` on `my_set.end()` is UB, and thus able to do anything.
A deeper dive into GCC specifically (since @appleapple could reproduce on GCC, while my test in MSVC found no infinite loop) revealed some interesting stuff:
The `operator++` call is implemented as a call to `_M_node = _Rb_tree_increment(_M_node);` and that one looks as follows:
```
static _Rb_tree_node_base*
local_Rb_tree_increment(_Rb_tree_node_base* __x) throw ()
{
if (__x->_M_right != 0)
{
__x = __x->_M_right;
while (__x->_M_left != 0)
__x = __x->_M_left;
}
else
{
_Rb_tree_node_base* __y = __x->_M_parent;
while (__x == __y->_M_right)
{
__x = __y;
__y = __y->_M_parent;
}
if (__x->_M_right != __y)
__x = __y;
}
return __x;
}
```
So, it defaults to finding the "next" node by taking the first right, and then running all the way to the left. **But!** a look in the debugger at the `my_set.end()` node reveals the following:
```
(gdb) s
366 _M_node = _Rb_tree_increment(_M_node);
(gdb) p _M_node
$1 = (std::_Rb_tree_const_iterator<Foo*>::_Base_ptr) 0x7fffffffe2b8
(gdb) p _M_node->_M_right
$2 = (std::_Rb_tree_node_base::_Base_ptr) 0x7fffffffe2b8
(gdb) p _M_node->_M_left
$3 = (std::_Rb_tree_node_base::_Base_ptr) 0x7fffffffe2b8
```
Both the left and right of the `end()` node apparently points at itself. Why? Ask the implementer, but probably because it makes something else easier or more optimizable. But it does mean that in your case the UB you run into is an infinite loop on essentially:
```
__x->_M_left = __x;
while (__x->_M_left != 0)
__x = __x->_M_left; // __x = __x;
```
Again, this is the case for GCC, on MSVC it did not loop (debug threw an exception, release just ignored it; finished the loop and printed "loop finished." and "finished" as if nothing strange had happened). But that is the "fun" part about UB - anything could happen... | ```
for(setIt = my_set.begin(); setIt != my_set.end();)
{
Foo * tmp_ob = *setIt;
std::cout << "Check object '" << tmp_ob << "'..." << std::endl;
// compare the objects
//
if(ob == tmp_ob)
{
// if the objects are equal, delete this object from the set
//
std::cout << "Delete object '" << tmp_ob << " from set..." << std::endl;
setIt = my_set.erase(setIt);
std::cout << "Deleted object '" << tmp_ob << " from set..." << std::endl;
}
else
setIt++;
}
``` |
241,123 | Look at the conversation below please:
>
> A)I want to travel to the Black Bear Island next weekend.
>
> B) Good idea! Make a plan first, \_\_\_\_\_\_ you will enjoy more beautiful scenery.
>
>
>
which of the options below fits better in the blank? (I know that Option A is not a good fit)
```
A. But
B. And
C. So (that)
```
Also, Please explain What the difference is between "and" and "so that" when they mean "as a result"? (Do they?) | 2020/03/21 | [
"https://ell.stackexchange.com/questions/241123",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/110499/"
] | Let's tackle this question together. I've divided my answer into two parts, if you want the quick answer skip the first part.
In the English language we have several words to refer to the **reason** why an action happened/happens. there are also a couple of words and structures to refer to the **purpose** of an action, Let's review them together:
>
> **REASON**: because, as a result of, on account of, due to, as, since,etc.
>
>
> **PURPOSE**: so (that), So as to, (in order) to, etc.
>
>
>
Let's look at some examples:
>
> Charles went home **so that he would see his family.**
>
>
> Charles stayed up late **in order to finish the project.**
>
>
>
In these examples, the bold portion of the sentence shows the purpose of his action.
>
> Charles went home **since his mom wanted him home for Christmas**
>
>
> Charles worked late **because his boss called a meeting**
>
>
>
In the examples above, the bold part shows the reason why he did those actions.
>
> Cause: His mom wanted him home
>
>
> Effect: he went home.
>
>
>
In a nutshell,
```
purpose: the reason for why something is done
reason: the cause/justification for an action or event.
```
Consider a dam. The purpose of the dam was to retain water for irrigation. The reason the dam broke was because the water got too high.
>
> REF:<https://english.stackexchange.com/questions/92095/reason-vs-purpose>.
>
>
> REF:<https://www.quora.com/What-is-the-difference-between-purpose-and-reason>
>
>
>
“Reason” concerns cause and effect. “Purpose “ deals with conscious intent. Therefore, **So that** doesn't mean **as a result of**
---
Now, with that out of the way, let's see if we can use **and** instead of **so that**.
consider these examples:
>
> eat this cake *and you will regret it*!
>
>
> Visit Spain *and you will enjoy the beautiful scenery*.
>
>
> Call him *and he will deliver the package to your door.*
>
>
>
in all of these examples, the *italic* portion is telling us about the result of the action.
```
DO A, *B* will happen.
```
there's a great deal of certainty with each one, as if with the completion of A, B will most definitely take place.
Keep in mind, a sentence like:
>
> Touch this cake so that you will regret it!
>
>
>
Doesn't make much sense, you wouldn't normally tell someone to do something with the purpose of making them regret it! So, in this instance we can't replace *and* with *so that*. Compare it with this:
>
> eat your vegetables so that you'll have a strong body.
>
> The sentence above is perfectly valid.
>
>
>
Therefore, we realize that **and** and **so that** are not always interchange.
in the other two examples, you could replace *and* with *so that*. Although keep in mind the meaning changes slightly:
>
> Visit Spain so that you can enjoy the beautiful scenery. (visit Spain with the intention of enjoying the beautiful scenery - the purpose for your visit is/should be enjoying the beautiful scenery)
>
>
> Visit Spain and you will enjoy the beautiful scenery (really strong, if you visit Spain you will without a doubt enjoy the scenery)
>
>
>
To recap:
>
> use **and** when you want to say if action A is done, Action B will most definitely take place or have certain result.
>
>
> use **so that** (and by extension **in order to**) to talk about the purpose of an action.
>
>
> use **because** (and by extension, other words I mentioned in the first part of my answer) to talk about the reason, cause or justification of an action.
>
>
> | ```
"and" shows that making a plan will allow you to enjoy more.
```
"so that" suggests an unspoken opposite can result if you don't plan. |
54,490,143 | Is there any way I can enable all notification settings by default when my app gets installed ?
Users are receiving notifications but sound is disabled by default and we need to manually enable it on the device. Not all users can do this manually. It would be great to know if there is any way we can check all these things when our app gets installed like WhatsApp or Telegram (they have everything checked by default)
[](https://i.stack.imgur.com/82l6I.png) | 2019/02/02 | [
"https://Stackoverflow.com/questions/54490143",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7389792/"
] | Try using with this below permission in AndroidManifest file
```
<uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY"/>
```
and set notification priority for both below and above Oreo versions `IMPORTANCE_HIGH` for Oreo and above, and `PRIORITY_HIGH or PRIORITY_MAX` for below Oreo versions
[Reference link for priority note](https://developer.android.com/training/notify-user/channels#importance)
**Priority for version below Oreo**
```
mBuilder.setSmallIcon(R.drawable.app_logo)
.setAutoCancel(true)
.setContentIntent(resultPendingIntent)
.setContentTitle(title)
.setStyle(bigPictureStyle)
.setSound(soundUri)
.setPriority(NotificationCompat.PRIORITY_HIGH) // prirority here for version below Oreo
.setWhen(System.currentTimeMillis())
.setLargeIcon(BitmapFactory.decodeResource(mCtx.getResources(), R.drawable.app_logo))
.setContentText(message)
.build();
```
**Priority for Oreo and above**
[Refer this link](https://developer.android.com/training/notify-user/channels#CreateChannel) | Android 8 or higher you need to use **NotificationChannel** to enable sound, vibration, sound etc.
```
Uri notification_sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
AudioAttributes attributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
notificationChannel.setSound(notification_sound, attributes);//for enable sound
notificationChannel.enableLights(true);
notificationManager.createNotificationChannel(notificationChannel);
}
```
but in **Redmi note 5 pro (MIUI 10.2.1.0)** still notification sound is disabled. I think there is a bug in MIUI. Run this same code in **mi A1(Android one mobile)** everything fine. It works.
refer this [link](https://developer.android.com/training/notify-user/channels) to know more about **Notification Channel** |
63,315,439 | I am a beginner in Jquery. Need your help on the below problem.
I have a html table with 3 columns and 3 rows. Each column has a header example col1,col2 and col3. There is a column approval status with values- Approved, approval pending and not approved. I have to take the sum of the values entered by user in each text box for each column. Currently in my code I'm taking that sum for each column. But I want to take the sum only when approval status is "Approved". I'm not sure which event handler to use as the user can either first enter the number or approval status random order. Thank you!
```html
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<style>
input {display: block;}
input.total {margin-top: 30px;}
[class*="total"] {
background: #ffff00;
p.double {border-style: double;}
}
.none{
display:none;
}
</style>
</head>
<body>
<table class="aa">
<th> Approval status</th>
<th>col1</th>
<th>col2</th>
<th>col3</th>
<tr>
<td id="selectBox1">
<select id = "myList1">
<option value = "1">Choose Approval Status</option>
<option value = "2">Approved</option>
<option value = "3">Approval Pending</option>
<option value = "4">Not Approved</option>
</select>
</td>
<td> <input type="text" class="qty1" value="" /> </td>
<td> <input type="text" class="qty2" value="" /> </td>
<td> <input type="text" class="qty3" value="" /> </td>
</tr>
<tr>
<td id="selectBox2">
<select id = "myList2">
<option value = "1">Choose Approval Status</option>
<option value = "2">Approved</option>
<option value = "3">Approval Pending</option>
<option value = "4">Not Approved</option>
</select>
</td>
<td> <input type="text" class="qty1" value="" /> </td>
<td> <input type="text" class="qty2" value="" /> </td>
<td> <input type="text" class="qty3" value="" /> </td>
</tr>
<tr>
<td> <input type="text" class="none" value="" /></td>
<td> <input type="text" class="total1" value="" /> </td>
<td> <input type="text" class="total2" value="" /> </td>
<td> <input type="text" class="total3" value="" /> </td>
</tr>
</table>
<script>
$(document).on("change", ".qty1", function() {
var sum = 0;
$(".qty1").each(function(){
sum += +$(this).val();
});
$(".total1").val("total:" + sum);
});
$(document).on("change", ".qty2", function() {
var sum = 0;
$(".qty2").each(function(){
sum += +$(this).val();
});
$(".total2").val("total:" + sum);
});
$(document).on("change", ".qty3", function() {
var sum = 0;
$(".qty3").each(function(){
sum += +$(this).val();
});
$(".total3").val("total:" + sum);
});
</script>
</body>
</html>
``` | 2020/08/08 | [
"https://Stackoverflow.com/questions/63315439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13841410/"
] | You have to commit `.gitignore` and have it in your repository, otherwise, you'll lose track of it :)
An example, if another friend clones your repository without the `.gitignore`, he will spam your repo with unnecessary files when committing/pushing.
Feel free to `git add .gitignore` and commit ;) | As [Balastrong answered](https://stackoverflow.com/a/63315381/1256452), you should generally add-and-commit a `.gitignore` file. (There can be special weird exceptional cases but usually if you're in that situation, you should be putting these items into `.git/info/exclude`.)
The thing to remember here is what *untracked file* really means, and how this interacts with Git and commits.
### Git stores commits
The reason Git exists is to store *commits*. It's actually the commits that form the branches, and that *are* the history. Each commit stores a complete snapshot of *every* file that Git knows about, in a special, read-only, Git-only, de-duplicated form. This de-duplication trick takes quick care of the fact that *most* commits mostly just re-use the files from a previous commit: that way, your Git repository does not grow huge even though each commit has a full (but shared!) copy of every file.
### The files you work with are *copies*
Given that nothing inside the commit can ever be changed—this is a consequence of the hashing trick that Git uses to number commits (and, internally, the files stored inside each commit)—this means that the files that you see and work with, when you do work in a repository, are *not* the files stored in the commits! Instead, they are copies, extracted out of some commit, and turned back into ordinary (not-read-only, not-compressed-and-de-duplicated) files.
These copies are in your *working tree* or *work-tree* (two terms for the same thing; Git mostly uses the longer spelling, but I like the shorter one). The work-tree is, technically at least, separate from the repository.1 Git has a mode, called a *bare repository*, in which there is no work-tree at all, and has the ability to add more work-trees to a repository, using `git worktree add`.
Because of this technical distinction, your work-tree is *yours*, to do with as you wish. You can create files in it that Git *doesn't* know about.
---
1In a normal, non-bare repository, the repository itself is in a `.git` directory at the top level of your work-tree. When using `git worktree add`, the added work-trees get a `.git` file containing the path name of the repository, so that Git can find it.
---
### The *index* or *staging area*
The way Git keeps track of the files that Git knows about—that is, the files that are in your work-tree right now, that will go into the *next* commit you might make—is to use a thing that Git calls, variously, the *index*, or the *staging area*, or sometimes—rarely these days—the *cache*. These names all refer to the same thing. The name "index" is because it's (mostly) stored in `.git/index`; the name *staging area* refers to how it functions.
What's in the index is a bit complicated, in part by its multiple roles: it takes on an expanded role during conflicted merges, for instance. But at *its* heart, the index is really just a list of files, in Git's read-only, compressed, Git-only, and de-duplicated form, that are *ready to go into the next commit*.
In effect, then, the index holds a *third* copy—but de-duplicated, so that it's never an actual *copy*—of each of your files. The three copies of each file are therefore:
* The copy from the current commit, that Git extracted when you ran `git clone` and/or `git checkout`. This file cannot be changed, because it's inside a commit.
* The copy in the index. It's in the read-only format, but you *can* change it—or rather *replace* it entirely—because it's *not* inside a commit.
* The copy in your work-tree. This one is *yours*, to do with as you will.
Whenever you change the work-tree copy, the index copy *isn't changed yet:* it still matches the copy in the commit (and thanks to the de-duplication, literally just shares that copy). To update the index copy, you must run `git add` on the file. This tells Git: *make the index copy match the work-tree copy*. Git will now compress, Git-ify, and de-duplicate the work-tree contents, turning the file into something that is ready to go into the *next* commit, and update the index with that copy.
**This is *why* the index is called the *staging area:* it holds each file that will go into the *next* commit, in a form ready to be committed. This is how Git knows which files to commit.** The index (or staging area) holds the copies of the files that will be in the next commit.
An *untracked file* is, quite simply, a file that is not in Git's index *right now*. That means that if you make a new commit, that file won't be in the new commit.
You can add a file to Git's index any time, with `git add`. You can remove a file from Git's index any time, with `git rm --cached` or `git rm`.2 These operations alter the index / staging-area contents, so that the *next* commit has different files—a different snapshot—in it.
---
2The difference between these two is that `git rm` will remove the index copy *and* the work-tree copy, while `git rm --cached` will remove only the index copy.
---
### `git checkout` / `git switch` fills both the index and your work-tree
When you use `git checkout` or (since Git 2.23) `git switch` to select a commit, you are telling Git: *Hey Git, fill in your index to match the commit I'm checking out, and adjust my work-tree to match.* This will, if necessary, *remove* some files from your work-tree, or create new files in your work-tree. So while your work-tree *is* yours, remember that some Git commands literally tell Git to modify your work-tree.
The details here can get pretty tricky, but what's in your index at the time you use these commands affects what happens. In particular, if you use `git rm --cached` to make a file become untracked, and then check out some other commit that doesn't have the file, Git *won't* remove your untracked work-tree copy. If you have the file *tracked*—in both Git's index and your work-tree—and you check out some other commit that doesn't have the file, Git *will* remove both its index copy and your work-tree copy.
### The index and work-tree are never cloned
When you use `git clone` to copy a repository, this copies the *commits* from the `origin` repository to your new clone. You do not get to see their Git's index, nor their work-tree (if they even have one: the repositories on hosting systems like GitHub and Bitbucket are generally bare clones).
The only *files* you have, then, after cloning, are the ones that were in some commit. After a fresh clone you won't have untracked files, because `git clone` only got the *commits* (and then, at the end, ran `git checkout master` or whatever was appropriate, to fill in Git's index and your work-tree).
This is why, in general, you will commit each `.gitignore` file: if the file should be quietly left untracked in *your* work-tree, it probably should be quitely left untracked in someone else's work-tree when *they* clone, too. |
42,054,960 | I'm downloading images using DropBox's API and displaying them in a Collection View. When the user scrolls, the image either disappears from the cell and another is loaded or a new image is reloaded and replaces the image in the cell. How can I prevent this from happening? I've tried using SDWebImage, this keeps the images in the right order but still the images disappear and reload each time they are scrolled off screen. Also, I'm downloading the images directly, not from a URL, I'd prefer to not have to write a work-a-round to be able to use SDWebImage.
I'd post a gif as example but my reputation is too low.
Any help would be welcomed :)
```
var filenames = [String]()
var selectedFolder = ""
// image cache
var imageCache = NSCache<NSString, UIImage>()
override func viewDidLoad() {
super.viewDidLoad()
getFileNames { (names, error) in
self.filenames = names
if error == nil {
self.collectionView?.reloadData()
print("Gathered filenames")
}
}
collectionView?.collectionViewLayout = gridLayout
collectionView?.reloadData()
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(true)
}
func getFileNames(completion: @escaping (_ names: [String], _ error: Error?) -> Void) {
let client = DropboxClientsManager.authorizedClient!
client.files.listFolder(path: "\(selectedFolder)", recursive: false, includeMediaInfo: true, includeDeleted: false, includeHasExplicitSharedMembers: false).response { response, error in
var names = [String]()
if let result = response {
for entry in result.entries {
if entry.name.hasSuffix("jpg") {
names.append(entry.name)
}
}
} else {
print(error!)
}
completion(names, error as? Error)
}
}
func checkForNewFiles() {
getFileNames { (names, error) in
if names.count != self.filenames.count {
self.filenames = names
self.collectionView?.reloadData()
}
}
}
func downloadFiles(fileName: String, completion:@escaping (_ image: UIImage?, _ error: Error?) -> Void) {
if let cachedImage = imageCache.object(forKey: fileName as NSString) as UIImage? {
print("using a cached image")
completion(cachedImage, nil)
} else {
let client = DropboxClientsManager.authorizedClient!
client.files.download(path: "\(selectedFolder)\(fileName)").response { response, error in
if let theResponse = response {
let fileContents = theResponse.1
if let image = UIImage(data: fileContents) {
// resize the image here and setObject the resized Image to save it to cache.
// use resized image for completion as well
self.imageCache.setObject(image, forKey: fileName as NSString)
completion(image, nil) // completion(resizedImage, nil)
}
else {
completion(nil, error as! Error?)
}
} else if let error = error {
completion(nil, error as? Error)
}
}
.progress { progressData in
}
}
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.filenames.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! ImageCell
cell.backgroundColor = UIColor.lightGray
let fileName = self.filenames[indexPath.item]
let cellIndex = indexPath.item
self.downloadFiles(fileName: fileName) { (image, error) in
if cellIndex == indexPath.item {
cell.imageCellView.image = image
print("image download complete")
}
}
return cell
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
gridLayout.invalidateLayout()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
imageCache.removeAllObjects()
}
``` | 2017/02/05 | [
"https://Stackoverflow.com/questions/42054960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I fixed it. It required setting the cell image = nil in the cellForItemAt func and canceling the image request if the user scrolled the cell off screen before it was finished downloading.
Here's the new cellForItemAt code:
```
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let fileId = indexPath.item
let fileName = self.filenames[indexPath.item]
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! ImageCell
cell.backgroundColor = UIColor.lightGray
if cell.request != nil {
print("request not nil; cancel ", fileName)
}
cell.request?.cancel()
cell.request = nil
cell.imageCellView.image = nil
print ("clear image ", fileId)
self.downloadFiles(fileId:fileId, fileName: fileName, cell:cell) { (image, error) in
guard let image = image else {
print("abort set image ", fileId)
return
}
cell.imageCellView.image = image
print ("download/cache: ", fileId)
}
return cell
}
``` | Use SDWebImage and add a placeholder image :
```
cell.imageView.sd_setImage(with: URL(string: "http://www.domain.com/path/to/image.jpg"), placeholderImage: UIImage(named: "placeholder.png"))
``` |
6,971,945 | I have an array of array .
Example like
```
a[0]={1,2,3};
a[1]={2,3,4};
**Edit** in a[2] from a[2]={4,5};
a[2]={2,4,5};
and more
```
How can I find common element which exist in all array ? | 2011/08/07 | [
"https://Stackoverflow.com/questions/6971945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/428705/"
] | You can avoid foreach loop by
```
call_user_func_array('array_intersect',$a);
``` | As the name suggest, I think you can just use [array-intersect](http://php.net/manual/en/function.array-intersect.php)
From that page:
```
<?php
$array1 = array("a" => "green", "red", "blue");
$array2 = array("b" => "green", "yellow", "red");
$result = array_intersect($array1, $array2);
print_r($result);
?>
```
gives
```
Array
(
[a] => green
[0] => red
)
``` |
18,787,509 | How can i count element once?
Right now, evert time, when i click #totalItems, alert is rised as many times, as many element are in #photoId ?
```
<script type="text/javascript">
$(document).ready(function(){
photoId = $('.photoId');
totalItems = $('#totalItems');
$(photoId).on('click', function(){
//alert ($(this).html());
$(this).clone().appendTo(totalItems);
$('#count').on('click', function(e){
sizes = (totalItems.children().size());
alert (sizes);
});
$('#count').off('click', function(e){
sizes = (totalItems.children().size());
alert (sizes);
});
});
});
</script>
``` | 2013/09/13 | [
"https://Stackoverflow.com/questions/18787509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2610146/"
] | Here is a sample of something expanding on the tip from SpykeBytes
```
<div ng-repeat="location in journey.locations">
<div id="location_div_{{ $index }}">
<label class="journey-label">Location name</label>
<input class="journey-input" id="location_{{ $index }}" type="text" ng-model="location.location_name" />
<button ng-show="editable" tabindex="-1" class="journey-button remove" ng-click="removeItem(journey.locations, $index)">
Remove location
</button>
```
Then in my controller I set up an action that takes deletes the individual item
```
$scope.removeItem = function(itemArray, index) {
return itemArray.splice(index, 1);
};
``` | Index won't help you here because the {{$index}} that ng-repeat provides is within the groupings. That is, each grouping restarts the $index variable. You are going to need a unique identifier for each record though. Without that there is no way to be sure that the record you want to remove is the right one.
As far as the groupings, you can recreate the model whenever you delete something. This wouldn't work with the sample data in the Fiddle, but it works when you're dealing with a real datasource. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.