问:
Passing an inner array to a function
I am trying to pass an inner array to a function in Perl.
Here is my Perl program.

```<code>#!/usr/bin/perl
use strict;
use warnings;

my %data = (
    'a' => (
        x => 'Hello',
        y => 'World'
    ),
    'b' => (
        x => 'Foo',
        y => 'Bar'
    )
);

#prototype
sub p(\%);

{ #main
    p(%data{'a'}); # should print "Hello Wolrd".
}

sub p(\%) {
    print "$_[0]{x} $_[0]{y}\n";
}
</code>```

Instead, I get the following error: Type of arg 1 to main::p must be hash (not key/value hash slice).

This works:

```<code>#!/usr/bin/perl
use strict;
use warnings;

#prototype
sub p(\%);

{ #main
    my %a = (
        x => 'Hello',
        y => 'World'
    );
    p(%a);
}

sub p(\%) {
    print "$_[0]{x} $_[0]{y}\n";
}
</code>```

So there must be something wrong with the method call. But what? The content of a is a hash, so the first character after p( must be % (I tried p($data{'a'}); too, but it leaves me with another error (which seems logical, since the content of a isn’t a scalar). I do not have to manually create a reference to the hash and dereference because I declare the function prototype. What am I missing?

答:
There are no arrays in your code. And there are no method calls in your code.

Your hash is defined incorrectly. You cannot embed hashes inside other hashes. You need to use hash references. Like this:

```<code>my %data = (
    'a' => {
        x => 'Hello',
        y => 'World'
    },
    'b' => {
        x => 'Foo',
        y => 'Bar'
    }
);
</code>```

Note, I'm using { ... } to define your inner hashes, not ( ... ).

That still gives us an error though.

Type of arg 1 to main::p must be hash (not hash element) at passhash line 20, near "})"

If that's unclear, we can always try adding use diagnostics to get more details of the error:

(F) This function requires the argument in that position to be of a certain type.  Arrays must be @NAME or @{EXPR}.  Hashes must be %NAME or %{EXPR}.  No implicit dereferencing is allowed--use the {EXPR} forms as an explicit dereference.  See perlref.

Parameter type definitions come from prototypes. Your prototype is \%. People often think that means a hash reference. It doesn't. It means, "give me a real hash in this position and I'll take a reference to it and pass that reference to the subroutine".

(See, this is why people say that prototypes shouldn't be used in Perl - they often don't do what you think they do.)

You're not passing a hash. You're passing a hash reference. You can fix it by dereferencing the hash in the subroutine call.

```<code>p(%{$data{a}});
</code>```

But that's a really silly idea. Take a hash reference and turn it into a hash, so that Perl can take its reference to pass it into a subroutine.

What you really want to do is to change the prototype to just $ so the subroutine accepts a hash reference. You can then check that you have a hash reference using ref.

But that's still overkill. People advise against using Perl prototypes for very good reasons. Just remove it.

Title: Passing an inner array to a function

Body:
I am trying to pass an inner array to a function in Perl.
Here is my Perl program.

#!/usr/bin/perl
use strict;
use warnings;

my %data = (
    'a' => (
        x => 'Hello',
        y => 'World'
    ),
    'b' => (
        x => 'Foo',
        y => 'Bar'
    )
);

#prototype
sub p(\%);

{ #main
    p(%data{'a'}); # should print "Hello Wolrd".
}

sub p(\%) {
    print "$_[0]{x} $_[0]{y}\n";
}

Instead, I get the following error: Type of arg 1 to main::p must be hash (not key/value hash slice).

This works:

#!/usr/bin/perl
use strict;
use warnings;

#prototype
sub p(\%);

{ #main
    my %a = (
        x => 'Hello',
        y => 'World'
    );
    p(%a);
}

sub p(\%) {
    print "$_[0]{x} $_[0]{y}\n";
}

So there must be something wrong with the method call. But what? The content of a is a hash, so the first character after p( must be % (I tried p($data{'a'}); too, but it leaves me with another error (which seems logical, since the content of a isn’t a scalar). I do not have to manually create a reference to the hash and dereference because I declare the function prototype. What am I missing?

Body:
There are no arrays in your code. And there are no method calls in your code.

Your hash is defined incorrectly. You cannot embed hashes inside other hashes. You need to use hash references. Like this:

my %data = (
    'a' => {
        x => 'Hello',
        y => 'World'
    },
    'b' => {
        x => 'Foo',
        y => 'Bar'
    }
);

Note, I'm using { ... } to define your inner hashes, not ( ... ).

That still gives us an error though.

Type of arg 1 to main::p must be hash (not hash element) at passhash line 20, near "})"

If that's unclear, we can always try adding use diagnostics to get more details of the error:

(F) This function requires the argument in that position to be of a certain type.  Arrays must be @NAME or @{EXPR}.  Hashes must be %NAME or %{EXPR}.  No implicit dereferencing is allowed--use the {EXPR} forms as an explicit dereference.  See perlref.

Parameter type definitions come from prototypes. Your prototype is \%. People often think that means a hash reference. It doesn't. It means, "give me a real hash in this position and I'll take a reference to it and pass that reference to the subroutine".

(See, this is why people say that prototypes shouldn't be used in Perl - they often don't do what you think they do.)

You're not passing a hash. You're passing a hash reference. You can fix it by dereferencing the hash in the subroutine call.

p(%{$data{a}});

But that's a really silly idea. Take a hash reference and turn it into a hash, so that Perl can take its reference to pass it into a subroutine.

What you really want to do is to change the prototype to just $ so the subroutine accepts a hash reference. You can then check that you have a hash reference using ref.

But that's still overkill. People advise against using Perl prototypes for very good reasons. Just remove it.


来源: stackexchange

问:
React Router 4 Nested Routes not rendering
I'm trying to do nested routing in one of my components.

Here's the parent component:

```<code>const App = () => (
  <BrowserRouter>
    <Provider store={store}>
      <Switch>
        <Route exact path="/" component={Landing} />
        <Route path="/contribute" component={Contribute} />
      </Switch>
    </Provider>
  </BrowserRouter>
);
</code>```

And here's the child component:

```<code>const Landing = () => (
  <div>
    <SearchBar />
    <section className="results-sctn">
      <Route exact path="/" component={ArtistList} />
      <Route path="/test" component={Test} />
    </section>
  </div>
);
</code>```

ArtistList renders fine on the / route, but /test renders a totally blank page. Any idea why this might be?

答:
This behaviour happens because have an exact attribute mentioned on the parent route

```<code><Route exact path="/" component={Landing} />
</code>```

So what happens is that react-router sees a path /test to match and then tries to match it starting from the top level. and it sees two routes one is exactly / and other is /contribute. None of them match the required path and hence you see a blank page

You need to write

```<code><Route path="/" component={Landing} />
</code>```

So when you do this, it will see / which matches /test partially and then will try to find a matched route in the landing component which it will find.

Also change the order of the parent Route, since Switch renders the first match and / is a partial match for /test so /contribute wont work

Your final code would look like

```<code>const App = () => (
  <BrowserRouter>
    <Provider store={store}>
      <Switch>
        <Route path="/contribute" component={Contribute} />
        <Route path="/" component={Landing} />
      </Switch>
    </Provider>
  </BrowserRouter>
);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to do nested routing in one of my components.

Here's the parent component:

const App = () => (
  <BrowserRouter>
    <Provider store={store}>
      <Switch>
        <Route exact path="/" component={Landing} />
        <Route path="/contribute" component={Contribute} />
      </Switch>
    </Provider>
  </BrowserRouter>
);

And here's the child component:

const Landing = () => (

    <SearchBar />

      <Route exact path="/" component={ArtistList} />
      <Route path="/test" component={Test} />

);

ArtistList renders fine on the / route, but /test renders a totally blank page. Any idea why this might be?

Body:
This behaviour happens because have an exact attribute mentioned on the parent route

<Route exact path="/" component={Landing} />

So what happens is that react-router sees a path /test to match and then tries to match it starting from the top level. and it sees two routes one is exactly / and other is /contribute. None of them match the required path and hence you see a blank page

You need to write

<Route path="/" component={Landing} />

So when you do this, it will see / which matches /test partially and then will try to find a matched route in the landing component which it will find.

Also change the order of the parent Route, since Switch renders the first match and / is a partial match for /test so /contribute wont work

Your final code would look like

const App = () => (
  <BrowserRouter>
    <Provider store={store}>
      <Switch>
        <Route path="/contribute" component={Contribute} />
        <Route path="/" component={Landing} />
      </Switch>
    </Provider>
  </BrowserRouter>
);


问:
How to efficiently remove duplicates from an array without using Set
I was asked to write my own implementation to remove duplicated values in an array. Here is what I have created. But after tests with 1,000,000 elements it took very long time to finish. Is there something that I can do to improve my algorithm or any bugs to remove ?

I need to write my own implementation - not to use Set, HashSet etc. Or any other tools such as iterators. Simply an array to remove duplicates.

```<code>public static int[] removeDuplicates(int[] arr) {

    int end = arr.length;

    for (int i = 0; i < end; i++) {
        for (int j = i + 1; j < end; j++) {
            if (arr[i] == arr[j]) {
                int shiftLeft = j;
                for (int k = j+1; k < end; k++, shiftLeft++) {
                    arr[shiftLeft] = arr[k];
                }
                end--;
                j--;
            }
        }
    }

    int[] whitelist = new int[end];
    for(int i = 0; i < end; i++){
        whitelist[i] = arr[i];
    }
    return whitelist;
}
</code>```

答:
```<code>public void removeDup(){
String[] arr = {"1","1","2","3","3"};
          boolean exists = false;
          String[] arr2 = new String[arr.length];
          int count1 = 0;
          for(int loop=0;loop<arr.length;loop++)
            {
              String val = arr[loop];
              exists = false;
              for(int loop2=0;loop2<arr2.length;loop2++)
              {
                  if(arr2[loop2]==null)break;
                  if(arr2[loop2]==val){
                        exists = true;
                }
              }
              if(!exists) {
                    arr2[count1] = val;
                    count1++;
              }
            }
}
</code>```

Body:
I was asked to write my own implementation to remove duplicated values in an array. Here is what I have created. But after tests with 1,000,000 elements it took very long time to finish. Is there something that I can do to improve my algorithm or any bugs to remove ?

I need to write my own implementation - not to use Set, HashSet etc. Or any other tools such as iterators. Simply an array to remove duplicates.

public static int[] removeDuplicates(int[] arr) {

    int end = arr.length;

    for (int i = 0; i < end; i++) {
        for (int j = i + 1; j < end; j++) {
            if (arr[i] == arr[j]) {
                int shiftLeft = j;
                for (int k = j+1; k < end; k++, shiftLeft++) {
                    arr[shiftLeft] = arr[k];
                }
                end--;
                j--;
            }
        }
    }

    int[] whitelist = new int[end];
    for(int i = 0; i < end; i++){
        whitelist[i] = arr[i];
    }
    return whitelist;
}


问:
Displaying a value in a populated combo box
Here is the situation:
I have populated a combo box with the names of divisions in my company and it is working fine. I go into edit mode and pull one record out of the data table so I bind all controls on the form with one record. I also populate this combo box with all divisions but want it to display the selected division. While I know how to display correct date in textbox controls, I do not know how to make combo box display only selected data. It displays the first record from the query which populates it. Any suggestions?

Thanks

答:
I'm not sure I understood your question correctly. But I think you just want to display the selectedValue in the dropdown list populated from a list of values.

< asp:DropDownList DataTextField="SomeDecsription" DataValueField="SomeValue" ...... />

I apologise if this is not what you were asking for

ContentLicense: CC BY-SA 2.5


问:
FB Instant Articles related articles section
Facebook's documentation for instant articles states that for "related articles" if we leave off the list of related articles, Facebook will automatically select 4 articles for us. I am not seeing this behavior. Instead, I get the error: Related Articles Block is Empty. Has anyone come across this?

The tag that I current have is as below:

```

答:
This is not actually the case.

I tried the same thing after reading the FB documentation, I thought facebook will get pages randomly but they don't.


问:
polymer-cli installation failure on Ubuntu
No matter what I try, every time I try to install polymer-cli, it always comes up with a PERMISSION_DENIED error.

```<code>bradley@gurulaptop:~$ sudo npm -g install polymer-cli
npm WARN deprecated bower@1.8.0: ..psst! While Bower is maintained, we recommend Yarn and Webpack for *new* front-end projects! Yarn's advantage is security and reliability, and Webpack's is support for both CommonJS and AMD projects. Currently there's no migration path but we hope you'll help us figure out one.
npm WARN deprecated @types/assert@0.0.29: See https://github.com/DefinitelyTyped/DefinitelyTyped/issues/12826
/usr/bin/polymer -> /usr/lib/node_modules/polymer-cli/bin/polymer.js

> wd@1.2.0 install /usr/lib/node_modules/polymer-cli/node_modules/wd
> node scripts/build-browser-scripts

/usr/lib/node_modules/polymer-cli/node_modules/mkdirp/index.js:90
                    throw err0;
                    ^

Error: EACCES: permission denied, mkdir '/usr/lib/node_modules/polymer-cli/node_modules/wd/build'
    at Object.fs.mkdirSync (fs.js:877:18)
    at sync (/usr/lib/node_modules/polymer-cli/node_modules/mkdirp/index.js:71:13)
    at Object.<anonymous> (/usr/lib/node_modules/polymer-cli/node_modules/wd/scripts/build-browser-scripts.js:6:1)
    at Module._compile (module.js:569:30)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)
    at Function.Module._load (module.js:458:3)
    at Function.Module.runMain (module.js:605:10)
    at startup (bootstrap_node.js:158:16)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! wd@1.2.0 install: `node scripts/build-browser-scripts`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the wd@1.2.0 install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/bradley/.npm/_logs/2017-06-06T13_10_23_400Z-debug.log
</code>```

How can I solve this?

答:
Solved the issue: polymer-cli global install error</p>

```<code>sudo npm install -g polymer-cli --unsafe-perm
</code>```

Body:
No matter what I try, every time I try to install polymer-cli, it always comes up with a PERMISSION_DENIED error.

bradley@gurulaptop:~$ sudo npm -g install polymer-cli
npm WARN deprecated bower@1.8.0: ..psst! While Bower is maintained, we recommend Yarn and Webpack for *new* front-end projects! Yarn's advantage is security and reliability, and Webpack's is support for both CommonJS and AMD projects. Currently there's no migration path but we hope you'll help us figure out one.
npm WARN deprecated @types/assert@0.0.29: See https://github.com/DefinitelyTyped/DefinitelyTyped/issues/12826
/usr/bin/polymer -> /usr/lib/node_modules/polymer-cli/bin/polymer.js

> wd@1.2.0 install /usr/lib/node_modules/polymer-cli/node_modules/wd
> node scripts/build-browser-scripts

/usr/lib/node_modules/polymer-cli/node_modules/mkdirp/index.js:90
                    throw err0;
                    ^

Error: EACCES: permission denied, mkdir '/usr/lib/node_modules/polymer-cli/node_modules/wd/build'
    at Object.fs.mkdirSync (fs.js:877:18)
    at sync (/usr/lib/node_modules/polymer-cli/node_modules/mkdirp/index.js:71:13)
    at Object.<anonymous> (/usr/lib/node_modules/polymer-cli/node_modules/wd/scripts/build-browser-scripts.js:6:1)
    at Module._compile (module.js:569:30)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)
    at Function.Module._load (module.js:458:3)
    at Function.Module.runMain (module.js:605:10)
    at startup (bootstrap_node.js:158:16)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! wd@1.2.0 install: `node scripts/build-browser-scripts`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the wd@1.2.0 install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/bradley/.npm/_logs/2017-06-06T13_10_23_400Z-debug.log

How can I solve this?

Body:
Solved the issue: polymer-cli global install error

sudo npm install -g polymer-cli --unsafe-perm


问:
How to DELETE an element from String Array? Important: I dont want to convert my Array to a List
I have a Generic method smallestValueInArray(T[] array) and this method gets an Array of any Type. This method looks like this:

```<code>public class Helper {

    public static <T extends Comparable<T>> T smallestValueInArray(T[] array) {
        T smallestValue = array[0];
        T smallerTempValue = array[0];

        for (int i = 0; i < array.length - 2; i+=2) {

            if (array[i].compareTo(array[i+1]) < 0) {
                smallerTempValue = array[i];
            } else {
                smallerTempValue = array[i+1];
            }

            if (smallestValue.compareTo(smallerTempValue) > 0) {
                smallestValue = smallerTempValue;
            }
        }
        return smallestValue;
    }
}
</code>```

In the Main method I want to do something like this:

```<code>for (int i = 0; i < stringArray.length; i++) {
        someOtherArray[i] = Helper.smallestValueInArray(stringArray);
        Helper.deleteElement(stringArray, stringArray[i]);
    }
</code>```

So I want to loop through stringArray, find the smallest element in that Array and add that element to a new array someOtherArray. After that I want to use a method deleteElement() and this method gets two parameters, first one is an Array, and the seccond one is the element position in that Array which should be deleted.

How should my deleteElement() method look like?

Important: I dont want to convert my array in a List and than use list.remove()!

答:
If you don't want to convert the array to a List, the only option I see is to create a new array that doesn't contain the removed element. Your deleteElement method will have to return that array.

```<code>public static <T> T[] deleteElement(T[] array, int i)
{
    // create new array of length array.length - 1
    // copy all the elements from the source array except of the i'th element
    // return the new array
}
</code>```

and you'll call it with:

```<code>stringArray = Helper.deleteElement (stringArray, i);
</code>```

Of course, it would be much simpler to convert the array to ArrayList, remove the i'th element, and convert back to array.

Body:
I have a Generic method smallestValueInArray(T[] array) and this method gets an Array of any Type. This method looks like this:

public class Helper {

    public static <T extends Comparable<T>> T smallestValueInArray(T[] array) {
        T smallestValue = array[0];
        T smallerTempValue = array[0];

        for (int i = 0; i < array.length - 2; i+=2) {

            if (array[i].compareTo(array[i+1]) < 0) {
                smallerTempValue = array[i];
            } else {
                smallerTempValue = array[i+1];
            }

            if (smallestValue.compareTo(smallerTempValue) > 0) {
                smallestValue = smallerTempValue;
            }
        }
        return smallestValue;
    }
}

In the Main method I want to do something like this:

for (int i = 0; i < stringArray.length; i++) {
        someOtherArray[i] = Helper.smallestValueInArray(stringArray);
        Helper.deleteElement(stringArray, stringArray[i]);
    }

So I want to loop through stringArray, find the smallest element in that Array and add that element to a new array someOtherArray. After that I want to use a method deleteElement() and this method gets two parameters, first one is an Array, and the seccond one is the element position in that Array which should be deleted.

How should my deleteElement() method look like?

Important: I dont want to convert my array in a List and than use list.remove()!

Body:
If you don't want to convert the array to a List, the only option I see is to create a new array that doesn't contain the removed element. Your deleteElement method will have to return that array.

public static <T> T[] deleteElement(T[] array, int i)
{
    // create new array of length array.length - 1
    // copy all the elements from the source array except of the i'th element
    // return the new array
}

and you'll call it with:

stringArray = Helper.deleteElement (stringArray, i);

Of course, it would be much simpler to convert the array to ArrayList, remove the i'th element, and convert back to array.


问:
Problem with session attributes in JSP EL using Spring MVC
I'm trying to show a session attribute "userSession" in a jsp page using JSP EL, but it returns null (case 1). Request attributes are shown properly in EL expressions though.

Using java scriptlet instead, behaves as shown in cases 2 and 3:

<c:out value="${userSession}"/> \\Returns null

<c:out value='<%=request.getSession().getAttribute("userSession")%>'/>
\\Works fine - returns session attribute

<c:out value='<%=session.getAttribute("userSession")%>'/>
\\Throws exception: cannot find variable session

Exception of case 3 may be related to case 1 problem, something like not recognizing the session variable for some reason and that affecting the EL expression then.

I'm using Spring MVC 2.5 and JSTL 1.1.2.

I can post anything else needed to clarify the problem.

答:
What does:

```<code><c:out value="${sessionScope.userSession}"/>
</code>```

or

```<code><c:out value="${sessionScope['userSession']}"/>
</code>```

give?

Body:
What does:

<c:out value="${sessionScope.userSession}"/>

or

<c:out value="${sessionScope['userSession']}"/>

give?


问:
R regular expression for p#q#c#
What would the regular expression be to encompass variable names such as p3q10000c150 and p29q2990c98? I want to add all variables in the format of p-any number-q-any number-c-any number to a list in R.

Thanks!

答:
I'll assume you have a data frame called df with variables names names(df). If you want to only retain the variables with the structure p<somenumbers>q<somenumbers>c<somenumbers> you could use the regex that Wiktor Stribiżew suggested in the comments like this:

```<code>valid_vars <- grepl("p\\d+q\\d+c\\d", names(df))
df2 <- df[, valid_vars]
</code>```

grepl() will return a vector of TRUE and FALSE values, indicating which element in names(df) follows the structure you suggested. Afterwards you use the output of grepl() to subset your data frame.

For clarity, observe:

```<code>var_names_test <- c("p3q10000c150", "p29q2990c98", "var1")
grepl("p\\d+q\\d+c\\d", var_names_test)
# [1] TRUE TRUE FALSE
</code>```

Title: R regular expression for p#q#c#

Body:
I'll assume you have a data frame called df with variables names names(df). If you want to only retain the variables with the structure p<somenumbers>q<somenumbers>c<somenumbers> you could use the regex that Wiktor Stribiżew suggested in the comments like this:

valid_vars <- grepl("p\\d+q\\d+c\\d", names(df))
df2 <- df[, valid_vars]

grepl() will return a vector of TRUE and FALSE values, indicating which element in names(df) follows the structure you suggested. Afterwards you use the output of grepl() to subset your data frame.

For clarity, observe:

var_names_test <- c("p3q10000c150", "p29q2990c98", "var1")
grepl("p\\d+q\\d+c\\d", var_names_test)
# [1] TRUE TRUE FALSE


问:
How to connect to MongoDB in Windows?
I'm trying to run Mongo from the Command-Line:
What's wrong? (I've IIS on localhost:80). And Apache on port 8080. Are there any issues
with this? </p>

```<code>C:\MONGO\Project1\mongo\bin>mongo --port 27017
MongoDB shell version: 2.0.3
connecting to: 127.0.0.1:27017/test
Sat Mar 10 16:16:45 Error: couldn't connect to server 127.0.0.1:27017 shell/mong
o.js:86
exception: connect failed
</code>```

答:
Go to C:\Program Files\MongoDB\Server\3.4\bin using cmd and
write mongod.

Open another cmd by right click and run as admin point to your
monogodb installed directory as mentioned above and then just like
write this mongo.exe

After that, write db.test.save({Field:'Hello mongodb'}) this command
will insert a field having name Field and value is Hello
mongodb.

After, check the record db.test.find() and press enter you will find
the record that you have recently entered.

Title: How to connect to MongoDB in Windows?

Body:
I'm trying to run Mongo from the Command-Line:
What's wrong? (I've IIS on localhost:80). And Apache on port 8080. Are there any issues
with this?

C:\MONGO\Project1\mongo\bin>mongo --port 27017
MongoDB shell version: 2.0.3
connecting to: 127.0.0.1:27017/test
Sat Mar 10 16:16:45 Error: couldn't connect to server 127.0.0.1:27017 shell/mong
o.js:86
exception: connect failed


问:
Javascript formdata is empty when trying to append values in it
following is my code when i do console.log(formData);  its empty. Cannot see a reason for it to fail down.

```<code>$("#add_meal_item").on('click', '#save_meal_item', function () {
                var meal_name = $("#add_meal_item_form").find('#meal_name').val();
                var meal_type = $("#add_meal_item_form").find('#meal_type').val();
                var logoImg = $("#add_meal_item_form").find('#meal_image').get(0).files[0];
                var formData = new FormData();
                formData.append('logo', logoImg);
                formData.append('meal_type', meal_type);
                formData.append('meal_name', meal_name);
                console.log(formData);
                var ajax_url = baseurl + '/save_meal_item';
                $.ajax({
                    url: ajax_url,
                    type: 'POST',
                    data: formData,
                    success: function (response) {

                    }
                });

            });
</code>```

答:
You need to get elements values first and then append them to formData, Like this:

```<code>var meal_name = $("#add_meal_item_form").find('#meal_name').val();
formData.append('meal_name ', meal_name );
</code>```

And to show all formData keys and values you have to use FormData.entries method :

```<code>for(var pair of formData.entries()) {
     console.log(pair[0]+ ', '+ pair[1]);
}
</code>```

Body:
following is my code when i do console.log(formData);  its empty. Cannot see a reason for it to fail down.

$("#add_meal_item").on('click', '#save_meal_item', function () {
                var meal_name = $("#add_meal_item_form").find('#meal_name').val();
                var meal_type = $("#add_meal_item_form").find('#meal_type').val();
                var logoImg = $("#add_meal_item_form").find('#meal_image').get(0).files[0];
                var formData = new FormData();
                formData.append('logo', logoImg);
                formData.append('meal_type', meal_type);
                formData.append('meal_name', meal_name);
                console.log(formData);
                var ajax_url = baseurl + '/save_meal_item';
                $.ajax({
                    url: ajax_url,
                    type: 'POST',
                    data: formData,
                    success: function (response) {

                    }
                });

            });

Body:
You need to get elements values first and then append them to formData, Like this:

var meal_name = $("#add_meal_item_form").find('#meal_name').val();
formData.append('meal_name ', meal_name );

And to show all formData keys and values you have to use FormData.entries method :

for(var pair of formData.entries()) {
     console.log(pair[0]+ ', '+ pair[1]);
}


问:
Apache Spark vs Apache Ignite
Currently I'm studying Apache spark and Apache ignite frameworks.

Some principle differences between them are described in this article ignite vs spark But I realized that I still don't understand their purposes.

I mean for which problems spark more preferable than ignite and vice versa?

答:
Although Apache Spark and Apache Ignite utilize the power of in-memory computing, they address different use cases. Spark processes but doesn’t store data. It loads the data, processes it, then discards it. Ignite, on the other hand, can be used to process data and it also provides a distributed in-memory key-value store with ACID compliant transactions and SQL support.
Spark is also for non-transactional, read-only data while Ignite supports non-transactional and transactional workloads. Finally, Apache Ignite also supports purely computational payloads for HPC and MPP use cases while Spark works only on data-driven payloads.

Spark and Ignite can complement each other very well. Ignite can provide shared storage for Spark so state can be passed from one Spark application or job to another. Ignite can also be used to provide distributed SQL with indexing that accelerates Spark SQL by up to 1,000x.

By Nikita Ivanov: http://www.odbms.org/blog/2017/06/on-apache-ignite-apache-spark-and-mysql-interview-with-nikita-ivanov/

ContentLicense: CC BY-SA 4.0

Title: Apache Spark vs Apache Ignite


问:
Update Subquery Question, with foreign key
I misremembered what the key was for this Templates table and therefore I added the wrong field as a foreign key. Now I need to add the foreign key and I want to populate its values based on this other field that is already populated. I started trying to do this with an update statement, but I'm not sure how to do it.

Part of my schema:

Products Table:

```<code>ProductName (key)
TemplateName
TemplateID
...
</code>```

I've added TemplateID, but it has no data in it yet and is nullable.

Templates Table:

```<code>TemplateID (key)
TemplateName
...
</code>```

I want to use the Templates table to find the matching TemplateID for each TemplateName in the Products table and fill that in the foreign key reference in the Products table.

Can I do this with a subquery in Update, or do I need to write some kind of Stored Proc? I'm using Sql Server 2008

答:
You can do it with a simple UPDATE query

```<code>UPDATE Products
SET Products.TemplateID = Templates.TemplateID
FROM Templates
WHERE Templates.TemplateName = Products.TemplateName
</code>```

You do not need to specify the Products table in the FROM clause, nor a JOIN clause.
Just specify the Templates table in the FROM clause.
You can use the tablename you use in the UPDATE clause in the WHERE clause, to correlate recordds from both tables.

OwnerDisplayName: Tony Peterson

Body:
I misremembered what the key was for this Templates table and therefore I added the wrong field as a foreign key. Now I need to add the foreign key and I want to populate its values based on this other field that is already populated. I started trying to do this with an update statement, but I'm not sure how to do it.

Part of my schema:

Products Table:

ProductName (key)
TemplateName
TemplateID
...

I've added TemplateID, but it has no data in it yet and is nullable.

Templates Table:

TemplateID (key)
TemplateName
...

I want to use the Templates table to find the matching TemplateID for each TemplateName in the Products table and fill that in the foreign key reference in the Products table.

Can I do this with a subquery in Update, or do I need to write some kind of Stored Proc? I'm using Sql Server 2008

Body:
You can do it with a simple UPDATE query

UPDATE Products
SET Products.TemplateID = Templates.TemplateID
FROM Templates
WHERE Templates.TemplateName = Products.TemplateName

You do not need to specify the Products table in the FROM clause, nor a JOIN clause.
Just specify the Templates table in the FROM clause.
You can use the tablename you use in the UPDATE clause in the WHERE clause, to correlate recordds from both tables.

OwnerDisplayName: Frederik Gheysels


问:
Difference between logger.info and logger.debug
What is the difference between logger.debug and logger.info ?

When will logger.debug be printed?

答:
It depends on which level you selected in your log4j configuration file.

```<code><Loggers>
        <Root level="info">
        ...
</code>```

If your level is "info" (by default), logger.debug(...) will not be printed in your console.
However, if your level is "debug", it will.

Depending on the criticality level of your code, you should use the most accurate level among the following ones :

```<code>ALL < TRACE < DEBUG < INFO < WARN < ERROR < FATAL < OFF
</code>```

Body:
It depends on which level you selected in your log4j configuration file.

<Loggers>
        <Root level="info">
        ...

If your level is "info" (by default), logger.debug(...) will not be printed in your console.
However, if your level is "debug", it will.

Depending on the criticality level of your code, you should use the most accurate level among the following ones :

ALL < TRACE < DEBUG < INFO < WARN < ERROR < FATAL < OFF


问:
how to display large list of data using reactJS as frontend and django rest framework as backend
I am having large list of data of ingredients required for cooking. More than 3000+

I am using Django rest framework as the backend and ReactJs as frontend.

Each item in the list has a name, id, measurementunit, density in kg/ltr and cost/measurementunit

In Django i have created an api endpoint to supply the data in JSON format.

I want to display the data in a table format and with search filter on the top. Also at a time i want to show maximum 300 results.

Can someone guide me how to achieve this. Should i fetch all the list at a time or use pagination from django. Should i use seperate api for search or do it using reactjs on the frontend.

Presently i dont need any authorization in django. The data is for local use only.

答:
3000 records is a lot to send down to the client in one chunk.  It is easier to develop against, but it doesn't scale well and is likely to create a measurable load time.  If you're OK with that, and you don't expect your data set to grow, then perhaps the pragmatic approach is to keep it as a big list... but it goes against best practices.

Either way, you likely don't want to show a giant 3k-row list to the user, so the UI will have some sort of pagination mechanism.  That might be "next", "previous" pages, or it might be infinite scrolling.  Either way, the data abstraction should be considering it as paged data.

Paging API
Assuming you decide to make your API support paging, you should use the backend framework's paging capabilities, like the Django Paging API or some other abstraction for your REST API.  There are lots of resources out there.

Search
The moment you decide to paginate the API, you are committing to handling search (filtering) on the backend as well.  The only way you can manage client-side filtering is if the client has access to all the data.  Since that isn't the case, you'll need to include a search filter in your data request.  Searching and pagination aren't mutually exclusive, so make sure your API supports both at the same time.  A common way to handle this would be like this:

```<code>http://yoursite.com/api/ingredients?page=5&page_size=100&search=carrot
</code>```

Client
On the React side, you can build your own UI (it is easy to do), or you can use a component which abstracts this for you, like react-js-pagination or react-paginate.  The client component shouldn't really care if the API is paged or not.  Instead, it just notifies you when to display different records and the rest is up to you.

If you decide to keep everything in one big REST call, then you still need to slice the data out of your array to display.  If you paginate your API, then you can keep an instance cache on the client side of the pages you've received.  If you don't have the data, make the REST call to get it, and populate an array with the data.  That way, if a user goes forwards and then backwards, you aren't re-fetching.

Conclusion
I hope this helps a bit.  Enjoy :)

