问:
Using Cereal to deserialize a JSON string
I am new to Cereal and I am having a hard time understanding how to deserialize a JSON string. Unfortunately, my work firewall restricts me from accessing Google Groups to post on the message board.

I have a class that I can turn into a JSON string but can’t for the life of me take the string and recreate the class. Any help would be appreciated and please be gentle I just got out of school, it is my first job, and I am way out my depth.

This is the error I am getting:

terminate called after throwing an instance of 'cereal::RapidJSONException' what():  rapidjson internal assertion failure: IsObject()

Below is MyClass.hpp class:

```<code>#include <cstdio>
#include <iostream>
#include <string>
#include "../cereal/access.hpp"

class MyClass{
Public: //function declarations
     template<class Archive> // public serialization (normal)
     void serialize(Archive & ar)
     {
         ar(x, y, z);
     }

private: // member variables
    string x;
    int y;
    bool z;
};
</code>```

Below is my Main.cpp:

```<code>#include <../cereal/types/unordered_map.hpp>
#include <../cereal/types/memory.hpp>
#include <../cereal/types/concepts/pair_associative_container.hpp>
#include <../cereal/archives/json.hpp>
#include <../cereal/types/vector.hpp>

#include <iostream>
#include <fstream>

#include "MyClass.hpp"

int main(){
    // serialize (this part all works... i think)
    {
        // create a class object and give it some data
        MyClass data("hello", 6, true);
        // create a string stream object
        std::stringstream os;
        // assign the string stream object to the Output Archive
        cereal::JSONOutputArchive archive_out(os);
        //write data to the output archive
        archive_out(CEREAL_NVP( data ));
        // write the string stream buffer to a variable
        string json_str = os.str();
    }
    // deserialize
    {
        // create a string stream object and pass it the string variable holding the JSON archive
        std::stringstream is( json_str );
        // pass the stream sting object into the input archive **** this is the line of code that generates the error
        cereal::JSONInputArchive archive_in( is );
        // create a new object of MyClass
        MyClass data_new;
        // use input archive to write data to my class
        archive_in( data_new );
    }
}
</code>```

答:
As per cereal documentation

Some archives in cereal can only safely finish flushing their contents upon their destruction. Make sure, especially for output serialization, that your archive is automatically destroyed when you are finished with it.

So it is imporant to call os.str() outside of serialize block, i.e.

```<code>MyClass data("hello", 6, true);
std::stringstream os;
{
    cereal::JSONOutputArchive archive_out(os);
    archive_out(CEREAL_NVP(data));
}
string json_str = os.str();
cout << json_str << endl;

// deserialize
std::stringstream is(json_str);
MyClass data_new;
{
    cereal::JSONInputArchive archive_in(is);
    archive_in(data_new);
    cout << data_new.y << endl;
}
</code>```

This is working code. You may want to change it further upon your needs

Body:
I am new to Cereal and I am having a hard time understanding how to deserialize a JSON string. Unfortunately, my work firewall restricts me from accessing Google Groups to post on the message board.

I have a class that I can turn into a JSON string but can’t for the life of me take the string and recreate the class. Any help would be appreciated and please be gentle I just got out of school, it is my first job, and I am way out my depth.

This is the error I am getting:

terminate called after throwing an instance of 'cereal::RapidJSONException' what():  rapidjson internal assertion failure: IsObject()

Below is MyClass.hpp class:

#include <cstdio>
#include <iostream>
#include <string>
#include "../cereal/access.hpp"

class MyClass{
Public: //function declarations
     template<class Archive> // public serialization (normal)
     void serialize(Archive & ar)
     {
         ar(x, y, z);
     }

private: // member variables
    string x;
    int y;
    bool z;
};

Below is my Main.cpp:

#include <../cereal/types/unordered_map.hpp>
#include <../cereal/types/memory.hpp>
#include <../cereal/types/concepts/pair_associative_container.hpp>
#include <../cereal/archives/json.hpp>
#include <../cereal/types/vector.hpp>

#include <iostream>
#include <fstream>

#include "MyClass.hpp"

int main(){
    // serialize (this part all works... i think)
    {
        // create a class object and give it some data
        MyClass data("hello", 6, true);
        // create a string stream object
        std::stringstream os;
        // assign the string stream object to the Output Archive
        cereal::JSONOutputArchive archive_out(os);
        //write data to the output archive
        archive_out(CEREAL_NVP( data ));
        // write the string stream buffer to a variable
        string json_str = os.str();
    }
    // deserialize
    {
        // create a string stream object and pass it the string variable holding the JSON archive
        std::stringstream is( json_str );
        // pass the stream sting object into the input archive **** this is the line of code that generates the error
        cereal::JSONInputArchive archive_in( is );
        // create a new object of MyClass
        MyClass data_new;
        // use input archive to write data to my class
        archive_in( data_new );
    }
}

Body:
As per cereal documentation

Some archives in cereal can only safely finish flushing their contents upon their destruction. Make sure, especially for output serialization, that your archive is automatically destroyed when you are finished with it.

So it is imporant to call os.str() outside of serialize block, i.e.

MyClass data("hello", 6, true);
std::stringstream os;
{
    cereal::JSONOutputArchive archive_out(os);
    archive_out(CEREAL_NVP(data));
}
string json_str = os.str();
cout << json_str << endl;

// deserialize
std::stringstream is(json_str);
MyClass data_new;
{
    cereal::JSONInputArchive archive_in(is);
    archive_in(data_new);
    cout << data_new.y << endl;
}

This is working code. You may want to change it further upon your needs


来源: stackexchange

问:
Overwrite ajaxComplete for particular ajax request
My application has a ajaxComplete() which is defined in a  generic .js file loaded in every view page. How can I overwrite this or better still avoid running it for specific $.ajax() call.</p>

答:
Set global: false in your $.ajax call.

From the API:

Whether to trigger global Ajax event handlers for this request. The default is true. Set to false to prevent the global handlers like ajaxStart or ajaxStop from being triggered.

Your call will look something like this:

```<code>$.ajax({
    url: 'http://example.com/',
    data: data,
    global: false,
    success: function() {

    }/* etc... */
});
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Set global: false in your $.ajax call.

From the API:

Whether to trigger global Ajax event handlers for this request. The default is true. Set to false to prevent the global handlers like ajaxStart or ajaxStop from being triggered.

Your call will look something like this:

$.ajax({
    url: 'http://example.com/',
    data: data,
    global: false,
    success: function() {

    }/* etc... */
});


问:
ReactJS: "Error: React.createElement is not a function"
I have been using React for a while now, and my version was horribly out of date. I updated to 0.12 without incident. Then I tried upgrading react tools as well. That is when everything broke. Now I am getting the following error: "Error: React.createElement is not a function". Other than a vague idea that this probably has something to do with the changes to the JSX transformer, I have no idea why upgrading react tools is leading to this error. Any help would be appreciated</p>

答:
This same class of problem can happen in other ways, so i will link to the other issue, rather than duplicating the same answer here. Not sure if there's a more 'standard' way to link two posts.

ReactJS: React.render is not a function and React.createElement is not a function

ContentLicense: CC BY-SA 3.0


问:
Azure virtual network hybrid connection
I've got an Azure Virtual Network setup and a VM setup within the network. I've installed the Hybrid Connection Manager app on the VM.

I also have an Azure App Service and I've created a hybrid connection between it and the VM and they are both claiming they are happily connected to each other.

Also on the VM I've installed an app that is listening on http://localhost:1234

Can someone tell me what IP I use from my app service to talk to http://localhost:1234 on the VM? e.g. Is it [VM internal IP]:1234 or [VM public IP]:1234, or something else. Nothing is talking at the moment so I want to make sure the IP address is not the problem.

答:
You should use VM host name, thanks for evilSnobu's link .

If you use an IP address, you may or may not reach the on-premises
  resource, depending on your client.

If you use VM public IP, traffic packets are transmitted over the Internet to your VM not VPN tunnel. localhost only could be used inside VM.

Also, if your app is listening on localhost(127.0.0.1), the service only could access inside your VM. As evilSnobu said, you need modify your service listening on 0.0.0.0 or private IP(like 10.0.0.4). You could check with following command.

For Linux

```<code>netstat -ant|grep 1234
</code>```

For Windows

```<code>netstat -ant|findstr 1234
</code>```

Title: Azure virtual network hybrid connection

Body:
You should use VM host name, thanks for evilSnobu's link .

If you use an IP address, you may or may not reach the on-premises
  resource, depending on your client.

If you use VM public IP, traffic packets are transmitted over the Internet to your VM not VPN tunnel. localhost only could be used inside VM.

Also, if your app is listening on localhost(127.0.0.1), the service only could access inside your VM. As evilSnobu said, you need modify your service listening on 0.0.0.0 or private IP(like 10.0.0.4). You could check with following command.

For Linux

netstat -ant|grep 1234

For Windows

netstat -ant|findstr 1234


问:
How to reference var from frame on timeline in an object class
I'm using Flash Professional cs5/AS3

I'll try and describe this the best I can. I'm new to ActionScript.

So, in my timeline I have a var on a frame that represents "lives" and i have some code in the timeline that takes down the number of lives depending on certain events, which all works great.

so, now i wanted to make a constructor class that I could reuse for a bunch of movie clip objects and I only want these objects to be able to move if the lives variable is greater than certain number. So now, building my constructor class for these objects i just wanted put an if statement that is looking to see if the lives are greater than a certain number, which if it is then should make these objects do what i want...But, when i run the project I get "1120: Access of undefined property lives." lives is the var I made obviously like I said, and it works fine being referenced everyone else except when I make a new .as file for these objects then try and reference it. I get the same error when I try and establish "lives" in the main project class too. I'm not sure where I should put this var or how I can make it so i can reference it from an object class.

I'm not really sure how to word or describe my issue which has made it hard to search for a tutorial. Any suggestions i'm sure this has to be a simple task.

答:
The other answers are definitely good solutions and were very helpful, the first one may be better. But what i decided to use for my situation was just create a function on the main frame that contained the code to decrease a life. Then I just ran the function from the other fram by doing this</p>

```<code>//created a var in my movieclip that "contained" the main timeline
var main:MovieClip = MovieClip(this.parent.parent);

