问:
Java Logger wont log into file
I can't make my logger to work.
Inside my code I have these lines :

```<code>private static final Logger log = Logger.getLogger(ServerThread.class.getName());
log.setUseParentHandlers(false);
FileHandler fh = new FileHandler("ex.txt", true);
SimpleFormatter sf = new SimpleFormatter();
fh.setFormatter(sf);
log.addHandler(fh);
log.setLevel(Level.FINE);
</code>```

And later when I get input from user :

```<code>log.log(Level.FINE,inputString);
</code>```

But all that happens is that fileHandler creates a file ex.txt, but nothing is logged into the file. I am sure that log.log() is being executed.

答:
You can also use this simple approach.</p>

```<code>public static Logger logger;

public static Logger startLogger() {

    DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd-HH-mm-ss");
    Date date = new Date();
    String datefor = dateFormat.format(date);

    logger = Logger.getLogger("MyLog");

    PropertyConfigurator.configure(CLASSPATH + "/" + "log4j.properties");
    Appender appender = null;
    try {

        appender = new FileAppender(new SimpleLayout(), CLASSPATH  + "/log/MyLogFile" + datefor + ".log");
        logger.addAppender(appender);
        appender.setLayout(new SimpleLayout());
    } catch (SecurityException exception) {
        exception.printStackTrace();
    } catch (IOException exception) {
        exception.printStackTrace();
    }
}
</code>```

Title: Java Logger wont log into file

Body:
I can't make my logger to work.
Inside my code I have these lines :

private static final Logger log = Logger.getLogger(ServerThread.class.getName());
log.setUseParentHandlers(false);
FileHandler fh = new FileHandler("ex.txt", true);
SimpleFormatter sf = new SimpleFormatter();
fh.setFormatter(sf);
log.addHandler(fh);
log.setLevel(Level.FINE);

And later when I get input from user :

log.log(Level.FINE,inputString);

But all that happens is that fileHandler creates a file ex.txt, but nothing is logged into the file. I am sure that log.log() is being executed.

Body:
You can also use this simple approach.

public static Logger logger;

public static Logger startLogger() {

    DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd-HH-mm-ss");
    Date date = new Date();
    String datefor = dateFormat.format(date);

    logger = Logger.getLogger("MyLog");

    PropertyConfigurator.configure(CLASSPATH + "/" + "log4j.properties");
    Appender appender = null;
    try {

        appender = new FileAppender(new SimpleLayout(), CLASSPATH  + "/log/MyLogFile" + datefor + ".log");
        logger.addAppender(appender);
        appender.setLayout(new SimpleLayout());
    } catch (SecurityException exception) {
        exception.printStackTrace();
    } catch (IOException exception) {
        exception.printStackTrace();
    }
}


来源: stackexchange

问:
List, Carousel response by Api.ai not working on Actions Simulator
In my app, one Intent returns list for Actions On Google which works fine on 'Test section' of Api.ai but fails to work on Actions Simulator.

Test on Api.ai try: (worked fine)

Test on Actions Simulator: (Fails)

NOTE: Other queries and intents are working fine on Actions Simulator for same app

Do we need to use 'list' with some other message content?
The problem is same for Carousel Card also.
Earlier I got the same problem with basic card but fixed but by joining card with simple response but here that also didn't work.

Like 'basic_card' needs 'simple response' compulsorily, does 'list' also needs to be adjoined with something?

Please help to solve.

答:
Fixed now!

Actually, There is Problem with synchronization between Api.ai and ActionsOnGoogle.

So, to fix this issue we have to disable Actions integration and re-enable it 2-3 times.

And make sure:

Additional triggering intents are chosen properly.*

List or Carousel is having more than two items. (compulsorily)

ContentLicense: CC BY-SA 3.0


问:
C# Unity3D Scale using Accelerometer with Clamp
I'm trying to translate the roll(y) of a phone into the scale of an object but with size limits.

I have had success scaling to infinity +- with the following code:

```<code>void Update () {
   float accelY = Input.acceleration.y;
   transform.localScale += new Vector3(0, accelY, 0);
}
</code>```

The problem I am having is with the max and min limits of the scale.

I attempted to use Clamp in the following way but have ended up just limiting the direction of scale where -y (rolling toward myself) equals 0 therefore no shrinking happens and +y (rolling away from self) scales up endlessly assumed at a max rate of 0.045f.

```<code>transform.localScale += new Vector3(0, Mathf.Clamp(accelY, 0f, 0.045f), 0);
</code>```

In an ideal world I'd like to have a min scale of y = 1 and a max scale y = 100 and as you roll the phone back and forth it would tween between the two sizes.

I can find code snippets for Translate and rotate but nothing for scaling.. Please help.

答:
I do believe you want to scale value from one range(accelerometer) to another 0 - 100. If that's the case then this is not best done with the clamp function. You can do it with the map function:

```<code>float mapValue(float mainValue, float inValueMin, float inValueMax, float outValueMin, float outValueMax)
{
    return (mainValue - inValueMin) * (outValueMax - outValueMin) / (inValueMax - inValueMin) + outValueMin;
}
</code>```

Pass the accelerometer value (Input.acceleration.y) as the main value. The inValueMin value should the minimum accelerometer value you prefer. The inValueMax value should the the maximum accelerometer value you prefer. This is totally up to you to decide.

The outValueMin and outValueMax values are the is range of the output. In your case, that's 0 and 100.

Something like below should get you started:

```<code>//Scale Min and max
public float scaleMin = 0;
public float scaleMax = 100f;

//Accelerometer min/max. Find this with Debug.Log(Input.acceleration.y);
public float accelYMin = -10;
public float accelYMax = 10;

void Update()
{
    float accelY = Input.acceleration.y;
    float scaledVal = mapValue(accelY, accelYMin, accelYMax, scaleMin, scaleMax);
    transform.localScale = new Vector3(0, scaledVal, 0);
}

float mapValue(float mainValue, float inValueMin, float inValueMax, float outValueMin, float outValueMax)
{
    return (mainValue - inValueMin) * (outValueMax - outValueMin) / (inValueMax - inValueMin) + outValueMin;
}
</code>```

Body:
I'm trying to translate the roll(y) of a phone into the scale of an object but with size limits.

I have had success scaling to infinity +- with the following code:

void Update () {
   float accelY = Input.acceleration.y;
   transform.localScale += new Vector3(0, accelY, 0);
}

The problem I am having is with the max and min limits of the scale.

I attempted to use Clamp in the following way but have ended up just limiting the direction of scale where -y (rolling toward myself) equals 0 therefore no shrinking happens and +y (rolling away from self) scales up endlessly assumed at a max rate of 0.045f.

transform.localScale += new Vector3(0, Mathf.Clamp(accelY, 0f, 0.045f), 0);

In an ideal world I'd like to have a min scale of y = 1 and a max scale y = 100 and as you roll the phone back and forth it would tween between the two sizes.

I can find code snippets for Translate and rotate but nothing for scaling.. Please help.

Body:
I do believe you want to scale value from one range(accelerometer) to another 0 - 100. If that's the case then this is not best done with the clamp function. You can do it with the map function:

float mapValue(float mainValue, float inValueMin, float inValueMax, float outValueMin, float outValueMax)
{
    return (mainValue - inValueMin) * (outValueMax - outValueMin) / (inValueMax - inValueMin) + outValueMin;
}

Pass the accelerometer value (Input.acceleration.y) as the main value. The inValueMin value should the minimum accelerometer value you prefer. The inValueMax value should the the maximum accelerometer value you prefer. This is totally up to you to decide.

The outValueMin and outValueMax values are the is range of the output. In your case, that's 0 and 100.

Something like below should get you started:

//Scale Min and max
public float scaleMin = 0;
public float scaleMax = 100f;

//Accelerometer min/max. Find this with Debug.Log(Input.acceleration.y);
public float accelYMin = -10;
public float accelYMax = 10;

void Update()
{
    float accelY = Input.acceleration.y;
    float scaledVal = mapValue(accelY, accelYMin, accelYMax, scaleMin, scaleMax);
    transform.localScale = new Vector3(0, scaledVal, 0);
}

float mapValue(float mainValue, float inValueMin, float inValueMax, float outValueMin, float outValueMax)
{
    return (mainValue - inValueMin) * (outValueMax - outValueMin) / (inValueMax - inValueMin) + outValueMin;
}


问:
PhalconPHP and phpunit
I've been following the docs to set up phpunit with phalcon. I have the example working.

However, I now want to actually put it to use and test my own classes, to do this I understand I need to register the directories in the loader, but instead of repeating the directories that are already defined in the config, I'm wanting to include the config in the php unit test helper class (from a `phalcon project' command). This sounds simple but is anything but.

Do I have to add additional code to access the $config?

Am I right in assuming that the docs are missing a large amount of code regarding testing your own classes, or, should it work straight out the box after following the docs?

答:
I have tried to implement this myself the basic idea is below for an implementation example head to: https://github.com/SavvySoftWorksLLC/phalcon_3_2_devtools_sample_project/tree/pks/setup_phpunit

If you externalize your loader like

```<code><?php

$loader = new \Phalcon\Loader();

/**
 * We're a registering a set of directories taken from the configuration file
 */
$loader->registerDirs(
    [
        $config->application->controllersDir,
        $config->application->modelsDir
    ]
)->register();
</code>```

And then call it in your entrypoint like this:

```<code>include ROOT_PATH . "/../app/config/loader.php";
</code>```

You will be able to reuse the same loader in your test helper provided you initialize a fresh DI container like the docs mention.

To give the big picture I pushed up a out of the box app create by devtools for you to look at.

Loader: https://github.com/SavvySoftWorksLLC/phalcon_3_2_devtools_sample_project/blob/master/app/config/loader.php

EntryPoint:
https://github.com/SavvySoftWorksLLC/phalcon_3_2_devtools_sample_project/tree/master/public

Title: PhalconPHP and phpunit

Body:
I have tried to implement this myself the basic idea is below for an implementation example head to: https://github.com/SavvySoftWorksLLC/phalcon_3_2_devtools_sample_project/tree/pks/setup_phpunit

If you externalize your loader like

<?php

$loader = new \Phalcon\Loader();

/**
 * We're a registering a set of directories taken from the configuration file
 */
$loader->registerDirs(
    [
        $config->application->controllersDir,
        $config->application->modelsDir
    ]
)->register();

And then call it in your entrypoint like this:

include ROOT_PATH . "/../app/config/loader.php";

You will be able to reuse the same loader in your test helper provided you initialize a fresh DI container like the docs mention.

To give the big picture I pushed up a out of the box app create by devtools for you to look at.

Loader: https://github.com/SavvySoftWorksLLC/phalcon_3_2_devtools_sample_project/blob/master/app/config/loader.php

EntryPoint:
https://github.com/SavvySoftWorksLLC/phalcon_3_2_devtools_sample_project/tree/master/public


问:
How to correct (Wicket in) Tomcat at /myapp behinds Apache proxy at / that send incorrect redirect to /myapp/xxx instead of /xxx?
I have deployed my Wicket app at /myapp in Tomcat, and I have put it behind Apache web server using

```<code>ProxyPass / http://localhost:8080/myapp/
ProxyPassReverse / http://localhost:8080/myapp/
</code>```

Now Wicket incorrectly redirect users to /myapp/xxx instead of /xxx.

Is there any way to make Wicket(1.3.5) use / as my root path (instead of /myapp which is servlet deployment context path)?!