Body:
3000 records is a lot to send down to the client in one chunk.  It is easier to develop against, but it doesn't scale well and is likely to create a measurable load time.  If you're OK with that, and you don't expect your data set to grow, then perhaps the pragmatic approach is to keep it as a big list... but it goes against best practices.

Either way, you likely don't want to show a giant 3k-row list to the user, so the UI will have some sort of pagination mechanism.  That might be "next", "previous" pages, or it might be infinite scrolling.  Either way, the data abstraction should be considering it as paged data.

Paging API
Assuming you decide to make your API support paging, you should use the backend framework's paging capabilities, like the Django Paging API or some other abstraction for your REST API.  There are lots of resources out there.

Search
The moment you decide to paginate the API, you are committing to handling search (filtering) on the backend as well.  The only way you can manage client-side filtering is if the client has access to all the data.  Since that isn't the case, you'll need to include a search filter in your data request.  Searching and pagination aren't mutually exclusive, so make sure your API supports both at the same time.  A common way to handle this would be like this:

http://yoursite.com/api/ingredients?page=5&page_size=100&search=carrot

Client
On the React side, you can build your own UI (it is easy to do), or you can use a component which abstracts this for you, like react-js-pagination or react-paginate.  The client component shouldn't really care if the API is paged or not.  Instead, it just notifies you when to display different records and the rest is up to you.