//then simply ran the function from the movieclip
main.decreaseLife();
</code>```

Body:
The other answers are definitely good solutions and were very helpful, the first one may be better. But what i decided to use for my situation was just create a function on the main frame that contained the code to decrease a life. Then I just ran the function from the other fram by doing this

//created a var in my movieclip that "contained" the main timeline
var main:MovieClip = MovieClip(this.parent.parent);

//then simply ran the function from the movieclip
main.decreaseLife();


问:
error: pathspec 'test-branch' did not match any file(s) known to git
I am a new user of Git. I have forked a repository called Spoon-Knife (available for practicing forking with Git). Then, I cloned it locally by running

```<code>git clone https://github.com/rohinichoudhary/Spoon-Knife.git
</code>```

This repository contains three branches, i.e.

master,

test-branch,

change-the-title.

When I run git branch, it only shows *master, not the remaining two branches. And when I run

```<code>git checkout test-branch
</code>```

I get the following error:

error: pathspec 'test-branch' did not match any file(s) known to git.

Why is this happening? How can I solve this problem?

答:
Solution:

To fix it you need to fetch first

```<code>$ git fetch origin

$ git rebase origin/master
</code>```

Current branch master is up to date.

```<code>$ git checkout develop
</code>```

Branch develop set up to track remote branch develop from origin.

Switched to a new branch ‘develop’

Body:
I am a new user of Git. I have forked a repository called Spoon-Knife (available for practicing forking with Git). Then, I cloned it locally by running

git clone https://github.com/rohinichoudhary/Spoon-Knife.git

This repository contains three branches, i.e.

master,

test-branch,

change-the-title.

When I run git branch, it only shows *master, not the remaining two branches. And when I run

git checkout test-branch

I get the following error:

error: pathspec 'test-branch' did not match any file(s) known to git.

Why is this happening? How can I solve this problem?

Body:
Solution:

To fix it you need to fetch first

$ git fetch origin

$ git rebase origin/master

Current branch master is up to date.

$ git checkout develop

Branch develop set up to track remote branch develop from origin.

Switched to a new branch ‘develop’


问:
Laravel attach object to many objects in many-to-many relationship without loop
I have a many-to-many relationship on a User model and Notification model.

To create a Notification and attach to many Users, I am currently doing:

```<code>$users = User::all();
$notification = new Notification(['title'=>'some title', 'body'=>'notification body']);
$notification->save();
foreach ($users as $user) {
   $user->notifications()->attach([$notification->id]);
}
</code>```

The foreach implementation won't be ideal if $users->count() becomes a very large number;
Please is there a better way to get this done without so many loops?

Thanks

答:
See here: https://laravel.com/docs/5.4/eloquent-relationships#updating-many-to-many-relationships

You can pass an array of ids to the attach() method like so:

```<code>$user_ids = User::pluck('id');
$notification = new Notification(['title'=>'some title', 'body'=>'notification body']);
$notification->save();
$notification->users()->attach($user_ids);
</code>```

Assuming your relationship on $notification is called users() of course

Body:
I have a many-to-many relationship on a User model and Notification model.

To create a Notification and attach to many Users, I am currently doing:

$users = User::all();
$notification = new Notification(['title'=>'some title', 'body'=>'notification body']);
$notification->save();
foreach ($users as $user) {
   $user->notifications()->attach([$notification->id]);
}

The foreach implementation won't be ideal if $users->count() becomes a very large number;
Please is there a better way to get this done without so many loops?

Thanks

Body:
See here: https://laravel.com/docs/5.4/eloquent-relationships#updating-many-to-many-relationships

You can pass an array of ids to the attach() method like so:

$user_ids = User::pluck('id');
$notification = new Notification(['title'=>'some title', 'body'=>'notification body']);
$notification->save();
$notification->users()->attach($user_ids);

Assuming your relationship on $notification is called users() of course


问:
About Tier of BigQuery Flatrate
BigQuery is now available for Tier 100 at Tier 1 rate.

https://cloud.google.com/bigquery/docs/release-notes

Will this also apply to Flatrate?

答: Compute tiers are irrelevant for flat rate reservations. For on-demand queries, compute tiers 1-100 are now treated as the same thing (you won't pay any extra).</p>

Title: About Tier of BigQuery Flatrate


问:
Visual Studio 2015 Error
My visual studio stopped working. When i try to open it shows me blank screen with error Source Control Explorer. Parameter is Not valid and no menu options.
tried uninstall and install, but still not working

答:
Pleas try below things to narrow down the issue:

1, Clean TFS and VS caches, copy below commands ans save as .bat or .cmd file to run it.

```<code>SET AppDataTF=%USERPROFILE%\AppData\Local\Microsoft\Team Foundation
SET AppLocallVS=%USERPROFILE%\AppData\Local\Microsoft\VisualStudio
SET AppDataVS=%APPDATA%\Microsoft\VisualStudio
IF EXIST "%AppDataTF%\4.0\Cache" rd /s /q "%AppDataTF%\4.0\Cache" > NUL
IF EXIST "%AppDataTF%\5.0\Cache" rd /s /q "%AppDataTF%\5.0\Cache" > NUL
IF EXIST "%AppDataTF%\6.0\Cache" rd /s /q "%AppDataTF%\6.0\Cache" > NUL
IF EXIST "%AppDataTF%\7.0\Cache" rd /s /q "%AppDataTF%\7.0\Cache" > NUL
IF EXIST "%AppLocallVS%\" rd /s /q "%AppDataTF%\" > NUL
IF EXIST "%AppDataVS%\10.0\Team Explorer" rd /s /q "%AppDataVS%\10.0\Team Explorer" > NUL
IF EXIST "%AppDataVS%\11.0\Team Explorer" rd /s /q "%AppDataVS%\11.0\Team Explorer" > NUL
IF EXIST "%AppDataVS%\12.0\Team Explorer" rd /s /q "%AppDataVS%\12.0\Team Explorer" > NUL
IF EXIST "%AppDataVS%\13.0\Team Explorer" rd /s /q "%AppDataVS%\13.0\Team Explorer" > NUL
IF EXIST "%AppDataVS%\14.0\Team Explorer" rd /s /q "%AppDataVS%\14.0\Team Explorer" > NUL
IF EXIST "%AppDataVS%\15.0\Team Explorer" rd /s /q "%AppDataVS%\15.0\Team Explorer" > NUL
</code>```

2, Run below command to reset the devenv.exe /resetuserdata

```<code>cd C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE
devenv.exe /resetuserdata
</code>```

3, If that still not work, just try to uninstall VS ( make sure you have removed all the components ), then reinstall VS.

Title: Visual Studio 2015 Error

Body:
Pleas try below things to narrow down the issue:

1, Clean TFS and VS caches, copy below commands ans save as .bat or .cmd file to run it.

SET AppDataTF=%USERPROFILE%\AppData\Local\Microsoft\Team Foundation
SET AppLocallVS=%USERPROFILE%\AppData\Local\Microsoft\VisualStudio
SET AppDataVS=%APPDATA%\Microsoft\VisualStudio
IF EXIST "%AppDataTF%\4.0\Cache" rd /s /q "%AppDataTF%\4.0\Cache" > NUL
IF EXIST "%AppDataTF%\5.0\Cache" rd /s /q "%AppDataTF%\5.0\Cache" > NUL
IF EXIST "%AppDataTF%\6.0\Cache" rd /s /q "%AppDataTF%\6.0\Cache" > NUL
IF EXIST "%AppDataTF%\7.0\Cache" rd /s /q "%AppDataTF%\7.0\Cache" > NUL
IF EXIST "%AppLocallVS%\" rd /s /q "%AppDataTF%\" > NUL
IF EXIST "%AppDataVS%\10.0\Team Explorer" rd /s /q "%AppDataVS%\10.0\Team Explorer" > NUL
IF EXIST "%AppDataVS%\11.0\Team Explorer" rd /s /q "%AppDataVS%\11.0\Team Explorer" > NUL
IF EXIST "%AppDataVS%\12.0\Team Explorer" rd /s /q "%AppDataVS%\12.0\Team Explorer" > NUL
IF EXIST "%AppDataVS%\13.0\Team Explorer" rd /s /q "%AppDataVS%\13.0\Team Explorer" > NUL
IF EXIST "%AppDataVS%\14.0\Team Explorer" rd /s /q "%AppDataVS%\14.0\Team Explorer" > NUL
IF EXIST "%AppDataVS%\15.0\Team Explorer" rd /s /q "%AppDataVS%\15.0\Team Explorer" > NUL

2, Run below command to reset the devenv.exe /resetuserdata

cd C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE
devenv.exe /resetuserdata

3, If that still not work, just try to uninstall VS ( make sure you have removed all the components ), then reinstall VS.


问:
Warning when presenting a UIViewController
I am creating another instance my main view controller and presenting it.

```<code>MainViewController *sm = [[MainViewController alloc]initWithNibName:@"MainViewController" bundle:nil];
[self presentModalViewController:sm animated:NO];
[sm release];
</code>```

This gives the following errors

warning: receiver 'MainViewController' is a forward class and corresponding @interface may not exist

warning: incompatible Objective-C types 'struct MainViewController *', expected 'struct UIViewController *' when passing argument 1 of 'presentModalViewController:animated:' from distinct Objective-C type

What am I doing wrong? How can I present the current version of MainViewController that exists?

答:
import "MainViewController.h"

in your .m file.

Body:
I am creating another instance my main view controller and presenting it.

MainViewController *sm = [[MainViewController alloc]initWithNibName:@"MainViewController" bundle:nil];
[self presentModalViewController:sm animated:NO];
[sm release];

This gives the following errors

warning: receiver 'MainViewController' is a forward class and corresponding @interface may not exist

warning: incompatible Objective-C types 'struct MainViewController *', expected 'struct UIViewController *' when passing argument 1 of 'presentModalViewController:animated:' from distinct Objective-C type

What am I doing wrong? How can I present the current version of MainViewController that exists?


答:
```<code>$users = User::all();

$notification = Notification::create([
    'title'=>'some title',
    'body'=>'notification body'
]);

$notification->user()->attach($users);
</code>```

Title: Laravel attach object to many objects in many-to-many relationship without loop


问:
Gulp gulp-sass "Error: EACCES: permission denied, open"
I have a node.js v4.2.1 and gulp. I use gulp-sass.
After the first compilation i get css file with permissions.

```<code>ls -la
-r--rw-r-- 1 user user 190K Oct 27 03:01 common.min.css
</code>```

After subsequent compilations i get error.

```<code>stream.js:74
  throw er; // Unhandled stream error in pipe.
  ^

Error: EACCES: permission denied, open '/home/user/prj/sample/front/bin/css/common.min.css'
  at Error (native)
