问:
exception handling in plsql procedure to handle insert giving unique constraint
I have an sql having multiple inserts but when I am running it is giving unique constraint for the first insert....and sql is skipping the other inserts.Can u help me with the exception handling for this scenario.  </p>

答:
You need to wrap your insert statements in a BEGIN/END block with an exception handler to catch the DUP_VAL_ON_INDEX exception. There you can do whatever you need to do or just ignore the error.

```<code>BEGIN
    -- first insert
    BEGIN
        Insert into myTab(ID,NAME) values (1,'name1');
    EXCEPTION
        when DUP_VAL_ON_INDEX then
            null; -- do something or ignore the error
    END;

    -- second insert
    BEGIN
        Insert into myTab(ID,NAME) values (2,'name2');
    EXCEPTION
        when DUP_VAL_ON_INDEX then
            null; -- do something or ignore the error
    END;
END;
</code>```

Body:
You need to wrap your insert statements in a BEGIN/END block with an exception handler to catch the DUP_VAL_ON_INDEX exception. There you can do whatever you need to do or just ignore the error.

BEGIN
    -- first insert
    BEGIN
        Insert into myTab(ID,NAME) values (1,'name1');
    EXCEPTION
        when DUP_VAL_ON_INDEX then
            null; -- do something or ignore the error
    END;

    -- second insert
    BEGIN
        Insert into myTab(ID,NAME) values (2,'name2');
    EXCEPTION
        when DUP_VAL_ON_INDEX then
            null; -- do something or ignore the error
    END;
END;


来源: stackexchange

问:
GraphQL-js mutation optional arguments
how would I achieve a GraphQL Mutation in nodeJS that has arguments which are optional?

My current mutation has an args field, but all the arguments are mandatory. Since I couldn't find anything in the documentation, I don't know how or if this is possible.

This is my current code:

```<code>const fakeDB = {
    count: 0
};

const schema = new GraphQLSchema({
    query: //...
    mutation: new GraphQLObjectType({
        name: 'adsF',
        fields: {
            updateCount: {
                type: GraphQLInt,
                args: {
                    count: { type: GraphQLInt } // I want to make this argument optional
                },
                resolve: (value, { count }) => {
                    // Catch if count is null or undefined
                    if (count == null) {
                        // If so just update with default
                        fakeDB.count = 5;
                    } else {
                        fakeDB.count = count
                    }
                    return fakeDB.count;
                })
            }
        }
    })
});
</code>```

Thanks for Your help!

答: Types in GraphQL are nullable by default. That means that the way you have specified the mutation at the moment makes the count optional. If you wanted a field to be mandatory you need to mark it as non null</p>

ContentLicense: CC BY-SA 3.0

Title: GraphQL-js mutation optional arguments

Body:
how would I achieve a GraphQL Mutation in nodeJS that has arguments which are optional?

My current mutation has an args field, but all the arguments are mandatory. Since I couldn't find anything in the documentation, I don't know how or if this is possible.

This is my current code:

const fakeDB = {
    count: 0
};

const schema = new GraphQLSchema({
    query: //...
    mutation: new GraphQLObjectType({
        name: 'adsF',
        fields: {
            updateCount: {
                type: GraphQLInt,
                args: {
                    count: { type: GraphQLInt } // I want to make this argument optional
                },
                resolve: (value, { count }) => {
                    // Catch if count is null or undefined
                    if (count == null) {
                        // If so just update with default
                        fakeDB.count = 5;
                    } else {
                        fakeDB.count = count
                    }
                    return fakeDB.count;
                })
            }
        }
    })
});

Thanks for Your help!


问:
Cocoa UI Analytics
I’d like to track user interaction inside of my OS X application. The goal is incredibly simple to start:

Track how many times a specific item is clicked on

I’m using sparkle to enable application updates and am able to send additional information through a delegate method. Read: Sending (client side) and storing (server side) the data isn’t an issue.

My Questions:

How can I cleanly attach a “hook” into my system to store an event (like “clicked”)

Where do I store the stats on the local machine? (incrementing plist property?)

Does such system already exist?

Really appreciate the help. I’m rather new to Cocoa so please ask if you need further clarification on any of the above points.

Thanks again,

Dustin

答:
If you set a view as the first responder methods such as -(void)mouseDown:(NSEvent *)theEvent will be fired on the required clicks. All you do, is increment your variable/plist/whatever in that method. Have a look at
this.

ContentLicense: CC BY-SA 2.5

Title: Cocoa UI Analytics


问:
Allowing special characters in URLRequest httpBody
here is what I am doing to post request to server.

```<code>    let urlStr = "someurl"
    var request = URLRequest(url: URL(string: urlStr)!)
    request.addValue(accessToken!, forHTTPHeaderField: "accessToken")

    let postString = self.makeRequestString(dict: paramDict)
    request.httpMethod = "POST"
    request.httpBody = postString.data(using: .utf8, allowLossyConversion: true)
    let session = URLSession.shared

    request.timeoutInterval = 60

    let task = session.dataTask(with: request) { data, response, error in

       }
</code>```

here is method description of  makeRequestString

```<code>func makeRequestString(dict:Dictionary<String,AnyObject>) -> String {
    let data = try? JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted)
    let str = String(data: data!, encoding: .utf8)
    return "key=" + str!
}
</code>```

The issue I am facing is if my dictionary parameters has some special characters in it like !@#$%^&() then server is not accepting the request and giving some undesired result.

Any suggestions or pointers in correcting code where I am missing anything.

EDIT:

For now I get desired response from the server if I change the following line of code in my method makeRequestString

```<code>    let str = String(data: data!, encoding: .utf8)?.replacingOccurrences(of: "&", with: "%26")
</code>```

答:
Try with this encoding:</p>

```<code>request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)!
</code>```

Body:
here is what I am doing to post request to server.

    let urlStr = "someurl"
    var request = URLRequest(url: URL(string: urlStr)!)
    request.addValue(accessToken!, forHTTPHeaderField: "accessToken")

    let postString = self.makeRequestString(dict: paramDict)
    request.httpMethod = "POST"
    request.httpBody = postString.data(using: .utf8, allowLossyConversion: true)
    let session = URLSession.shared

    request.timeoutInterval = 60

    let task = session.dataTask(with: request) { data, response, error in

       }

here is method description of  makeRequestString

func makeRequestString(dict:Dictionary<String,AnyObject>) -> String {
    let data = try? JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted)
    let str = String(data: data!, encoding: .utf8)
    return "key=" + str!
}

The issue I am facing is if my dictionary parameters has some special characters in it like !@#$%^&() then server is not accepting the request and giving some undesired result.

Any suggestions or pointers in correcting code where I am missing anything.

EDIT:

For now I get desired response from the server if I change the following line of code in my method makeRequestString

    let str = String(data: data!, encoding: .utf8)?.replacingOccurrences(of: "&", with: "%26")

Body:
Try with this encoding:

request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)!


问:
PolymerJs Dom-repeat: observe array's sub property
I am using an array in a dom-repeat in polymerjs. Say, the array is items and each element of array is item. Then if there is a property item.errors for every item . I want to call a function every time any of the item.errors change. How to do that?</p>

答:
Observer, e.g.</p>

```<code>observers: [
    "errorObserver(items.errors)"
]
errorObserver: function(itemErrors) {}
</code>```

Body:
Observer, e.g.

observers: [
    "errorObserver(items.errors)"
]
errorObserver: function(itemErrors) {}


问:
pugjs template submit button not working
I'm using pugjs for html templating. But a template with submit button not working at all.

template code:

```<code>extends layout
block content
    div.col-md-12.col-xs-12
        h1 #{html.title}
        - var content = html.contents
        div
            != content
        if(comments.length>0)
            each comment in comments
                div.col-md-12.col-xs-12.comment
                    div
                          !=comment.content
        div.col-md-12.col-xs-12.add
            form(action="/comment/"+message.postId method="post")
                div.input-group
                    input.form-control(type="text" placeholder="Comment:" name="comment" required)
                    span.input-group-btn
                        btn.btn.btn-secondary(type="submit") Submit
</code>```

Other pages using the same layout works, but this template's submit button does not work at all. No network activity was recorded when I clicked the button.

When using the inspection tools to inspect the page,it shows that the form action was correctly binded like
    <form action="/comment/-1669628617" method="post">

答:
Probably you should use input or button tags for that.

<input type="submit" value="Submit">
<button type="submit" form="form-name" value="Submit">Submit</button>```

Body:
I'm using pugjs for html templating. But a template with submit button not working at all.

template code:

extends layout
block content
    div.col-md-12.col-xs-12
        h1 #{html.title}
        - var content = html.contents
        div
            != content
        if(comments.length>0)
            each comment in comments
                div.col-md-12.col-xs-12.comment
                    div
                          !=comment.content
        div.col-md-12.col-xs-12.add
            form(action="/comment/"+message.postId method="post")
                div.input-group
                    input.form-control(type="text" placeholder="Comment:" name="comment" required)
                    span.input-group-btn
                        btn.btn.btn-secondary(type="submit") Submit

Other pages using the same layout works, but this template's submit button does not work at all. No network activity was recorded when I clicked the button.

When using the inspection tools to inspect the page,it shows that the form action was correctly binded like
    <form action="/comment/-1669628617" method="post">


问:
How to line up each word in a list so that entries start at the same point horizontally?
Here's an example I've changed slightly from a previous SO question:
http://jsfiddle.net/tPjQR/72/

ol {
    font-family: Georgia, serif;
}
ol span {
    font-family: Arial, sans-serif;
    font-size: 17px
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ol>
    <li><span>Entry one</span></li>
    <li><span>Entry two</span></li>
    <li><span>Entrye three</span></li>
    <li><span>Entry five</span></li>
    <li><span>Entry six</span></li>
    <li><span>Entry Long Long Long Long Long Long Long Long Long Long Long Long Long Long Long Long Long</span></li>
</ol></code>```

I would like to line up the columns so that, no matter how much text is in one column, the first characters of each column will be lined up.

E.g.

not

```<code>Entry one
Entry two
Entrye three
Entry five
Entry six
</code>```

rather

```<code>Entry  one
Entry  two
Entrye three
Entry  five
Entry  six
</code>```

Is there a way to do this with list items, or do I need to use a table?

答:
What you are trying to do is not possible beacuse the DOM object rendering is based on its architructure and what you want to do is possible through the tables.