If you decide to keep everything in one big REST call, then you still need to slice the data out of your array to display.  If you paginate your API, then you can keep an instance cache on the client side of the pages you've received.  If you don't have the data, make the REST call to get it, and populate an array with the data.  That way, if a user goes forwards and then backwards, you aren't re-fetching.

Conclusion
I hope this helps a bit.  Enjoy :)


问:
Create new data series based on two data series with different sampling time
I have two data sets with speed and directional data, recorded with different time steps.

One data set (A) is recorded every 10 minutes, and the other (B) is recorded every hour.

The start times are not exactly the same.

A (speed and directional data) is sampled every 10 minutes e.g. 00.00, 00.10, 00.20, ...

B (directional data) is sampled every hour e.g. 23.54, 00.54, 01.54, ...

I would like to create a new version of data set B with directional data (kind of a synthesized data set) based on data set A where I fill in the recordings for every 10 minutes from data set A and keep the original recording of data set B for every hour.

Example data:

```<code>% columns: timestamp, direction, speed
A = [732381.006944445  22.70  2.23
     732381.013888889  18.20  3.41
     732381.020833333  31.00  6.97
     732381.027777778  36.90  5.63];

% columns: timestamp, direction
B = [732381.038078704   3.01
     732381.079745370   5.63
     732381.121412037   0.68
     732381.163078704 359.56];
</code>```