</code>```

Why it is happens? Why is it sets this permissions? Previously, no such problems. Thank's.

答:
check file permissions and ownsership and make sure you have the right to READ, WRITE & EXCUTE on this file ... or simply remove it and gulp will build a new file after transpiling. for more details on file permissions and if you are a linux user check this out.
Introduction to Linux Permissions</p>

Body:
I have a node.js v4.2.1 and gulp. I use gulp-sass.
After the first compilation i get css file with permissions.

ls -la
-r--rw-r-- 1 user user 190K Oct 27 03:01 common.min.css

After subsequent compilations i get error.

stream.js:74
  throw er; // Unhandled stream error in pipe.
  ^

Error: EACCES: permission denied, open '/home/user/prj/sample/front/bin/css/common.min.css'
  at Error (native)

Why it is happens? Why is it sets this permissions? Previously, no such problems. Thank's.


问:
Differences between a class with static members and a namespace/module in typescript
There are a lot of discussions about how and when to use static classes and how to achieve a real static class in typescript. But I have not found any explanation about the differences between a class with only static members paired with an unuseable constructor and a namespace/module.

How do them both affect the global namespace and what is the difference for the memory and usage?

Because in my opinion and what the official documentation says, it would be more easy to achieve the functionality of a static class by using a namespace construct. It is less code and more easy then to use a real class.

答:
You can always look at the compiled javascript output to see the difference. A namespace is an object that will be merged with other namespaces with the same name.

```<code>namespace A{
    export function b(){

    }
}
</code>```

javascript output:

```<code>var A;
(function (A) {
    function b() {
    }
    A.b = b;
})(A || (A = {}));
</code>```

A class is a function and a static member is a property of the function.

```<code>class A{
    public static b(){

    }
}
</code>```

javascript output:

```<code>var A = /** @class */ (function () {
    function A() {
    }
    A.b = function () {
    };
    return A;
}());
</code>```

Both, namespace and class, will occupy the same name "A" in the global namespace. From the perspecive of a client, there is no difference in accessing a static class member or a function inside a namespace:

```<code>A.b();
</code>```

Personally, I don't use static class members or namespaces, i always define functions and variables at the top level inside a module, and use different modules to group different functions.
The typescript homepage has a good topic about this: https://www.typescriptlang.org/docs/handbook/namespaces-and-modules.html

Body:
You can always look at the compiled javascript output to see the difference. A namespace is an object that will be merged with other namespaces with the same name.

namespace A{
    export function b(){

    }
}

javascript output:

var A;
(function (A) {
    function b() {
    }
    A.b = b;
})(A || (A = {}));

A class is a function and a static member is a property of the function.

class A{
    public static b(){

    }
}

javascript output:

var A = /** @class */ (function () {
    function A() {
    }
    A.b = function () {
    };
    return A;
}());

Both, namespace and class, will occupy the same name "A" in the global namespace. From the perspecive of a client, there is no difference in accessing a static class member or a function inside a namespace:

A.b();

Personally, I don't use static class members or namespaces, i always define functions and variables at the top level inside a module, and use different modules to group different functions.
The typescript homepage has a good topic about this: https://www.typescriptlang.org/docs/handbook/namespaces-and-modules.html


问:
Initial indexes of sorted elements of ArrayList
The following code implements sorting of nfit in ascending order.

```<code>public static void main(String[] args) {
    ArrayList<Double> nfit = new ArrayList<Double>();

    nfit.add(2.0);
    nfit.add(5.0);
    nfit.add(1.0);
    nfit.add(8.0);
    nfit.add(3.0);

    // Sort individuals in ascending order
    Collections.sort(nfit);

    System.out.print(nfit);

}
</code>```

The output is:

```<code>[1.0, 2.0, 3.0, 5.0, 8.0]
</code>```

My question is how to get initial indexes of sorted elements? In this example the answer to my question would be the following:

```<code>[2, 0, 4, 1, 3]
</code>```

How can I get these indexes?

答:
Bubble sort is always your friend. You can use it to sort the array and at the same time keep track of original array indices. It will also work when you have multiple similar elements in your array.

```<code>import java.util.*;
import java.util.Arrays;
import java.util.Random;
public class BubbleSort {
    public static void main(String[] args) {
        Random rnd = new Random();
        int count = 5;
        ArrayList<Double> array = new ArrayList<Double>();
        int[] indices = new int[count];
        for(int i = 0; i < indices.length; i++) {
            array.add(rnd.nextDouble() * count);
            indices[i] = i;
        }
        ArrayList<Double> values = new ArrayList<Double>(array);
        bubbleSort(values, indices);
        System.out.println("Unsorted input array   :" + array);
        System.out.print("Sorted   input array   : ");
        for(int i = 0; i < array.size(); i++) {
            System.out.print(array.get(indices[i]) + " " );
        }
        System.out.println();
    }
    private static void bubbleSort(ArrayList<Double> values, int[] indices) {
        for(int k = 0; k < values.size(); k++) {
            for(int l = k + 1; l < values.size(); l++) {
                if(values.get(k) > values.get(l)) {
                    double temp_value = values.get(k);
                    values.set(k, values.get(l));
                    values.set(l, temp_value);
                    int temp_index = indices[k];
                    indices[k] = indices[l];
                    indices[l] = temp_index;
                }
            }
        }
    }
}
</code>```

The reason I answered this question after this many years is that the  accepted answer will fail if you have multiple elements with similar values because in indexes[n] = nstore.indexOf(nfit.get(n));, indexOf method is always returning the first occurrence of the specified element which results in an incorrect indices array while having similar elements in the input array.

Last, copy and paste the code in BubbleSort.java and then run javac BubbleSort.java && java BubbleSort to compile and see the results.

Body:
The following code implements sorting of nfit in ascending order.

public static void main(String[] args) {
    ArrayList<Double> nfit = new ArrayList<Double>();

    nfit.add(2.0);
    nfit.add(5.0);
    nfit.add(1.0);
    nfit.add(8.0);
    nfit.add(3.0);

    // Sort individuals in ascending order
    Collections.sort(nfit);

    System.out.print(nfit);

}

The output is:

[1.0, 2.0, 3.0, 5.0, 8.0]

My question is how to get initial indexes of sorted elements? In this example the answer to my question would be the following:

[2, 0, 4, 1, 3]

How can I get these indexes?

Body:
Bubble sort is always your friend. You can use it to sort the array and at the same time keep track of original array indices. It will also work when you have multiple similar elements in your array.

import java.util.*;
import java.util.Arrays;
import java.util.Random;
public class BubbleSort {
    public static void main(String[] args) {
        Random rnd = new Random();
        int count = 5;
        ArrayList<Double> array = new ArrayList<Double>();
        int[] indices = new int[count];
        for(int i = 0; i < indices.length; i++) {
            array.add(rnd.nextDouble() * count);
            indices[i] = i;
        }
        ArrayList<Double> values = new ArrayList<Double>(array);
        bubbleSort(values, indices);
        System.out.println("Unsorted input array   :" + array);
        System.out.print("Sorted   input array   : ");
        for(int i = 0; i < array.size(); i++) {
            System.out.print(array.get(indices[i]) + " " );
        }
        System.out.println();
    }
    private static void bubbleSort(ArrayList<Double> values, int[] indices) {
        for(int k = 0; k < values.size(); k++) {
            for(int l = k + 1; l < values.size(); l++) {
                if(values.get(k) > values.get(l)) {
                    double temp_value = values.get(k);
                    values.set(k, values.get(l));
                    values.set(l, temp_value);
                    int temp_index = indices[k];
                    indices[k] = indices[l];
                    indices[l] = temp_index;
                }
            }
        }
    }
}

The reason I answered this question after this many years is that the  accepted answer will fail if you have multiple elements with similar values because in indexes[n] = nstore.indexOf(nfit.get(n));, indexOf method is always returning the first occurrence of the specified element which results in an incorrect indices array while having similar elements in the input array.

Last, copy and paste the code in BubbleSort.java and then run javac BubbleSort.java && java BubbleSort to compile and see the results.


问:
ContactsContract lookup Phone Number by Contact Id
I am attempting to lookup the phone number for contacts by their contactId, bll results are returning - Phone Number: 1

I've tried using other examples around SO but I keep getting a 0 count on the cursor

```<code>Uri uri = ContentUris.withAppendedId(Data.CONTENT_URI, contactId);

Log.i(TAG, "Locate Contact by Id: " + contactId + " at Uri: " + uri.toString());

Cursor cursor = this.getContentResolver().query(uri, null, null, null, null);

try {
    if (cursor.moveToFirst()) {
        Log.i(TAG, "Phone Number: " + cursor.getString(cursor.getColumnIndex(Phone.NUMBER)));
    }
} finally {
    cursor.close();
}
</code>```

答:
try this:</p>

```<code>private ArrayList<String> getPhoneNumbers(String id)
{
    ArrayList<String> phones = new ArrayList<String>();

    Cursor cursor = mContentResolver.query(
            CommonDataKinds.Phone.CONTENT_URI,
            null,
            CommonDataKinds.Phone.CONTACT_ID +" = ?",
            new String[]{id}, null);

    while (cursor.moveToNext())
    {
        phones.add(cursor.getString(cursor.getColumnIndex(CommonDataKinds.Phone.NUMBER)));
    }

    cursor.close();
    return(phones);
}
</code>```

Body:
I am attempting to lookup the phone number for contacts by their contactId, bll results are returning - Phone Number: 1

I've tried using other examples around SO but I keep getting a 0 count on the cursor

Uri uri = ContentUris.withAppendedId(Data.CONTENT_URI, contactId);

Log.i(TAG, "Locate Contact by Id: " + contactId + " at Uri: " + uri.toString());

Cursor cursor = this.getContentResolver().query(uri, null, null, null, null);

try {
    if (cursor.moveToFirst()) {
        Log.i(TAG, "Phone Number: " + cursor.getString(cursor.getColumnIndex(Phone.NUMBER)));
    }
} finally {
    cursor.close();
}

Body:
try this:

private ArrayList<String> getPhoneNumbers(String id)
{
    ArrayList<String> phones = new ArrayList<String>();

    Cursor cursor = mContentResolver.query(
            CommonDataKinds.Phone.CONTENT_URI,
            null,
            CommonDataKinds.Phone.CONTACT_ID +" = ?",
            new String[]{id}, null);

    while (cursor.moveToNext())
    {
        phones.add(cursor.getString(cursor.getColumnIndex(CommonDataKinds.Phone.NUMBER)));
    }

    cursor.close();
    return(phones);
}


问:
How to make Dynamic one row 7 columns that has horizontal Scroll
So i have been working on my android project and the layout has gotten me and I cannot figure out what is the best to do something like this.
Currently my XML looks like this.
What i am trying to do is have 7 columns with one row that is filled with textviews. I was looking at Grid views but it seems like the entire point of the grid is to scroll with more than one row. How do I achieve this layout?</p>

```<code> <android.support.constraint.ConstraintLayout
    android:id="@+id/ConstraintLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/foodmenuexample"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="TextView" />

            <HorizontalScrollView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1">

                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:orientation="horizontal">

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:layout_weight="1"
                        android:orientation="vertical">

                        <TextView
                            android:id="@+id/textView9"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:text="TextView" />

                        <TextView
                            android:id="@+id/textView10"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:text="TextView" />
                    </LinearLayout>

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:layout_weight="1"
                        android:orientation="vertical">

                        <TextView
                            android:id="@+id/textView8"
                            android:layout_width="fill_parent"
                            android:layout_height="wrap_content"
                            android:layout_weight="1"
                            android:text="TextView" />
                    </LinearLayout>

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:layout_weight="1"
                        android:orientation="vertical">

                        <TextView
                            android:id="@+id/textView11"
                            android:layout_width="fill_parent"
                            android:layout_height="wrap_content"
                            android:ellipsize="end"
                            android:maxLines="1"
                            android:text="123456789123456789123456789123456789123456789123456789123456789" />
                    </LinearLayout>

                </LinearLayout>
            </HorizontalScrollView>

            <TextView
                android:id="@+id/textView12"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="TextView" />

        </LinearLayout>
    </ScrollView>