* {
    font-family: Georgia, serif;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
<tr><td>Entry</td><td>One</td></tr>
<tr><td>Entry</td><td>Two</td></tr>
<tr><td>Entry Xyz</td><td>Three</td></tr>
<tr><td>Entry</td><td>Four</td></tr>
<tr><td>Entry</td><td>Five</td></tr>
<tr><td>Entry</td><td>Six</td></tr>
</table></code>```

Body:
Here's an example I've changed slightly from a previous SO question:
http://jsfiddle.net/tPjQR/72/

ol {
    font-family: Georgia, serif;
}
ol span {
    font-family: Arial, sans-serif;
    font-size: 17px
}

Entry one

Entry two

Entrye three

Entry five

Entry six

Entry Long Long Long Long Long Long Long Long Long Long Long Long Long Long Long Long Long

I would like to line up the columns so that, no matter how much text is in one column, the first characters of each column will be lined up.

E.g.

not

Entry one
Entry two
Entrye three
Entry five
Entry six

rather

Entry  one
Entry  two
Entrye three
Entry  five
Entry  six

Is there a way to do this with list items, or do I need to use a table?

Body:
What you are trying to do is not possible beacuse the DOM object rendering is based on its architructure and what you want to do is possible through the tables.

* {
    font-family: Georgia, serif;
}

<table>
<tr><td>Entry</td><td>One</td></tr>
<tr><td>Entry</td><td>Two</td></tr>
<tr><td>Entry Xyz</td><td>Three</td></tr>
<tr><td>Entry</td><td>Four</td></tr>
<tr><td>Entry</td><td>Five</td></tr>
<tr><td>Entry</td><td>Six</td></tr>
</table>


问:
Passing value from one component to another
How to pass values from one component to another component through service or any other way, when components are not parent to child or child to parent?</p>

答:
You can user a service to pass datas from a component to an other.

data.service.ts :

```<code>@Injectable()
export class DataService {
   private data: string;

   constructor() {
      this.data = 'myData'
   }

   getData(): Promise<string> {
     return Promise.resolve(this.data);
   }

   setData(data: string) {
      this.data = data;
   }
}
</code>```

component A :

```<code>export class ComponentA {

   private data: string;
   constructor(private dataService: dataService) {
      this.getData();
   }

   getData() {
     this.dataService.getData().subscribe(
       (data) => {
         this.data = data;
       }
     )
   }

   setData(data: string) {
     this.dataService.setData(data);
   }
}
</code>```

component B :

```<code>export class ComponentB {

   private data: string;
   constructor(private dataService: dataService) {
      this.getData();
   }

   getData() {
     this.dataService.getData().subscribe(
       (data) => {
         this.data = data;
       }
     )
   }

   setData(data: string) {
     this.dataService.setData(data);
  }
}
</code>```

Body:
You can user a service to pass datas from a component to an other.

data.service.ts :

@Injectable()
export class DataService {
   private data: string;

   constructor() {
      this.data = 'myData'
   }

   getData(): Promise<string> {
     return Promise.resolve(this.data);
   }

   setData(data: string) {
      this.data = data;
   }
}

component A :

export class ComponentA {

   private data: string;
   constructor(private dataService: dataService) {
      this.getData();
   }

   getData() {
     this.dataService.getData().subscribe(
       (data) => {
         this.data = data;
       }
     )
   }

   setData(data: string) {
     this.dataService.setData(data);
   }
}

component B :

export class ComponentB {

   private data: string;
   constructor(private dataService: dataService) {
      this.getData();
   }

   getData() {
     this.dataService.getData().subscribe(
       (data) => {
         this.data = data;
       }
     )
   }

   setData(data: string) {
     this.dataService.setData(data);
  }
}


问:
Simplest way to listen to another server?
I have server A (Windows, C#.NET), which  needs to send an alert/signal to server B (Linux, Java, Apache) everytime a certain process is done. I need to do this using a method call from .NET. What would be the easiest way to do this? I am thinking of setting up a web server on server B on some port which would listen to requests from server A. But how should I go about this? I am new to Java and have no experience with writing java web services, and I need to get this up quick, that is why I want to do this as easy as possible.</p>

答: Since you say apache: Use WebClient</p>

Body: Since you say apache: Use WebClient


问:
Why firebase enter the ondatachange in my query
I have very simple database

```<code>TokenAdmin:
---xccsaccxvkkgmcdds :
     ---token: "cxcxzcfsdfdsfdsfs"
     ---uid: "xccsaccxvkkgmcdds"
---hjhbnghtfgdgdgdffg :
     ---token: "vhghtytyryyr"
     ---uid: "hjhbnghtfgdgdgdffg"
</code>```

Now in my code I want to check and execute some code only if it find uid equal to "hjhbnghtfgdgdgdffg"
Here is my code :

```<code> mDatabase.child("TokenAdmin").orderByChild("uid").equalTo(mycurrUser.getUID()).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

               //say here toast "A"
            } else {
                //toast "B"
            }

        }
        @Override
        public void onCancelled(DatabaseError databaseError) {

            // ...

        }

    });
</code>```

Now I run the code with  mycurrUser.getUID() value set to "xxx" which I don't have listed in the database. I expected the code output was toast B, but instead I always get toast A, which in my understanding, it has found the value in the db. How to fix this, where did I do wrong ?

答:
You need to use something like this:

```<code>mDatabase.child("TokenAdmin").orderByChild("uid").equalTo(mycurrUser.getUID()).addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if(dataSnapshot.exists()) {
            //Toast A
        } else {
            //Toast B
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
});
</code>```

Hope it helps.

Body:
I have very simple database

TokenAdmin:
---xccsaccxvkkgmcdds :
     ---token: "cxcxzcfsdfdsfdsfs"
     ---uid: "xccsaccxvkkgmcdds"
---hjhbnghtfgdgdgdffg :
     ---token: "vhghtytyryyr"
     ---uid: "hjhbnghtfgdgdgdffg"

Now in my code I want to check and execute some code only if it find uid equal to "hjhbnghtfgdgdgdffg"
Here is my code :

 mDatabase.child("TokenAdmin").orderByChild("uid").equalTo(mycurrUser.getUID()).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

               //say here toast "A"
            } else {
                //toast "B"
            }

        }
        @Override
        public void onCancelled(DatabaseError databaseError) {

            // ...

        }

    });

Now I run the code with  mycurrUser.getUID() value set to "xxx" which I don't have listed in the database. I expected the code output was toast B, but instead I always get toast A, which in my understanding, it has found the value in the db. How to fix this, where did I do wrong ?

Body:
You need to use something like this:

mDatabase.child("TokenAdmin").orderByChild("uid").equalTo(mycurrUser.getUID()).addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if(dataSnapshot.exists()) {
            //Toast A
        } else {
            //Toast B
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
});

Hope it helps.


问:
Ionic 2 to 3 Update Gulp ERROR
So i upgraded to Ionic 3 and got this Error when i perform ionic serve:

[ERROR] Gulpfile not found: .\gulpfile.js
          You can set the gulpFile attribute in ionic.config.json for custom
          Gulpfile locations, otherwise the default Ionic Gulpfile can be
          downloaded from
          https://github.com/ionic-team/ionic-app-base/blob/master/gulpfile.js

```<code>    Or, if you no longer use gulp, you can remove the CLI Gulp Plugin:

    npm uninstall --save-dev --save-exact @ionic/cli-plugin-gulp@latest
</code>```

My Package.json looks like this:

{   "dependencies": {
      "@angular/common": "4.1.2",
      "@angular/compiler": "4.1.2",
      "@angular/compiler-cli": "4.1.2",
      "@angular/core": "4.1.2",
      "@angular/forms": "4.1.2",
      "@angular/http": "4.1.2",
      "@angular/platform-browser": "4.1.2",
      "@angular/platform-browser-dynamic": "4.1.2",
      "@ionic-native/core": "3.10.2",
      "@ionic-native/splash-screen": "3.10.2",
      "@ionic-native/status-bar": "3.10.2",
      "@ionic/storage": "2.0.1",
      "gulp-concat": "^2.6.1",
      "gulp-install": "^1.1.0",
      "ionic-angular": "3.3.0",
      "ionicons": "3.0.0",
      "rxjs": "5.1.1",
      "sw-toolbox": "3.6.0",
      "zone.js": "0.8.11"   },   "devDependencies": {
      "@ionic/app-scripts": "1.3.7",
      "@ionic/cli-plugin-gulp": "1.0.1",
      "@ionic/cli-plugin-ionic-angular": "1.3.1",
      "gulp": "github:gulpjs/gulp#4.0",
      "typescript": "2.3.3",
      "@ionic/cli-plugin-cordova": "1.0.0",

```<code>"del": "2.2.0",