..and I want something like this..

```<code>% columns: timestamp, direction
B_new = [732381.038078704 'some value based on value in A at that time'
         732381.079745370 'some value based on value in A at that time'
         732381.121412037 'some value based on value in A at that time'
         732381.163078704 'some value based on value in A at that time'];
</code>```

So the first column in the B_new matrix are time stamps of 10 minutes, not the original timestamps of one hour. Ie. we create a new timeseries (B_new) with a sampling of 10 minutes. So something like you already showed @Wolfie, but with timestep of matrix A.

What is the best way to assign the direction data in B as the direction data at the closest available time in A while still keeping the same data sampling as A in the new matrix B?

答:
This is easily achieved with interp1 (a table lookup function).

Interpolating to slower sampling

Let's say you have some nice clean data A and B for this demo...

```<code>% Columns: time (0.1s timestep), data (just the row number)
A = [ (1:0.1:2); (1:11) ].';
% Columns: time (1.0s timestep), data (doesn't even matter, to be removed)
B = [ (1:1:2); rand(1,2) ].';
</code>```

Now we use interp1 to get the closest data value (in terms of the time column) from A and assign it to B_new.

```<code>B_new = zeros(size(B)); % Initialise
B_new(:,1) = B(:,1);    % Get time data from B
% Get nearest neighbour by specifying the 'nearest' method.
% Using 'extrap' means we extrapolate if B's times aren't contained by A's
B_new(:,2) = interp1(A(:,1), A(:,2), B_new(:,1), 'nearest', 'extrap');

% Output
disp(B_new)
% >> [ 1   1
%      2  11 ]
% This is as expected, because 1 and 11 are the values at t = 1 and 2
% in the A data, where t = 1 and 2 are the time values in the B data.
</code>```

Interpolating to higher sampling

We can do the opposite too. You suggested you want to take some base data, A, and in-fill the points which you had for B (or nearest match).

```<code>B_new = A;    % Initialise to fast sample data
% Get row indices of nearest neighbour (in time) by using interp1 and mapping
% onto a list of integers 1 to number of rows in A
idx = interp1(A(:,1), 1:size(A,1), B(:,1), 'nearest', 'extrap');
% Overwrite those values (which were originally from A) with values from B
B_new(idx,2) = B(:,2);
</code>```

Body:
I have two data sets with speed and directional data, recorded with different time steps.

One data set (A) is recorded every 10 minutes, and the other (B) is recorded every hour.

The start times are not exactly the same.

A (speed and directional data) is sampled every 10 minutes e.g. 00.00, 00.10, 00.20, ...

B (directional data) is sampled every hour e.g. 23.54, 00.54, 01.54, ...

I would like to create a new version of data set B with directional data (kind of a synthesized data set) based on data set A where I fill in the recordings for every 10 minutes from data set A and keep the original recording of data set B for every hour.

Example data:

% columns: timestamp, direction, speed
A = [732381.006944445  22.70  2.23
     732381.013888889  18.20  3.41
     732381.020833333  31.00  6.97
     732381.027777778  36.90  5.63];

% columns: timestamp, direction
B = [732381.038078704   3.01
     732381.079745370   5.63
     732381.121412037   0.68
     732381.163078704 359.56];

..and I want something like this..

% columns: timestamp, direction
B_new = [732381.038078704 'some value based on value in A at that time'
         732381.079745370 'some value based on value in A at that time'
         732381.121412037 'some value based on value in A at that time'
         732381.163078704 'some value based on value in A at that time'];

So the first column in the B_new matrix are time stamps of 10 minutes, not the original timestamps of one hour. Ie. we create a new timeseries (B_new) with a sampling of 10 minutes. So something like you already showed @Wolfie, but with timestep of matrix A.

What is the best way to assign the direction data in B as the direction data at the closest available time in A while still keeping the same data sampling as A in the new matrix B?

Body:
This is easily achieved with interp1 (a table lookup function).

Interpolating to slower sampling

Let's say you have some nice clean data A and B for this demo...