</android.support.constraint.ConstraintLayout>
</code>```

答:
The answer is... it depends.  For simplicity, you can use a GridLayout, which if you have all your data within the view, this would work well.
However if you want the data to load from a database, or if there is an indeterminate amount of columns, then a gridview is your best bet inside a horizontal scrollview.  You can just set the number of rows to 1, and the number of columns programmatically.

Example of that:

```<code>GridView gridView = (GridView) findViewById(R.id.gridview);
gridView.setNumColumns(numOfColumns);
</code>```

Gridviews are more complicated because you will have to use an adapter, which you can learn about here:

https://developer.android.com/guide/topics/ui/layout/gridview.html

However, if you are looking for static simplicity, here is what you could do:

```<code> <?xml version="1.0" encoding="utf-8"?>
    <android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <HorizontalScrollView
        android:layout_width="wrap_content"
        android:layout_height="match_parent">

        <GridLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:rowCount="1"
            android:columnCount="7">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="15dp"
                android:text="Lots of text on this one" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="15dp"
                android:text="Some text on this one" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="15dp"
                android:text="Textview3" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="15dp"
                android:text="Textview4" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="15dp"
                android:text="Textview5" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="15dp"
                android:text="Textview6" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="15dp"
                android:text="Textview7" />

        </GridLayout>
    </HorizontalScrollView>

</android.support.constraint.ConstraintLayout>
</code>```

Body:
So i have been working on my android project and the layout has gotten me and I cannot figure out what is the best to do something like this.
Currently my XML looks like this.
What i am trying to do is have 7 columns with one row that is filled with textviews. I was looking at Grid views but it seems like the entire point of the grid is to scroll with more than one row. How do I achieve this layout?

 <android.support.constraint.ConstraintLayout
    android:id="@+id/ConstraintLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/foodmenuexample"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="TextView" />

            <HorizontalScrollView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1">

                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:orientation="horizontal">

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:layout_weight="1"
                        android:orientation="vertical">

                        <TextView
                            android:id="@+id/textView9"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:text="TextView" />

                        <TextView
                            android:id="@+id/textView10"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:text="TextView" />
                    </LinearLayout>

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:layout_weight="1"
                        android:orientation="vertical">

                        <TextView
                            android:id="@+id/textView8"
                            android:layout_width="fill_parent"
                            android:layout_height="wrap_content"
                            android:layout_weight="1"
                            android:text="TextView" />
                    </LinearLayout>

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:layout_weight="1"
                        android:orientation="vertical">

                        <TextView
                            android:id="@+id/textView11"
                            android:layout_width="fill_parent"
                            android:layout_height="wrap_content"
                            android:ellipsize="end"
                            android:maxLines="1"
                            android:text="123456789123456789123456789123456789123456789123456789123456789" />
                    </LinearLayout>

                </LinearLayout>
            </HorizontalScrollView>

            <TextView
                android:id="@+id/textView12"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="TextView" />

        </LinearLayout>
    </ScrollView>
</android.support.constraint.ConstraintLayout>

Body:
The answer is... it depends.  For simplicity, you can use a GridLayout, which if you have all your data within the view, this would work well.
However if you want the data to load from a database, or if there is an indeterminate amount of columns, then a gridview is your best bet inside a horizontal scrollview.  You can just set the number of rows to 1, and the number of columns programmatically.

Example of that:

GridView gridView = (GridView) findViewById(R.id.gridview);
gridView.setNumColumns(numOfColumns);

Gridviews are more complicated because you will have to use an adapter, which you can learn about here:

https://developer.android.com/guide/topics/ui/layout/gridview.html

However, if you are looking for static simplicity, here is what you could do:

 <?xml version="1.0" encoding="utf-8"?>
    <android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <HorizontalScrollView
        android:layout_width="wrap_content"
        android:layout_height="match_parent">

        <GridLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:rowCount="1"
            android:columnCount="7">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="15dp"
                android:text="Lots of text on this one" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="15dp"
                android:text="Some text on this one" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="15dp"
                android:text="Textview3" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="15dp"
                android:text="Textview4" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="15dp"
                android:text="Textview5" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="15dp"
                android:text="Textview6" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="15dp"
                android:text="Textview7" />

        </GridLayout>
    </HorizontalScrollView>

</android.support.constraint.ConstraintLayout>


问:
JavaScript Calculation?

function Submit() {
var city=0;
    if (document.getElementById("louis").checked){
        city=40;
    }
    else if (document.getElementById("milwaukee").checked){
    city=20;
    }
    else if (document.getElementById("detroit").cheked){
    city=35;
    }

var hotel=0;
    if (document.getElementById("economy").checked){
        hotel=50;
    }
    else if (document.getElementById("standard").checked){
    hotel=70;
    }
    else if (document.getElementById("upscale").cheked){
    hotel=120;
    }

var numtravelers = parseInt(document.getElementById("travelers").value);

var daystravel = parseInt(document.getElementById("day").value);
var mealchoice=0;
    if (document.getElementById("none").checked){
        mealchoice=0;
    }
    else if (document.getElementById("snack").checked){
    mealchoice=5;
    }
    else if (document.getElementById("fullmeal").cheked){
    mealchoice=10;
    }

var extra=0;
    if (document.getElementById("Wifi").checked){
        extra=10;
    }
    else if (document.getElementById("recline").checked){
    extra=20;
    }

var cost=0;

cost=(city*numtravelers)+(hotel*daystravel)+(numtravelers*mealchoice)+(numtravelers*extra);
document.getElementById("OutputResult").innerHTML="your total cost is $" + cost.toString();

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body
{background-color: #000080;
color: #C0C0C0;}
 a {
   color: #00ffff;
   border-style: solid;
   border-color: #00ff00;
 }

 form {color: #00ffff;

 }

 h1 {font-style: italic;
   text-align: center;
   color: #FFD700;
   font-family: Helvetica;
   border-style: solid;
   border-style: solid;
   border-color: gold;
 }

 footer {
font-style: italic;
font-family: cursive;
text-align: center;
color: #FFFFFF;

 }

#contact {
  text-align: center;

}</code>```

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Make a Reservation</title>

<link rel="stylesheet" type="text/css" href="final_project_css.css">

            Make a Reservation
            Contact Us
            Join Our Mailing List
            Home

 Mad Men Bus Company

      <form name="reservation">

First Name: <input type="text">

Last Name: <input type="text">

Arrival City:

            St. Louis($40)<input type="radio" name="Arrival" id="louis" value="40"/>

            Milwaukee($20)<input type="radio" name="Arrival" id="milwaukee" value="20"/>

            Detroit($35)<input type="radio" name="Arrival" id="detroit" value="35"/>

Hotel Choice:

            Economy($50/day)<input type="radio" name="Hotel" id="economy" value="50"/>

            Standard($70/day)<input type="radio" name="Hotel" id="standard" value="70"/>

            Upscale($120/day)<input type="radio" name="Hotel"id="upscale" value="120"/>

Number of Travelers

<select id="travelers">
          <option value="1">1</option>
          <option value="2">2</option>
          <option value="3">3</option>
          <option value="4">4</option>
          <option value="5">5</option>
          <option value="6">6</option>
</select>

Number of Days

    <select id="day">
          <option value="2">2</option>
          <option value="3">3</option>
          <option value="4">4</option>
          <option value="5">5</option>
          <option value="6">6</option>
          <option value="7">7</option>
    </select>

Extras

            <input type="checkbox" name="extra" id="Wifi" value="10">Wifi

            <input type="checkbox" name="extra" id="recline" value="20">Fully-reclining seat

Meal Choice:

            None<input type="radio" name="Meal" id="none"/>

            Snack($5)<input type="radio" name="Meal" id="snack" value="5"/>

            Full Meal($10)<input type="radio" name="Meal" id="fullmeal" value="10"/>

Special Requests:

        <input type="text" name="SpecialRequests"/>

<input type="button" value="Book My Trip" onclick="Submit()">

Total

</form>

100 Manly Avenue New York, New York 10016, 555-555-5555, info@madmenbusline.com