"gulp-watch": "4.3.5",
"ionic-gulp-browserify-typescript": "^2.0.0",
"ionic-gulp-fonts-copy": "^1.0.0",
"ionic-gulp-html-copy": "^1.0.0",
"ionic-gulp-sass-build": "^1.0.0",
"ionic-gulp-scripts-copy": "^2.0.0",
"run-sequence": "1.1.5"   },   "name": "FancyApplication",   "description": "myFancyApplication: An Ionic project",
</code>```

"cordovaPlugins": [
      "cordova-plugin-device",
      "cordova-plugin-console",
      "cordova-plugin-whitelist",
      "cordova-plugin-splashscreen",
      "cordova-plugin-statusbar",
      "ionic-plugin-keyboard"   ],

"cordovaPlatforms": [
      {
        "platform": "android",
        "locator": "browser"
      }   ] }

I already tried to install/uninstall gulp globally also tried to link it. The gulpfile is in the main application folder where it always was. Never moved it.

Did i forgot something to update ? Do i have to move something or do i have to set the attribute? If so i would like to know how.

Thanks already for any help!

答:
i solved my problem.

npm update

npm remove gulp-sass

npm install gulp-sass --save-dev

Title: Ionic 2 to 3 Update Gulp ERROR

Body:
So i upgraded to Ionic 3 and got this Error when i perform ionic serve:

[ERROR] Gulpfile not found: .\gulpfile.js
          You can set the gulpFile attribute in ionic.config.json for custom
          Gulpfile locations, otherwise the default Ionic Gulpfile can be
          downloaded from
          https://github.com/ionic-team/ionic-app-base/blob/master/gulpfile.js

    Or, if you no longer use gulp, you can remove the CLI Gulp Plugin:

    npm uninstall --save-dev --save-exact @ionic/cli-plugin-gulp@latest

My Package.json looks like this:

{   "dependencies": {
      "@angular/common": "4.1.2",
      "@angular/compiler": "4.1.2",
      "@angular/compiler-cli": "4.1.2",
      "@angular/core": "4.1.2",
      "@angular/forms": "4.1.2",
      "@angular/http": "4.1.2",
      "@angular/platform-browser": "4.1.2",
      "@angular/platform-browser-dynamic": "4.1.2",
      "@ionic-native/core": "3.10.2",
      "@ionic-native/splash-screen": "3.10.2",
      "@ionic-native/status-bar": "3.10.2",
      "@ionic/storage": "2.0.1",
      "gulp-concat": "^2.6.1",
      "gulp-install": "^1.1.0",
      "ionic-angular": "3.3.0",
      "ionicons": "3.0.0",
      "rxjs": "5.1.1",
      "sw-toolbox": "3.6.0",
      "zone.js": "0.8.11"   },   "devDependencies": {
      "@ionic/app-scripts": "1.3.7",
      "@ionic/cli-plugin-gulp": "1.0.1",
      "@ionic/cli-plugin-ionic-angular": "1.3.1",
      "gulp": "github:gulpjs/gulp#4.0",
      "typescript": "2.3.3",
      "@ionic/cli-plugin-cordova": "1.0.0",

"del": "2.2.0",

"gulp-watch": "4.3.5",
"ionic-gulp-browserify-typescript": "^2.0.0",
"ionic-gulp-fonts-copy": "^1.0.0",
"ionic-gulp-html-copy": "^1.0.0",
"ionic-gulp-sass-build": "^1.0.0",
"ionic-gulp-scripts-copy": "^2.0.0",
"run-sequence": "1.1.5"   },   "name": "FancyApplication",   "description": "myFancyApplication: An Ionic project",

"cordovaPlugins": [
      "cordova-plugin-device",
      "cordova-plugin-console",
      "cordova-plugin-whitelist",
      "cordova-plugin-splashscreen",
      "cordova-plugin-statusbar",
      "ionic-plugin-keyboard"   ],

"cordovaPlatforms": [
      {
        "platform": "android",
        "locator": "browser"
      }   ] }

I already tried to install/uninstall gulp globally also tried to link it. The gulpfile is in the main application folder where it always was. Never moved it.

Did i forgot something to update ? Do i have to move something or do i have to set the attribute? If so i would like to know how.

Thanks already for any help!


问:
I wanna make a textbox that can collect the answer and bind with search url
I am trying to create a textbox that can collect the answer and bind it with the search url.

My problems are that I can type in the text box, but it won't the script.

The error being displayed is:

Uncaught TypeError: document.getElementById is not a constructor

at myFunction (index.html:23)

at HTMLButtonElement.onclick (index.html:14)

Tested in Chrome and Maxthon 5

And Here is my Code
https://hastebin.com/uqelimudoc.xml

答:
The issue is in line no 23.

```<code>var z = new document.getElementById("version").innerHTML;
</code>```

Remove the new keyword and execute the code.

Going through the code in line no 21

```<code>var y = document.getElementById("myForm").elements[0].value;
</code>```

This line works but going further assign unique ID's for elements and get elements using that ID. As the code gets lengthier, ID's will help you a lot.

Use this for reference https://www.w3schools.com/

After getting familiar with JavaScript go through jQuery

working fiddle is here

Body:
The issue is in line no 23.

var z = new document.getElementById("version").innerHTML;

Remove the new keyword and execute the code.

Going through the code in line no 21

var y = document.getElementById("myForm").elements[0].value;

This line works but going further assign unique ID's for elements and get elements using that ID. As the code gets lengthier, ID's will help you a lot.

Use this for reference https://www.w3schools.com/

After getting familiar with JavaScript go through jQuery

working fiddle is here


问:
Add images in ListView in Fragment - Navigation Drawer
In my app i am using Navigation Drawer with ListView in Fragment. And i successfully implemented the list view inside Fragment. but now i want to do add image in this list.How to do it. Need some example

This is my Vegall.java file

```<code>import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class Vegall extends Fragment {
    private ListView lv;
    private static String[] vegalllist = {"Vegetables1", "Vegetables2"};

    public static Vegall newInstance()
    {
        Vegall vegall =new Vegall();
        return vegall;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View rootView=inflater.inflate(R.layout.vegall, null);

        lv = (ListView) rootView.findViewById(R.id.vegall_lv);

        lv.setAdapter(new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1, vegalllist));

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l){
                //Toast.makeText(getActivity(), vegcat[i], Toast.LENGTH_SHORT).show();
                selectItem(i);

            }
        });
        return rootView;
    }
    private void selectItem(int i){
        Fragment newFragment;
        FragmentTransaction transaction = getFragmentManager().beginTransaction();

        switch (i){
            case 0:
                newFragment = new Vegetables1();
                transaction.replace(R.id.containerID, newFragment);
                transaction.addToBackStack(null);
                transaction.commit();
                break;

            case 1:
                Intent intent = new Intent(getActivity(), Vegetables2.class);
                startActivity(intent);
                break;
        }
    }
    @Override
    public String toString(){
        return "Home";
    }

}
</code>```

This is my Vegall.xml

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ListView
        android:id="@+id/vegall_lv"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>
</code>```

答:
You have to make customized adapter like BaseAdapter  instead of arrayadapter  and add the images in the drawable folder.
Have a look into the BaseAdapter tutorial
 http://theopentutorials.com/tutorials/android/listview/android-custom-listview-with-image-and-text-using-baseadapter/</p>

Body:
In my app i am using Navigation Drawer with ListView in Fragment. And i successfully implemented the list view inside Fragment. but now i want to do add image in this list.How to do it. Need some example

This is my Vegall.java file

import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class Vegall extends Fragment {
    private ListView lv;
    private static String[] vegalllist = {"Vegetables1", "Vegetables2"};

    public static Vegall newInstance()
    {
        Vegall vegall =new Vegall();
        return vegall;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View rootView=inflater.inflate(R.layout.vegall, null);

        lv = (ListView) rootView.findViewById(R.id.vegall_lv);

        lv.setAdapter(new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1, vegalllist));

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l){
                //Toast.makeText(getActivity(), vegcat[i], Toast.LENGTH_SHORT).show();
                selectItem(i);

            }
        });
        return rootView;
    }
    private void selectItem(int i){
        Fragment newFragment;
        FragmentTransaction transaction = getFragmentManager().beginTransaction();

        switch (i){
            case 0:
                newFragment = new Vegetables1();
                transaction.replace(R.id.containerID, newFragment);
                transaction.addToBackStack(null);
                transaction.commit();
                break;

            case 1:
                Intent intent = new Intent(getActivity(), Vegetables2.class);
                startActivity(intent);
                break;
        }
    }
    @Override
    public String toString(){
        return "Home";
    }

}

This is my Vegall.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ListView
        android:id="@+id/vegall_lv"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>


问:
sql table partition best practice
I have done a table partition for existing table.
can you advice on the best optimization of this since my transaction log is getting full on running the below table partition query</p>

```<code>BEGIN TRANSACTION

CREATE PARTITION FUNCTION [pfDimHeader_HIST](nvarchar(6)) AS RANGE LEFT FOR VALUES ( N'201401', N'201501', N'201601', N'201602', N'201603', N'201604', N'201605', N'201606', N'201607', N'201608', N'201609', N'201610', N'201611', N'201612', N'201701', N'201702', N'201703', N'201704', N'201705', N'201706', N'201707')

CREATE PARTITION SCHEME [psDimHeader_HIST] AS PARTITION [pfDimHeader_HIST] TO ([PRIMARY], [PRIMARY], [PRIMARY], [PRIMARY], [PRIMARY], [PRIMARY], [PRIMARY], [PRIMARY], [PRIMARY], [PRIMARY], [PRIMARY], [PRIMARY], [PRIMARY], [PRIMARY], [PRIMARY], [PRIMARY], [PRIMARY], [PRIMARY], [PRIMARY], [PRIMARY], [PRIMARY], [PRIMARY])

SET ANSI_PADDING ON

CREATE CLUSTERED INDEX [ClusteredIndex_on_psDimHeader_HIST_636336478362776789] ON [cdw].[DimHeader_HIST]
(
    [ReportingPeriod]
)WITH (SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF) ON [psDimHeader_HIST]([ReportingPeriod])

DROP INDEX [ClusteredIndex_on_psDimHeader_HIST_636336478362776789] ON [cdw].[DimHeader_HIST]

COMMIT TRANSACTION
</code>```

答:
[0] Generally speaking, to lower impact on transaction log, transactions should be smaller. So, instead of using a single transaction to create index and then to deleted (the same index; it makes no sense to me - at least in this moment) you could use two separate transactions (for example).

[1] I would use following query

```<code>SELECT db.name, db.log_reuse_wait_desc
FROM sys.databases db
WHERE db.name = DB_NAME()
</code>```

to see the main cause of log size increase.

[2] The most probable causes are [2.1] database recovery model is FULL/BULK LOGGED(same as FULL recovery model but optimised for BULK operations) and [2.2] missing of log backups and/or [2.3] low frequency log backups. In this case I would create a maintenance plan for backup transaction log or [if exists] I would execute the SQL Agent job.

Note: if the answer isn't clear enough please comment.

Title: sql table partition best practice

Body:
I have done a table partition for existing table.
can you advice on the best optimization of this since my transaction log is getting full on running the below table partition query

BEGIN TRANSACTION

CREATE PARTITION FUNCTION [pfDimHeader_HIST](nvarchar(6)) AS RANGE LEFT FOR VALUES ( N'201401', N'201501', N'201601', N'201602', N'201603', N'201604', N'201605', N'201606', N'201607', N'201608', N'201609', N'201610', N'201611', N'201612', N'201701', N'201702', N'201703', N'201704', N'201705', N'201706', N'201707')

CREATE PARTITION SCHEME [psDimHeader_HIST] AS PARTITION [pfDimHeader_HIST] TO ([PRIMARY], [PRIMARY], [PRIMARY], [PRIMARY], [PRIMARY], [PRIMARY], [PRIMARY], [PRIMARY], [PRIMARY], [PRIMARY], [PRIMARY], [PRIMARY], [PRIMARY], [PRIMARY], [PRIMARY], [PRIMARY], [PRIMARY], [PRIMARY], [PRIMARY], [PRIMARY], [PRIMARY], [PRIMARY])

SET ANSI_PADDING ON

CREATE CLUSTERED INDEX [ClusteredIndex_on_psDimHeader_HIST_636336478362776789] ON [cdw].[DimHeader_HIST]
(
    [ReportingPeriod]
)WITH (SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF) ON [psDimHeader_HIST]([ReportingPeriod])

DROP INDEX [ClusteredIndex_on_psDimHeader_HIST_636336478362776789] ON [cdw].[DimHeader_HIST]

COMMIT TRANSACTION

Body:
[0] Generally speaking, to lower impact on transaction log, transactions should be smaller. So, instead of using a single transaction to create index and then to deleted (the same index; it makes no sense to me - at least in this moment) you could use two separate transactions (for example).

[1] I would use following query

SELECT db.name, db.log_reuse_wait_desc
FROM sys.databases db
WHERE db.name = DB_NAME()