Edit: There is a solution described at following link but it doesn't works for 1.3.5 version:
I found it: https://cwiki.apache.org/WICKET/wicket-behind-a-front-end-proxy.html

Edit: The problem is that wicket uses relative path redirects with ServletResponse#sendRedirect and Tomcat convert them to absolutes redirects containing /myapp at beginning. I have tried mod_jk(AJP) but there was no difference!

There should be some way to tell proxy-pass or mod-jk to rewrite redirects before sending them to client!

答: Not tested myself, but have you looked at mod_rewrite? There are some examples describing what you want to do here.</p>

ContentLicense: CC BY-SA 2.5

Body:
I have deployed my Wicket app at /myapp in Tomcat, and I have put it behind Apache web server using

ProxyPass / http://localhost:8080/myapp/
ProxyPassReverse / http://localhost:8080/myapp/

Now Wicket incorrectly redirect users to /myapp/xxx instead of /xxx.

Is there any way to make Wicket(1.3.5) use / as my root path (instead of /myapp which is servlet deployment context path)?!

Edit: There is a solution described at following link but it doesn't works for 1.3.5 version:
I found it: https://cwiki.apache.org/WICKET/wicket-behind-a-front-end-proxy.html

Edit: The problem is that wicket uses relative path redirects with ServletResponse#sendRedirect and Tomcat convert them to absolutes redirects containing /myapp at beginning. I have tried mod_jk(AJP) but there was no difference!

There should be some way to tell proxy-pass or mod-jk to rewrite redirects before sending them to client!


问:
How to undo commit, put into new branch then do a PR?
I have a master branch that is protected with push only by PR.

Say I thoughtlessly on master:

```<code>git add .
git commit -m "bunch of changes"
</code>```

But I push to the branch and am rejected because the branch is protected.
How do I backtrack, preserve my changes, and do a PR?

答:
```<code>git reset HEAD~
git checkout -b "name-of-new-branch"
git -am "my fancy new commit"
git push origin "name-of-new-branch"
</code>```

reset HEAD~ will undo your last commit. Checkout -b makes creates a new branch and checks it out, then you just add and commit your changes there and push

Body:
I have a master branch that is protected with push only by PR.

Say I thoughtlessly on master:

git add .
git commit -m "bunch of changes"

But I push to the branch and am rejected because the branch is protected.
How do I backtrack, preserve my changes, and do a PR?

Body:
git reset HEAD~
git checkout -b "name-of-new-branch"
git -am "my fancy new commit"
git push origin "name-of-new-branch"

reset HEAD~ will undo your last commit. Checkout -b makes creates a new branch and checks it out, then you just add and commit your changes there and push


答:
Undo the last commit of master branch.

```<code>$ git reset --soft HEAD~1      # undo the last commit and keep the changes in working tree
</code>```

Checkout to new branch (say, feature), then Add, Commit and Push to remote feature branch.

```<code>$ git checkout -b feature      # create and checkout to new 'feature' branch
$ git add -A                   # add the changes
$ git commit -m 'message'      # commit
$ git push origin HEAD         # push to remote 'feature' branch
</code>```

Now, Create a PR from feature branch.

Alternate:

Checkout to new branch (say, feature) and push the feature branch to remote.

```<code>$ git checkout -b feature
$ git push origin HEAD
</code>```

Switch to master branch and undo the last commit.

```<code>$ git checkout master
$ git reset --hard HEAD~1

Or, (reset the local 'master' with 'origin/master')
$ git checkout master
$ git fetch origin
$ git reset --hard origin/master
</code>```

Now, Create a PR from feature branch.

Title: How to undo commit, put into new branch then do a PR?

Body:
Undo the last commit of master branch.

$ git reset --soft HEAD~1      # undo the last commit and keep the changes in working tree

Checkout to new branch (say, feature), then Add, Commit and Push to remote feature branch.

$ git checkout -b feature      # create and checkout to new 'feature' branch
$ git add -A                   # add the changes
$ git commit -m 'message'      # commit
$ git push origin HEAD         # push to remote 'feature' branch

Now, Create a PR from feature branch.

Alternate:

Checkout to new branch (say, feature) and push the feature branch to remote.

$ git checkout -b feature
$ git push origin HEAD

Switch to master branch and undo the last commit.

$ git checkout master
$ git reset --hard HEAD~1

Or, (reset the local 'master' with 'origin/master')
$ git checkout master
$ git fetch origin
$ git reset --hard origin/master

Now, Create a PR from feature branch.


问:
EXC_BAD_ACCESS error (only on simulator) when reading fetchedObjects property of NSFetchedResultsController
This issue strangely only occurs on iOS simulator.

After I make a change and save my data, and then try and access the controller's fetchedObjects I get a bad access error.

Even if I just try and check if fetchedObjects is nil, I get the EXC_BAD_ACCESS access. The controller definitely exists and I can print the description of it or for example the fetchRequest property. It's just when accessing the fetchedObjects array it errors.

I'm not sure how to debug this as it seems to come from the SDK.

Any help would be greatly appreciated.

答:
I got a similar issue too. ios 10 , xcode 8.3.3. In simulator and real device.

when I set myFetchRequest.fetchBatchSize = 30 // not 0

then in tableViewController. access to myFetchResutlController.fetchedObejcts will get that error.


问:
JSONException: End of input at character 0
i am trying to get JSON values from server. I don't know what is wrong with my code. I am using AsyncTask and here is my code in doInBackground

Code:

```<code>@Override
    protected Void doInBackground(List<String>... articlesRec) {
        for (List<String> articlesPostValue : articlesRec) {
            event = articlesPostValue.get(0);
            category = articlesPostValue.get(1);
            paged = articlesPostValue.get(2);
            deviceID = articlesPostValue.get(3);
        }

        List<NameValuePair> articlesPostValues = new ArrayList<NameValuePair>();
        articlesPostValues.add(new BasicNameValuePair("_event", event));
        articlesPostValues.add(new BasicNameValuePair("cat", category));
        articlesPostValues.add(new BasicNameValuePair("paged", paged));
        articlesPostValues.add(new BasicNameValuePair("_deviceID", deviceID));

        HttpClient hc = new DefaultHttpClient();
        HttpPost hp = new HttpPost(AutoLifeConstants.BASE_URL);

        try {
            hp.setEntity(new UrlEncodedFormEntity(articlesPostValues));

            // Execute HTTP Post Request
            HttpResponse response = hc.execute(hp);

            String result = EntityUtils.toString(response.getEntity());
            String jsontext = new String(result);

            JSONObject entries = new JSONObject(jsontext);

            this.response = entries.getString("response_code");

            try {
                String totalPageStr = entries.getString("total_pages");
                totalPage = Integer.valueOf(totalPageStr);
            } catch (Exception e) {

            }

            JSONArray postListArray = entries.getJSONArray("posts_list");

            for (int i = 0; i < postListArray.length(); i++) {
                JSONObject postListObj = postListArray.getJSONObject(i);

                String articlesTitle = postListObj.getString("title");
                String dateTime = postListObj.getString("date");
                String articlesImage = postListObj.getString("feature_image");
                String descrition = postListObj.getString("content");
                String fullDescription = postListObj.getString("full_content");

                articlesNewesttitle.add(articlesTitle);
                articlesNewestPostTime.add(dateTime);
                articlesNewestPostImage.add(articlesImage);
                articlesNewestPostDescription.add(descrition);
                postFullDescription.add(fullDescription);

                Log.d("Title",articlesTitle);
            }

        } catch (Exception e) {
            Log.e("catched error","Exceptin occured");
            e.printStackTrace();
        }

        return null;
    }
</code>```

And here is catch(Exception e) on logcat

```<code>    06-19 13:22:32.229: W/System.err(19647): org.json.JSONException: End of input at character 0 of
06-19 13:22:32.264: W/System.err(19647):    at org.json.JSONTokener.syntaxError(JSONTokener.java:450)
06-19 13:22:32.265: W/System.err(19647):    at org.json.JSONTokener.nextValue(JSONTokener.java:97)
06-19 13:22:32.268: W/System.err(19647):    at org.json.JSONObject.<init>(JSONObject.java:154)
06-19 13:22:32.269: W/System.err(19647):    at org.json.JSONObject.<init>(JSONObject.java:171)
06-19 13:22:32.270: W/System.err(19647):    at np.com.autolife.adapters.NewsActivity$Get_postlist.doInBackground(NewsActivity.java:169)
06-19 13:22:32.272: W/System.err(19647):    at np.com.autolife.adapters.NewsActivity$Get_postlist.doInBackground(NewsActivity.java:1)
06-19 13:22:32.272: W/System.err(19647):    at android.os.AsyncTask$2.call(AsyncTask.java:287)
06-19 13:22:32.273: W/System.err(19647):    at java.util.concurrent.FutureTask.run(FutureTask.java:234)
06-19 13:22:32.273: W/System.err(19647):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
06-19 13:22:32.274: W/System.err(19647):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
06-19 13:22:32.274: W/System.err(19647):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
06-19 13:22:32.281: W/System.err(19647):    at java.lang.Thread.run(Thread.java:838)
</code>```

Here is JSON format

```<code>    {
    "get": [],
    "post": {
        "_event": "get_posts",
        "_deviceID": "490154203237518",
        "cat": "2",
        "paged": "1"
    },
    "response_code": "success",
    "posts_total": 8,
    "total_pages": 2,
    "paged": 1,
    "posts_list": [
        {
            "ID": 9168,
            "title": "MAXXIS Introduce Trepador Tires",
            "content": "",
            "full_content": "http:xxxxxx",
            "date": "June 13, 2014",
            "category": "All News & Events, Local News",
            "feature_image": "http:xxxxx.jpg",
            "feature_image_thumb": "http:xxxx.jpg",
            "author": "AutoLife Team"
        },
        {
            "ID": 9162,
            "title": "5 Year Warranty On All Hero Motorcycles",
            "content": "",
            "full_content": "http://xxxxx",
            "date": "June 13, 2014",
            "category": "All News & Events, Local News",
            "feature_image": "http://xxxxxx.jpg",
            "feature_image_thumb": "http://xxxx.jpg",
            "author": "AutoLife Team"
        },
        {
            "ID": 8130,
            "title": "All new 11th Generation Toyota Corolla Launched",
            "content": "",
            "full_content": "http://xxxxxx",
            "date": "May 1, 2014",
            "category": "Events & Schemes",
            "feature_image": "http://xxxxxx.png",
            "feature_image_thumb": "http://xxxxxx.png",
            "author": "supervisor"
        },
        {
            "ID": 9178,
            "title": "New Launches From TATA Motors : TATA Nano Twist",
            "content": "",
            "full_content": "http://xxxxxx",
            "date": "February 15, 2014",
            "category": "All News & Events, International News",
            "feature_image": "http://xxxxx.jpg",
            "feature_image_thumb": "xxxxxxx.jpg",
            "author": "AutoLife Team"
        },
        {
            "ID": 9175,
            "title": "New Launches From TATA Motors : Revotron Engine",
            "content": "",
            "full_content": "xxxxxxx",
            "date": "February 15, 2014",
            "category": "All News & Events, International News",
            "feature_image": "http://xxxxx.jpg",
            "feature_image_thumb": "http://xxxxx.jpg",
            "author": "AutoLife Team"
        }
    ]
}
</code>```