% Columns: time (0.1s timestep), data (just the row number)
A = [ (1:0.1:2); (1:11) ].';
% Columns: time (1.0s timestep), data (doesn't even matter, to be removed)
B = [ (1:1:2); rand(1,2) ].';

Now we use interp1 to get the closest data value (in terms of the time column) from A and assign it to B_new.

B_new = zeros(size(B)); % Initialise
B_new(:,1) = B(:,1);    % Get time data from B
% Get nearest neighbour by specifying the 'nearest' method.
% Using 'extrap' means we extrapolate if B's times aren't contained by A's
B_new(:,2) = interp1(A(:,1), A(:,2), B_new(:,1), 'nearest', 'extrap');

% Output
disp(B_new)
% >> [ 1   1
%      2  11 ]
% This is as expected, because 1 and 11 are the values at t = 1 and 2
% in the A data, where t = 1 and 2 are the time values in the B data.

Interpolating to higher sampling

We can do the opposite too. You suggested you want to take some base data, A, and in-fill the points which you had for B (or nearest match).

B_new = A;    % Initialise to fast sample data
% Get row indices of nearest neighbour (in time) by using interp1 and mapping
% onto a list of integers 1 to number of rows in A
idx = interp1(A(:,1), 1:size(A,1), B(:,1), 'nearest', 'extrap');
% Overwrite those values (which were originally from A) with values from B
B_new(idx,2) = B(:,2);


问:
Tensorflow Estimator: How to run an operation within model_fn
I got a very short question, which has probably a very simple answer but I just can't figure it out, although I tried for hours now.

I'm using Tensorflow Estimator and I want to access the global step within my model_fn. I've tried tf.train.get_global_step, which returns me a Tensor. I need the global_step as an integer though (or as a string)!

So I've tried to eval() (= tf.get_default_session().run(t)), but it doesn't work..

Cheers!

答:
You can use tf.cast to cast the Tensor to int or string.

For example,

```<code>tf.cast(tf.train.get_global_step(), dtype=tf.int)
</code>```

See the reference here.

Body:
You can use tf.cast to cast the Tensor to int or string.

For example,

tf.cast(tf.train.get_global_step(), dtype=tf.int)

See the reference here.


问:
Wordpress post page get 404 but Homepage works
I already red a lot about this problem, but non of the solutions helped me out. I installed a fresh Wordpress on my Apache. After changing the permalink structure from default (www.domain.com/?p=id) to another one, wordpress delivers me an 404 error for each page except the homepage.

I already checked the following:

mod_rewrite is installed and enabled (checked through phpinfo)

.htaccess is read- and writable

Here is my default .htaccess

```<code># BEGIN WordPress
<IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteBase /
 RewriteRule ^index\.php$ - [L]
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteRule . /index.php [L]
</IfModule>
# END WordPress
</code>```

Using the plugin "Debug this", I could also find out, that the rewrite rule always deliveres additional index.php? at the beginning. E.g. sitemap_index\.xml$ is rewrited as index.php?sitemap=1

What can I do so solve the problem? Default links like www.domain.com/?p=1 but that kills all my SEO.

Edit: After the installation, there was also /index.php/%postname% written in the custom permalink. But this setting is also returning a 404.

答:
open this file

```<code>/etc/apache2/apache2.conf
</code>```

chnage all AllowOverride None to AllowOverride All and restart your apache
after that update your permalink structure to post and update it.

path can be different from "/etc/apache2/apache2.conf"

Body:
I already red a lot about this problem, but non of the solutions helped me out. I installed a fresh Wordpress on my Apache. After changing the permalink structure from default (www.domain.com/?p=id) to another one, wordpress delivers me an 404 error for each page except the homepage.

I already checked the following:

mod_rewrite is installed and enabled (checked through phpinfo)

.htaccess is read- and writable

Here is my default .htaccess

# BEGIN WordPress
<IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteBase /
 RewriteRule ^index\.php$ - [L]
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteRule . /index.php [L]
</IfModule>
# END WordPress

Using the plugin "Debug this", I could also find out, that the rewrite rule always deliveres additional index.php? at the beginning. E.g. sitemap_index\.xml$ is rewrited as index.php?sitemap=1

What can I do so solve the problem? Default links like www.domain.com/?p=1 but that kills all my SEO.

Edit: After the installation, there was also /index.php/%postname% written in the custom permalink. But this setting is also returning a 404.

Body:
open this file

/etc/apache2/apache2.conf

chnage all AllowOverride None to AllowOverride All and restart your apache
after that update your permalink structure to post and update it.

path can be different from "/etc/apache2/apache2.conf"


问:
Mongodb .net updating one of the embedded documents
I have an orders and each has transactions embedded.

```<code>{
    _id: orderId1,
    other_fields: something else,
    transactions: [
       {
           _id: someId,
           price: 25,
           status: 1
       },
       {
           _id: someId2,
           price: 30,
           status: 0
       }
    ]
}
</code>```

Now i want to change the status of one of the transactions(lets say: someId2). How can i do that?

Both orders and transactions are models with transaction as ICollection<Transaction>

Also, is it possible without using any magic string?

答:
This can be done using the below query

```<code>db.collection.update({"transactions._id":"someId2"}, {$set:{"transactions.$.status":2}})
</code>```

First part of the query is to find the record and the second part is to update the document, this update is positional update

Please note that positional update will be done for only one matching document. Even if we have multiple documents matching the query only one document will be updated, so to safely use the positional update give the maximum condition in find part of the query to retrieve the unique matching document, say in this case the modified query is

```<code>db.collection.update({"_id":"orderId1", "transactions._id":"someId2"}, {$set:{"transactions.$.status":1}})
</code>```

Body:
I have an orders and each has transactions embedded.

{
    _id: orderId1,
    other_fields: something else,
    transactions: [
       {
           _id: someId,
           price: 25,
           status: 1
       },
       {
           _id: someId2,
           price: 30,
           status: 0
       }
    ]
}

Now i want to change the status of one of the transactions(lets say: someId2). How can i do that?

Both orders and transactions are models with transaction as ICollection<Transaction>

Also, is it possible without using any magic string?

Body:
This can be done using the below query

db.collection.update({"transactions._id":"someId2"}, {$set:{"transactions.$.status":2}})

First part of the query is to find the record and the second part is to update the document, this update is positional update

Please note that positional update will be done for only one matching document. Even if we have multiple documents matching the query only one document will be updated, so to safely use the positional update give the maximum condition in find part of the query to retrieve the unique matching document, say in this case the modified query is

db.collection.update({"_id":"orderId1", "transactions._id":"someId2"}, {$set:{"transactions.$.status":1}})


问:
using web fonts?
I did read somewhere that using web fonts is not a good idea as it makes the web pages to load slow or can cause any other problems, is it true? Is the use of web font not recommended generally? Thanks for your thoughts.</p>

答: I'm using web fonts in my website, and I would say that as long as you have a backup font specified so that the reader can see something while the font is loading or in case it fails, there is no problem.</p>

Title: using web fonts?


问:
Plotly/D3 – Reading data from CSV into separate traces
I am attempting to utilize Plotly (based on D3) to read through a CSV and return data into three separate traces - one for each year, in this case.

This Pen depicts the intended result with the data hardcoded into the JS: ‘sales’ data (y-axis), by car dealership (x-axis) and year (essentially a “grouping” variable).

Intended Output

I have researched examples of D3 reading CSV data but am unclear how to read my data into the separate traces by year.

Plotly example – reading CSV

Plotly example - basic time series

For what it’s worth, here is the sample data.

If anyone can point me in the right direction I would appreciate it!
Thank you!

(I apologize if this is an ‘easy’ question as I am new to JavaScript and have very little Plotly or D3 experience.)

答:
@etienne was able to point me in the right direction with this Pen (https://codepen.io/etpinard/pen/VrzwyP)

JS:

```<code>var years = ['2014', '2015', '2016']

Plotly.d3.csv('https://raw.githubusercontent.com/apodagrosi/datasets/master/PlotlyTest_Summary_SalesByDealerByYear.csv', (err, rows) => {
  var data = years.map(y => {
    var d = rows.filter(r => r.year === y)

    return {
      type: 'bar',
      name: y,
      x: d.map(r => r.dealer),
      y: d.map(r => r.sales)
    }
  })

  Plotly.newPlot('graph', data)
})
</code>```

HTML:

```<code><head>
  <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>
<body>
  <div id="graph"></div>
</body>
</code>```

I also utilized 'category order' to order the x-axis values that did not have sales (y-axis) values.

Body:
@etienne was able to point me in the right direction with this Pen (https://codepen.io/etpinard/pen/VrzwyP)

JS:

var years = ['2014', '2015', '2016']

Plotly.d3.csv('https://raw.githubusercontent.com/apodagrosi/datasets/master/PlotlyTest_Summary_SalesByDealerByYear.csv', (err, rows) => {
  var data = years.map(y => {
    var d = rows.filter(r => r.year === y)

    return {
      type: 'bar',
      name: y,
      x: d.map(r => r.dealer),
      y: d.map(r => r.sales)
    }
  })

  Plotly.newPlot('graph', data)
})

HTML:

<head>
  <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>
<body>
  <div id="graph"></div>
</body>

I also utilized 'category order' to order the x-axis values that did not have sales (y-axis) values.


问:
Synchronize 2 processes using a mutex
I have 2 processes:

The first one creates a memory mapped region, a mutex and spawns
the second process. Then writes some pairs of numbers in the memory mapped region.

The second one opens the memory mapped region, opens the mutex and then reads the numbers written by the process 1.

I intended the first process to write a pair of numbers and the second one to immediately read it.

The process 2 seems to be starving.

What did I do wrong?

Process 1:

```<code>#include "stdafx.h"
#include <windows.h>
#include <iostream>

using namespace std;

int main()
{
    DWORD memSize = 400 * sizeof(DWORD);
    HANDLE map_file = CreateFileMapping(NULL, NULL, PAGE_READWRITE, 0, memSize, TEXT("mem1"));

    if (map_file == NULL)
    {
        _tprintf(_T("(Parent) File mapping is null\n"));
        return 1;
    }

    char* map_ptr = (char *) MapViewOfFile(map_file, FILE_MAP_READ, 0, 0, 0);
    if (map_ptr == NULL)
    {
        _tprintf(_T("(Parent) PTR is null \n"));
    }

    HANDLE hMutex = CreateMutex(NULL, TRUE, _T("mt"));
    LPTSTR szCmdline = _tcsdup(TEXT("C:\\Users\\cristi\\source\\repos\\process_synchronization_reader\\Debug\\process_synchronization_reader.exe"));
    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    ZeroMemory(&si, sizeof(si));
    si.cb = sizeof(si);
    ZeroMemory(&pi, sizeof(pi));

    if (!CreateProcess(NULL, szCmdline, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi))
    {
        _tprintf(_T("Process created\n"));
    }

    _tprintf(_T("pare ca s-a creat"));
    for (int i = 1; i <= 200; ++i)
    {
        WaitForSingleObject(hMutex, INFINITE);

        _tprintf(_T("(Parent %d) writing from the parent\n"), i);
        DWORD a, b;

        CopyMemory((LPVOID) &a, map_ptr, sizeof(DWORD));
        map_ptr += sizeof (DWORD);

        CopyMemory((LPVOID) &b, map_ptr, sizeof(DWORD));
        map_ptr += sizeof(DWORD);

        ReleaseMutex(hMutex);
    }

    int n;
    cin >> n;
    CloseHandle(map_file);

    return 0;
}
</code>```

Process 2:

```<code>#include "stdafx.h"
#include <windows.h>

int main()
{
    HANDLE map_file = OpenFileMapping(FILE_MAP_READ, FALSE, TEXT("mem1"));

    if (map_file == NULL)
    {
        _tprintf(_T("(Child) File mapping is null\n"));
        return 1;
    }

    char* map_ptr = (char *) MapViewOfFile(map_file, FILE_MAP_READ, 0, 0, 0);

    if (map_ptr == NULL)
    {
        _tprintf(_T("(Child) PTR is null \n"));
    }

    _tprintf(_T("(CHILD) BEfore reading the first number\n"));
    HANDLE hMutex = OpenMutex(SYNCHRONIZE, TRUE, _T("mt"));
    for (int i = 1; i <= 200; i++)
    {
        WaitForSingleObject(hMutex, INFINITE);
        DWORD a = i;
        DWORD b = 2 * i;

        CopyMemory((LPVOID) map_ptr, &a, sizeof(DWORD));
        map_ptr += sizeof(DWORD);

        CopyMemory((LPVOID) map_ptr, &b, sizeof(DWORD));
        map_ptr += sizeof(DWORD);

        _tprintf(_T("[================================================]\n"));
        _tprintf(_T("( %d %d )\n"), a, b);
        _tprintf(_T("[=================================================]\n"));

        ReleaseMutex(hMutex);
    }

    return 0;
}
</code>```

答:
You create a mutex as initially owned (the second argument to CreateMutex is TRUE) and then you call a wait-function on it. So even after calling ReleaseMutex, it is still owned by a main thread of the first process.

Either change the argument to FALSE, or skip calling WaitForSingleObject for the first loop iteration.

Title: Synchronize 2 processes using a mutex

Body:
I have 2 processes:

The first one creates a memory mapped region, a mutex and spawns
the second process. Then writes some pairs of numbers in the memory mapped region.

The second one opens the memory mapped region, opens the mutex and then reads the numbers written by the process 1.

I intended the first process to write a pair of numbers and the second one to immediately read it.

The process 2 seems to be starving.

What did I do wrong?

Process 1:

#include "stdafx.h"
#include <windows.h>
#include <iostream>

using namespace std;

int main()
{
    DWORD memSize = 400 * sizeof(DWORD);
    HANDLE map_file = CreateFileMapping(NULL, NULL, PAGE_READWRITE, 0, memSize, TEXT("mem1"));

    if (map_file == NULL)
    {
        _tprintf(_T("(Parent) File mapping is null\n"));
        return 1;
    }

    char* map_ptr = (char *) MapViewOfFile(map_file, FILE_MAP_READ, 0, 0, 0);
    if (map_ptr == NULL)
    {
        _tprintf(_T("(Parent) PTR is null \n"));
    }

    HANDLE hMutex = CreateMutex(NULL, TRUE, _T("mt"));
    LPTSTR szCmdline = _tcsdup(TEXT("C:\\Users\\cristi\\source\\repos\\process_synchronization_reader\\Debug\\process_synchronization_reader.exe"));
    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    ZeroMemory(&si, sizeof(si));
    si.cb = sizeof(si);
    ZeroMemory(&pi, sizeof(pi));

    if (!CreateProcess(NULL, szCmdline, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi))
    {
        _tprintf(_T("Process created\n"));
    }

    _tprintf(_T("pare ca s-a creat"));
    for (int i = 1; i <= 200; ++i)
    {
        WaitForSingleObject(hMutex, INFINITE);

        _tprintf(_T("(Parent %d) writing from the parent\n"), i);
        DWORD a, b;

        CopyMemory((LPVOID) &a, map_ptr, sizeof(DWORD));
        map_ptr += sizeof (DWORD);

        CopyMemory((LPVOID) &b, map_ptr, sizeof(DWORD));
        map_ptr += sizeof(DWORD);

        ReleaseMutex(hMutex);
    }

    int n;
    cin >> n;
    CloseHandle(map_file);

    return 0;
}

Process 2:

#include "stdafx.h"
#include <windows.h>

int main()
{
    HANDLE map_file = OpenFileMapping(FILE_MAP_READ, FALSE, TEXT("mem1"));

    if (map_file == NULL)
    {
        _tprintf(_T("(Child) File mapping is null\n"));
        return 1;
    }

    char* map_ptr = (char *) MapViewOfFile(map_file, FILE_MAP_READ, 0, 0, 0);

    if (map_ptr == NULL)
    {
        _tprintf(_T("(Child) PTR is null \n"));
    }

    _tprintf(_T("(CHILD) BEfore reading the first number\n"));
    HANDLE hMutex = OpenMutex(SYNCHRONIZE, TRUE, _T("mt"));
    for (int i = 1; i <= 200; i++)
    {
        WaitForSingleObject(hMutex, INFINITE);
        DWORD a = i;
        DWORD b = 2 * i;

        CopyMemory((LPVOID) map_ptr, &a, sizeof(DWORD));
        map_ptr += sizeof(DWORD);

        CopyMemory((LPVOID) map_ptr, &b, sizeof(DWORD));
        map_ptr += sizeof(DWORD);

        _tprintf(_T("[================================================]\n"));
        _tprintf(_T("( %d %d )\n"), a, b);
        _tprintf(_T("[=================================================]\n"));

        ReleaseMutex(hMutex);
    }

    return 0;
}


问:
Python - Pandas - DataFrame - Explode single column into multiple boolean columns based on conditions
Good morning chaps,

Any pythonic way to explode a dataframe column into multiple columns with boolean flags, based on some condition (str.contains in this case)?

Let's say I have this:

```<code>Position Letter
1        a
2        b
3        c
4        b
5        b
</code>```

And I'd like to achieve this:

```<code>Position Letter is_a     is_b    is_C
1        a      TRUE     FALSE   FALSE
2        b      FALSE    TRUE    FALSE
3        c      FALSE    FALSE   TRUE
4        b      FALSE    TRUE    FALSE
5        b      FALSE    TRUE    FALSE
</code>```

Can do with a loop through 'abc' and explicitly creating new df columns, but wondering if some built-in method already exists in pandas. Number of possible values, and hence number of new columns is variable.

Thanks and regards.

答:
use Series.str.get_dummies():

```<code>In [31]: df.join(df.Letter.str.get_dummies())
Out[31]:
   Position Letter  a  b  c
0         1      a  1  0  0
1         2      b  0  1  0
2         3      c  0  0  1
3         4      b  0  1  0
4         5      b  0  1  0
</code>```

or

```<code>In [32]: df.join(df.Letter.str.get_dummies().astype(bool))
Out[32]:
   Position Letter      a      b      c
0         1      a   True  False  False
1         2      b  False   True  False
2         3      c  False  False   True
3         4      b  False   True  False
4         5      b  False   True  False
</code>```

Body:
Good morning chaps,

Any pythonic way to explode a dataframe column into multiple columns with boolean flags, based on some condition (str.contains in this case)?

Let's say I have this:

Position Letter
1        a
2        b
3        c
4        b
5        b

And I'd like to achieve this:

Position Letter is_a     is_b    is_C
1        a      TRUE     FALSE   FALSE
2        b      FALSE    TRUE    FALSE
3        c      FALSE    FALSE   TRUE
4        b      FALSE    TRUE    FALSE
5        b      FALSE    TRUE    FALSE

Can do with a loop through 'abc' and explicitly creating new df columns, but wondering if some built-in method already exists in pandas. Number of possible values, and hence number of new columns is variable.

Thanks and regards.

Body:
use Series.str.get_dummies():

In [31]: df.join(df.Letter.str.get_dummies())
Out[31]:
   Position Letter  a  b  c
0         1      a  1  0  0
1         2      b  0  1  0
2         3      c  0  0  1
3         4      b  0  1  0
4         5      b  0  1  0

or

In [32]: df.join(df.Letter.str.get_dummies().astype(bool))
Out[32]:
   Position Letter      a      b      c
0         1      a   True  False  False
1         2      b  False   True  False
2         3      c  False  False   True
3         4      b  False   True  False
4         5      b  False   True  False


问:
C# Nullable Equality Operations, Why does null <= null resolve as false?
Why is it that in .NET

```<code>null >= null
</code>```

resolves as false, but

```<code>null == null
</code>```

resolves as true?

In other words, why isn't null >= null equivalent to null > null || null == null?

Does anyone have the official answer?

答:
This behaviour is defined in the C# specification (ECMA-334) in section 14.2.7 (I have highlighted the relevant part):

For the relational operators

```<code>< > <= >=
</code>```

a lifted form of an operator exists if the operand types are both non-nullable value types and if the result type
  is bool. The lifted form is constructed by adding a single ? modifier to each operand type. The lifted
  operator produces the value false if one or both operands are null. Otherwise, the lifted operator unwraps
  the operands and applies the underlying operator to produce the bool result.

In particular, this means that the usual laws of relations don't hold; x >= y does not imply !(x < y).

Gory details

Some people have asked why the compiler decides that this is a lifted operator for int? in the first place. Let's have a look. :)

We start with 14.2.4, 'Binary operator overload resolution'. This details the steps to follow.

First, the user-defined operators are examined for suitability. This is done by examining the operators defined by the types on each side of >=... which raises the question of what the type of null is! The null literal actually doesn't have any type until given one, it's simply the "null literal". By following the directions under 14.2.5 we discover there are no operators suitable here, since the null literal doesn't define any operators.

This step instructs us to examine the set of predefined operators for suitability. (Enums are also excluded by this section, since neither side is an enum type.) The relevant predefined operators are listed in sections 14.9.1 to 14.9.3, and they are all operators upon primitive numeric types, along with the lifted versions of these operators (note that strings operators are not included here).

Finally, we must perform overload resolution using these operators and the rules in 14.4.2.

Actually performing this resolution would be extremely tedious, but luckily there is a shortcut. Under 14.2.6 there is an informative example given of the results of overload resolution, which states:

...consider the predefined implementations of the binary * operator:

```<code>int operator *(int x, int y);
uint operator *(uint x, uint y);
long operator *(long x, long y);
ulong operator *(ulong x, ulong y);
void operator *(long x, ulong y);
void operator *(ulong x, long y);
float operator *(float x, float y);
double operator *(double x, double y);
decimal operator *(decimal x, decimal y);
</code>```

When overload resolution rules (§14.4.2) are applied to this set of operators, the effect is to select the first of
  the operators for which implicit conversions exist from the operand types.

Since both sides are null we can immediately throw out all unlifted operators. This leaves us with the lifted numeric operators on all primitive numeric types.

Then, using the previous information, we select the first of the operators for which an implicit conversion exists. Since the null literal is implicitly convertible to a nullable type, and a nullable type exists for int, we select the first operator from the list, which is int? >= int?.

Body:
Why is it that in .NET

null >= null

resolves as false, but

null == null

resolves as true?

In other words, why isn't null >= null equivalent to null > null || null == null?

Does anyone have the official answer?

Body:
This behaviour is defined in the C# specification (ECMA-334) in section 14.2.7 (I have highlighted the relevant part):

For the relational operators

< > <= >=

a lifted form of an operator exists if the operand types are both non-nullable value types and if the result type
  is bool. The lifted form is constructed by adding a single ? modifier to each operand type. The lifted
  operator produces the value false if one or both operands are null. Otherwise, the lifted operator unwraps
  the operands and applies the underlying operator to produce the bool result.

In particular, this means that the usual laws of relations don't hold; x >= y does not imply !(x < y).

Gory details

Some people have asked why the compiler decides that this is a lifted operator for int? in the first place. Let's have a look. :)

We start with 14.2.4, 'Binary operator overload resolution'. This details the steps to follow.

First, the user-defined operators are examined for suitability. This is done by examining the operators defined by the types on each side of >=... which raises the question of what the type of null is! The null literal actually doesn't have any type until given one, it's simply the "null literal". By following the directions under 14.2.5 we discover there are no operators suitable here, since the null literal doesn't define any operators.

This step instructs us to examine the set of predefined operators for suitability. (Enums are also excluded by this section, since neither side is an enum type.) The relevant predefined operators are listed in sections 14.9.1 to 14.9.3, and they are all operators upon primitive numeric types, along with the lifted versions of these operators (note that strings operators are not included here).

Finally, we must perform overload resolution using these operators and the rules in 14.4.2.

Actually performing this resolution would be extremely tedious, but luckily there is a shortcut. Under 14.2.6 there is an informative example given of the results of overload resolution, which states:

...consider the predefined implementations of the binary * operator:

int operator *(int x, int y);
uint operator *(uint x, uint y);
long operator *(long x, long y);
ulong operator *(ulong x, ulong y);
void operator *(long x, ulong y);
void operator *(ulong x, long y);
float operator *(float x, float y);
double operator *(double x, double y);
decimal operator *(decimal x, decimal y);

When overload resolution rules (§14.4.2) are applied to this set of operators, the effect is to select the first of
  the operators for which implicit conversions exist from the operand types.

Since both sides are null we can immediately throw out all unlifted operators. This leaves us with the lifted numeric operators on all primitive numeric types.

Then, using the previous information, we select the first of the operators for which an implicit conversion exists. Since the null literal is implicitly convertible to a nullable type, and a nullable type exists for int, we select the first operator from the list, which is int? >= int?.


问:
Delphi Exception message text in wrong language
I have an application where I catch exceptions and show the message text to the user as part of the error message. Allthough RAD Studio (10.1) is set to English and the Locale ID is set to 409 English in the Version Info options for all Targets the error message is output in German. This happens both on a German Windows 10 and other Windows machines with other languages, even a Japanese customer got this.

The exception is a system exception like failed to open file, file not found, but it seems it happens on all kind of exceptions that I do not raise with my own message text.

The project has been migrated from Delphi 2007 recently and I had to do some manual clean up in the project files regarding the version numbers. But checking the Locale in the project file reveals no surprise: 1033 -> $0409 - English.

Where could be the reason for the German messages?

答:
After searching for the solution every time I could spend some minutes in the last days, I solved it!

When using the BDSSetLanguage.exe tool in the bin folder of Rad Studio you not only can change the IDE's language but also the library's language. IDE was set to English and Library was set to German. Setting the library's language to English solved the problem.

Thanks to @mrabat sending me in the right direction. But since his tip was only a hack rather than a permanent solution, I think I can't give any official credits here.


问:
Hide div with JS select box based on one of the Div's JSON values
I need help getting my Javascript to work for a select dropdown that will hide a div based on a value of it's data in JSON. I have a page/laravel blade that loads furniture groups by using foreach loops and contains them in a div called .group-container. This is all done using a controller that builds our order form into a variable called $orderFormData, and then builds out the groups and individual products from there.

Here's the main basic structure, so you have an idea:

```<code>@foreach ($orderFormData->pgroups as $pgroup)
<div class="group-container">
        <h3 style="font-size: 26px; padding: 10px 0;">{{ $pgroup->group_name }} - {{ $pgroup->group_code }}</h3>
        <p class="uk-text-muted" style="font-size: 20px;" >{!! html_entity_decode($pgroup->group_desc) !!}</p> <!--Group Description-->

            @foreach ($pgroup->pskus as $psku)

            //table of rows for info

                    @endforeach
                    </tbody>
                </table>
            </div>

        </div>
@endforeach
</code>```

So, I want 2 values in my dropdown to show/hide a .group-container if it has a certain value of 1 or 0, depending on the selection.

The dropdown has options for popularity and recently ordered. So if the user chooses popularity, I need it to map to pgroups->topseller and if that has a value of 1 show it, if it has a value of 0 hide it. Same for recently ordered, but I want that to map to $pgroups->reorder.

Here's a screenshot of the JSON data of $orderFormData when I dump it:

So you can see the structure is $orderFormData->pgroups->topseller/reorder

Here's the Search bar:

```<code><div style="text-align:center;">
   <div>
     <span style="color:#fff;"><strong>Sort by:</strong></span>
       <select id="filterText" class="uk-text-muted" style="margin-top:10px; width:33%; height:30px; font-size: 16px;" >
         <option id="allitems" class="uk-text-muted" style="font-size: 16px;" selected data-default value="" selected data-default>All Items</option>
         <option id="popular" class="uk-text-muted" style="font-size: 16px;" value="popularity" >Popularity</option>
         <option id="recent" class="uk-text-muted" style="font-size: 16px;" value="recently_ordered">Recently Ordered </option>
       </select>
    </div>
 </div>
</code>```

And here's the Javascript:

```<code><script type="text/javascript">
$(function(){
var topsellers = "<?php echo $pgroups->topseller; ?>";
var reorder    = "<?php echo $pgroups->reorder; ?>";
//console.log( topsellers );
$('#filterText').on('change', function() {
  var currentVal = $(this).val();

  if (currentVal == 'popularity' && topsellers == "1" || currentVal == 'recently_ordered' && reorder == "1") {

    $(".groupcontainer").show();
   } else {
    $(".groupcontainer").hide();
   }
  });
});
</script>
</code>```

I'm thinking/hoping I'm just declaring something wrong but JS and JSON are not my wheelhouse. I just need to make sure everything's mapped correctly so that I can show/hide a div based on those values and the dropdown selection. Any help very appreciated.

答:
From your code, the variables topsellers and reorder are assigned whatever values is output by the <?php echo> command. From your comments, those values are false or true.

Therefore you simply need to match your JS equality check with those values :

```<code>$('#filterText').on('change', function() {
  var currentVal = $(this).val();

  if (currentVal == 'popularity' && topsellers == "true" || currentVal == 'recently_ordered' && reorder == "true") {

    $(".groupcontainer").show();
   } else {
    $(".groupcontainer").hide();
   }
  });
});
</code>```

Body:
I need help getting my Javascript to work for a select dropdown that will hide a div based on a value of it's data in JSON. I have a page/laravel blade that loads furniture groups by using foreach loops and contains them in a div called .group-container. This is all done using a controller that builds our order form into a variable called $orderFormData, and then builds out the groups and individual products from there.

Here's the main basic structure, so you have an idea:

@foreach ($orderFormData->pgroups as $pgroup)

{{ $pgroup->group_name }} - {{ $pgroup->group_code }}

{!! html_entity_decode($pgroup->group_desc) !!}

            @foreach ($pgroup->pskus as $psku)

            //table of rows for info

                    @endforeach

@endforeach

So, I want 2 values in my dropdown to show/hide a .group-container if it has a certain value of 1 or 0, depending on the selection.

The dropdown has options for popularity and recently ordered. So if the user chooses popularity, I need it to map to pgroups->topseller and if that has a value of 1 show it, if it has a value of 0 hide it. Same for recently ordered, but I want that to map to $pgroups->reorder.

Here's a screenshot of the JSON data of $orderFormData when I dump it:

So you can see the structure is $orderFormData->pgroups->topseller/reorder

Here's the Search bar:

     Sort by:
       <select id="filterText" class="uk-text-muted" style="margin-top:10px; width:33%; height:30px; font-size: 16px;" >
         <option id="allitems" class="uk-text-muted" style="font-size: 16px;" selected data-default value="" selected data-default>All Items</option>
         <option id="popular" class="uk-text-muted" style="font-size: 16px;" value="popularity" >Popularity</option>
         <option id="recent" class="uk-text-muted" style="font-size: 16px;" value="recently_ordered">Recently Ordered </option>
       </select>

And here's the Javascript:

I'm thinking/hoping I'm just declaring something wrong but JS and JSON are not my wheelhouse. I just need to make sure everything's mapped correctly so that I can show/hide a div based on those values and the dropdown selection. Any help very appreciated.

Body:
From your code, the variables topsellers and reorder are assigned whatever values is output by the <?php echo> command. From your comments, those values are false or true.

Therefore you simply need to match your JS equality check with those values :

$('#filterText').on('change', function() {
  var currentVal = $(this).val();

  if (currentVal == 'popularity' && topsellers == "true" || currentVal == 'recently_ordered' && reorder == "true") {

    $(".groupcontainer").show();
   } else {
    $(".groupcontainer").hide();
   }
  });
});


问:
java servlet sort json data by month name
I have a json array having single object with key as month name. When coming from Db it looks like
 [{
    "January": "January",
    "February": "February",
    "March": "March",
    "April": "April",
    "May": "May",
    "June": "June",
    "July": "July",
    "August": "August",
    "September": "September",
    "October": "October",
    "November": "November",
    "December": "December"
}]
and on frontend it looks like

```<code><select data-field-id="317" class="form-control selectchange to_month" id="searchform_to_month" name="searchform_to_month"><option value="">Select To Month</option><option value="June">June</option><option value="October">October</option><option value="December">December</option><option value="May">May</option><option value="September">September</option><option value="March">March</option><option value="July">July</option><option value="January">January</option><option value="February">February</option><option value="April">April</option><option value="August">August</option><option value="November">November</option></select>
</code>```

How can I sort it by month name so that it comes in dropdown like Jan, Feb and so on..

Below is the piece of code used

```<code>JSONArray jsonArray = new JSONArray(rowfielddata.getString("option_values"));
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject json = jsonArray.getJSONObject(i);
                        Iterator<String> keys = json.keys();
                        while (keys.hasNext()) {
                            String key = keys.next();
                            f2 = f2 + "<option value='" + key + "'>" + json.get(key) + "</option>";
                        }

                    }
</code>```

Thanks in advance!!

答:
To me your input json looks to be incorrect, if you can modify the JSON to below structure:

```<code>    [{"monthName": "January","order":1},
      {"monthName": "February","order":2},
       {"monthName": "March","order":3},
        {"monthName": "April","order":4},
        {"monthName": "May","order":5},
        {"monthName": "June","order":6},
        {"monthName": "July","order":7},
        {"monthName": "August","order":8},
        {"monthName": "September","order":9},
        {"monthName": "October","order":10},
        {"monthName": "November","order":11},
        {"monthName": "December","order":12}]
</code>```

Above JSON will give you array
Now next you need to do after reading data in JSONArray sort the data based on order value

```<code>JSONArray jsonArray = jsonResult.getJSONArray("getalldata");

JSONArray sortedJsonArray = new JSONArray();
    List<JSONObject> jsonValues = new ArrayList<JSONObject>();
    for (int i = 0; i < jsonArr.length(); i++) {
        jsonValues.add(jsonArr.getJSONObject(i));
    }
    Collections.sort( jsonValues, new Comparator<JSONObject>() {

        private static final String KEY_NAME = "order";

        @Override
        public int compare(JSONObject a, JSONObject b) {
            String valA = new String();
            String valB = new String();

            try {
                valA = (String) a.get(KEY_NAME);
                valB = (String) b.get(KEY_NAME);
            }
            catch (JSONException e) {
                //do something
            }
            return valA.compareTo(valB);
           }
    });

    for (int i = 0; i < jsonValues.length(); i++) {
        JSONObject jsonObj= jsonValues.getJSONObject(i);
                             f2 = f2 + "<option value='" +
      jsonObj.optString("id")+ "'>" + jsonObj.optString("monthName") + "
      </option>";
    }
</code>```

I assume there is another attribute also in the json with name id as this is being used to assign value in option tag

Body:
I have a json array having single object with key as month name. When coming from Db it looks like
 [{
    "January": "January",
    "February": "February",
    "March": "March",
    "April": "April",
    "May": "May",
    "June": "June",
    "July": "July",
    "August": "August",
    "September": "September",
    "October": "October",
    "November": "November",
    "December": "December"
}]
and on frontend it looks like

<select data-field-id="317" class="form-control selectchange to_month" id="searchform_to_month" name="searchform_to_month"><option value="">Select To Month</option><option value="June">June</option><option value="October">October</option><option value="December">December</option><option value="May">May</option><option value="September">September</option><option value="March">March</option><option value="July">July</option><option value="January">January</option><option value="February">February</option><option value="April">April</option><option value="August">August</option><option value="November">November</option></select>

How can I sort it by month name so that it comes in dropdown like Jan, Feb and so on..

Below is the piece of code used

JSONArray jsonArray = new JSONArray(rowfielddata.getString("option_values"));
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject json = jsonArray.getJSONObject(i);
                        Iterator<String> keys = json.keys();
                        while (keys.hasNext()) {
                            String key = keys.next();
                            f2 = f2 + "<option value='" + key + "'>" + json.get(key) + "</option>";
                        }

                    }