to see the main cause of log size increase.

[2] The most probable causes are [2.1] database recovery model is FULL/BULK LOGGED(same as FULL recovery model but optimised for BULK operations) and [2.2] missing of log backups and/or [2.3] low frequency log backups. In this case I would create a maintenance plan for backup transaction log or [if exists] I would execute the SQL Agent job.

Note: if the answer isn't clear enough please comment.


问:
return search results if enter button is clicked
I have been struggling trying to trigger the button if enter button is pressed. I have tried trigger() and click() and no luck. I cannot figure out why it will not execute and the search button does work correctly when clicked with a mouse, but not when an enter button is pressed.

$(document).ready(function() {

    //alert("this");
    //$('#btnsearch').trigger('click');

$("#txtsearch").keyup(function(event){
    if(event.keyCode == 13){
        $("#btnsearch").click();
    }
});
    $('#btnsearch').click(function(event) {
        var searchText = $('#txtsearch').val();
        $.ajax({

            url: domain + "",
            type: "GET",
            headers: {
              Accept: "application/json;odata=verbose"
            },
            success: function(data) {

              $.each(data.d.results, function(index, item) {
                $('#tblResult tbody').append('
' + 'href = "' + item.Details + '">' + item.Title + '
');

              }

            )};

          event.preventDefault();

        });
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form class="navbar-form navbar-right">
                <div id="" class="navbar-form navbar-right">
                    <div class="input-group">
                        <input id="txtsearch" type="text" class="form-control" placeholder="Search" />
                        <div class="input-group-btn">
                            <button id="btnsearch" class="btn btn-default" type="button">
                                <i class="glyphicon glyphicon-search"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </form></code>```

答:
This is the event handler for pressing enter:

$(document).keypress(function(e) {
    if(e.which == 13) {
        alert('You pressed enter!');
    }
});```
</div>
</div>
</p>

<p>Edit:
You should run your click in a function so you can reuse it for the 2 scenarios (keyup and click) like:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function() {

    //alert("this");
    //$('#btnsearch').trigger('click');

  function submitSearch(){
    var searchText = $('#txtsearch').val();
    $.ajax({
      url: domain + "",
      type: "GET",
      headers: {
        Accept: "application/json;odata=verbose"
      },
      success: function(data) {
        $.each(data.d.results, function(index, item) {
          $('#tblResult tbody').append('<tr><td style="">' + 'href = "' + item.Details + '">' + item.Title + '</td></tr>');
        }
      )};
  }

  $('#btnsearch').click(function(event) {
    submitSearch();
    event.preventDefault();
  });

  $(document).keyup(function(event){
      submitSearch();
  });

});</code>```

Body:
I have been struggling trying to trigger the button if enter button is pressed. I have tried trigger() and click() and no luck. I cannot figure out why it will not execute and the search button does work correctly when clicked with a mouse, but not when an enter button is pressed.

$(document).ready(function() {

    //alert("this");
    //$('#btnsearch').trigger('click');

$("#txtsearch").keyup(function(event){
    if(event.keyCode == 13){
        $("#btnsearch").click();
    }
});
    $('#btnsearch').click(function(event) {
        var searchText = $('#txtsearch').val();
        $.ajax({

            url: domain + "",
            type: "GET",
            headers: {
              Accept: "application/json;odata=verbose"
            },
            success: function(data) {

              $.each(data.d.results, function(index, item) {
                $('#tblResult tbody').append('
' + '' + item.Title + '
');

              }

            )};

          event.preventDefault();

        });
    });
});

<form class="navbar-form navbar-right">

                        <input id="txtsearch" type="text" class="form-control" placeholder="Search" />

                            <button id="btnsearch" class="btn btn-default" type="button">

                            </button>

            </form>

Body:
This is the event handler for pressing enter:

$(document).keypress(function(e) {
    if(e.which == 13) {
        alert('You pressed enter!');
    }
});

Edit:
You should run your click in a function so you can reuse it for the 2 scenarios (keyup and click) like:

$(document).ready(function() {

    //alert("this");
    //$('#btnsearch').trigger('click');

  function submitSearch(){
    var searchText = $('#txtsearch').val();
    $.ajax({
      url: domain + "",
      type: "GET",
      headers: {
        Accept: "application/json;odata=verbose"
      },
      success: function(data) {
        $.each(data.d.results, function(index, item) {
          $('#tblResult tbody').append('<tr><td style="">' + '<a href = "' + item.Details + '">' + item.Title + '</td></tr>');
        }
      )};
  }

  $('#btnsearch').click(function(event) {
    submitSearch();
    event.preventDefault();
  });

  $(document).keyup(function(event){
      submitSearch();
  });

});


问:
Mounting a symlinked folder in vagrant & virtualbox
Okay, so here is my problem:
I use vagrant with VirtualBox. The host is Windows 8.1, the guest is Ubuntu (64bit). I am trying to use a symlinked windows folder created by

```<code>mklink /j somefolder someotherfolder
</code>```

as synced folder in Vagrant. In my Vagrantfile I have

```<code># disable the default synced folder
config.vm.synced_folder ".", "/vagrant", disabled: true
# sync my desired folder
config.vm.synced_folder "./somefolder", "/vagrant"
</code>```

Unfortunately this does not work, but gives the following error:

```<code>Failed to mount folders in Linux guest. This is usually because
the "vboxsf" file system is not available. Please verify that
the guest additions are properly installed in the guest and
can work properly. The command attempted was:

mount -t vboxsf -o uid=`id -u vagrant`,gid=`getent group vagrant | cut -d: -f3`
vagrant /vagrant
mount -t vboxsf -o uid=`id -u vagrant`,gid=`id -g vagrant` vagrant /vagrant

The error output from the last command was:

stdin: is not a tty
/sbin/mount.vboxsf: mounting failed with the error: Invalid argument
</code>```

Before you ask: Guest additions are installed, and mounting regular folders works flawlessly.

Is there a way to use symlinked directories as synced folders in vagrant with vbox?

Thanks for your help!

答: Cut the folder to where you need it from the VM, after that create the junction (or symlink) at the original location.</p>

Body:
Okay, so here is my problem:
I use vagrant with VirtualBox. The host is Windows 8.1, the guest is Ubuntu (64bit). I am trying to use a symlinked windows folder created by

mklink /j somefolder someotherfolder

as synced folder in Vagrant. In my Vagrantfile I have

# disable the default synced folder
config.vm.synced_folder ".", "/vagrant", disabled: true
# sync my desired folder
config.vm.synced_folder "./somefolder", "/vagrant"

Unfortunately this does not work, but gives the following error:

Failed to mount folders in Linux guest. This is usually because
the "vboxsf" file system is not available. Please verify that
the guest additions are properly installed in the guest and
can work properly. The command attempted was:

mount -t vboxsf -o uid=`id -u vagrant`,gid=`getent group vagrant | cut -d: -f3`
vagrant /vagrant
mount -t vboxsf -o uid=`id -u vagrant`,gid=`id -g vagrant` vagrant /vagrant

The error output from the last command was:

stdin: is not a tty
/sbin/mount.vboxsf: mounting failed with the error: Invalid argument

Before you ask: Guest additions are installed, and mounting regular folders works flawlessly.

Is there a way to use symlinked directories as synced folders in vagrant with vbox?

Thanks for your help!


问:
Elasticsearch reserve node
I have 4-nodes elasticsearch cluster (1 of them is client, es 1.3.5).

It works fine most of time, but sometimes on peaks gone out of resources.
Can i add any reserve node in cluster that will be enabled only when peaks occured (1-2 day in months) and will be disabled all other time? Does it makes sense?

答:
There's no notion of backup/standby/reserve node. You monitor the cluster activity and you start a new node when the peak happens. If you would have used a newer version you could have used Marvel (the monitoring part) and Watcher (the alerting part) to get notified on the peaks. At that point you could have started the new node.

There are also examples of watches that alert you in case of high memory or cpu usage: https://www.elastic.co/guide/en/watcher/current/watching-marvel-data.html#watching-memory-usage

Title: Elasticsearch reserve node


问:
How to set cookie domain and path with Spring boot
In Tomcat, we can do it like this:

```<code><Context useHttpOnly="true" sessionCookiePath="/"sessionCookieDomain=".XXXX.com"/>
</code>```

I want to share the cookie for second level domain with Spring Boot, how to do it?

答:
My solution was to define a CookieSerializer bean and provide the domain pattern that fits my setup.

Like this: Spring Session - Custom Cookie

Body:
In Tomcat, we can do it like this:

<Context useHttpOnly="true" sessionCookiePath="/"sessionCookieDomain=".XXXX.com"/>

I want to share the cookie for second level domain with Spring Boot, how to do it?


问:
Why am I getting a NoSuchMethodError in this code?
```<code>import java.util.*;

public class Lab50 {
    public static void main(String[] args) {
        System.out.println("Student Information");
        TreeSet set = new TreeSet();
        set.add(new Student(87, "Andy"));
        set.add(new Student(99, "Bichel"));
        set.add(new Student(12, "Chuck"));
        set.add(new Student(45, "David"));

        Iterator it = set.iterator();
        while (it.hasNext()) {
            System.out.println(it.next());
        }
    }
}

class Student implements Comparable {
    int sid;
    String name;

    Student(int sid, String name) {
        this.sid = sid;
        this.name = name;
    }

    public int compareTo(Object obj) {
        if (obj instanceof Student) {
            Student st = (Student) obj;
            return this.sid - st.sid;
        }
        return 0;
    }

    public String toString() {
        return sid + "\t" + name;
    }
}
</code>```

I am getting the error on the first line of adding the element of Andy. Following is the error message on the console :

Exception in thread "main" java.lang.NoSuchMethodError: Student.(ILjava/lang/String;)V
          at Lab50.main(Lab50.java:6)

答:
The javadoc for that exception is pretty clear:

Thrown when a particular method cannot be found.

This means: at runtime, when your JVM executes a class; the JVM wants to invoke a certain method. It looks into the corresponding class - and it doesn't find a method with that name/signature in that class. In your case, the compiled Student.class simply does not contain a constructor that fits the intended usage.

That happens when you have A.java and B.java; and A is calling something in B. Then you change B.java, and re-compile it; but you forgot to recompile A.java.

In other words: you ran into a inconsistency where some A class is trying to use a method of some B class that B.class actually does not contain.

The real answer here: make sure that your compiled output is always consistent. Meaning: recompile everything together.

In the "real" world, such things are handled by build systems for example. In other words: if you want to avoid such issues, either use an IDE that keeps track of all your classes in your project and tells you about such problems when you insert them into your code; or learn how to use a build system such as ant, maven, gradle, ... that allows to "clean" up your build output, or that automatically re-compiles all artifacts that need re-compiling.

Body:
import java.util.*;

public class Lab50 {
    public static void main(String[] args) {
        System.out.println("Student Information");
        TreeSet set = new TreeSet();
        set.add(new Student(87, "Andy"));
        set.add(new Student(99, "Bichel"));
        set.add(new Student(12, "Chuck"));
        set.add(new Student(45, "David"));

        Iterator it = set.iterator();
        while (it.hasNext()) {
            System.out.println(it.next());
        }
    }
}

class Student implements Comparable {
    int sid;
    String name;

    Student(int sid, String name) {
        this.sid = sid;
        this.name = name;
    }

    public int compareTo(Object obj) {
        if (obj instanceof Student) {
            Student st = (Student) obj;
            return this.sid - st.sid;
        }
        return 0;
    }

    public String toString() {
        return sid + "\t" + name;
    }
}

I am getting the error on the first line of adding the element of Andy. Following is the error message on the console :

Exception in thread "main" java.lang.NoSuchMethodError: Student.(ILjava/lang/String;)V
          at Lab50.main(Lab50.java:6)


问:
angular2 - How to I use md-error with a custom validator
How to I use md-error with a custom validator?  Required works..great! but what about my custom validator?

```<code><md-input-container>
     <input mdInput formControlName="etr" >

     <md-error *ngIf="WHAT!!!!!!!!!!!!!!!!!!!">
               ETR must be >=0 or <1
     </md-error>
     <md-error *ngIf="myForm.controls['etr'].hasError('required')">
            <strong>required</strong>
     </md-error>

 </md-input-container>
</code>```

Here is my type script:

```<code>     this.myForm = fb.group({
         etr: [,[Validators.required,ModelValidators.validEtr]],

     })
</code>```

I does show the error underline but how do I show the message?

I tried this but did not work:

```<code>    *ngIf="myForm.controls['etr'].hasError('validEtr')"
</code>```

Below is my validator.ts file

```<code>import { FormControl } from '@angular/forms';

export class ModelValidators{

static validEtr(control: FormControl){
        var valid: any;
        valid=null;
        if (control.value>=0 && control.value<1){
            valid = true;
        }
        return valid ? null : { validLambda: true };

    }
}
</code>```

答:
validLambda is the error type returned from your custom validator when validate failed.

so the solution is as below:

```<code>*ngIf="myForm.controls['etr'].hasError('validLambda')"
</code>```

Body:
How to I use md-error with a custom validator?  Required works..great! but what about my custom validator?

<md-input-container>
     <input mdInput formControlName="etr" >

     <md-error *ngIf="WHAT!!!!!!!!!!!!!!!!!!!">
               ETR must be >=0 or <1
     </md-error>
     <md-error *ngIf="myForm.controls['etr'].hasError('required')">
            required
     </md-error>

 </md-input-container>

Here is my type script:

     this.myForm = fb.group({
         etr: [,[Validators.required,ModelValidators.validEtr]],

     })

I does show the error underline but how do I show the message?

I tried this but did not work:

    *ngIf="myForm.controls['etr'].hasError('validEtr')"

Below is my validator.ts file

import { FormControl } from '@angular/forms';

export class ModelValidators{

static validEtr(control: FormControl){
        var valid: any;
        valid=null;
        if (control.value>=0 && control.value<1){
            valid = true;
        }
        return valid ? null : { validLambda: true };

    }
}

Body:
validLambda is the error type returned from your custom validator when validate failed.

so the solution is as below:

*ngIf="myForm.controls['etr'].hasError('validLambda')"


问:
Java Server socket stuck on accept call (Android Client, Java Server)
Below I have put a fragment of code to help understand my problem. I have a server code, works fine for the first time the client loads and sends a packet. After the first packet is received, the server is stuck on "accept".

I have wireshark configured for this port, and the server is getting those packets. I just wonder why accept wont return more than once. Its driving me nuts.

Server Code

```<code> public class DAPool implements Runnable {
 private ServerSocket serverSocket;
 private ArrayList<DA> pool;
 private LinkedList<Socket> clientConnQ;
 public DAPool(int newPoolSize, int serverPort) {
  try {
     serverSocket = new ServerSocket(serverPort, 500, InetAddress.getByName("127.0.0.1"));
  } catch (IOException e) {
     e.printStackTrace();
     return;
  }
  poolSize = newPoolSize;
  clientConnQ = new LinkedList<Socket>();
  pool = new ArrayList<DA>(poolSize);
                DA deviceThread;
  for (int threads = 0; threads < poolSize; threads++) {
     deviceThread = new DA();
     connPool.add(deviceThread);
     deviceThread.start();
  }
 }
 public void run() {
    while (true) {
       Socket incomingSocket;
       try {
           incomingSocket = serverSocket.accept();
       } catch (IOException e) {
           e.printStackTrace();
       return;
     }
     insertNewConnToQ(incomingSocket);
  }
 }

 private class DA extends Thread {
  private Socket clientSocket;
  private ObjectInputStream inputObjectStream;
  public DA() {
  }
  public void run() {
   while (true) {

    while (clientConnQ.isEmpty()) {
     synchronized (clientConnQ) {
      try {
       clientConnQ.wait();
      } catch (InterruptedException ignored) {
       ignored.printStackTrace();
      }
     }
    }
    synchronized (clientConnQ) {
     clientSocket = (Socket) clientConnQ.removeFirst();
     try {
      inputObjectStream = new ObjectInputStream(clientSocket.getInputStream());
     } catch (IOException e) {
      e.printStackTrace();
      return;
     }
        // Do something useful here
                                    }
    }
   }
  }
 }
</code>```

Client Code

```<code>public class SendQueue extends Thread {
 LinkedList<Message> requestQ;
 Message sendRequest, requestMessage;

 Socket clientSocket;
 OutputStream outputStream;
 ObjectOutputStream objectOutputStream;

 public SendQueue(Socket newClientSocket) {
  requestQ = new LinkedList<Message>();
  clientSocket = newClientSocket;
 }

 public void run() {
  while (true) {
   synchronized (requestQ) {
    while (requestQ.isEmpty()) {
     try {
      requestQ.wait();
     } catch (InterruptedException ignored) {
      ignored.printStackTrace();
     }
    }
    sendRequest = requestQ.removeFirst();
   }
   try {
    outputStream = clientSocket.getOutputStream();
    objectOutputStream = new ObjectOutputStream(outputStream);
    objectOutputStream.writeObject(sendRequest);
    objectOutputStream.flush();
    outputStream.flush();
   } catch (IOException e) {
    e.printStackTrace();
   } catch (RuntimeException e) {
    e.printStackTrace();
   }
  }
 }

 public int sendRequest(Message message) {
  synchronized (requestQ) {
   requestQ.addLast(message);
   requestQ.notify();
  }
  return 0;
 }
}
</code>```

答:
Ok, if I got a $ for everytime I asked a silly question :)

Here goes. A client socket connects and thats when a server receives a accept call. For some silly reason I was waiting on accept for receiving further data from the client. Infact, I should just wait for something on the "stream" and then process the stream. I should not wait on the accept for that connection.

Accept is to be called to "connect" to the socket, not to receive data continuously.

Thanks for your all your help. You forced me to think about thread synchronization, the design, sockets in general and finally arrive that the solution.

Fantastic responses people. Thanks.
Siddharth

Body:
Below I have put a fragment of code to help understand my problem. I have a server code, works fine for the first time the client loads and sends a packet. After the first packet is received, the server is stuck on "accept".

I have wireshark configured for this port, and the server is getting those packets. I just wonder why accept wont return more than once. Its driving me nuts.

Server Code

 public class DAPool implements Runnable {
 private ServerSocket serverSocket;
 private ArrayList<DA> pool;
 private LinkedList<Socket> clientConnQ;
 public DAPool(int newPoolSize, int serverPort) {
  try {
     serverSocket = new ServerSocket(serverPort, 500, InetAddress.getByName("127.0.0.1"));
  } catch (IOException e) {
     e.printStackTrace();
     return;
  }
  poolSize = newPoolSize;
  clientConnQ = new LinkedList<Socket>();
  pool = new ArrayList<DA>(poolSize);
                DA deviceThread;
  for (int threads = 0; threads < poolSize; threads++) {
     deviceThread = new DA();
     connPool.add(deviceThread);
     deviceThread.start();
  }
 }
 public void run() {
    while (true) {
       Socket incomingSocket;
       try {
           incomingSocket = serverSocket.accept();
       } catch (IOException e) {
           e.printStackTrace();
       return;
     }
     insertNewConnToQ(incomingSocket);
  }
 }

 private class DA extends Thread {
  private Socket clientSocket;
  private ObjectInputStream inputObjectStream;
  public DA() {
  }
  public void run() {
   while (true) {

    while (clientConnQ.isEmpty()) {
     synchronized (clientConnQ) {
      try {
       clientConnQ.wait();
      } catch (InterruptedException ignored) {
       ignored.printStackTrace();
      }
     }
    }
    synchronized (clientConnQ) {
     clientSocket = (Socket) clientConnQ.removeFirst();
     try {
      inputObjectStream = new ObjectInputStream(clientSocket.getInputStream());
     } catch (IOException e) {
      e.printStackTrace();
      return;
     }
        // Do something useful here
                                    }
    }
   }
  }
 }

Client Code

public class SendQueue extends Thread {
 LinkedList<Message> requestQ;
 Message sendRequest, requestMessage;

 Socket clientSocket;
 OutputStream outputStream;
 ObjectOutputStream objectOutputStream;

 public SendQueue(Socket newClientSocket) {
  requestQ = new LinkedList<Message>();
  clientSocket = newClientSocket;
 }

 public void run() {
  while (true) {
   synchronized (requestQ) {
    while (requestQ.isEmpty()) {
     try {
      requestQ.wait();
     } catch (InterruptedException ignored) {
      ignored.printStackTrace();
     }
    }
    sendRequest = requestQ.removeFirst();
   }
   try {
    outputStream = clientSocket.getOutputStream();
    objectOutputStream = new ObjectOutputStream(outputStream);
    objectOutputStream.writeObject(sendRequest);
    objectOutputStream.flush();
    outputStream.flush();
   } catch (IOException e) {
    e.printStackTrace();
   } catch (RuntimeException e) {
    e.printStackTrace();
   }
  }
 }

 public int sendRequest(Message message) {
  synchronized (requestQ) {
   requestQ.addLast(message);
   requestQ.notify();
  }
  return 0;
 }
}


问:
How to split string in ruby
I have a string:

```<code>"1 chocolate bar at 25"
</code>```

and I want to split this string into:

```<code> [1, "chocolate bar", 25]
</code>```

I don't know how to write a regex for this split. And I wanted to know whether there are any other functions to accomplish it.

答:
You could use scan with a regex:

```<code>"1 chocolate bar at 25".scan(/^(\d+) ([\w ]+) at (\d+)$/).first
</code>```

The above method doesn't work if item_name has special characters.

If you want a more robust solution, you can use split:

```<code>number1, *words, at, number2 = "1 chocolate bar at 25".split
p [number1, words.join(' '), number2]
# ["1", "chocolate bar", "25"]
</code>```

number1 is the first part, number2 is the last one, at the second to last, and *words is an array with everything in-between. number2 is guaranteed to be the last word.

This method has the advantage of working even if there are numbers in the middle, " at " somewhere in the string or if prices are given as floats.

Title: How to split string in ruby

Body:
I have a string:

"1 chocolate bar at 25"

and I want to split this string into:

 [1, "chocolate bar", 25]

I don't know how to write a regex for this split. And I wanted to know whether there are any other functions to accomplish it.

Body:
You could use scan with a regex:

"1 chocolate bar at 25".scan(/^(\d+) ([\w ]+) at (\d+)$/).first

The above method doesn't work if item_name has special characters.

If you want a more robust solution, you can use split:

number1, *words, at, number2 = "1 chocolate bar at 25".split
p [number1, words.join(' '), number2]
# ["1", "chocolate bar", "25"]

number1 is the first part, number2 is the last one, at the second to last, and *words is an array with everything in-between. number2 is guaranteed to be the last word.

This method has the advantage of working even if there are numbers in the middle, " at " somewhere in the string or if prices are given as floats.


问:
404 return doesn't work when refresh with nginx and angular
I'm using nginx with Angular and want to return a 404 when a user go to page /error404
I did the redirection with angular routing module with this :

```<code>{ path: 'error404', component: PageNotFoundComponent},
{ path: '**', redirectTo: 'error404', pathMatch: 'full'}
</code>```

and to return the 404 with nginx I try this in the conf file :

```<code>error_page 404 /error404;
location  /error404 {
 internal;
}
</code>```

or just :

```<code>error_page 404 =301 /error404;
</code>```

When I go directly to /error404 I get a 404 not found and not my page but when i use the angular redirection with random url i go well on the /error404 and print my page

答:
Angular router does not redirect to an url but to a given component.

You should create a component to handle 404 pages, it'll also save webserver load by not requesting it.

see this for further information : https://angular.io/guide/router#wildcard-route

Body:
I'm using nginx with Angular and want to return a 404 when a user go to page /error404
I did the redirection with angular routing module with this :

{ path: 'error404', component: PageNotFoundComponent},
{ path: '**', redirectTo: 'error404', pathMatch: 'full'}

and to return the 404 with nginx I try this in the conf file :

error_page 404 /error404;
location  /error404 {
 internal;
}

or just :

error_page 404 =301 /error404;

When I go directly to /error404 I get a 404 not found and not my page but when i use the angular redirection with random url i go well on the /error404 and print my page


问:
Sending JSON with enum data types
I am trying to send a json with a data type that is a enum according to the ebay documantion here:

http://developer.ebay.com/devzone/rest/api-ref/inventory/types/OperatingHours.html

The field in question is the dayOfWeekEnum, which I tried sending in my JSON several ways:

```<code>{"dayOfWeekEnum": "FRIDAY"}
{"dayOfWeekEnum": 0}
{"dayOfWeekEnum": {"dayOfWeekEnum": "FRIDAY"}}
</code>```

And none of them didn't work. I alwyas get the message saying it could not serialize the field dayOfWeekEnum:

```<code>[{"errorId"=>2004, "domain"=>"ACCESS", "category"=>"REQUEST", "message"=>"Invalid request", "longMessage"=>"The request has errors. For help, see the documentation for this API.", "parameters"=>[{"name"=>"reason", "value"=>"Could not serialize field [operatingHours.dayOfWeekEnum]"}]}]
</code>```

I am assuming ebay runs a Java api, so how should I send my JSON enum info properly?

答: I know from experience that eBay's documentation can be wrong when it comes to the names of fields. Have you tried passing dayOfWeek instead of dayOfWeekEnum?

Title: Sending JSON with enum data types

Body:
I am trying to send a json with a data type that is a enum according to the ebay documantion here:

http://developer.ebay.com/devzone/rest/api-ref/inventory/types/OperatingHours.html

The field in question is the dayOfWeekEnum, which I tried sending in my JSON several ways:

{"dayOfWeekEnum": "FRIDAY"}
{"dayOfWeekEnum": 0}
{"dayOfWeekEnum": {"dayOfWeekEnum": "FRIDAY"}}

And none of them didn't work. I alwyas get the message saying it could not serialize the field dayOfWeekEnum:

[{"errorId"=>2004, "domain"=>"ACCESS", "category"=>"REQUEST", "message"=>"Invalid request", "longMessage"=>"The request has errors. For help, see the documentation for this API.", "parameters"=>[{"name"=>"reason", "value"=>"Could not serialize field [operatingHours.dayOfWeekEnum]"}]}]

I am assuming ebay runs a Java api, so how should I send my JSON enum info properly?


问:
Is it possible to Serialize QSettings and then recover them?
I would like to pass the settings saved with QSetting through two instances of an application, for example through a socket.

I could not see any function in the official documentation. The only thing I read is for example this post

Save Configuration Settings to XML file in QT?

But I do not want to save the settings in a XML file, for example in Windows I want to continue using the Registry.

I just want to collect all the settings, and pass them through a socket. And the receiver could check the settings and eventually substitute its own settings with the received ones.

Well, I suppose I could do something similar using QSettings::allKeys(), checking all the values, convert to strings, etc etc...but do you know if there is some native function in Qt already implemented?

Thanks to everyone in advance

答:
Best solution that I found:

Create a QMap from QSettings

```<code>QMap<QString, QVariant> keysValuesPairs;
QStringList keys = settings.allKeys();
QStringListIterator it(keys);
while ( it.hasNext() )
{
    QString currentKey = it.next();
    keysValuesPairs.insert(currentKey, settings.value(currentKey));
}
</code>```

And then write it in a QJson with the function (see the official documentation http://doc.qt.io/qt-5/qjsonobject.html)

QJsonObject::fromVariantMap

then in the other side recover it with

QJsonObject::toVariantMap()

and rewrite the settings

```<code>for ( int i = 0; i < keys.size(); i++ )
{
    settings.setValue( keys.at(i), keysValuesPairsMap.value(keys.at(i)) );
}
</code>```

Body:
Best solution that I found:

Create a QMap from QSettings

QMap<QString, QVariant> keysValuesPairs;
QStringList keys = settings.allKeys();
QStringListIterator it(keys);
while ( it.hasNext() )
{
    QString currentKey = it.next();
    keysValuesPairs.insert(currentKey, settings.value(currentKey));
}

And then write it in a QJson with the function (see the official documentation http://doc.qt.io/qt-5/qjsonobject.html)

QJsonObject::fromVariantMap

then in the other side recover it with

QJsonObject::toVariantMap()

and rewrite the settings

for ( int i = 0; i < keys.size(); i++ )
{
    settings.setValue( keys.at(i), keysValuesPairsMap.value(keys.at(i)) );
}


问:
jQuery draggable + toggleClass problem
the problem here is that the toggleClass position top:0px; left:0px will not trigger.. only the width and height and background-color will activate.. it will work if i will not drag the div(draggable).. if i start to drag the element, the toggled class positioning will not effect.. i dont know if there's such a function in jquery to help this..</p>

```<code><html>
<head>
    <title></title>
    <script type="text/javascript" src="jquery-1.4.2.js"></script>
    <script type="text/javascript" src="jquery.ui.core.js"></script>
    <script type="text/javascript" src="jquery.ui.widget.js"></script>
    <script type="text/javascript" src="jquery.ui.mouse.js"></script>
    <script type="text/javascript" src="jquery.ui.resizable.js"></script>
    <script type="text/javascript" src="jquery.ui.draggable.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $("#x").draggable().dblclick(function(){
                $(this).toggleClass("hi");
            });
        });
    </script>
    <style>
        .hello {
            background:red;
            width:200px;
            height:200px;
            position:relative;
            top:100px;
            left:100px;
        }

        .hi {
            background:yellow;
            position:relative;
            width:300px;
            height:300px;
            top:0px;
            left:0px;
        }
    </style>
</head>
<body>
    <div id="x" class="hello">

    </div>
</body>
</html>
</code>```

答:
The draggable stuff is interfering with your positioning. Draggable will assign specific left and top CSS via a style attribute as you drag the the
 around, style attributes override the values that come from the class attribute. You can get around this by using !important:

```<code>.hi {
    background: yellow;
    position: relative;
    width: 300px;
    height: 300px;
    top: 0px !important;
    left: 0px !important;
}
</code>```

Of course, the
 will cease to be draggable once the hi class is added as the !important positions will override what the draggable is trying to do.

I'd recommend that you get yourself a WebKit browser (such as Chrome or Safari) for testing and debugging, WebKit's "inspect element" is awesome and better than anything else I've come across for sorting out HTML/CSS issues.

Title: jQuery draggable + toggleClass problem

Body:
the problem here is that the toggleClass position top:0px; left:0px will not trigger.. only the width and height and background-color will activate.. it will work if i will not drag the div(draggable).. if i start to drag the element, the toggled class positioning will not effect.. i dont know if there's such a function in jquery to help this..

    <title></title>

Body:
The draggable stuff is interfering with your positioning. Draggable will assign specific left and top CSS via a style attribute as you drag the the <div> around, style attributes override the values that come from the class attribute. You can get around this by using !important:

.hi {
    background: yellow;
    position: relative;
    width: 300px;
    height: 300px;
    top: 0px !important;
    left: 0px !important;
}

Of course, the <div> will cease to be draggable once the hi class is added as the !important positions will override what the draggable is trying to do.

I'd recommend that you get yourself a WebKit browser (such as Chrome or Safari) for testing and debugging, WebKit's "inspect element" is awesome and better than anything else I've come across for sorting out HTML/CSS issues.


问:
Valgrind errors. Use of malloc and realloc in functions
I am trying to make mystrcat function to work. It seems to return right string but valgrind gives errors on my code which I cant seem to fix.

```<code>char *mystrcat(char *dest, const char *src) {
    int len = strlen(dest) * 2;
    char *origdest = realloc(dest, len);
    while(*dest) {
        dest++;
    }

    while (*src) {
        *dest++ = *src++;
    }
    return origdest;
}

int main(void) {
    char *str = malloc(7);
    strcpy(str, "First");

    str = mystrcat(str, "Second");
    printf("%s\n", str);
    free(str);
}
</code>```

Valgrind errors which I don't understand:

==10== Invalid read of size 1
==10==    at 0x40068B: mystrcat (mystrcat.c:9)
==10==    by 0x40070F: main (mystrcat.c:25)
==10==  Address 0x5203040 is 0 bytes inside a block of size 7 free'd
==10==    at 0x4C2FD5F: realloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==10==    by 0x40067B: mystrcat (mystrcat.c:8)
==10==    by 0x40070F: main (mystrcat.c:25)
==10==  Block was alloc'd at
==10==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==10==    by 0x4006E6: main (mystrcat.c:22)
==10==
==10== Invalid write of size 1
==10==    at 0x4006AF: mystrcat (mystrcat.c:14)
==10==    by 0x40070F: main (mystrcat.c:25)
==10==  Address 0x5203046 is 6 bytes inside a block of size 7 free'd
==10==    at 0x4C2FD5F: realloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==10==    by 0x40067B: mystrcat (mystrcat.c:8)
==10==    by 0x40070F: main (mystrcat.c:25)
==10==  Block was alloc'd at
==10==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==10==    by 0x4006E6: main (mystrcat.c:22)
```

答:
You need this (see comments for explanations):

```<code>char *mystrcat(char *dest, const char *src) {
    int len = strlen(dest) * 2;
    char *newdest = realloc(dest, len);
    // newdest contains the pointer to the newly allocated memory
    // and dest is now no longer valid

    dest = newdest;
    while(*dest) {
        dest++;
    }

    // now dest points to the end of the string in the newly
    // allocated memory

    while (*src) {
        *dest++ = *src++;
    }

    // add NUL terminator
    *dest = 0;

    // we return the newly allocated memory
    return newdest;
}
</code>```

But this function is still not entirely correct.

This is wrong:

```<code>int len = strlen(dest) * 2;
</code>```

Doubling the size is wrong, because if src is longer than the length of the dest string, there won't be enough memory and you'll get a buffer overflow.

The memory size needed for the concatenated string is:

size of the original string + size of the string to be concatenated + 1

The +1 is needed because of the NUL string terminator.

You therefore need this:

```<code>int len = strlen(dest) + strlen(src) + 1;
</code>```

And another thing:

```<code>char *mystrcat(char *dest, const char *src)
</code>```

can be replaced by

```<code>char *mystrcat(const char *dest, const char *src)
</code>```

because we actually don't modify the memory pointed by dest.

Be aware that your mystrcat only works if the destinatino pointer has been allocated with a malloc-like function.

Body:
I am trying to make mystrcat function to work. It seems to return right string but valgrind gives errors on my code which I cant seem to fix.

char *mystrcat(char *dest, const char *src) {
    int len = strlen(dest) * 2;
    char *origdest = realloc(dest, len);
    while(*dest) {
        dest++;
    }

    while (*src) {
        *dest++ = *src++;
    }
    return origdest;
}

int main(void) {
    char *str = malloc(7);
    strcpy(str, "First");

    str = mystrcat(str, "Second");
    printf("%s\n", str);
    free(str);
}

Valgrind errors which I don't understand:

==10== Invalid read of size 1
==10==    at 0x40068B: mystrcat (mystrcat.c:9)
==10==    by 0x40070F: main (mystrcat.c:25)
==10==  Address 0x5203040 is 0 bytes inside a block of size 7 free'd
==10==    at 0x4C2FD5F: realloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==10==    by 0x40067B: mystrcat (mystrcat.c:8)
==10==    by 0x40070F: main (mystrcat.c:25)
==10==  Block was alloc'd at
==10==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==10==    by 0x4006E6: main (mystrcat.c:22)
==10==
==10== Invalid write of size 1
==10==    at 0x4006AF: mystrcat (mystrcat.c:14)
==10==    by 0x40070F: main (mystrcat.c:25)
==10==  Address 0x5203046 is 6 bytes inside a block of size 7 free'd
==10==    at 0x4C2FD5F: realloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==10==    by 0x40067B: mystrcat (mystrcat.c:8)
==10==    by 0x40070F: main (mystrcat.c:25)
==10==  Block was alloc'd at
==10==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==10==    by 0x4006E6: main (mystrcat.c:22)

Body:
You need this (see comments for explanations):

char *mystrcat(char *dest, const char *src) {
    int len = strlen(dest) * 2;
    char *newdest = realloc(dest, len);
    // newdest contains the pointer to the newly allocated memory
    // and dest is now no longer valid

    dest = newdest;
    while(*dest) {
        dest++;
    }

    // now dest points to the end of the string in the newly
    // allocated memory

    while (*src) {
        *dest++ = *src++;
    }

    // add NUL terminator
    *dest = 0;

    // we return the newly allocated memory
    return newdest;
}

But this function is still not entirely correct.

This is wrong:

int len = strlen(dest) * 2;

Doubling the size is wrong, because if src is longer than the length of the dest string, there won't be enough memory and you'll get a buffer overflow.

The memory size needed for the concatenated string is:

size of the original string + size of the string to be concatenated + 1

The +1 is needed because of the NUL string terminator.

You therefore need this:

int len = strlen(dest) + strlen(src) + 1;

And another thing:

char *mystrcat(char *dest, const char *src)

can be replaced by

char *mystrcat(const char *dest, const char *src)

because we actually don't modify the memory pointed by dest.

Be aware that your mystrcat only works if the destinatino pointer has been allocated with a malloc-like function.


问:
How to simulate/test AJAX exception handler?
I have a PrototypeJS AJAX request like this (third party code):

```<code>new Ajax.Request(url,
{
    method: 'get',
    onException: function(transport, e)
    {
        //...
    },
    onComplete: function(transport)
    {
        //...
    }
});
</code>```

and want to test the behavior of onException. I have control over the server side, so I can change the response. But simply returning a 500 status does not do the trick, it is still handled by onComplete.

So what possibilities do I have to trigger the onException handler?

答:
onException is only fired when there was an exception while dispatching other callbacks, see here, in Ajax response callbacks. So I'm not sure there is a way to test it.

EDIT:

I read (in french, didn't find anything in english) that if you make a cross-domain request it fires the vent.

Body:
I have a PrototypeJS AJAX request like this (third party code):

new Ajax.Request(url,
{
    method: 'get',
    onException: function(transport, e)
    {
        //...
    },
    onComplete: function(transport)
    {
        //...
    }
});

and want to test the behavior of onException. I have control over the server side, so I can change the response. But simply returning a 500 status does not do the trick, it is still handled by onComplete.

So what possibilities do I have to trigger the onException handler?


问:
c3.js cannot load lines value
I post some code here.I don't know why the value of lines in old_chart can't update.
I have been searched all I can do.So I wish U guys can help me to figure out this.
Thanks a lot!!</p>

```<code>        <script>
    old_chart = c3.generate({
    bindto: '#chart',
     data: {
    columns: []
    },
     grid: {
    x: {
    show: true
    },
     y: {
    show: true,
     lines: []
    }
    }
    });

   $.ajax({type:"GET",
            url:"threshold",
            success: function(result){
              threshold_in_server = JSON.parse(result);
              input_threshold(threshold_in_server);

            }
    });

input_threshold = function(threshold_in_server){

      old_chart.load({
        y: {
              lines: [{value:threshold_in_server[0] },
                      {value:threshold_in_server[1] }]
            }
       });
    };
    </script>
<body>
<div id='chart' style='position:absolute;top:25px'></div>
<>/body
</code>```

答:
To update additional grid lines you should use .ygrids() api method, not .load():

```<code>old_chart.ygrids([{value:threshold_in_server[0] },
                  {value:threshold_in_server[1] }])
</code>```

Title: c3.js cannot load lines value

Body:
I post some code here.I don't know why the value of lines in old_chart can't update.
I have been searched all I can do.So I wish U guys can help me to figure out this.
Thanks a lot!!

<>/body

Body:
To update additional grid lines you should use .ygrids() api method, not .load():

old_chart.ygrids([{value:threshold_in_server[0] },
                  {value:threshold_in_server[1] }])


问:
indexOf on CharSequence implementations that support it
In my program I use a lot of Strings and StringBuilders. I would like to get rid of the StringBuilder toString() method and use CharSequences throughout. However I need access to the indexOf method (which is available in both StringBuilder and String but not in other implementations). How might I implement an interface that will make this function visible?</p>

答: You can use the default method from TextUtils: indexOf</p>


问:
How to declare a generic type Multi-Dimensional array in java
I want to store an array of 100 int elements in rows ie 1 row of 100 int datatypes.And every single element contains an array of 100 objects.How to do this in java or android. </p>

答:
Use a collection, a "List of List":

```<code>List<List<YourType>> matrix2D = new ArrayList<List<YourType>>();
</code>```

This structure can easily store a table with 200 rows and 100 columns where each element is of type YourType.

Otherwise - if your size is fixed and you just want to store YourType values, theres no need for generics:

```<code>int rows = 200;
int columns = 200;
YourType[][] matrix2D = new YourType[rows][columns];
</code>```

Body:
Use a collection, a "List of List":

List<List<YourType>> matrix2D = new ArrayList<List<YourType>>();

This structure can easily store a table with 200 rows and 100 columns where each element is of type YourType.

Otherwise - if your size is fixed and you just want to store YourType values, theres no need for generics:

int rows = 200;
int columns = 200;
YourType[][] matrix2D = new YourType[rows][columns];


问:
Send an HTTP request to a URL using PHP
I am trying to send an HTTP request to an URL using the below code,but keep getting error

(file_get_contents(http://localhost:81/Help/Api/POST-SMS): failed to
  open stream: HTTP request failed! HTTP/1.1 500 Internal Server Error)

, any idea?
Thank in advance

```<code><?php

$url = 'http://localhost:81/Help/Api/POST-SMS';
 $data = array('message' => 'hi', 'mobile' => '12345678');
$options = array(
'http' => array(
    'header'  => "Content-type: application/json",
    'method'  => 'POST',
    'content' => http_build_query($data)
)
);
 $context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { /* Handle error */ }
var_dump($result);
?>
</code>```

答:
From the server response "HTTP request failed! HTTP/1.1 500 Internal Server Error" - that means the http://localhost:81/Help/Api/POST-SMS failed - not your actual script that you posted above.

I also recommend using the curl approach in PHP: http://php.net/manual/en/curl.examples-basic.php
http://php.net/manual/en/book.curl.php

Another exemple that might help you is this: PHP + curl, HTTP POST sample code?

Title: Send an HTTP request to a URL using PHP

Body:
I am trying to send an HTTP request to an URL using the below code,but keep getting error

(file_get_contents(http://localhost:81/Help/Api/POST-SMS): failed to
  open stream: HTTP request failed! HTTP/1.1 500 Internal Server Error)

, any idea?
Thank in advance

<?php

$url = 'http://localhost:81/Help/Api/POST-SMS';
 $data = array('message' => 'hi', 'mobile' => '12345678');
$options = array(
'http' => array(
    'header'  => "Content-type: application/json",
    'method'  => 'POST',
    'content' => http_build_query($data)
)
);
 $context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { /* Handle error */ }
var_dump($result);
?>


问:
Getting the currently open file in VSCode
Is there a command in the vscode namespace that allows you to get the TextDocument instance for the currently open file? I found vscode.workspace.onDidOpenTextDocument, but it doesn't work for files that are open on launch

答:
A few options depending on your needs:

```<code>// Single active editor. Editors have a `.document` property
vscode.window.activeTextEditor

// All showing text editors. For a split view, there are two active editors
vscode.window.visibleTextEditors

// All open documents that vscode knows about. Do not have to be showing
vscode.workspace.textDocuments
</code>```

See the vscode API for more info: https://code.visualstudio.com/docs/extensionAPI/vscode-api

Body:
A few options depending on your needs:

// Single active editor. Editors have a `.document` property
vscode.window.activeTextEditor

// All showing text editors. For a split view, there are two active editors
vscode.window.visibleTextEditors

// All open documents that vscode knows about. Do not have to be showing
vscode.workspace.textDocuments

See the vscode API for more info: https://code.visualstudio.com/docs/extensionAPI/vscode-api


问:
Qt creator - simply show a working folder without creating extra Qt files
I have a makefile C/C++ project which multiple people are working on. I want to use Qt as an IDE because I really like the ease of autocompletion and links to declarations etc. However, it seems that I can't just open a working directly in Qt - I have to import or create a new project.

When creating a new project by importing an existing project, Qt creates several files (I do not want this), and when a new .c file or whatever is created outside Qt it is not shown in Qt.

Does someone have a solution to this?

答:
You have to import your project as you are already doing.

You can ignore the files created by Qt Creator in your .gitignore file. Here's a nice repo for the templates: https://github.com/github/gitignore

Whenever you add a new file, you can add those using Add Existing files... option by right clicking on the project name.


问:
OnOptionsItemSelected for action 1 not showing new alert dialog
On my onOptionsItemSelected method when the user taps action settings 1, my new alert dialog does not show?

```<code>package com.karanvir.search;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import static com.karanvir.search.MainActivity.urlGlobal;

public class Main2Activity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        //finding webview
        WebView webView=(WebView) findViewById(R.id.web1);

//whole bunch of settings you might want to do if you .
        //do this because javascript is so wildely used that if you dont use this anywebsites you display wont be displayed properly
        webView.getSettings().setJavaScriptEnabled(true);
        //this is because on a number of phones if you dont do this it will jump to the devices default browser, and ddisplay the websview their instead.
        webView.setWebViewClient(new WebViewClient());
        webView.loadUrl("https://www.google.ca/?gws_rd=ssl#q="+urlGlobal);
        //reminder ask permission
        //you can load content using loaddata
        //then add type of data
        //then add character encoded were using

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings4) {
            Intent intentGoogle= new Intent(getApplicationContext(),Main2Activity.class);
            startActivity(intentGoogle);

            return true;
        } else if(id ==R.id.action_settings2){
            Intent intentGoogle= new Intent(getApplicationContext(),Yahoo.class);
            startActivity(intentGoogle);

            return true;

        }else if (id==R.id.action_settings3){
            Intent intentGoogle= new Intent(getApplicationContext(),MainActivity.class);
            startActivity(intentGoogle);

            return true;

        }else if(id==R.id.action_settings1){
            new AlertDialog.Builder(getApplicationContext())
                    .setIcon(android.R.drawable.ic_dialog_info)
                    .setTitle("About")
                    .setMessage("This app interchanges between different search engines, to help guess what your looking for. We dont not acess your location, also we do not save any information. Right now we are working on a way to make the app completely private in congnito.Email us if you want to help with this project also. Please email Dhillonapps93@gmail.com for help/inquries. We run this app with no ads, we also accept donations at runescapegold1291@hotmail.com. Yes I used to play runescape lol. Thanks for reading and enjoy");
            return true;

        }

        return super.onOptionsItemSelected(item);
    }

 }
</code>```

答:
You forgot to call .show() on the new dialog. You only created it ;)</p>

```<code>else if(id==R.id.action_settings1){
    new AlertDialog.Builder(this)
            .setIcon(android.R.drawable.ic_dialog_info)
            .setTitle("About")
            .setMessage(".....")
            .show();
    return true;
}
</code>```

Body:
On my onOptionsItemSelected method when the user taps action settings 1, my new alert dialog does not show?

package com.karanvir.search;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import static com.karanvir.search.MainActivity.urlGlobal;

public class Main2Activity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        //finding webview
        WebView webView=(WebView) findViewById(R.id.web1);

//whole bunch of settings you might want to do if you .
        //do this because javascript is so wildely used that if you dont use this anywebsites you display wont be displayed properly
        webView.getSettings().setJavaScriptEnabled(true);
        //this is because on a number of phones if you dont do this it will jump to the devices default browser, and ddisplay the websview their instead.
        webView.setWebViewClient(new WebViewClient());
        webView.loadUrl("https://www.google.ca/?gws_rd=ssl#q="+urlGlobal);
        //reminder ask permission
        //you can load content using loaddata
        //then add type of data
        //then add character encoded were using

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings4) {
            Intent intentGoogle= new Intent(getApplicationContext(),Main2Activity.class);
            startActivity(intentGoogle);

            return true;
        } else if(id ==R.id.action_settings2){
            Intent intentGoogle= new Intent(getApplicationContext(),Yahoo.class);
            startActivity(intentGoogle);

            return true;

        }else if (id==R.id.action_settings3){
            Intent intentGoogle= new Intent(getApplicationContext(),MainActivity.class);
            startActivity(intentGoogle);

            return true;

        }else if(id==R.id.action_settings1){
            new AlertDialog.Builder(getApplicationContext())
                    .setIcon(android.R.drawable.ic_dialog_info)
                    .setTitle("About")
                    .setMessage("This app interchanges between different search engines, to help guess what your looking for. We dont not acess your location, also we do not save any information. Right now we are working on a way to make the app completely private in congnito.Email us if you want to help with this project also. Please email Dhillonapps93@gmail.com for help/inquries. We run this app with no ads, we also accept donations at runescapegold1291@hotmail.com. Yes I used to play runescape lol. Thanks for reading and enjoy");
            return true;

        }

        return super.onOptionsItemSelected(item);
    }

 }

Body:
You forgot to call .show() on the new dialog. You only created it ;)