```

When the user chooses upscale hotel choice and or detroit each of those options returns a value of 0 when I click to calculate total cost. I have the right value assigned to them I'm confused why it is not adding the price that I associated with each of those two variables. I do not think my else if statements are wrong... Can someone provide me a hint as to why it may not be working?

答:
When the user chooses upscale hotel choice and or detroit

You have spelled checked incorrectly in both of those places. In this situation, cheked will return undefined which is falsy. Therefore you will get a 0 instead of your expected number

All you need to is fix

```<code>else if (document.getElementById("detroit").cheked){
</code>```

and

```<code>else if (document.getElementById("upscale").cheked){
</code>```

Title: JavaScript Calculation?

Body:
function Submit() {
var city=0;
    if (document.getElementById("louis").checked){
        city=40;
    }
    else if (document.getElementById("milwaukee").checked){
    city=20;
    }
    else if (document.getElementById("detroit").cheked){
    city=35;
    }

var hotel=0;
    if (document.getElementById("economy").checked){
        hotel=50;
    }
    else if (document.getElementById("standard").checked){
    hotel=70;
    }
    else if (document.getElementById("upscale").cheked){
    hotel=120;
    }

var numtravelers = parseInt(document.getElementById("travelers").value);

var daystravel = parseInt(document.getElementById("day").value);
var mealchoice=0;
    if (document.getElementById("none").checked){
        mealchoice=0;
    }
    else if (document.getElementById("snack").checked){
    mealchoice=5;
    }
    else if (document.getElementById("fullmeal").cheked){
    mealchoice=10;
    }

var extra=0;
    if (document.getElementById("Wifi").checked){
        extra=10;
    }
    else if (document.getElementById("recline").checked){
    extra=20;
    }

var cost=0;

cost=(city*numtravelers)+(hotel*daystravel)+(numtravelers*mealchoice)+(numtravelers*extra);
document.getElementById("OutputResult").innerHTML="your total cost is $" + cost.toString();

}

body
{background-color: #000080;
color: #C0C0C0;}
 a {
   color: #00ffff;
   border-style: solid;
   border-color: #00ff00;
 }

 form {color: #00ffff;

 }

 h1 {font-style: italic;
   text-align: center;
   color: #FFD700;
   font-family: Helvetica;
   border-style: solid;
   border-style: solid;
   border-color: gold;
 }

 footer {
font-style: italic;
font-family: cursive;
text-align: center;
color: #FFFFFF;

 }

#contact {
  text-align: center;

}

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Make a Reservation</title>

<link rel="stylesheet" type="text/css" href="final_project_css.css">

            Make a Reservation
            Contact Us
            Join Our Mailing List
            Home

 Mad Men Bus Company

      <form name="reservation">

First Name: <input type="text">

Last Name: <input type="text">

Arrival City:

            St. Louis($40)<input type="radio" name="Arrival" id="louis" value="40"/>

            Milwaukee($20)<input type="radio" name="Arrival" id="milwaukee" value="20"/>

            Detroit($35)<input type="radio" name="Arrival" id="detroit" value="35"/>

Hotel Choice:

            Economy($50/day)<input type="radio" name="Hotel" id="economy" value="50"/>

            Standard($70/day)<input type="radio" name="Hotel" id="standard" value="70"/>

            Upscale($120/day)<input type="radio" name="Hotel"id="upscale" value="120"/>

Number of Travelers

<select id="travelers">
          <option value="1">1</option>
          <option value="2">2</option>
          <option value="3">3</option>
          <option value="4">4</option>
          <option value="5">5</option>
          <option value="6">6</option>
</select>

Number of Days

    <select id="day">
          <option value="2">2</option>
          <option value="3">3</option>
          <option value="4">4</option>
          <option value="5">5</option>
          <option value="6">6</option>
          <option value="7">7</option>
    </select>

Extras

            <input type="checkbox" name="extra" id="Wifi" value="10">Wifi

            <input type="checkbox" name="extra" id="recline" value="20">Fully-reclining seat

Meal Choice:

            None<input type="radio" name="Meal" id="none"/>

            Snack($5)<input type="radio" name="Meal" id="snack" value="5"/>

            Full Meal($10)<input type="radio" name="Meal" id="fullmeal" value="10"/>

Special Requests:

        <input type="text" name="SpecialRequests"/>

<input type="button" value="Book My Trip" onclick="Submit()">

Total

</form>

100 Manly Avenue New York, New York 10016, 555-555-5555, info@madmenbusline.com

When the user chooses upscale hotel choice and or detroit each of those options returns a value of 0 when I click to calculate total cost. I have the right value assigned to them I'm confused why it is not adding the price that I associated with each of those two variables. I do not think my else if statements are wrong... Can someone provide me a hint as to why it may not be working?

Body:
When the user chooses upscale hotel choice and or detroit

You have spelled checked incorrectly in both of those places. In this situation, cheked will return undefined which is falsy. Therefore you will get a 0 instead of your expected number

All you need to is fix

else if (document.getElementById("detroit").cheked){

and

else if (document.getElementById("upscale").cheked){


问:
Surface plotting using a CSV file
I use a csv file containing all surface data, the storing format is as following:

The data  can be easily plotted by matlab routine surf（）：

Now I need to plot the data using gnuplot. I've tried pm3d script. But the result was not good. Can any one help me with this? Any ideas will be appreciate!

答:
```<code>splot "data.csv" nonuniform matrix u 1:2:3 w pm3d,\
</code>```

"line.csv" u 1:2:3 w l lc 1 lw 3

Everything is as expected when using this snip of code with gp507. But the same code would produce quirk results if running with higher version of gnuplot. So I think it's something with gnuplot, not my script.

ContentLicense: CC BY-SA 4.0

Title: Surface plotting using a CSV file

Body:
splot "data.csv" nonuniform matrix u 1:2:3 w pm3d,\

"line.csv" u 1:2:3 w l lc 1 lw 3

Everything is as expected when using this snip of code with gp507. But the same code would produce quirk results if running with higher version of gnuplot. So I think it's something with gnuplot, not my script.


问:
Flinging with RecyclerView + AppBarLayout
I am using the new CoordinatorLayout with AppBarLayout and CollapsingToolbarLayout. Below AppBarLayout, I have a RecyclerView with a list of content.

I have verified that fling scrolling works on the RecyclerView when I am scrolling up and down the list. However, I would also like the AppBarLayout to smoothly scroll during expansion.

When scrolling up to expand the CollaspingToolbarLayout, scrolling immediately stops once lifting your finger off the screen. If you scroll up in a quick motion, sometimes the CollapsingToolbarLayout re-collapses as well. This behavior with the RecyclerView seems to function much differently than when using a NestedScrollView.

I've tried to set different scroll properties on the recyclerview but I haven't been able to figure this out.

Here is a video showing some of the scrolling issues.
https://youtu.be/xMLKoJOsTAM

Here is an example showing the issue with the RecyclerView (CheeseDetailActivity).
https://github.com/tylerjroach/cheesesquare

Here is the original example that uses a NestedScrollView from Chris Banes.
https://github.com/chrisbanes/cheesesquare

答:
Answer: It's fixed in support library v26

but v26 has some issue in flinging. Sometimes, AppBar bounces back again even if fling is not too hard.

How do I remove the bouncing effect on appbar?

If you encounter the same issue when updating to support v26, here's the summary of this answer.

Solution: Extend AppBar's default Behavior and block the call for
  AppBar.Behavior's onNestedPreScroll() and onNestedScroll() when AppBar
  is touched while NestedScroll hasn't stopped yet.


问:
Get data from a directory in worksheet cell
I have question that my code cant run from the y = Workbooks.Open(source). I want to read the directory from a cell but it does not works. Why?</p>

```<code>Sub Button4_Click()
Application.ScreenUpdating = False

Dim x As Workbook
Dim y As Workbook
Dim source As String

source = Cells(14, 6)
Set x = ActiveWorkbook
y = Workbooks.Open(source)

y.Sheets("Sheet1").Range("A:Z").Copy
Destination:=x.Sheets("Sheet3").Range("A:Z")
y.Close savechanges = False

End Sub
</code>```

答:
You are missing the all-important Set keyword, which is required to set references to objects.  So

```<code>y = Workbooks.Open(source)
</code>```

should be

```<code>Set y = Workbooks.Open(source)
</code>```

You also have a few other issues with your code, which should probably look like:

```<code>Sub Button4_Click()
    Application.ScreenUpdating = False

    Dim x As Workbook
    Dim y As Workbook
    Dim source As String

    'Note - this next line is using whatever worksheet is active in whichever
    ' workbook is active.  This is potentially dangerous.
    source = Cells(14, 6)
    Set x = ActiveWorkbook
    Set y = Workbooks.Open(source)
    'You were missing a line continuation character on this statement
    y.Sheets("Sheet1").Range("A:Z").Copy _
           Destination:=x.Sheets("Sheet3").Range("A:Z")
    'You were missing a colon in the named parameter of this statement
    y.Close savechanges:= False

    'You should reset ScreenUpdating
    Application.ScreenUpdating = True
End Sub
</code>```

Is the : in savechanges:=False important?  Yes.

Your current code y.Close savechanges = False is firstly comparing the value of a variable called savechanges to the constant False.  As you have not declared that variable, nor assigned a value to it, savechanges will be assumed to be a numeric zero. Thus you are performing the test 0 = False. Because VBA treats zero as False and -1 as True, savechanges = False will return True.  So that means you are doing the equivalent of y.Close True - which is almost certainly the exact opposite of what you intended.

With the : included, the syntax is treating SaveChanges:=False to be setting the Close method's named parameter SaveChanges to a value of False.

Body:
I have question that my code cant run from the y = Workbooks.Open(source). I want to read the directory from a cell but it does not works. Why?

Sub Button4_Click()
Application.ScreenUpdating = False

Dim x As Workbook
Dim y As Workbook
Dim source As String

source = Cells(14, 6)
Set x = ActiveWorkbook
y = Workbooks.Open(source)

y.Sheets("Sheet1").Range("A:Z").Copy
Destination:=x.Sheets("Sheet3").Range("A:Z")
y.Close savechanges = False

End Sub

Body:
You are missing the all-important Set keyword, which is required to set references to objects.  So

y = Workbooks.Open(source)

should be

Set y = Workbooks.Open(source)

You also have a few other issues with your code, which should probably look like:

Sub Button4_Click()
    Application.ScreenUpdating = False

    Dim x As Workbook
    Dim y As Workbook
    Dim source As String

    'Note - this next line is using whatever worksheet is active in whichever
    ' workbook is active.  This is potentially dangerous.
    source = Cells(14, 6)
    Set x = ActiveWorkbook
    Set y = Workbooks.Open(source)
    'You were missing a line continuation character on this statement
    y.Sheets("Sheet1").Range("A:Z").Copy _
           Destination:=x.Sheets("Sheet3").Range("A:Z")
    'You were missing a colon in the named parameter of this statement
    y.Close savechanges:= False

    'You should reset ScreenUpdating
    Application.ScreenUpdating = True
End Sub

Is the : in savechanges:=False important?  Yes.

Your current code y.Close savechanges = False is firstly comparing the value of a variable called savechanges to the constant False.  As you have not declared that variable, nor assigned a value to it, savechanges will be assumed to be a numeric zero. Thus you are performing the test 0 = False. Because VBA treats zero as False and -1 as True, savechanges = False will return True.  So that means you are doing the equivalent of y.Close True - which is almost certainly the exact opposite of what you intended.

With the : included, the syntax is treating SaveChanges:=False to be setting the Close method's named parameter SaveChanges to a value of False.


问:
Is there a good and easy way to visualize high dimensional data?
Can someone please tell me if there is a good (easy) way to visualize high dimensional data? My data is currently 21 dimensions but I would like to see how whether it is dense or sparse. Are there techniques to achieve this?</p>

答:
Try using http://hypertools.readthedocs.io/en/latest/.

HyperTools is a library for visualizing and manipulating high-dimensional data in Python.


问:
How to restart an Azure appservice from Azure Powershell
How can you restart an AppService from Azure's Powershell running in a Runbook in an Automation Account in an ARM subscription in Azure?

I thought the approach would be:

```<code>Restart-AzureWebsite -Name "your-appservice-name"
</code>```

but that gets:

```<code>Restart-AzureWebsite : No default subscription has been designated.
Use select-AzureSubscription -Default #<subscriptionName> to set the default subscription.
</code>```

There is no Restart-AzureRmWebApp available in Azure PowerShell.

All combinations of the following lead to just a bunch of other error messages:

```<code>$Cred = Get-AutomationPSCredential -Name 'your-credentials-name'
Add-AzureAccount -Credential $Cred
Add-AzureRMAccount -Credential $Cred
Get-AzureSubscription –SubscriptionName 'your-subscription-name' | Select-AzureSubscription -Default
Restart-AzureWebsite -Name "your-appservice-name"
</code>```

答:
This Powershell script works inside an Azure Automation Runbook:

```<code>Invoke-AzureRmResourceAction -ResourceGroupName "<your-resource-group-name>" -ResourceName "<your-resource-name>" -ResourceType 'Microsoft.Web/sites' -Action 'Restart' -Force
</code>```

Edit

However the next script is probably better; it relies on @Tom Sun's answer above, i.e.

Upgrade the modules - go to Automation Accounts / Modules / Update Azure Modules.

Import the AzureRm.Websites module - go to Automation Accounts / Modules / Browse Gallery.

Create  under Automation Accounts / Credentials.

```<code>$Cred = Get-AutomationPSCredential -Name '<your-credentials>'
Add-AzureRMAccount -Credential $Cred

Get-AzureRmSubscription –SubscriptionName '<your-subscription-name>' | Select-AzureRmSubscription

Restart-AzureRmWebApp -ResourceGroupName "office" -Name "<your-appservice-name>"
</code>```

Body:
How can you restart an AppService from Azure's Powershell running in a Runbook in an Automation Account in an ARM subscription in Azure?

I thought the approach would be:

Restart-AzureWebsite -Name "your-appservice-name"

but that gets:

Restart-AzureWebsite : No default subscription has been designated.
Use select-AzureSubscription -Default #<subscriptionName> to set the default subscription.

There is no Restart-AzureRmWebApp available in Azure PowerShell.

All combinations of the following lead to just a bunch of other error messages:

$Cred = Get-AutomationPSCredential -Name 'your-credentials-name'
Add-AzureAccount -Credential $Cred
Add-AzureRMAccount -Credential $Cred
Get-AzureSubscription –SubscriptionName 'your-subscription-name' | Select-AzureSubscription -Default
Restart-AzureWebsite -Name "your-appservice-name"

Body:
This Powershell script works inside an Azure Automation Runbook:

Invoke-AzureRmResourceAction -ResourceGroupName "<your-resource-group-name>" -ResourceName "<your-resource-name>" -ResourceType 'Microsoft.Web/sites' -Action 'Restart' -Force

Edit

However the next script is probably better; it relies on @Tom Sun's answer above, i.e.

Upgrade the modules - go to Automation Accounts / Modules / Update Azure Modules.

Import the AzureRm.Websites module - go to Automation Accounts / Modules / Browse Gallery.

Create  under Automation Accounts / Credentials.

$Cred = Get-AutomationPSCredential -Name '<your-credentials>'
Add-AzureRMAccount -Credential $Cred

Get-AzureRmSubscription –SubscriptionName '<your-subscription-name>' | Select-AzureRmSubscription

Restart-AzureRmWebApp -ResourceGroupName "office" -Name "<your-appservice-name>"


问:
Sails.JS - Created user wont return user object
I have a function in my Sails 1.0 application that adds a new user to the MongoDB and then at the end should return the User object as JSON...

The User does get added to the collection but it throws an error when trying to get the _id of the new User object. When I attempt to console.log() the createdUser it comes back as Undefined. Trying to figure out how the user can get created in Mongo but not be returned as an object in the same function?

In short the Register() function does the following:

Validates some inputs

Checks for valid email address

Encrypts the password

Finds Gravatar URL if applicable

Inserts User into collection

Set user._id in req.session (ERROR IS OCCURRING HERE)

Return User object as JSON

Error:

```<code>info: ·• Auto-migrating...  (alter)
info:    Hold tight, this could take a moment.
info:  ✓ Auto-migration complete.

warn: Ignored attempt to bind route (/resend-username) to unknown action :: UserController.resendUsername
info:
info:                .-..-.
info:
info:    Sails              <|    .-..-.
info:    v1.0.0-37           |\
info:                       /|.\
info:                      / || \
info:                    ,'  |'  \
info:                 .-'.-==|/_--'
info:                 `--'-------'
info:    __---___--___---___--___---___--___
info:  ____---___--___---___--___---___--___-__
info:
info: Server lifted in `D:\Development\Sails\goknack-sails-1.0`
info: To shut down Sails, press <CTRL> + C at any time.

debug: -------------------------------------------------------
debug: :: Tue Sep 05 2017 18:08:33 GMT-0500 (Central Daylight Time)

debug: Environment : development
debug: Port        : 1337
debug: -------------------------------------------------------
undefined
D:\Development\Sails\goknack-sails-1.0\node_modules\mongodb\lib\utils.js:123
    process.nextTick(function() { throw err; });
                                  ^

TypeError: Cannot read property '_id' of undefined
    at D:\Development\Sails\goknack-sails-1.0\api\controllers\UserController.js:259:47
    at D:\Development\Sails\goknack-sails-1.0\node_modules\parley\lib\private\Deferred.js:232:16
    at _afterTalkingToAdapter (D:\Development\Sails\goknack-sails-1.0\node_modules\waterline\lib\waterline\methods\create.js:282:22)
    at D:\Development\Sails\goknack-sails-1.0\node_modules\sails-mongo\lib\private\do-with-connection.js:223:16
    at D:\Development\Sails\goknack-sails-1.0\node_modules\sails-mongo\lib\private\do-with-connection.js:123:18
    at Object.success (D:\Development\Sails\goknack-sails-1.0\node_modules\sails-mongo\lib\private\build-std-adapter-method.js:61:47)
    at afterMaybeArtificiallyWaiting (D:\Development\Sails\goknack-sails-1.0\node_modules\sails-mongo\node_modules\machine\lib\private\intercept-exit-callbacks.js:406:21)
    at maybeArtificiallyWait (D:\Development\Sails\goknack-sails-1.0\node_modules\sails-mongo\node_modules\machine\lib\private\intercept-exit-callbacks.js:220:20)
    at afterPotentiallyCaching (D:\Development\Sails\goknack-sails-1.0\node_modules\sails-mongo\node_modules\machine\lib\private\intercept-exit-callbacks.js:240:11)
    at _cacheIfAppropriate (D:\Development\Sails\goknack-sails-1.0\node_modules\sails-mongo\node_modules\machine\lib\private\intercept-exit-callbacks.js:98:18)
    at Function._interceptExit [as success] (D:\Development\Sails\goknack-sails-1.0\node_modules\sails-mongo\node_modules\machine\lib\private\intercept-exit-callbacks.js:111:9)
    at D:\Development\Sails\goknack-sails-1.0\node_modules\sails-mongo\lib\private\machines\create-record.js:99:22
    at D:\Development\Sails\goknack-sails-1.0\node_modules\mongodb\lib\collection.js:437:18
    at handleCallback (D:\Development\Sails\goknack-sails-1.0\node_modules\mongodb\lib\utils.js:120:56)
    at D:\Development\Sails\goknack-sails-1.0\node_modules\mongodb\lib\collection.js:743:5
    at D:\Development\Sails\goknack-sails-1.0\node_modules\mongodb-core\lib\connection\pool.js:461:18
                              ^
</code>```

I have tried switching id to _id since it is Mongo but no luck, when I try to console.log createdUser it is Undefined.

The record is being created in the database... Any help on where I might be screwing up would be appreciated.

The full Register function I am using:

```<code>  register: function (req, res) {

    if (_.isUndefined(req.param('first'))) {
      return res.badRequest('A first name is required!');
    }

    if (_.isUndefined(req.param('last'))) {
      return res.badRequest('A last name is required!');
    }

    if (_.isUndefined(req.param('phone'))) {
      return res.badRequest('A phone number is required!');
    }

    if (_.isUndefined(req.param('email'))) {
      return res.badRequest('An email address is required!');
    }

    if (req.param('email') !== req.param('emailConfirm')) {
      return res.badRequest('Email addresses do not match!');
    }

    if (_.isUndefined(req.param('password'))) {
      return res.badRequest('A password is required!');
    }

    if (req.param('password').length < 6) {
      return res.badRequest('Password must be at least 6 characters!');
    }

    if (req.param('password') !== req.param('confirmPassword')) {
      return res.badRequest('Passwords do not match!');
    }

    if (_.isUndefined(req.param('tos'))) {
      return res.badRequest('You must review and accept the Goknack Terms of Service & Privacy policy.');
    }

    Emailaddresses.validate({
      string: req.param('email'),
    }).exec({
      // An unexpected error occurred.
      error: function (err) {
        return res.serverError(err);
      },
      // The provided string is not an email address.
      invalid: function () {
        return res.badRequest('Doesn\'t look like an email address to me!');
      },
      // OK.
      success: function () {

        Passwords.encryptPassword({
          password: req.param('password'),
        }).exec({

          error: function (err) {
            return res.serverError(err);
          },

          success: function (result) {

            var options = {};

            // gravitar image for user, if present
            try {

              options.gravatarURL = Gravatar.getImageUrl({
                emailAddress: req.param('email')
              }).execSync();

            } catch (err) {
              return res.serverError(err);
            }

            options.email = req.param('email');
            options.username = req.param('username');
            options.encryptedPassword = result;
            options.deleted = false;
            options.deletedDate = '';
            options.admin = false;
            options.banned = false;
            options.paypalEmail = '';

            // validate that email address has not been used before
            User.find({email: req.param('email')}).exec(function(err, user) {
              if (err) {
                return res.negotiate(err);
              }

              if (user.length > 0) {
                return res.badRequest('Invalid email, this email address is already in use.');
              } else {
                // create new user
                User.create(options).exec(function (err, createdUser) {

                  if (err) {
                    console.log('the error is: ', err.invalidAttributes);
                    return res.negotiate(err);
                  }

                  // Log the user in
                  console.log(createdUser);
                  req.session.userId = createdUser._id;

                  // NOTHING IS BEING RETURNED IN createdUser

                  return res.json(createdUser);
                });

              }
            });

          }
        });
      }
    });
  },
</code>```

答:
As of sails 1.0 you need to specify that you want that model to be returned from the create call. To do that chain you create with a fetch call.

```<code>let createdUser = await User.create({ name: "Some name" }).fetch();
</code>```

Also, await is now preferred over callbacks.

More on this here: https://next.sailsjs.com/documentation/reference/waterline-orm/models/create

Body:
I have a function in my Sails 1.0 application that adds a new user to the MongoDB and then at the end should return the User object as JSON...

The User does get added to the collection but it throws an error when trying to get the _id of the new User object. When I attempt to console.log() the createdUser it comes back as Undefined. Trying to figure out how the user can get created in Mongo but not be returned as an object in the same function?

In short the Register() function does the following:

Validates some inputs

Checks for valid email address

Encrypts the password

Finds Gravatar URL if applicable

Inserts User into collection

Set user._id in req.session (ERROR IS OCCURRING HERE)

Return User object as JSON

Error:

info: ·• Auto-migrating...  (alter)
info:    Hold tight, this could take a moment.
info:  ✓ Auto-migration complete.

warn: Ignored attempt to bind route (/resend-username) to unknown action :: UserController.resendUsername
info:
info:                .-..-.
info:
info:    Sails              <|    .-..-.
info:    v1.0.0-37           |\
info:                       /|.\
info:                      / || \
info:                    ,'  |'  \
info:                 .-'.-==|/_--'
info:                 `--'-------'
info:    __---___--___---___--___---___--___
info:  ____---___--___---___--___---___--___-__
info:
info: Server lifted in `D:\Development\Sails\goknack-sails-1.0`
info: To shut down Sails, press <CTRL> + C at any time.

debug: -------------------------------------------------------
debug: :: Tue Sep 05 2017 18:08:33 GMT-0500 (Central Daylight Time)

debug: Environment : development
debug: Port        : 1337
debug: -------------------------------------------------------
undefined
D:\Development\Sails\goknack-sails-1.0\node_modules\mongodb\lib\utils.js:123
    process.nextTick(function() { throw err; });
                                  ^

TypeError: Cannot read property '_id' of undefined
    at D:\Development\Sails\goknack-sails-1.0\api\controllers\UserController.js:259:47
    at D:\Development\Sails\goknack-sails-1.0\node_modules\parley\lib\private\Deferred.js:232:16
    at _afterTalkingToAdapter (D:\Development\Sails\goknack-sails-1.0\node_modules\waterline\lib\waterline\methods\create.js:282:22)
    at D:\Development\Sails\goknack-sails-1.0\node_modules\sails-mongo\lib\private\do-with-connection.js:223:16
    at D:\Development\Sails\goknack-sails-1.0\node_modules\sails-mongo\lib\private\do-with-connection.js:123:18
    at Object.success (D:\Development\Sails\goknack-sails-1.0\node_modules\sails-mongo\lib\private\build-std-adapter-method.js:61:47)
    at afterMaybeArtificiallyWaiting (D:\Development\Sails\goknack-sails-1.0\node_modules\sails-mongo\node_modules\machine\lib\private\intercept-exit-callbacks.js:406:21)
    at maybeArtificiallyWait (D:\Development\Sails\goknack-sails-1.0\node_modules\sails-mongo\node_modules\machine\lib\private\intercept-exit-callbacks.js:220:20)
    at afterPotentiallyCaching (D:\Development\Sails\goknack-sails-1.0\node_modules\sails-mongo\node_modules\machine\lib\private\intercept-exit-callbacks.js:240:11)
    at _cacheIfAppropriate (D:\Development\Sails\goknack-sails-1.0\node_modules\sails-mongo\node_modules\machine\lib\private\intercept-exit-callbacks.js:98:18)
    at Function._interceptExit [as success] (D:\Development\Sails\goknack-sails-1.0\node_modules\sails-mongo\node_modules\machine\lib\private\intercept-exit-callbacks.js:111:9)
    at D:\Development\Sails\goknack-sails-1.0\node_modules\sails-mongo\lib\private\machines\create-record.js:99:22
    at D:\Development\Sails\goknack-sails-1.0\node_modules\mongodb\lib\collection.js:437:18
    at handleCallback (D:\Development\Sails\goknack-sails-1.0\node_modules\mongodb\lib\utils.js:120:56)
    at D:\Development\Sails\goknack-sails-1.0\node_modules\mongodb\lib\collection.js:743:5
    at D:\Development\Sails\goknack-sails-1.0\node_modules\mongodb-core\lib\connection\pool.js:461:18
                              ^

I have tried switching id to _id since it is Mongo but no luck, when I try to console.log createdUser it is Undefined.

The record is being created in the database... Any help on where I might be screwing up would be appreciated.

The full Register function I am using:

  register: function (req, res) {

    if (_.isUndefined(req.param('first'))) {
      return res.badRequest('A first name is required!');
    }

    if (_.isUndefined(req.param('last'))) {
      return res.badRequest('A last name is required!');
    }

    if (_.isUndefined(req.param('phone'))) {
      return res.badRequest('A phone number is required!');
    }

    if (_.isUndefined(req.param('email'))) {
      return res.badRequest('An email address is required!');
    }

    if (req.param('email') !== req.param('emailConfirm')) {
      return res.badRequest('Email addresses do not match!');
    }

    if (_.isUndefined(req.param('password'))) {
      return res.badRequest('A password is required!');
    }

    if (req.param('password').length < 6) {
      return res.badRequest('Password must be at least 6 characters!');
    }

    if (req.param('password') !== req.param('confirmPassword')) {
      return res.badRequest('Passwords do not match!');
    }

    if (_.isUndefined(req.param('tos'))) {
      return res.badRequest('You must review and accept the Goknack Terms of Service & Privacy policy.');
    }

    Emailaddresses.validate({
      string: req.param('email'),
    }).exec({
      // An unexpected error occurred.
      error: function (err) {
        return res.serverError(err);
      },
      // The provided string is not an email address.
      invalid: function () {
        return res.badRequest('Doesn\'t look like an email address to me!');
      },
      // OK.
      success: function () {

        Passwords.encryptPassword({
          password: req.param('password'),
        }).exec({

          error: function (err) {
            return res.serverError(err);
          },

          success: function (result) {

            var options = {};

            // gravitar image for user, if present
            try {

              options.gravatarURL = Gravatar.getImageUrl({
                emailAddress: req.param('email')
              }).execSync();

            } catch (err) {
              return res.serverError(err);
            }

            options.email = req.param('email');
            options.username = req.param('username');
            options.encryptedPassword = result;
            options.deleted = false;
            options.deletedDate = '';
            options.admin = false;
            options.banned = false;
            options.paypalEmail = '';

            // validate that email address has not been used before
            User.find({email: req.param('email')}).exec(function(err, user) {
              if (err) {
                return res.negotiate(err);
              }

              if (user.length > 0) {
                return res.badRequest('Invalid email, this email address is already in use.');
              } else {
                // create new user
                User.create(options).exec(function (err, createdUser) {

                  if (err) {
                    console.log('the error is: ', err.invalidAttributes);
                    return res.negotiate(err);
                  }

                  // Log the user in
                  console.log(createdUser);
                  req.session.userId = createdUser._id;

                  // NOTHING IS BEING RETURNED IN createdUser

                  return res.json(createdUser);
                });

              }
            });

          }
        });
      }
    });
  },

Body:
As of sails 1.0 you need to specify that you want that model to be returned from the create call. To do that chain you create with a fetch call.

let createdUser = await User.create({ name: "Some name" }).fetch();

Also, await is now preferred over callbacks.

More on this here: https://next.sailsjs.com/documentation/reference/waterline-orm/models/create


问:
Case-insensitive string matching in Rust
Is there a simple way to use str::matches case-insensitively?

答:
You can always convert both strings to the same casing. This will work for some cases:

let needle = "μτς";
let haystack = "ΜΤΣ";

let needle = needle.to_lowercase();
let haystack = haystack.to_lowercase();

for i in haystack.matches(&needle) {
    println!("{:?}", i);
}
```
<p>See also <code>str::to_ascii_lowercase</code> for ASCII-only variants.</p>
<p>In other cases, the regex crate might do enough case-folding (potentially Unicode) for you:</p>
<pre class="lang-rust prettyprint-override"><code>use regex::RegexBuilder; // 1.4.3

fn main() {
    let needle = "μτς";
    let haystack = "ΜΤΣ";

    let needle = RegexBuilder::new(needle)
        .case_insensitive(true)
        .build()
        .expect("Invalid Regex");

    for i in needle.find_iter(haystack) {
        println!("{:?}", i);
    }
}
</code>```

However, remember that ultimately Rust's strings are UTF-8. Yes, you need to deal with all of UTF-8. This means that picking upper- or lower-case might change your results. Likewise, the only correct way to change text casing requires that you know the language of the text; it's not an inherent property of the bytes. Yes, you can have strings which contain emoji and other exciting things beyond the Basic Multilingual Plane.

See also:

How can I case fold a string in Rust?

Why is capitalizing the first letter of a string so convoluted in Rust?

Body:
You can always convert both strings to the same casing. This will work for some cases:

let needle = "μτς";
let haystack = "ΜΤΣ";

let needle = needle.to_lowercase();
let haystack = haystack.to_lowercase();

for i in haystack.matches(&needle) {
    println!("{:?}", i);
}

See also str::to_ascii_lowercase for ASCII-only variants.

In other cases, the regex crate might do enough case-folding (potentially Unicode) for you:

use regex::RegexBuilder; // 1.4.3

fn main() {
    let needle = "μτς";
    let haystack = "ΜΤΣ";

    let needle = RegexBuilder::new(needle)
        .case_insensitive(true)
        .build()
        .expect("Invalid Regex");

    for i in needle.find_iter(haystack) {
        println!("{:?}", i);
    }
}

However, remember that ultimately Rust's strings are UTF-8. Yes, you need to deal with all of UTF-8. This means that picking upper- or lower-case might change your results. Likewise, the only correct way to change text casing requires that you know the language of the text; it's not an inherent property of the bytes. Yes, you can have strings which contain emoji and other exciting things beyond the Basic Multilingual Plane.

See also:

How can I case fold a string in Rust?

Why is capitalizing the first letter of a string so convoluted in Rust?


问:
How to prove admissibility of a heuristic function
I know that a heuristic function which never overestimates the real distance to the goal is called admissible. I found a heuristic function does that in practice but i don't know how to give a formal proof. How can i prove that a heuristic function is admissible? For example: Manhattan Distance Heuristic.</p>

答:
If you can formally define the real distance from the goal, then you can simply eliminate a constraint in order to develop an admissible heuristic.

For example:
The Manhattan distance from point (x1, y1) to point (x2,y2) is equal to |x1-x2|+|y1-y2|.
You can simply eliminate a term to come up with a heuristic. For example h = |x1-x2|.
To prove that this is an admissible heuristic, you show that |x1-x2| is less than or equal to |x1-x2|+|y1-y2|

...for all x1, x2, y1, y2.

Another admissible heuristic would be the straight line distance, and you can prove that that is always less than the Manhattan distance.

In general, relaxing constraints will lead to admissible heuristics.

If you're working with distances, the straight line distance will always be an admissible heuristic because that will never be an overestimate.

Let me know if this answers your question :)


问:
Visual Studio 2017 package tab is missing in project settings
I created a simple library .NET Framework project.

I would like to generate NuGet packages after build as described here.

However, the Package tab is missing, here is a screenshot:

答:
Visual Studio 2017 package tab is missing in project settings

That because your project is library .NET Framework, which still using packages.config to manage NuGet packages. And Package tab is only supported by the new nuget package management form: PackageReference.

.NET Standard class library or .NET Core projects come with PackageReference enabled by default. So you can create .NET Standard class library or .NET Core project, then you will see Package tab on the properties window.

If you want to use the Package tab for library .NET Framework project, you can convert your project from the old .csproj to new .csproj, (Right click your project->Unload project->Edit .csproj. Replace the contents of your csproj with the following:

```<code><Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net46</TargetFramework>
  </PropertyGroup>
</Project>
</code>```

See Old csproj to new csproj: Visual Studio 2017 upgrade guide for more info about convert old .csproj to new .csproj.

Note: Need to delete the AssemblyInfo.cs file in the Properties.

After convert to new .csproj, you will get the Package tab for library .NET Framework project:

Hope this helps.

Body:
Visual Studio 2017 package tab is missing in project settings

That because your project is library .NET Framework, which still using packages.config to manage NuGet packages. And Package tab is only supported by the new nuget package management form: PackageReference.

.NET Standard class library or .NET Core projects come with PackageReference enabled by default. So you can create .NET Standard class library or .NET Core project, then you will see Package tab on the properties window.

If you want to use the Package tab for library .NET Framework project, you can convert your project from the old .csproj to new .csproj, (Right click your project->Unload project->Edit .csproj. Replace the contents of your csproj with the following:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net46</TargetFramework>
  </PropertyGroup>
</Project>

See Old csproj to new csproj: Visual Studio 2017 upgrade guide for more info about convert old .csproj to new .csproj.

Note: Need to delete the AssemblyInfo.cs file in the Properties.

After convert to new .csproj, you will get the Package tab for library .NET Framework project:

Hope this helps.


问:
Json.Net unexpected characters ("\") when serializing my entities
I am using the excellent Json.Net library to serialize my entities generated by entity framework. I use the following code to do so :

```<code>using (MyVoucherEntities context = new MyVoucherEntities())
{
  List<MyObject> list = context.MyObjects.ToList();
  string json = JsonConvert.SerializeObject(list);
}
</code>```

Everything goes well I mean, the objects are correctly serialized except one think : it adds escape characters "\" that makes me having nightmare when deserializing on the client side.

```<code> [
     {
         \"$id\": \"1\",
         \"CreationDate\": \"\\\/Date(1293186324257+0000)\\\/\",
        \"ImageUrl\": \"http:\/\/www.google.com\",
         \"Title\": \"Here is a title\"
     } ]
</code>```

Does anybody know why and how I can get rid of these escape characters slash "\" ?

答:
I suspect it's not actually adding escape characters at all. I suspect you're just looking at the string in a debugger, and that's adding the escaping.

Try dumping it to a file or the console.

Body:
I am using the excellent Json.Net library to serialize my entities generated by entity framework. I use the following code to do so :

using (MyVoucherEntities context = new MyVoucherEntities())
{
  List<MyObject> list = context.MyObjects.ToList();
  string json = JsonConvert.SerializeObject(list);
}

Everything goes well I mean, the objects are correctly serialized except one think : it adds escape characters "\" that makes me having nightmare when deserializing on the client side.

 [
     {
         \"$id\": \"1\",
         \"CreationDate\": \"\\\/Date(1293186324257+0000)\\\/\",
        \"ImageUrl\": \"http:\/\/www.google.com\",
         \"Title\": \"Here is a title\"
     } ]

Does anybody know why and how I can get rid of these escape characters slash "\" ?


问:
How do you order the indexing columns in MySQL if you are using order by in your query?
I am reading an article about how Pinterest shards their MySQL database: https://medium.com/@Pinterest_Engineering/sharding-pinterest-how-we-scaled-our-mysql-fleet-3f341e96ca6f

And here they have an example of a table:

```<code>CREATE TABLE board_has_pins (
  board_id INT,
  pin_id INT,
  sequence INT,
  INDEX(board_id, pin_id, sequence)
) ENGINE=InnoDB;
</code>```

And they are showing how they query from that table:

```<code>SELECT pin_id FROM board_has_pins
WHERE board_id=241294561224164665 ORDER BY sequence
LIMIT 50 OFFSET 150
</code>```

What I don't understand here is the ordering of the index. Would it not make more sense if the index was like this since they are ordering by sequence and filtering by board_id?

```<code>INDEX(board_id, sequence, pin_id)
</code>```

Am I missing something here or have I misunderstood how indexing works?

答:
You are correct. The better index for this query is:

```<code>INDEX(board_id, sequence, pin_id)
</code>```

The columns should be in this order:

Column(s) involved in equality comparisons. If there are multiple columns, their order does not matter.

Column(s) involved the ORDER BY clause, in the same order they appear in the ORDER BY.

Other columns used to fetch values, like pin_id.

Once the equality conditions find the subset of matching rows, they are all tied with respect to their order, because naturally they all have the same value for the column of the quality condition (board_id in this case).

The tie is resolved by the order of the next column in the index. If (and only if) the next column is the one used in the ORDER BY clause, then the rows can be read in index order, with no further work needed to sort them.

I don't know what is the explanation for the Pinterest blog post you linked to. I guess it's a mistake, because the index is not optimal for the query they showed.

Body:
I am reading an article about how Pinterest shards their MySQL database: https://medium.com/@Pinterest_Engineering/sharding-pinterest-how-we-scaled-our-mysql-fleet-3f341e96ca6f

And here they have an example of a table:

CREATE TABLE board_has_pins (
  board_id INT,
  pin_id INT,
  sequence INT,
  INDEX(board_id, pin_id, sequence)
) ENGINE=InnoDB;

And they are showing how they query from that table:

SELECT pin_id FROM board_has_pins
WHERE board_id=241294561224164665 ORDER BY sequence
LIMIT 50 OFFSET 150

What I don't understand here is the ordering of the index. Would it not make more sense if the index was like this since they are ordering by sequence and filtering by board_id?

INDEX(board_id, sequence, pin_id)

Am I missing something here or have I misunderstood how indexing works?

Body:
You are correct. The better index for this query is:

INDEX(board_id, sequence, pin_id)

The columns should be in this order:

Column(s) involved in equality comparisons. If there are multiple columns, their order does not matter.

Column(s) involved the ORDER BY clause, in the same order they appear in the ORDER BY.

Other columns used to fetch values, like pin_id.

Once the equality conditions find the subset of matching rows, they are all tied with respect to their order, because naturally they all have the same value for the column of the quality condition (board_id in this case).

The tie is resolved by the order of the next column in the index. If (and only if) the next column is the one used in the ORDER BY clause, then the rows can be read in index order, with no further work needed to sort them.

I don't know what is the explanation for the Pinterest blog post you linked to. I guess it's a mistake, because the index is not optimal for the query they showed.


问:
how to learn language model?

I'm trying to train a language model with LSTM based on Penn Treebank (PTB) corpus.

I was thinking that I should simply train with every bigram in the corpus so that it could predict the next word given previous words, but then it wouldn't be able to predict next word based on multiple preceding words.

So what exactly is it to train a language model?

In my current implementation, I have batch size=20 and the vocabulary size is 10000, so I have 20 resulting matrices of 10k entries (parameters?) and the loss is calculated by making comparison to 20 ground-truth matrices of 10k entries, where only the index for actual next word is 1 and other entries are zero. Is this a right implementation? I'm getting perplexity of around 2 that hardly changes over iterations, which is definitely not in a right range of what it usually is, say around 100.

答:
So what exactly is it to train a language model?

I think you don't need to train with every bigram in the corpus. Just use a sequence to sequence model, and when you predict the next word given previous words you just choose the one with the highest probability.

so I have 20 resulting matrices of 10k entries (parameters?)

Yes, per step of decoding.

Is this a right implementation? I'm getting perplexity of around 2 that hardly changes over iterations, which is definitely not in a right range of what it usually is, say around 100.

You can first read some open source code as a reference. For instance: word-rnn-tensorflow and char-rnn-tensorflow. The perplexity is at large -log(1/10000) which is around 9 per word(which means the model is not trained at all and selects the words totally randomly, as the model being tuned the complexity will decrease, so 2 is reasonable). I think 100 in your statement may mean the complexity per sentence.

For example, if tf.contrib.seq2seq.sequence_loss is employed to calculate the complexity, the result will be less than 10 if you set both average_across_timesteps and average_across_batch to be True as default, but if you set the average_across_timesteps to be False and the average length of the sequence is about 10, it will be about 100.

Title: how to learn language model?