Thanks in advance!!

Body:
To me your input json looks to be incorrect, if you can modify the JSON to below structure:

    [{"monthName": "January","order":1},
      {"monthName": "February","order":2},
       {"monthName": "March","order":3},
        {"monthName": "April","order":4},
        {"monthName": "May","order":5},
        {"monthName": "June","order":6},
        {"monthName": "July","order":7},
        {"monthName": "August","order":8},
        {"monthName": "September","order":9},
        {"monthName": "October","order":10},
        {"monthName": "November","order":11},
        {"monthName": "December","order":12}]

Above JSON will give you array
Now next you need to do after reading data in JSONArray sort the data based on order value

JSONArray jsonArray = jsonResult.getJSONArray("getalldata");

JSONArray sortedJsonArray = new JSONArray();
    List<JSONObject> jsonValues = new ArrayList<JSONObject>();
    for (int i = 0; i < jsonArr.length(); i++) {
        jsonValues.add(jsonArr.getJSONObject(i));
    }
    Collections.sort( jsonValues, new Comparator<JSONObject>() {

        private static final String KEY_NAME = "order";

        @Override
        public int compare(JSONObject a, JSONObject b) {
            String valA = new String();
            String valB = new String();

            try {
                valA = (String) a.get(KEY_NAME);
                valB = (String) b.get(KEY_NAME);
            }
            catch (JSONException e) {
                //do something
            }
            return valA.compareTo(valB);
           }
    });

    for (int i = 0; i < jsonValues.length(); i++) {
        JSONObject jsonObj= jsonValues.getJSONObject(i);
                             f2 = f2 + "<option value='" +
      jsonObj.optString("id")+ "'>" + jsonObj.optString("monthName") + "
      </option>";
    }