答: The reason why you get this error is because you attempt to access the response more than once. For example lets lets say you do a log with the response, then create a json object with the same response object, it will trigger this one time acees error.</p>

Body:
i am trying to get JSON values from server. I don't know what is wrong with my code. I am using AsyncTask and here is my code in doInBackground

Code:

@Override
    protected Void doInBackground(List<String>... articlesRec) {
        for (List<String> articlesPostValue : articlesRec) {
            event = articlesPostValue.get(0);
            category = articlesPostValue.get(1);
            paged = articlesPostValue.get(2);
            deviceID = articlesPostValue.get(3);
        }

        List<NameValuePair> articlesPostValues = new ArrayList<NameValuePair>();
        articlesPostValues.add(new BasicNameValuePair("_event", event));
        articlesPostValues.add(new BasicNameValuePair("cat", category));
        articlesPostValues.add(new BasicNameValuePair("paged", paged));
        articlesPostValues.add(new BasicNameValuePair("_deviceID", deviceID));

        HttpClient hc = new DefaultHttpClient();
        HttpPost hp = new HttpPost(AutoLifeConstants.BASE_URL);

        try {
            hp.setEntity(new UrlEncodedFormEntity(articlesPostValues));

            // Execute HTTP Post Request
            HttpResponse response = hc.execute(hp);

            String result = EntityUtils.toString(response.getEntity());
            String jsontext = new String(result);

            JSONObject entries = new JSONObject(jsontext);

            this.response = entries.getString("response_code");

            try {
                String totalPageStr = entries.getString("total_pages");
                totalPage = Integer.valueOf(totalPageStr);
            } catch (Exception e) {

            }

            JSONArray postListArray = entries.getJSONArray("posts_list");

            for (int i = 0; i < postListArray.length(); i++) {
                JSONObject postListObj = postListArray.getJSONObject(i);

                String articlesTitle = postListObj.getString("title");
                String dateTime = postListObj.getString("date");
                String articlesImage = postListObj.getString("feature_image");
                String descrition = postListObj.getString("content");
                String fullDescription = postListObj.getString("full_content");

                articlesNewesttitle.add(articlesTitle);
                articlesNewestPostTime.add(dateTime);
                articlesNewestPostImage.add(articlesImage);
                articlesNewestPostDescription.add(descrition);
                postFullDescription.add(fullDescription);

                Log.d("Title",articlesTitle);
            }

        } catch (Exception e) {
            Log.e("catched error","Exceptin occured");
            e.printStackTrace();
        }

        return null;
    }

And here is catch(Exception e) on logcat

    06-19 13:22:32.229: W/System.err(19647): org.json.JSONException: End of input at character 0 of
06-19 13:22:32.264: W/System.err(19647):    at org.json.JSONTokener.syntaxError(JSONTokener.java:450)
06-19 13:22:32.265: W/System.err(19647):    at org.json.JSONTokener.nextValue(JSONTokener.java:97)
06-19 13:22:32.268: W/System.err(19647):    at org.json.JSONObject.<init>(JSONObject.java:154)
06-19 13:22:32.269: W/System.err(19647):    at org.json.JSONObject.<init>(JSONObject.java:171)
06-19 13:22:32.270: W/System.err(19647):    at np.com.autolife.adapters.NewsActivity$Get_postlist.doInBackground(NewsActivity.java:169)
06-19 13:22:32.272: W/System.err(19647):    at np.com.autolife.adapters.NewsActivity$Get_postlist.doInBackground(NewsActivity.java:1)
06-19 13:22:32.272: W/System.err(19647):    at android.os.AsyncTask$2.call(AsyncTask.java:287)
06-19 13:22:32.273: W/System.err(19647):    at java.util.concurrent.FutureTask.run(FutureTask.java:234)
06-19 13:22:32.273: W/System.err(19647):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
06-19 13:22:32.274: W/System.err(19647):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
06-19 13:22:32.274: W/System.err(19647):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
06-19 13:22:32.281: W/System.err(19647):    at java.lang.Thread.run(Thread.java:838)

Here is JSON format

    {
    "get": [],
    "post": {
        "_event": "get_posts",
        "_deviceID": "490154203237518",
        "cat": "2",
        "paged": "1"
    },
    "response_code": "success",
    "posts_total": 8,
    "total_pages": 2,
    "paged": 1,
    "posts_list": [
        {
            "ID": 9168,
            "title": "MAXXIS Introduce Trepador Tires",
            "content": "",
            "full_content": "http:xxxxxx",
            "date": "June 13, 2014",
            "category": "All News & Events, Local News",
            "feature_image": "http:xxxxx.jpg",
            "feature_image_thumb": "http:xxxx.jpg",
            "author": "AutoLife Team"
        },
        {
            "ID": 9162,
            "title": "5 Year Warranty On All Hero Motorcycles",
            "content": "",
            "full_content": "http://xxxxx",
            "date": "June 13, 2014",
            "category": "All News & Events, Local News",
            "feature_image": "http://xxxxxx.jpg",
            "feature_image_thumb": "http://xxxx.jpg",
            "author": "AutoLife Team"
        },
        {
            "ID": 8130,
            "title": "All new 11th Generation Toyota Corolla Launched",
            "content": "",
            "full_content": "http://xxxxxx",
            "date": "May 1, 2014",
            "category": "Events & Schemes",
            "feature_image": "http://xxxxxx.png",
            "feature_image_thumb": "http://xxxxxx.png",
            "author": "supervisor"
        },
        {
            "ID": 9178,
            "title": "New Launches From TATA Motors : TATA Nano Twist",
            "content": "",
            "full_content": "http://xxxxxx",
            "date": "February 15, 2014",
            "category": "All News & Events, International News",
            "feature_image": "http://xxxxx.jpg",
            "feature_image_thumb": "xxxxxxx.jpg",
            "author": "AutoLife Team"
        },
        {
            "ID": 9175,
            "title": "New Launches From TATA Motors : Revotron Engine",
            "content": "",
            "full_content": "xxxxxxx",
            "date": "February 15, 2014",
            "category": "All News & Events, International News",
            "feature_image": "http://xxxxx.jpg",
            "feature_image_thumb": "http://xxxxx.jpg",
            "author": "AutoLife Team"
        }
    ]
}


问:
convert list of dicts to pandas dataframe
This is my dataset

I have an odd one that I have been working on for a week and need some help now.  I have a list of dicts like this:

```<code>[index 0 : {'Total_Salary': 49900.0, 'Total_Value': 490.0,
 'pers_1': {'value': 71.1, 'Name': 'Bob', 'Salary': 10100, 'nick_name': 'foo'},
 'pers_2': {'value': 43.1, 'Name': 'Joe', 'Salary': 9200, 'nick_name': 'bar'}}
 'pers_3': {'value': 42.1, 'Name': 'james', 'Salary': 9750, 'nick_name': 'sam'}}
 'pers_4': {'value': 41.1, 'Name': 'rick', 'Salary': 9700, 'nick_name': 'suzy'}}
 'pers_5': {'value': 23.1, 'Name': 'blop', 'Salary': 9400, 'nick_name': 'jill'}}
 'pers_6': {'value': 54.1, 'Name': 'burp', 'Salary': 9280, 'nick_name': 'yup'}}
</code>```

index 1: (will have a different total salary, total value number because the people will change, but the format stays the same as above)
...
     index n: 'Total_Salary' = ..., 'Total_Value' = ..., person_n...
     ]

Every dictionary in the list of dicts has a total_salary and total_value key.  It is the sum of each persons 'Salary' and 'Value' front the person-1 through person-6.  The list has several hundred dicts just like above appended.  I want to loop through the list of dicts and put each dict into one dataframe.

Ideally, the dataframe would be indexed with Team 1 as an index (then team 2 , team 3 , etc).

答:
```<code>import pandas as pd

team = {
    'pers_1': {'value': 71.1, 'Name': 'Bob', 'Salary': 10100, 'nick_name': 'foo'},
    'pers_2': {'value': 43.1, 'Name': 'Joe', 'Salary': 9200, 'nick_name': 'bar'},
    'pers_3': {'value': 42.1, 'Name': 'james', 'Salary': 9750, 'nick_name': 'sam'},
    'pers_4': {'value': 41.1, 'Name': 'rick', 'Salary': 9700, 'nick_name': 'suzy'},
    'pers_5': {'value': 23.1, 'Name': 'blop', 'Salary': 9400, 'nick_name': 'jill'},
    'pers_6': {'value': 54.1, 'Name': 'burp', 'Salary': 9280, 'nick_name': 'yup'}}

df = (pd.DataFrame(team)
      .T
      .append(pd.Series({'value': df['value'].sum(),
                         'Salary': df['Salary'].sum()},
                        name='Total'))
      .assign(team='team_1')
      .set_index('team', append=True)
      .swaplevel())

print(df)
</code>```

Results in

```<code>                Name  Salary nick_name  value
team
team_1 pers_1    Bob   10100       foo   71.1
       pers_2    Joe    9200       bar   43.1
       pers_3  james    9750       sam   42.1
       pers_4   rick    9700      suzy   41.1
       pers_5   blop    9400      jill   23.1
       pers_6   burp    9280       yup   54.1
       Total     NaN  172290       NaN  823.8
</code>```

You can do the same for the other teams, and then concatenate all the dataframes. In mixed pseudocode:

```<code>all_teams_list = []
# loop for all teams
    # create `df`
    all_teams_list.append(df)
all_teams = pd.concat(all_teams_list)
</code>```

Body:
This is my dataset

I have an odd one that I have been working on for a week and need some help now.  I have a list of dicts like this:

[index 0 : {'Total_Salary': 49900.0, 'Total_Value': 490.0,
 'pers_1': {'value': 71.1, 'Name': 'Bob', 'Salary': 10100, 'nick_name': 'foo'},
 'pers_2': {'value': 43.1, 'Name': 'Joe', 'Salary': 9200, 'nick_name': 'bar'}}
 'pers_3': {'value': 42.1, 'Name': 'james', 'Salary': 9750, 'nick_name': 'sam'}}
 'pers_4': {'value': 41.1, 'Name': 'rick', 'Salary': 9700, 'nick_name': 'suzy'}}
 'pers_5': {'value': 23.1, 'Name': 'blop', 'Salary': 9400, 'nick_name': 'jill'}}
 'pers_6': {'value': 54.1, 'Name': 'burp', 'Salary': 9280, 'nick_name': 'yup'}}

index 1: (will have a different total salary, total value number because the people will change, but the format stays the same as above)
...
     index n: 'Total_Salary' = ..., 'Total_Value' = ..., person_n...
     ]

Every dictionary in the list of dicts has a total_salary and total_value key.  It is the sum of each persons 'Salary' and 'Value' front the person-1 through person-6.  The list has several hundred dicts just like above appended.  I want to loop through the list of dicts and put each dict into one dataframe.

Ideally, the dataframe would be indexed with Team 1 as an index (then team 2 , team 3 , etc).

Body:
import pandas as pd

team = {
    'pers_1': {'value': 71.1, 'Name': 'Bob', 'Salary': 10100, 'nick_name': 'foo'},
    'pers_2': {'value': 43.1, 'Name': 'Joe', 'Salary': 9200, 'nick_name': 'bar'},
    'pers_3': {'value': 42.1, 'Name': 'james', 'Salary': 9750, 'nick_name': 'sam'},
    'pers_4': {'value': 41.1, 'Name': 'rick', 'Salary': 9700, 'nick_name': 'suzy'},
    'pers_5': {'value': 23.1, 'Name': 'blop', 'Salary': 9400, 'nick_name': 'jill'},
    'pers_6': {'value': 54.1, 'Name': 'burp', 'Salary': 9280, 'nick_name': 'yup'}}