else if(id==R.id.action_settings1){
    new AlertDialog.Builder(this)
            .setIcon(android.R.drawable.ic_dialog_info)
            .setTitle("About")
            .setMessage(".....")
            .show();
    return true;
}


问:
how to plot 2d random data with imshow method in python
```<code>import numpy as np
C=np.random.rand (500)
S=np.random.rand(500)
def function(s,c):
    return s*2+c
dc=[]
for i in range(len(C)):
    dc.append(function(S[i],C[i])
</code>```

I don't know how to imshow the random result with imshow. I want to get the image like this:

答:
You can convert a 1d- into a 2d-array using np.reshape. Also, you don't need to do your array arithmetics element-wise -- numpy does that for you. The below code hopefully does what you want (it's not quite clear from your question):

```<code>import numpy as np
from matplotlib import pyplot as plt

C=np.random.rand(500).reshape((20,25))
S=np.random.rand(500).reshape((20,25))

def function(s,c):
    return s*2+c

dc = function(S,C)

plt.imshow(dc)
plt.show()
</code>```

The result looks like this:

Body:
import numpy as np
C=np.random.rand (500)
S=np.random.rand(500)
def function(s,c):
    return s*2+c
dc=[]
for i in range(len(C)):
    dc.append(function(S[i],C[i])

I don't know how to imshow the random result with imshow. I want to get the image like this:

Body:
You can convert a 1d- into a 2d-array using np.reshape. Also, you don't need to do your array arithmetics element-wise -- numpy does that for you. The below code hopefully does what you want (it's not quite clear from your question):