I assume there is another attribute also in the json with name id as this is being used to assign value in option tag


问:
SELECT multivalues from same table in one row
I have the below table. as a reference table for values in the system.

```<code>Item    Item_code
Turkey  c01
KSA     c02
USA     c03
NY      s01
JED     s03
Dubai   j01
London  j02
.       .
.       .
.       .
</code>```

In the display page for users I want to show readable data " KSA, NY ..." not the codes. having the results in one row would save a lot code line.I don't want to do 5 select statements to get each value separately

example: I want to display the Item column of c02, s01 and s03 in one row.

desired result :

```<code>first Item     second Item    third Item ...
KSA             JED           NY
</code>```

this goes for 5 columns.

答:
What about conditional MAX()

```<code> SELECT MAX( CASE WHEN Item_code = 'c02' THEN Item END ) as first_item,
        MAX( CASE WHEN Item_code = 's01' THEN Item END ) as second_item,
        MAX( CASE WHEN Item_code = 's03' THEN Item END ) as third_item
 FROM Items
</code>```

Body:
I have the below table. as a reference table for values in the system.

Item    Item_code
Turkey  c01
KSA     c02
USA     c03
NY      s01
JED     s03
Dubai   j01
London  j02
.       .
.       .
.       .

In the display page for users I want to show readable data " KSA, NY ..." not the codes. having the results in one row would save a lot code line.I don't want to do 5 select statements to get each value separately