df = (pd.DataFrame(team)
      .T
      .append(pd.Series({'value': df['value'].sum(),
                         'Salary': df['Salary'].sum()},
                        name='Total'))
      .assign(team='team_1')
      .set_index('team', append=True)
      .swaplevel())

print(df)

Results in

                Name  Salary nick_name  value
team
team_1 pers_1    Bob   10100       foo   71.1
       pers_2    Joe    9200       bar   43.1
       pers_3  james    9750       sam   42.1
       pers_4   rick    9700      suzy   41.1
       pers_5   blop    9400      jill   23.1
       pers_6   burp    9280       yup   54.1
       Total     NaN  172290       NaN  823.8

You can do the same for the other teams, and then concatenate all the dataframes. In mixed pseudocode:

all_teams_list = []
# loop for all teams
    # create `df`
    all_teams_list.append(df)
all_teams = pd.concat(all_teams_list)


Title: Removing similar elements but leaving unique ones by looping

Body:
I have to remove similar elements from a list which is not sorted, looks like this.

[(579, 271, 97, 114), (580, 271, 97, 114), (578, 272, 97, 114), (579, 272, 97, 114), (580, 272, 97, 114), (581, 272, 97, 114), (577, 273, 97, 114), (578, 273, 97, 114), (579, 273, 97, 114), (580, 273, 97, 114), (581, 273, 97, 114), (582, 273, 97, 114), (577, 274, 97, 114), (578, 274, 97, 114), (579, 274, 97, 114), (580, 274, 97, 114), (581, 274, 97, 114), (582, 274, 97, 114), (577, 275, 97, 114), (578, 275, 97, 114), (579, 275, 97, 114), (580, 275, 97, 114), (581, 275, 97, 114), (578, 276, 97, 114), (579, 276, 97, 114), (580, 276, 97, 114), (581, 276, 97, 114), (579, 277, 97, 114), (22, 460, 97, 114), (23, 460, 97, 114), (133, 460, 97, 114), (134, 460, 97, 114), (21, 461, 97, 114), (22, 461, 97, 114), (23, 461, 97, 114), (24, 461, 97, 114), (132, 461, 97, 114), (133, 461, 97, 114), (134, 461, 97, 114), (135, 461, 97, 114), (20, 462, 97, 114), (21, 462, 97, 114), (22, 462, 97, 114), (23, 462, 97, 114), (24, 462, 97, 114), (131, 462, 97, 114), (132, 462, 97, 114), (133, 462, 97, 114), (134, 462, 97, 114), (135, 462, 97, 114), (136, 462, 97, 114), (20, 463, 97, 114), (21, 463, 97, 114), (22, 463, 97, 114), (23, 463, 97, 114), (24, 463, 97, 114), (131, 463, 97, 114), (132, 463, 97, 114), (133, 463, 97, 114), (134, 463, 97, 114), (135, 463, 97, 114), (136, 463, 97, 114), (20, 464, 97, 114), (21, 464, 97, 114), (22, 464, 97, 114), (23, 464, 97, 114), (24, 464, 97, 114), (131, 464, 97, 114), (132, 464, 97, 114), (133, 464, 97, 114), (134, 464, 97, 114), (135, 464, 97, 114), (136, 464, 97, 114), (21, 465, 97, 114), (22, 465, 97, 114), (23, 465, 97, 114), (132, 465, 97, 114), (133, 465, 97, 114), (134, 465, 97, 114), (135, 465, 97, 114), (22, 466, 97, 114), (133, 466, 97, 114), (134, 466, 97, 114)]

i want to leave unique elements from comes up first in the head, but remove elements within the difference of 5.

I've coded a function compare difference between each element, but it keeps getting large.

def compare_remove(input_list):
    cnt = 0
    glob_cnt = 0
    output_list = [input_list[0]]

    while True:

        for i in range(len(input_list)):
            if i <= cnt:
                print 'jump || '
                continue

            if abs(output_list[cnt][0] - input_list[i][0]) <= 5:
                if abs(output_list[cnt][0] - input_list[i][0]) == 0:
                    continue

                print 'skip ||' + str(output_list[cnt]) +' || ' + str(input_list[i])
                continue
            else:
                print 'append || ' + str(input_list[i])
                output_list.append(input_list[i])

        print 'loop out || '
        input_list = output_list
        cnt+=1

        if cnt == 100:
            break
        try:
            output_list[cnt]
        except:
            break

    return output_list

it compares the first element of elements, and the difference between previous one, remove it.

Body:
I'm not sure if I understood the question, but here is the code that leaves unique elements from comes up first in the head, but removes elements within the difference of 5.

input=[(579, 271, 97, 114), (580, 271, 97, 114), (578, 272, 97, 114), (579, 272, 97, 114), (580, 272, 97, 114), (581, 272, 97, 114), (577, 273, 97, 114), (578, 273, 97, 114), (579, 273, 97, 114), (580, 273, 97, 114), (581, 273, 97, 114), (582, 273, 97, 114), (577, 274, 97, 114), (578, 274, 97, 114), (579, 274, 97, 114), (580, 274, 97, 114), (581, 274, 97, 114), (582, 274, 97, 114), (577, 275, 97, 114), (578, 275, 97, 114), (579, 275, 97, 114), (580, 275, 97, 114), (581, 275, 97, 114), (578, 276, 97, 114), (579, 276, 97, 114), (580, 276, 97, 114), (581, 276, 97, 114), (579, 277, 97, 114), (22, 460, 97, 114), (23, 460, 97, 114), (133, 460, 97, 114), (134, 460, 97, 114), (21, 461, 97, 114), (22, 461, 97, 114), (23, 461, 97, 114), (24, 461, 97, 114), (132, 461, 97, 114), (133, 461, 97, 114), (134, 461, 97, 114), (135, 461, 97, 114), (20, 462, 97, 114), (21, 462, 97, 114), (22, 462, 97, 114), (23, 462, 97, 114), (24, 462, 97, 114), (131, 462, 97, 114), (132, 462, 97, 114), (133, 462, 97, 114), (134, 462, 97, 114), (135, 462, 97, 114), (136, 462, 97, 114), (20, 463, 97, 114), (21, 463, 97, 114), (22, 463, 97, 114), (23, 463, 97, 114), (24, 463, 97, 114), (131, 463, 97, 114), (132, 463, 97, 114), (133, 463, 97, 114), (134, 463, 97, 114), (135, 463, 97, 114), (136, 463, 97, 114), (20, 464, 97, 114), (21, 464, 97, 114), (22, 464, 97, 114), (23, 464, 97, 114), (24, 464, 97, 114), (131, 464, 97, 114), (132, 464, 97, 114), (133, 464, 97, 114), (134, 464, 97, 114), (135, 464, 97, 114), (136, 464, 97, 114), (21, 465, 97, 114), (22, 465, 97, 114), (23, 465, 97, 114), (132, 465, 97, 114), (133, 465, 97, 114), (134, 465, 97, 114), (135, 465, 97, 114), (22, 466, 97, 114), (133, 466, 97, 114), (134, 466, 97, 114)]
srt_input=sorted(input)
mini=srt_input[0][0]
output=[srt_input[0]]
for i in srt_input:
    if i[0]<=mini+5:continue
    mini=i[0]
    output.append(i)
print(output)
---------
[(20, 462, 97, 114), (131, 462, 97, 114), (577, 273, 97, 114)]

you can just select the minimum, and ignore if the next one's head < selected one's head+5.

If this is not what you want, please let me know what output are you expected.


问:
PyQt QSqlDatabase: QMYSQL driver not loaded
I am trying to connect to a MySQL database using PyQt5 on Python 3.6 for 64-bit Windows. When I call QSqlDatabase.addDatabase('MYSQL') and run my utility, it shows up with this error message:

QSqlDatabase: QMYSQL driver not loaded
QSqlDatabase: available drivers: QSQLITE QMYSQL QMYSQL3 QODBC QODBC3 QP
SQL QPSQL7

This confuses me since according to the error message, the QMYSQL driver is loaded. I installed PyQt through the default installer, so the MySQL plugin should be installed. Has anyone else experienced this problem or does someone know the cause of this?

答: It said driver available but you need to rebuid a new Mysql driver base on Qt Source code and Mysql Library.</p>


问:
how to close geany terminal
Whenever a program finishes to run when executing it with geany, the terminal doesn't close.
geany terminal waits for a keystroke to close. How do I change this behavior and make it close automatically when the program reaches it's end? Is there a script I can write?</p>

答:
A variant of pohly's answer worked for me:
In Build -> Set Build Commands -> Execute commands
I replaced "./%e" by "./%e" && exit

Title: how to close geany terminal


问:
Java - Arrays binarySearch returning unexpected result after custom sort
Here is the simple piece of code that I build to understand Arrays.binarySearch. But it is returning a result which I did not even expect.

```<code>    String[] c = {"A", "Z", "B"};
    Arrays.sort(c, new MyNewComparator1()); //Z, B, A
    System.out.println(Arrays.binarySearch(c, "Z")); //0
    System.out.println(Arrays.binarySearch(c, "S")); //-2 based on insertion point
    System.out.println(Arrays.binarySearch(c, "N")); //Unpredicable result we can expect
</code>```

Here is my custom Comparator

```<code>class MyNewComparator1 implements Comparator<String> {
    public int compare(String s1, String s2) {
        return s2.compareTo(s1);
    }
}
</code>```

Result I am expecting 0, -2, Unpredictable

But the result it is returning -4, -4, -4

Can someone please help me to understand why it is returning -4 for all the search?

Thanks

答:
As the Javadoc states, your array must be:

The array must be  sorted into ascending order according to the
  natural ordering of its elements (as by the sort(Object []) method)
  prior to making this call.

The sort(Object []) method that the above refers to clarifies:

Sorts the specified array of objects into ascending order, according
  to the natural ordering of its elements.

You need to sort in ascending order but you are sorting in descending order.

You need to change your comparator to make it sort in ascending order:

```<code>class MyNewComparator1 implements Comparator<String> {
    public int compare(String s1, String s2) {
        return s1.compareTo(s2); // <-- swap s1 and s2
    }
}
</code>```

There is an alternative solution. You can redefine what ascending means by passing your own Comparator to the binarySearch method call as the last argument. If you do that, then don't change the comparator - leave it as you originally posted it. But change the binarySearch method calls:

```<code>MyNewComparator1 comparator = new MyNewComparator1();
System.out.println(Arrays.binarySearch(c, "Z", comparator)); // 0
System.out.println(Arrays.binarySearch(c, "S", comparator)); // -2 based on insertion point
System.out.println(Arrays.binarySearch(c, "N", comparator)); // Unpredicable result we can expect
</code>```

Body:
Here is the simple piece of code that I build to understand Arrays.binarySearch. But it is returning a result which I did not even expect.

    String[] c = {"A", "Z", "B"};
    Arrays.sort(c, new MyNewComparator1()); //Z, B, A
    System.out.println(Arrays.binarySearch(c, "Z")); //0
    System.out.println(Arrays.binarySearch(c, "S")); //-2 based on insertion point
    System.out.println(Arrays.binarySearch(c, "N")); //Unpredicable result we can expect