import numpy as np
from matplotlib import pyplot as plt

C=np.random.rand(500).reshape((20,25))
S=np.random.rand(500).reshape((20,25))

def function(s,c):
    return s*2+c

dc = function(S,C)

plt.imshow(dc)
plt.show()

The result looks like this:


问:
Can not find the tag library descriptor for "http://www.springframework.org/tags/form" with java configuration
I am currently learning spring mvc and made an example "my app" which  includes spring mvc and apache tiles. Everything works fine but in jsp i get this following error:

Can not find the tag library descriptor for "http://www.springframework.org/tags/form"

here is my mainLayout.jsp

```<code>    <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
    <%@ page isELIgnored="false" %>
    <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    <%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>

    <html>

    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title><tiles:getAsString name="title" /></title>
        <link href="<c:url value='/static/css/bootstrap.css' />"  rel="stylesheet"></link>
        <link href="<c:url value='/static/css/app.css' />" rel="stylesheet"></link>
    </head>

    <body>
            <header id="header">
                <tiles:insertAttribute name="header" />
            </header>

            <section id="site-content">
                <tiles:insertAttribute name="body" />
            </section>

            <footer id="footer">
                <tiles:insertAttribute name="footer" />
            </footer>
    </body>
    </html>
</code>```

before you ask, I have included all the spring ,tiles and jstl dependency in my pom.
only the form tag gives error.

答:
It seems that your tag library is missing form the class-path
As You don't have to configure anything. Since JSP 2.0 taglibs can be discovered automatically.

All You need to do is place them in WEB-INF or it's sub-folders. If you are packaging Your TLDs as JAR files, place them in WEB-INF/lib or META-INF of the JAR

Body:
I am currently learning spring mvc and made an example "my app" which  includes spring mvc and apache tiles. Everything works fine but in jsp i get this following error:

Can not find the tag library descriptor for "http://www.springframework.org/tags/form"

here is my mainLayout.jsp

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
    <%@ page isELIgnored="false" %>
    <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    <%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>

        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title><tiles:getAsString name="title" /></title>
        <link href="<c:url value='/static/css/bootstrap.css' />"  rel="stylesheet"></link>
        <link href="<c:url value='/static/css/app.css' />" rel="stylesheet"></link>

                <tiles:insertAttribute name="header" />

                <tiles:insertAttribute name="body" />

                <tiles:insertAttribute name="footer" />

before you ask, I have included all the spring ,tiles and jstl dependency in my pom.
only the form tag gives error.