example: I want to display the Item column of c02, s01 and s03 in one row.

desired result :

first Item     second Item    third Item ...
KSA             JED           NY

this goes for 5 columns.

Body:
What about conditional MAX()

 SELECT MAX( CASE WHEN Item_code = 'c02' THEN Item END ) as first_item,
        MAX( CASE WHEN Item_code = 's01' THEN Item END ) as second_item,
        MAX( CASE WHEN Item_code = 's03' THEN Item END ) as third_item
 FROM Items


问:
iPhone - core data inspecting inside a NSSet attribute on a fetch
I have a core data structure of Books and Bundles. A book can belong to one or more bundles, so, I have a many-to-many attribute in place between the two. On the book this attribute is called fromBundle.

I have my class for each entity. This class was written when instead a many-to-many I had just a to-many relationship... so, at that time, fromBundle was not a NSSet. My problem is this, I have to build a predicate that could look inside the fromBundle NSSet and see if the set contains the bundle I am looking for.

This is the code I had before the change.

```<code>Bundle *aBundle = [Bundle bundleComNumber:aNumber  inManagedObjectContext:context];

NSArray *all = nil;

NSFetchRequest *request = [[NSFetchRequest alloc] init];

request.entity = [NSEntityDescription entityForName:@"Book" inManagedObjectContext:context];

// the problem is on the next line... as I see, the line is not looking inside the NSSet
// I may be wrong, but when I run this, it crashes and stops on the executeFetchRequest line
// saying **to-many key not allowed here**

request.predicate = [NSPredicate predicateWithFormat:
                     @"(fromBundle == %@)", aBundle];

[request setResultType:NSDictionaryResultType];
[request setReturnsDistinctResults:YES];
[request setPropertiesToFetch:[NSArray arrayWithObjects: @"Name", @"Number", nil]];

NSSortDescriptor *sortByItem =  [NSSortDescriptor sortDescriptorWithKey:ordem ascending:YES selector:@selector(compare:)];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortByItem];
[request setSortDescriptors:sortDescriptors];

NSError *error = nil;
all = [context executeFetchRequest:request error:&error];  // it is crashing here saying **to-many key not allowed here**
[request release];

return all;
</code>```

what am I missing?
thanks

答: Have you tried using a predicate like @"%@ IN fromBundle" instead?

Body:
I have a core data structure of Books and Bundles. A book can belong to one or more bundles, so, I have a many-to-many attribute in place between the two. On the book this attribute is called fromBundle.

I have my class for each entity. This class was written when instead a many-to-many I had just a to-many relationship... so, at that time, fromBundle was not a NSSet. My problem is this, I have to build a predicate that could look inside the fromBundle NSSet and see if the set contains the bundle I am looking for.

This is the code I had before the change.

Bundle *aBundle = [Bundle bundleComNumber:aNumber  inManagedObjectContext:context];

NSArray *all = nil;

NSFetchRequest *request = [[NSFetchRequest alloc] init];

request.entity = [NSEntityDescription entityForName:@"Book" inManagedObjectContext:context];

// the problem is on the next line... as I see, the line is not looking inside the NSSet
// I may be wrong, but when I run this, it crashes and stops on the executeFetchRequest line
// saying **to-many key not allowed here**

request.predicate = [NSPredicate predicateWithFormat:
                     @"(fromBundle == %@)", aBundle];

[request setResultType:NSDictionaryResultType];
[request setReturnsDistinctResults:YES];
[request setPropertiesToFetch:[NSArray arrayWithObjects: @"Name", @"Number", nil]];

NSSortDescriptor *sortByItem =  [NSSortDescriptor sortDescriptorWithKey:ordem ascending:YES selector:@selector(compare:)];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortByItem];
[request setSortDescriptors:sortDescriptors];

NSError *error = nil;
all = [context executeFetchRequest:request error:&error];  // it is crashing here saying **to-many key not allowed here**
[request release];

return all;

what am I missing?
thanks


问:
Removal of constant columns in R
I was using the prcomp function when I received this error

```<code>Error in prcomp.default(x, ...) :
cannot rescale a constant/zero column to unit variance
</code>```

I know I can scan my data manually but is there any function or command in R that can help me remove these constant variables?
I know this is a very simple task, but I have never been across any function that does this.

Thanks,

答:
Since this Q&A is a popular Google search result but the answer is a bit slow for a large matrix and @raymkchow version is slow with NAs i propose a new version using exponential search and data.table power.

This a function I implemented in dataPreparation package.

First build an example data.table, with more lines than columns (which is usually the case) and 10% of NAs

```<code>ncol = 1000
nrow = 100000
df <- matrix(sample(1:(ncol*nrow),ncol*nrow,replace = FALSE), ncol = ncol)
df <- apply (df, 2, function(x) {x[sample( c(1:nrow), floor(nrow/10))] <- NA; x} ) # Add 10% of NAs
df[,sample(1:ncol,70,replace = FALSE)] <- rep(1,times = nrow) # df is a large matrix
df <- as.data.table(df)
</code>```

Then benchmark all approaches:

```<code>time1 <- system.time(df1 <- df[,apply(df, 2, var, na.rm=TRUE) != 0, with = F]) # the first method
time2 <- system.time(df2 <- df[,!apply(df, MARGIN = 2, function(x) max(x, na.rm = TRUE) == min(x, na.rm = TRUE)), with = F]) # raymkchow
time3 <- system.time(df3 <- df[,apply(df, 2, function(col) { length(unique(col)) > 1 }), with = F]) # Keith's method
time4 <- system.time(df4 <- df[,-which_are_constant(df, verbose=FALSE)]) # My method
</code>```

The results are the following:

```<code>time1 # Variance approch
#   user  system elapsed
#   2.55    1.45    4.07
time2 # Min = max approach
#   user  system elapsed
#  2.72      1.5    4.22
time3 # length(unique()) approach
#   user  system elapsed
#    6.7    2.75    9.53
time4 # Exponential search approach
#   user  system elapsed
#   0.39    0.07    0.45
all.equal(df1, df2)
# [1] TRUE
all.equal(df3, df2)
# [1] TRUE
all.equal(df4, df2)
# [1] TRUE
</code>```

dataPreparation:which_are_constant is 10 times faster than the other approaches.

Plus the more rows you have the more interesting it is to use.

Title: Removal of constant columns in R

Body:
I was using the prcomp function when I received this error

Error in prcomp.default(x, ...) :
cannot rescale a constant/zero column to unit variance

I know I can scan my data manually but is there any function or command in R that can help me remove these constant variables?
I know this is a very simple task, but I have never been across any function that does this.

Thanks,

Body:
Since this Q&A is a popular Google search result but the answer is a bit slow for a large matrix and @raymkchow version is slow with NAs i propose a new version using exponential search and data.table power.

This a function I implemented in dataPreparation package.

First build an example data.table, with more lines than columns (which is usually the case) and 10% of NAs

ncol = 1000
nrow = 100000
df <- matrix(sample(1:(ncol*nrow),ncol*nrow,replace = FALSE), ncol = ncol)
df <- apply (df, 2, function(x) {x[sample( c(1:nrow), floor(nrow/10))] <- NA; x} ) # Add 10% of NAs
df[,sample(1:ncol,70,replace = FALSE)] <- rep(1,times = nrow) # df is a large matrix
df <- as.data.table(df)

Then benchmark all approaches:

time1 <- system.time(df1 <- df[,apply(df, 2, var, na.rm=TRUE) != 0, with = F]) # the first method
time2 <- system.time(df2 <- df[,!apply(df, MARGIN = 2, function(x) max(x, na.rm = TRUE) == min(x, na.rm = TRUE)), with = F]) # raymkchow
time3 <- system.time(df3 <- df[,apply(df, 2, function(col) { length(unique(col)) > 1 }), with = F]) # Keith's method
time4 <- system.time(df4 <- df[,-which_are_constant(df, verbose=FALSE)]) # My method

The results are the following:

time1 # Variance approch
#   user  system elapsed
#   2.55    1.45    4.07
time2 # Min = max approach
#   user  system elapsed
#  2.72      1.5    4.22
time3 # length(unique()) approach
#   user  system elapsed
#    6.7    2.75    9.53
time4 # Exponential search approach
#   user  system elapsed
#   0.39    0.07    0.45
all.equal(df1, df2)
# [1] TRUE
all.equal(df3, df2)
# [1] TRUE
all.equal(df4, df2)
# [1] TRUE

dataPreparation:which_are_constant is 10 times faster than the other approaches.

Plus the more rows you have the more interesting it is to use.