Here is my custom Comparator

class MyNewComparator1 implements Comparator<String> {
    public int compare(String s1, String s2) {
        return s2.compareTo(s1);
    }
}

Result I am expecting 0, -2, Unpredictable

But the result it is returning -4, -4, -4

Can someone please help me to understand why it is returning -4 for all the search?

Thanks

Body:
As the Javadoc states, your array must be:

The array must be  sorted into ascending order according to the
  natural ordering of its elements (as by the sort(Object []) method)
  prior to making this call.

The sort(Object []) method that the above refers to clarifies:

Sorts the specified array of objects into ascending order, according
  to the natural ordering of its elements.

You need to sort in ascending order but you are sorting in descending order.

You need to change your comparator to make it sort in ascending order:

class MyNewComparator1 implements Comparator<String> {
    public int compare(String s1, String s2) {
        return s1.compareTo(s2); // <-- swap s1 and s2
    }
}

There is an alternative solution. You can redefine what ascending means by passing your own Comparator to the binarySearch method call as the last argument. If you do that, then don't change the comparator - leave it as you originally posted it. But change the binarySearch method calls:

MyNewComparator1 comparator = new MyNewComparator1();
System.out.println(Arrays.binarySearch(c, "Z", comparator)); // 0
System.out.println(Arrays.binarySearch(c, "S", comparator)); // -2 based on insertion point
System.out.println(Arrays.binarySearch(c, "N", comparator)); // Unpredicable result we can expect


问:
URI formats are not supported in webclient c#
I call my service as you can see like this :

```<code>  public ReceptionView ReceptionViewByReceptionId(string receptionId)
    {
        ClientRequest.Headers["Content-type"] = "application/json";
        ClientRequest.Encoding = System.Text.Encoding.UTF8;
        string result = ClientRequest.DownloadString("http://localhost:1111" + " /ReceptionService.svc/ReceptionViewByReceptionId/" + receptionId);

        var javascriptserializer = new JavaScriptSerializer();
        return javascriptserializer.Deserialize<ReceptionView>(result);
    }
</code>```

But i get this error in DownloadString:

```<code>{"URI formats are not supported."}
</code>```

my service works ok and when i call my service by browser like this :

```<code>http://localhost:1111/ReceptionService.svc/ReceptionViewByReceptionId/1
</code>```

I get the expected result .but in my application i can't

My service interface

```<code> [WebGet( UriTemplate = "/ReceptionViewByReceptionId/{receptionId}", RequestFormat = WebMessageFormat.Json,
    ResponseFormat = WebMessageFormat.Json)]

    ReceptionView ReceptionViewByReceptionId(string receptionId);
</code>```

As a note my function worked before without any error ,but today suddenly returns this error.

My fiddler result in browser:

答:
The problem was the space here " /Reception as you can see in the url

```<code>string result = ClientRequest.DownloadString("http://localhost:1111" + " /ReceptionService.svc/ReceptionViewByReceptionId/" + receptionId);
</code>```

I removed that and every thing worked fine .

Body:
I call my service as you can see like this :

  public ReceptionView ReceptionViewByReceptionId(string receptionId)
    {
        ClientRequest.Headers["Content-type"] = "application/json";
        ClientRequest.Encoding = System.Text.Encoding.UTF8;
        string result = ClientRequest.DownloadString("http://localhost:1111" + " /ReceptionService.svc/ReceptionViewByReceptionId/" + receptionId);

        var javascriptserializer = new JavaScriptSerializer();
        return javascriptserializer.Deserialize<ReceptionView>(result);
    }

But i get this error in DownloadString:

{"URI formats are not supported."}

my service works ok and when i call my service by browser like this :

http://localhost:1111/ReceptionService.svc/ReceptionViewByReceptionId/1

I get the expected result .but in my application i can't

My service interface

 [WebGet( UriTemplate = "/ReceptionViewByReceptionId/{receptionId}", RequestFormat = WebMessageFormat.Json,
    ResponseFormat = WebMessageFormat.Json)]

    ReceptionView ReceptionViewByReceptionId(string receptionId);

As a note my function worked before without any error ,but today suddenly returns this error.

My fiddler result in browser:

Body:
The problem was the space here " /Reception as you can see in the url

string result = ClientRequest.DownloadString("http://localhost:1111" + " /ReceptionService.svc/ReceptionViewByReceptionId/" + receptionId);

I removed that and every thing worked fine .


问:
Using a string argument to represent an object
If I have the following code:

```<code>TextBox txtUsername = new TextBox();
void setEnabled(string str, bool enable)
{
    // use str to find the TextBox object
    // str.Enabled = enable;
}
</code>```

Is this kinda thing even possible?

I want to be passing in 'Username' and then be prepending it with 'txt'.

答:
Yes, you need to set the Name-Property, then you can access it via it's owner:

```<code>this.Controls.Item(str).Enabled = enabled;
</code>```

Body:
If I have the following code:

TextBox txtUsername = new TextBox();
void setEnabled(string str, bool enable)
{
    // use str to find the TextBox object
    // str.Enabled = enable;
}

Is this kinda thing even possible?

I want to be passing in 'Username' and then be prepending it with 'txt'.

Body:
Yes, you need to set the Name-Property, then you can access it via it's owner:

this.Controls.Item(str).Enabled = enabled;


问:
Error in Web API Config file c#
I am New to C# and I am developing a web api to perform CRUD Operations on SQL Server.

I am receiving the error in web config file.

I have Created Model Class:

```<code>public class Test_Automation_Data
{
    private String strTest_Automation_Group;
    private String strTest_Automation_Application;
    private String strTest_Automation_Count;

    public string Test_Automation_Group { get => strTest_Automation_Group; set => strTest_Automation_Group = value; }
    public string Test_Automation_Application { get => strTest_Automation_Application; set => strTest_Automation_Application = value; }
    public string Test_Automation_Count { get => strTest_Automation_Count; set => strTest_Automation_Count = value; }
}
public class TestAutomationDataModel
{

    private SqlConnection GetSQLConnection()
    {
        SqlConnection objConnection = null;
        try
        {
            String ConnectionString = "Data Source=**********;Initial Catalog=***********;User ID=************;Password=*********";
            objConnection = new SqlConnection(ConnectionString);
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return objConnection;
    }

    public List<Test_Automation_Data> GetTestData()
    {
        List<Test_Automation_Data> Data = new List<Test_Automation_Data>();
        try
        {
            SqlConnection obj_Connection = GetSQLConnection();
            obj_Connection.Open();
            string SQL_Query = "SELECT * FROM Test_Automation_Inventory";
            if (obj_Connection.State == System.Data.ConnectionState.Open)
            {
                SqlCommand objCommand = new SqlCommand(SQL_Query, obj_Connection);
                SqlDataReader DataReader = objCommand.ExecuteReader();
                if (DataReader.HasRows)
                {
                    while (DataReader.Read())
                    {
                        Test_Automation_Data obj_TestData = new Test_Automation_Data();
                        obj_TestData.Test_Automation_Group = DataReader.GetValue(0).ToString();
                        obj_TestData.Test_Automation_Application = DataReader.GetValue(1).ToString();
                        obj_TestData.Test_Automation_Count = DataReader.GetValue(2).ToString();
                        Data.Add(obj_TestData);
                    }
                    DataReader.Close();
                    obj_Connection.Close();
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return Data;

    }

    public int DeleteTest(String Test_Group, String Test_Application)
    {
        int RowCount = 0;
        try
        {
            SqlConnection obj_Connection = GetSQLConnection();
            obj_Connection.Open();
            string SQL_Query = "DELETE FROM Test_Automation_Inventory WHERE Test_Inventory_Group = '" + Test_Group + "' and Test_Inventory_Application = '" + Test_Application + "'";
            if (obj_Connection.State == System.Data.ConnectionState.Open)
            {
                SqlCommand objCommand = new SqlCommand(SQL_Query, obj_Connection);
                RowCount = int.Parse(objCommand.ExecuteNonQuery().ToString());
            }
            obj_Connection.Close();
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return RowCount;
    }

    public int CreateTest(String Test_Group, String Test_Application)
    {
        int RowCount = 0;
        try
        {
            SqlConnection obj_Connection = GetSQLConnection();
            obj_Connection.Open();
            if (obj_Connection.State == System.Data.ConnectionState.Open)
            {
                SqlCommand objCommand = new SqlCommand();
                objCommand.CommandType = System.Data.CommandType.Text;
                objCommand.CommandText = "INSERT INTO Test_Automation_Inventory  Values (@Test_Group,@Test_Application,@Test_Count)";
                objCommand.Connection = obj_Connection;

                objCommand.Parameters.AddWithValue("@Test_Group", Test_Group);
                objCommand.Parameters.AddWithValue("@Test_Application", Test_Application);
                objCommand.Parameters.AddWithValue("@Test_Count", 0);
                RowCount = objCommand.ExecuteNonQuery();
            }
            obj_Connection.Close();
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return RowCount;
    }
}
</code>```

And here is my Controller Class:

```<code>public class TestController : ApiController
{

    // GET: api/TestAutomationInventory
    public List<Test_Automation_Data> Get()
    {
        TestAutomationDataModel obj = new TestAutomationDataModel();
        return obj.GetTestData();
    }
}
</code>```

Here is my Web Config File :

```<code> <compilers>
  <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
  <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
</compilers>
</code>```

I am Receiving the following error when i am trying to run the project :

```<code>Line 39:       <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
</code>```

How to resolve the issue

答:
The version of the DLL you have in your Packages folder (used by Nuget), reference folder or GAC is not </p>

```<code>Version=1.0.3.0
</code>```

Title: Error in Web API Config file c#

Body:
I am New to C# and I am developing a web api to perform CRUD Operations on SQL Server.

I am receiving the error in web config file.

I have Created Model Class:

public class Test_Automation_Data
{
    private String strTest_Automation_Group;
    private String strTest_Automation_Application;
    private String strTest_Automation_Count;

    public string Test_Automation_Group { get => strTest_Automation_Group; set => strTest_Automation_Group = value; }
    public string Test_Automation_Application { get => strTest_Automation_Application; set => strTest_Automation_Application = value; }
    public string Test_Automation_Count { get => strTest_Automation_Count; set => strTest_Automation_Count = value; }
}
public class TestAutomationDataModel
{

    private SqlConnection GetSQLConnection()
    {
        SqlConnection objConnection = null;
        try
        {
            String ConnectionString = "Data Source=**********;Initial Catalog=***********;User ID=************;Password=*********";
            objConnection = new SqlConnection(ConnectionString);
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return objConnection;
    }

    public List<Test_Automation_Data> GetTestData()
    {
        List<Test_Automation_Data> Data = new List<Test_Automation_Data>();
        try
        {
            SqlConnection obj_Connection = GetSQLConnection();
            obj_Connection.Open();
            string SQL_Query = "SELECT * FROM Test_Automation_Inventory";
            if (obj_Connection.State == System.Data.ConnectionState.Open)
            {
                SqlCommand objCommand = new SqlCommand(SQL_Query, obj_Connection);
                SqlDataReader DataReader = objCommand.ExecuteReader();
                if (DataReader.HasRows)
                {
                    while (DataReader.Read())
                    {
                        Test_Automation_Data obj_TestData = new Test_Automation_Data();
                        obj_TestData.Test_Automation_Group = DataReader.GetValue(0).ToString();
                        obj_TestData.Test_Automation_Application = DataReader.GetValue(1).ToString();
                        obj_TestData.Test_Automation_Count = DataReader.GetValue(2).ToString();
                        Data.Add(obj_TestData);
                    }
                    DataReader.Close();
                    obj_Connection.Close();
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return Data;

    }

    public int DeleteTest(String Test_Group, String Test_Application)
    {
        int RowCount = 0;
        try
        {
            SqlConnection obj_Connection = GetSQLConnection();
            obj_Connection.Open();
            string SQL_Query = "DELETE FROM Test_Automation_Inventory WHERE Test_Inventory_Group = '" + Test_Group + "' and Test_Inventory_Application = '" + Test_Application + "'";
            if (obj_Connection.State == System.Data.ConnectionState.Open)
            {
                SqlCommand objCommand = new SqlCommand(SQL_Query, obj_Connection);
                RowCount = int.Parse(objCommand.ExecuteNonQuery().ToString());
            }
            obj_Connection.Close();
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return RowCount;
    }

    public int CreateTest(String Test_Group, String Test_Application)
    {
        int RowCount = 0;
        try
        {
            SqlConnection obj_Connection = GetSQLConnection();
            obj_Connection.Open();
            if (obj_Connection.State == System.Data.ConnectionState.Open)
            {
                SqlCommand objCommand = new SqlCommand();
                objCommand.CommandType = System.Data.CommandType.Text;
                objCommand.CommandText = "INSERT INTO Test_Automation_Inventory  Values (@Test_Group,@Test_Application,@Test_Count)";
                objCommand.Connection = obj_Connection;

                objCommand.Parameters.AddWithValue("@Test_Group", Test_Group);
                objCommand.Parameters.AddWithValue("@Test_Application", Test_Application);
                objCommand.Parameters.AddWithValue("@Test_Count", 0);
                RowCount = objCommand.ExecuteNonQuery();
            }
            obj_Connection.Close();
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return RowCount;
    }
}

And here is my Controller Class:

public class TestController : ApiController
{

    // GET: api/TestAutomationInventory
    public List<Test_Automation_Data> Get()
    {
        TestAutomationDataModel obj = new TestAutomationDataModel();
        return obj.GetTestData();
    }
}

Here is my Web Config File :

 <compilers>
  <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
  <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
</compilers>

I am Receiving the following error when i am trying to run the project :

Line 39:       <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />

How to resolve the issue

Body:
The version of the DLL you have in your Packages folder (used by Nuget), reference folder or GAC is not

Version=1.0.3.0


问:
Which of these two numpy slices are better to use?
I am learning Python through an online course. We were asked to slice a 6x6 numpy array and get the diagonal. As a group we developed two methods, shown below. Is one better than the other?

```<code>import numpy as n
six = n.arange(1, 73, 2)
six.reshape(6,6)
</code>```

Solutions found

```<code>six[::7]
six.reshape(36)[::7]
</code>```

My answers both return array([ 1, 15, 29, 43, 57, 71])

I like the first, my partner likes the second. Any help would be very appreciated.

Thank you!

答:
Let's fix your code a bit first so it does what you intend:

```<code>six = np.arange(1, 73, 2).reshape(6, 6)
</code>```

Now comparing your approach:

```<code>>>> six[::7]
array([[ 1,  3,  5,  7,  9, 11]])
</code>```

To your partner's:

```<code>>>> six.reshape(36)[::7]
array([ 1, 15, 29, 43, 57, 71])
</code>```

Body:
I am learning Python through an online course. We were asked to slice a 6x6 numpy array and get the diagonal. As a group we developed two methods, shown below. Is one better than the other?

import numpy as n
six = n.arange(1, 73, 2)
six.reshape(6,6)

Solutions found

six[::7]
six.reshape(36)[::7]

My answers both return array([ 1, 15, 29, 43, 57, 71])

I like the first, my partner likes the second. Any help would be very appreciated.

Thank you!

Body:
Let's fix your code a bit first so it does what you intend:

six = np.arange(1, 73, 2).reshape(6, 6)

Now comparing your approach:

>>> six[::7]
array([[ 1,  3,  5,  7,  9, 11]])

To your partner's:

>>> six.reshape(36)[::7]
array([ 1, 15, 29, 43, 57, 71])


问:
Twitter share page does not open in an iframe
I'm trying to open the Twitter share URL http://twitter.com/share?url=http://google.com&text=Google using Highslide iframe http://highslide.com/ref/hs.objectType

But the Highslide popup has no content!

Anybody knows what seems to be the problem?

答:
The page has code specifically to prevent you from displaying it in a frame. The page is only made visible if it detects that it's not inside a frame.

So, you shouldn't put it in an iframe.


问:
How to do get request from website that is protected?
Site is protected with username and password. How can i do get some data from that page if it is protected. Any suggestion? When i access it i need to enter username and password to get content. I owe that site and i know username and password but it need to be protected because its in develop mode.</p>

答:
Try adding usrename and password in request url like this

```<code>http://username:password@kodex.dev.lapps.ws/
</code>```

or

you can use basic Authorization header in your http request

Body:
Try adding usrename and password in request url like this

http://username:password@kodex.dev.lapps.ws/

or

you can use basic Authorization header in your http request


问:
On running my first simulation of castalia, i get the following error
Simulation terminated with exit code: 139 Working directory: /home/roopali/omnetpp-4.6/samples/Castalia_proj/Simulations/Parameters Command line: ../../src/Castalia_proj -r 0 -n ..:../../src First_Obj.ini

Environment variables: PATH=/home/roopali/omnetpp-4.6/bin::/home/roopali/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games LD_LIBRARY_PATH=/home/roopali/omnetpp-4.6/lib:: OMNETPP_IMAGE_PATH=/home/roopali/omnetpp-4.6/images

I have tried making this simulation using the steps on page https://chevy67.wordpress.com/tag/castalia/

答:
The blog post you linked (and tried to follow instructions from) refers to a very old version of Castalia. Follow the installation guidelines found in the official repo for Castalia:

https://github.com/boulis/Castalia

After you have installed Castalia successfully, read the manual (found again in the above link),  especially Chapter 3, to run your first simulation.


问:
Want to make it so prices actually reflect the choices
Hope everyone is having a good weekend!

If you select a Small Cheese pizza the price comes out to $5. However, if you select a Small Cheese and Peanut Butter, it still comes out to $5. I think I might need to add a loop/array. I am definitely missing something. Thanks for your help. Also, I am a total newbie to all of this so no answers that are may seem out of knowledge based off what I have written. Thanks!

var pizzaPrice = 0;

function Pizza(size,toppings,pizzaPrice) {
  this.size = size;
  this.toppings = toppings;
  this.pizzaPrice = 0;
}

Pizza.prototype.price = function() {
  if (this.size === "Small") {
    this.pizzaPrice += 2;
  }
  else if (this.size === "Medium") {
    this.pizzaPrice += 3;
  }
  else if (this.size === "Large") {
    this.pizzaPrice += 4;
  }
  if (this.toppings === "Cheese") {
    this.pizzaPrice += 3;
  }

  else if (this.toppings === "Cheese" && this.toppings === "Peanut Butter") {
    this.pizzaPrice += 10;
    console.log("hey");

  }

  else if (this.toppings === "Vegetarian") {
    this.pizzaPrice += 2;
  }
  else if (this.toppings === "Supreme") {
    this.pizzaPrice += 4;
  }
  else if (this.toppings === "Pepperoni") {
    this.pizzaPrice += 3;
  }

return this.pizzaPrice;
}

$(document).ready(function(){
  $("form#pizza").submit(function(event){
    event.preventDefault();

    var size = $("input[type=radio][name=size]:checked").val();
    var toppings = $("input[type=checkbox][name=toppings]:checked").val();
    var newPizza = new Pizza(size,toppings,pizzaPrice);
    newPizza.price();

    $("#responses").append("
" + "You ordered a " + newPizza.size + " " + newPizza.toppings + " pizza. " + " Your total price is " + newPizza.pizzaPrice + "
");

      });
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
  <head>
    <title>Pizza Pizza</title>
    <link href="css/bootstrap.css" rel="stylesheet" type="text/css">
    <link href="css/styles.css" rel="stylesheet" type="text/css">
    <script src="js/jquery-3.2.0.js"></script>
    <script src="js/scripts.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  </head>
  <body>
    <div class="container">
      <div class="jumbotron">
        <h2>Pizza Toppings</h2>
      </div>
      <form id="pizza">
        <div class="form-group">
          <p>What size would you like your pizza:</p>
          <input type="radio" name="size" value="Small">Small.<br>
          <input type="radio" name="size" value="Medium">Medium.<br>
          <input type="radio" name="size" value="Large">Large.<br>
        </div>
        <div class="form-group">
          <p>Which toppings would you like</p>
          <input type="checkbox" name="toppings" value="Cheese">Cheese.<br>
          <input type="checkbox" name="toppings" value="Vegetarian">Vegetarian.<br>
          <input type="checkbox" name="toppings" value="Supreme">Supreme.<br>
          <input type="checkbox" name="toppings" value="Pepperoni">Pepperoni.<br>
          <input type="checkbox" name="toppings" value="Fruit">Fruit.<br>
          <input type="checkbox" name="toppings" value="Bacon">Bacon.<br>
          <input type="checkbox" name="toppings" value="Artichoke">Artichoke.<br>
          <input type="checkbox" name="toppings" value="Peanut Butter">Peanut butter.<br>
        </div>
       <button type="submit">Let's get your order</button>
      </form>
      <ul id="responses">
      </ul>
    </div>
  </body>
</html></code>```

答:
Firstly, you need to get values of all checked toppings in an array, currently you are getting only the first one. Then you need to add prices for each topping selected while calculating the price. you can use indexOf for this:

var pizzaPrice = 0;

function Pizza(size,toppings,pizzaPrice) {
  this.size = size;
  this.toppings = toppings;
  this.pizzaPrice = 0;
}

Pizza.prototype.price = function() {
  if (this.size === "Small") {
    this.pizzaPrice += 2;
  }
  else if (this.size === "Medium") {
    this.pizzaPrice += 3;
  }
  else if (this.size === "Large") {
    this.pizzaPrice += 4;
  }
  if (this.toppings.indexOf("Cheese") >= 0) {
    this.pizzaPrice += 3;
  }

  if (this.toppings.indexOf("Peanut Butter") >= 0) {
    this.pizzaPrice += 10;

  }

  if (this.toppings.indexOf("Vegetarian") >= 0) {
    this.pizzaPrice += 2;
  }
  if (this.toppings.indexOf("Supreme") >= 0) {
    this.pizzaPrice += 4;
  }
  if (this.toppings.indexOf("Pepperoni") >= 0) {
    this.pizzaPrice += 3;
  }

return this.pizzaPrice;
}

$(document).ready(function(){
  $("form#pizza").submit(function(event){
    event.preventDefault();

    var size = $("input[type=radio][name=size]:checked").val();
    var toppings = [];
    $("input[type=checkbox][name=toppings]:checked").each(function(){
           toppings.push($(this).val());
    });
    var newPizza = new Pizza(size,toppings,pizzaPrice);
    newPizza.price();

    $("#responses").append("
" + "You ordered a " + newPizza.size + " " + newPizza.toppings + " pizza. " + " Your total price is " + newPizza.pizzaPrice + "
");

      });
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
  <head>
    <title>Pizza Pizza</title>
    <link href="css/bootstrap.css" rel="stylesheet" type="text/css">
    <link href="css/styles.css" rel="stylesheet" type="text/css">
    <script src="js/jquery-3.2.0.js"></script>
    <script src="js/scripts.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  </head>
  <body>
    <div class="container">
      <div class="jumbotron">
        <h2>Pizza Toppings</h2>
      </div>
      <form id="pizza">
        <div class="form-group">
          <p>What size would you like your pizza:</p>
          <input type="radio" name="size" value="Small">Small.<br>
          <input type="radio" name="size" value="Medium">Medium.<br>
          <input type="radio" name="size" value="Large">Large.<br>
        </div>
        <div class="form-group">
          <p>Which toppings would you like</p>
          <input type="checkbox" name="toppings" value="Cheese">Cheese.<br>
          <input type="checkbox" name="toppings" value="Vegetarian">Vegetarian.<br>
          <input type="checkbox" name="toppings" value="Supreme">Supreme.<br>
          <input type="checkbox" name="toppings" value="Pepperoni">Pepperoni.<br>
          <input type="checkbox" name="toppings" value="Fruit">Fruit.<br>
          <input type="checkbox" name="toppings" value="Bacon">Bacon.<br>
          <input type="checkbox" name="toppings" value="Artichoke">Artichoke.<br>
          <input type="checkbox" name="toppings" value="Peanut Butter">Peanut butter.<br>
        </div>
       <button type="submit">Let's get your order</button>
      </form>
      <ul id="responses">
      </ul>
    </div>
  </body>
</html></code>```

Body:
Hope everyone is having a good weekend!

If you select a Small Cheese pizza the price comes out to $5. However, if you select a Small Cheese and Peanut Butter, it still comes out to $5. I think I might need to add a loop/array. I am definitely missing something. Thanks for your help. Also, I am a total newbie to all of this so no answers that are may seem out of knowledge based off what I have written. Thanks!

var pizzaPrice = 0;

function Pizza(size,toppings,pizzaPrice) {
  this.size = size;
  this.toppings = toppings;
  this.pizzaPrice = 0;
}

Pizza.prototype.price = function() {
  if (this.size === "Small") {
    this.pizzaPrice += 2;
  }
  else if (this.size === "Medium") {
    this.pizzaPrice += 3;
  }
  else if (this.size === "Large") {
    this.pizzaPrice += 4;
  }
  if (this.toppings === "Cheese") {
    this.pizzaPrice += 3;
  }

  else if (this.toppings === "Cheese" && this.toppings === "Peanut Butter") {
    this.pizzaPrice += 10;
    console.log("hey");

  }

  else if (this.toppings === "Vegetarian") {
    this.pizzaPrice += 2;
  }
  else if (this.toppings === "Supreme") {
    this.pizzaPrice += 4;
  }
  else if (this.toppings === "Pepperoni") {
    this.pizzaPrice += 3;
  }

return this.pizzaPrice;
}

$(document).ready(function(){
  $("form#pizza").submit(function(event){
    event.preventDefault();

    var size = $("input[type=radio][name=size]:checked").val();
    var toppings = $("input[type=checkbox][name=toppings]:checked").val();
    var newPizza = new Pizza(size,toppings,pizzaPrice);
    newPizza.price();

    $("#responses").append("
" + "You ordered a " + newPizza.size + " " + newPizza.toppings + " pizza. " + " Your total price is " + newPizza.pizzaPrice + "
");

      });
    });

<!DOCTYPE html>

    <title>Pizza Pizza</title>
    <link href="css/bootstrap.css" rel="stylesheet" type="text/css">
    <link href="css/styles.css" rel="stylesheet" type="text/css">

Pizza Toppings

      <form id="pizza">

What size would you like your pizza:

          <input type="radio" name="size" value="Small">Small.

          <input type="radio" name="size" value="Medium">Medium.

          <input type="radio" name="size" value="Large">Large.

Which toppings would you like

          <input type="checkbox" name="toppings" value="Cheese">Cheese.

          <input type="checkbox" name="toppings" value="Vegetarian">Vegetarian.

          <input type="checkbox" name="toppings" value="Supreme">Supreme.

          <input type="checkbox" name="toppings" value="Pepperoni">Pepperoni.

          <input type="checkbox" name="toppings" value="Fruit">Fruit.

          <input type="checkbox" name="toppings" value="Bacon">Bacon.

          <input type="checkbox" name="toppings" value="Artichoke">Artichoke.

          <input type="checkbox" name="toppings" value="Peanut Butter">Peanut butter.

       <button type="submit">Let's get your order</button>
      </form>

Body:
Firstly, you need to get values of all checked toppings in an array, currently you are getting only the first one. Then you need to add prices for each topping selected while calculating the price. you can use indexOf for this:

var pizzaPrice = 0;

function Pizza(size,toppings,pizzaPrice) {
  this.size = size;
  this.toppings = toppings;
  this.pizzaPrice = 0;
}

Pizza.prototype.price = function() {
  if (this.size === "Small") {
    this.pizzaPrice += 2;
  }
  else if (this.size === "Medium") {
    this.pizzaPrice += 3;
  }
  else if (this.size === "Large") {
    this.pizzaPrice += 4;
  }
  if (this.toppings.indexOf("Cheese") >= 0) {
    this.pizzaPrice += 3;
  }

  if (this.toppings.indexOf("Peanut Butter") >= 0) {
    this.pizzaPrice += 10;

  }

  if (this.toppings.indexOf("Vegetarian") >= 0) {
    this.pizzaPrice += 2;
  }
  if (this.toppings.indexOf("Supreme") >= 0) {
    this.pizzaPrice += 4;
  }
  if (this.toppings.indexOf("Pepperoni") >= 0) {
    this.pizzaPrice += 3;
  }

return this.pizzaPrice;
}

$(document).ready(function(){
  $("form#pizza").submit(function(event){
    event.preventDefault();

    var size = $("input[type=radio][name=size]:checked").val();
    var toppings = [];
    $("input[type=checkbox][name=toppings]:checked").each(function(){
           toppings.push($(this).val());
    });
    var newPizza = new Pizza(size,toppings,pizzaPrice);
    newPizza.price();

    $("#responses").append("<li>" + "You ordered a " + newPizza.size + " " + newPizza.toppings + " pizza. " + " Your total price is " + newPizza.pizzaPrice + "</li>");

      });
    });

<!DOCTYPE html>
<html>
  <head>
    <title>Pizza Pizza</title>
    <link href="css/bootstrap.css" rel="stylesheet" type="text/css">
    <link href="css/styles.css" rel="stylesheet" type="text/css">
    <script src="js/jquery-3.2.0.js"></script>
    <script src="js/scripts.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  </head>
  <body>
    <div class="container">
      <div class="jumbotron">
        <h2>Pizza Toppings</h2>
      </div>
      <form id="pizza">
        <div class="form-group">
          <p>What size would you like your pizza:</p>
          <input type="radio" name="size" value="Small">Small.<br>
          <input type="radio" name="size" value="Medium">Medium.<br>
          <input type="radio" name="size" value="Large">Large.<br>
        </div>
        <div class="form-group">
          <p>Which toppings would you like</p>
          <input type="checkbox" name="toppings" value="Cheese">Cheese.<br>
          <input type="checkbox" name="toppings" value="Vegetarian">Vegetarian.<br>
          <input type="checkbox" name="toppings" value="Supreme">Supreme.<br>
          <input type="checkbox" name="toppings" value="Pepperoni">Pepperoni.<br>
          <input type="checkbox" name="toppings" value="Fruit">Fruit.<br>
          <input type="checkbox" name="toppings" value="Bacon">Bacon.<br>
          <input type="checkbox" name="toppings" value="Artichoke">Artichoke.<br>
          <input type="checkbox" name="toppings" value="Peanut Butter">Peanut butter.<br>
        </div>
       <button type="submit">Let's get your order</button>
      </form>
      <ul id="responses">
      </ul>
    </div>
  </body>
</html>


问:
Need to pick up the SUM OF Tax Amount for the highest Sequence number Per Year, Per SSN, Per employer
Consider Employee table:

```<code>Employerid ssn  year  Seqnumber     q1taxamt   q2taxamt     q3taxamt     q4taxamt
1004       101  2013    1             2000       0            0             0
1004       101  2013    2             2000       100          0             0
1004       101  2013    3             2000       100          200           0
1004       101  2013    4             2000       100          200           300
1004       102  2013    1             3000       0            0             0
1004       102  2013    2             3000       200          0             0
1004       102  2013    3             3000       200          300           0
1004       102  2013    4             3000       200          300           400
1004       102  2013    5             3000       200          300           400
</code>```

Here the  transformation rule is we need to pick the highest Seqnumber with respect to each ssn per year per

Employerid and the amounts.

i.e for 10004 for sum(q1taxamt) is 2000 +3000 = 5000

The Logic is ssn 101 has highest seq number of 4 and ssn 102 has highest seq number of 5 so we need to pick those values wrt to employerid

Example:
Want to check for q1taxamt: 2000 +3000 = 5000

Want to check for q4taxamt: 300 +400 = 700

output must be:

```<code>Employerid  YEAR     q1taxamt   q2taxamt     q3taxamt     q4taxamt
10004        2013     5000        300          500           700
</code>```

The below query is generating wrong result:

```<code>Select
    Sum(E1.q1taxamt) q1taxamt,
    Sum(E1.q2taxamt) q2taxamt,
    Sum(E1.q3taxamt) q3taxamt,
    Sum(E1.q4taxamt) q4taxamt,
    E1.Employerid,
    E1.YEAR
from Employee E1
join
(
    select
        E.Employerid,
        MAX(E.seqnumber) seqnumber,
        E.YEAR
    from Employee E
    group by E.Employerid,E.SSn,E.year
)E2
on E1.Employerid=E2.Employerid
AND E1.YEAR=E2.YEAR
and E1.seqnumber=E2.Taxseqnumber
</code>```

答:
You missing SSN join predicate between E1 and E2 thats why you are getting wrong result. I think this might be faster than Row_Number method.

```<code>Select
    Sum(E1.q1taxamt) q1taxamt,
    Sum(E1.q2taxamt) q2taxamt,
    Sum(E1.q3taxamt) q3taxamt,
    Sum(E1.q4taxamt) q4taxamt,
    E1.Employerid,
    E1.YEAR
from Employee E1
join
(
    select
        E.Employerid,
        E.SSn,
        MAX(E.seqnumber) seqnumber,
        E.YEAR
    from Employee E
    group by E.Employerid,E.SSn,E.year
)E2
on E1.Employerid=E2.Employerid
AND E1.YEAR=E2.YEAR
AND E1.SSN = E2.SSN --Here
and E1.seqnumber=E2.Taxseqnumber
</code>```

Body:
Consider Employee table:

Employerid ssn  year  Seqnumber     q1taxamt   q2taxamt     q3taxamt     q4taxamt
1004       101  2013    1             2000       0            0             0
1004       101  2013    2             2000       100          0             0
1004       101  2013    3             2000       100          200           0
1004       101  2013    4             2000       100          200           300
1004       102  2013    1             3000       0            0             0
1004       102  2013    2             3000       200          0             0
1004       102  2013    3             3000       200          300           0
1004       102  2013    4             3000       200          300           400
1004       102  2013    5             3000       200          300           400

Here the  transformation rule is we need to pick the highest Seqnumber with respect to each ssn per year per

Employerid and the amounts.

i.e for 10004 for sum(q1taxamt) is 2000 +3000 = 5000

The Logic is ssn 101 has highest seq number of 4 and ssn 102 has highest seq number of 5 so we need to pick those values wrt to employerid

Example:
Want to check for q1taxamt: 2000 +3000 = 5000

Want to check for q4taxamt: 300 +400 = 700

output must be:

Employerid  YEAR     q1taxamt   q2taxamt     q3taxamt     q4taxamt
10004        2013     5000        300          500           700

The below query is generating wrong result:

Select
    Sum(E1.q1taxamt) q1taxamt,
    Sum(E1.q2taxamt) q2taxamt,
    Sum(E1.q3taxamt) q3taxamt,
    Sum(E1.q4taxamt) q4taxamt,
    E1.Employerid,
    E1.YEAR
from Employee E1
join
(
    select
        E.Employerid,
        MAX(E.seqnumber) seqnumber,
        E.YEAR
    from Employee E
    group by E.Employerid,E.SSn,E.year
)E2
on E1.Employerid=E2.Employerid
AND E1.YEAR=E2.YEAR
and E1.seqnumber=E2.Taxseqnumber

Body:
You missing SSN join predicate between E1 and E2 thats why you are getting wrong result. I think this might be faster than Row_Number method.

Select
    Sum(E1.q1taxamt) q1taxamt,
    Sum(E1.q2taxamt) q2taxamt,
    Sum(E1.q3taxamt) q3taxamt,
    Sum(E1.q4taxamt) q4taxamt,
    E1.Employerid,
    E1.YEAR
from Employee E1
join
(
    select
        E.Employerid,
        E.SSn,
        MAX(E.seqnumber) seqnumber,
        E.YEAR
    from Employee E
    group by E.Employerid,E.SSn,E.year
)E2
on E1.Employerid=E2.Employerid
AND E1.YEAR=E2.YEAR
AND E1.SSN = E2.SSN --Here
and E1.seqnumber=E2.Taxseqnumber


问:
Update a single object property in an array of objects based on the current value with redux
Within my state, I have an array of objects that have a few descriptive properties, a quantity, and a unique id. The data within this object comes back from an API response, and within my action creator, I check the state to see if it exists already and if so dispatch an increment action for my reducer. This is what my action creator looks like:

```<code>export const getProductDetails = upc => (dispatch, getState) => {
const state = getState();
const products = state.table.products;
if (_find(products, upc) !== undefined) {
  dispatch({ type: INCREMENT_QUANTITY, payload: upc });
} else {
axios
  .post(<--POST TO ENDPOINT-->) }
  })
  .then(res => {
    dispatch({ type: POST_UPC, payload: res.data });
  })
  .catch(err => {
    errorHandler(dispatch, err.response, AUTH_ERROR);
  });
 }
};
</code>```

My reducer for this case looks is structured as so:

```<code>case INCREMENT_QUANTITY:
  return {
    ...state,
    products: state.products.map(product => {
      action.payload === product.upc
        ? { ...product, quantity: product.quantity + 1 }
        : product;
    })
  };
</code>```

I based this reducer logic from this
this excellent response, but for some reason when the action is dispatched, the duplicate product is overwritten as null instead of incrementing the quantity as expected. I'm still trying to learn redux right now, so forgive my ignorance. Ideally, I'd like to avoid bringing in a library or package just to increment a value. What exactly am I missing within my reducer?

答:
You're not returning anything in your map callback, you're creating a block thus you don't get the intended result. Instead, omit the brackets { … }:

```<code>products: state.products.map(product =>
  action.payload === product.upc
    ? { ...product, quantity: product.quantity + 1 }
    : product;
);
</code>```

This will use arrow function syntax to implicitly return the result of the ternary operator.

Body:
Within my state, I have an array of objects that have a few descriptive properties, a quantity, and a unique id. The data within this object comes back from an API response, and within my action creator, I check the state to see if it exists already and if so dispatch an increment action for my reducer. This is what my action creator looks like:

export const getProductDetails = upc => (dispatch, getState) => {
const state = getState();
const products = state.table.products;
if (_find(products, upc) !== undefined) {
  dispatch({ type: INCREMENT_QUANTITY, payload: upc });
} else {
axios
  .post(<--POST TO ENDPOINT-->) }
  })
  .then(res => {
    dispatch({ type: POST_UPC, payload: res.data });
  })
  .catch(err => {
    errorHandler(dispatch, err.response, AUTH_ERROR);
  });
 }
};

My reducer for this case looks is structured as so:

case INCREMENT_QUANTITY:
  return {
    ...state,
    products: state.products.map(product => {
      action.payload === product.upc
        ? { ...product, quantity: product.quantity + 1 }
        : product;
    })
  };

I based this reducer logic from this
this excellent response, but for some reason when the action is dispatched, the duplicate product is overwritten as null instead of incrementing the quantity as expected. I'm still trying to learn redux right now, so forgive my ignorance. Ideally, I'd like to avoid bringing in a library or package just to increment a value. What exactly am I missing within my reducer?

Body:
You're not returning anything in your map callback, you're creating a block thus you don't get the intended result. Instead, omit the brackets { … }:

products: state.products.map(product =>
  action.payload === product.upc
    ? { ...product, quantity: product.quantity + 1 }
    : product;
);

This will use arrow function syntax to implicitly return the result of the ternary operator.


问:
Why does this confuse the F# compiler's type inference?
No problem here:

```<code>module Seq =
    let private rnd = Random Environment.TickCount

    let random =
        fun (items : 'T seq) ->
            let count = Seq.length items
            items |> Seq.nth (rnd.Next count)
</code>```

The signature of Seq.random is items:seq<'T> -> 'T.  All good.

Yes, I know that I could just let random items = [...], that is not the point.

The point is that items is suddenly constrained to be type seq<obj> when I do this:

```<code>module Seq =
    let random =
        let rnd = Random Environment.TickCount
        fun (items : 'T seq) ->
            let count = Seq.length items
            items |> Seq.nth (rnd.Next count)
</code>```

... i.e. I add the Random object as a closure.  If I hover over random, Intellisense shows me that the signature has become items:seq<obj> -> obj.

Interestingly, if I select the code and hit [Alt]+[Enter] to execute it in F# Interactive, the signature shows as seq<'a> -> 'a.  WTH??

So, what's going on, here?  Why the confusion and inconsistency in type inference?

答:
This is due to the so-called Value Restriction. Cutting a long story short, syntactical values cannot be generic, because it might break things when mutations occur, and the compiler cannot always reliably prove immutability. (note that, even though random is a function semantically, it is still a value syntactically, and that's what matters)

But sometimes the compiler can prove immutability. This is why your first example works: when the right side of a let is a straight up lambda expression, the compiler can tell with certainty that it is immutable, and so it lets this pass.

Another example would be let x = [] - here the compiler can see that the nil list [] is immutable. On the other hand, let x = List.append [] [] won't work, because the compiler can't prove immutability in that case.

This "relaxation" of value restriction is done in F# on a case-by-case basis. F# compiler only goes as far as to handle a few special cases: literals, lambda expressions, etc., but it doesn't have a full-fledged mechanism for proving immutability in general. This is why, once you step outside of those special cases, you're not allowed to have generic values.

You can technically defeat this by adding explicit type arguments. Logically, this tells the compiler "Yes, I know it's a generic value, and that's what I meant for it to be".

```<code>let random<'t> : seq<'t> -> 't =
    let rnd = Random Environment.TickCount
    fun items ->
        let count = Seq.length items
        items |> Seq.nth (rnd.Next count)

let x = random [1;2;3]
</code>```

But this will still not do what you want, because behind the scenes, such definition will be compiled to a parameterless generic method, and every time you reference such "value", the method will be called and return you a new function - with a brand new rnd baked in for every call. In other words, the above code will be equivalent to this:

```<code>let random() =
    let rnd = Random Environment.TickCount
    fun items ->
        let count = Seq.length items
        items |> Seq.nth (rnd.Next count)

let x = random() [1;2;3]
</code>```

Body:
No problem here:

module Seq =
    let private rnd = Random Environment.TickCount

    let random =
        fun (items : 'T seq) ->
            let count = Seq.length items
            items |> Seq.nth (rnd.Next count)

The signature of Seq.random is items:seq<'T> -> 'T.  All good.

Yes, I know that I could just let random items = [...], that is not the point.

The point is that items is suddenly constrained to be type seq<obj> when I do this:

module Seq =
    let random =
        let rnd = Random Environment.TickCount
        fun (items : 'T seq) ->
            let count = Seq.length items
            items |> Seq.nth (rnd.Next count)

... i.e. I add the Random object as a closure.  If I hover over random, Intellisense shows me that the signature has become items:seq<obj> -> obj.

Interestingly, if I select the code and hit [Alt]+[Enter] to execute it in F# Interactive, the signature shows as seq<'a> -> 'a.  WTH??

So, what's going on, here?  Why the confusion and inconsistency in type inference?

Body:
This is due to the so-called Value Restriction. Cutting a long story short, syntactical values cannot be generic, because it might break things when mutations occur, and the compiler cannot always reliably prove immutability. (note that, even though random is a function semantically, it is still a value syntactically, and that's what matters)

But sometimes the compiler can prove immutability. This is why your first example works: when the right side of a let is a straight up lambda expression, the compiler can tell with certainty that it is immutable, and so it lets this pass.

Another example would be let x = [] - here the compiler can see that the nil list [] is immutable. On the other hand, let x = List.append [] [] won't work, because the compiler can't prove immutability in that case.

This "relaxation" of value restriction is done in F# on a case-by-case basis. F# compiler only goes as far as to handle a few special cases: literals, lambda expressions, etc., but it doesn't have a full-fledged mechanism for proving immutability in general. This is why, once you step outside of those special cases, you're not allowed to have generic values.

You can technically defeat this by adding explicit type arguments. Logically, this tells the compiler "Yes, I know it's a generic value, and that's what I meant for it to be".

let random<'t> : seq<'t> -> 't =
    let rnd = Random Environment.TickCount
    fun items ->
        let count = Seq.length items
        items |> Seq.nth (rnd.Next count)

let x = random [1;2;3]

But this will still not do what you want, because behind the scenes, such definition will be compiled to a parameterless generic method, and every time you reference such "value", the method will be called and return you a new function - with a brand new rnd baked in for every call. In other words, the above code will be equivalent to this:

let random() =
    let rnd = Random Environment.TickCount
    fun items ->
        let count = Seq.length items
        items |> Seq.nth (rnd.Next count)

let x = random() [1;2;3]


问:
How to spawn object over network as child
Hi I'm having an issue where I'm trying to spawn an object for all players into a scroll view. On the host, they get spawned properly, but on the remote clients that have joined, the objects are just placed into the hierarchy.

I'm using NetworkServer.Spawn to do so, and I can't seem to find a solution.

Any help?

Thanks

答:
In the Unity Docs, it states the parameters of NetworkServer.spawn.

Parameters

obj   - Game object with NetworkIdentity to spawn.

I'm going to go on a limb here and say that you don't have a Network Identity on your object, which is why it spawns in your host but not in your remote clients.

Either that or as @DanRayson stated...you don't have a Network Transform.