问:
Problems integrating openId selector with Asp.Net MVC 2
I am trying to use the openid selector javascript library to allow OpenId login for a web site.  I'm following the instructions on this site, but I'm not usually a web programmer and its not working and I'm not certain why.  I'm sure its something fairly trivial but I can't see it.

The problem is that no image with the open Id bits on it is rendered in the place where it should go, which is the

 I'm assuming.  This seems to indicate to me that the function which is supposed to set the contents of this div is not being run.

I suspected the scripts.

I have added the script references to the Site.Master as it indicates:

```<code><script type="text/javascript" src="../../Scripts/jquery-1.4.1.min.js"></script>
<script type="text/javascript" src="../../Scripts/openid-jquery.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        alert("document ready"); // <- I added this to verfiy that this is being called
        openid.init('openid_identifier');
    });
</script>
</code>```

and it seems to call the function on each page (the alert is shown) and it should then, I assume, call the openid.init function.

this is defined in the openid-jquery.js script:

```<code>var openid = {
version: '1.2', // version constant
demo: false,
demo_text: null,
cookie_expires: 6 * 30, // 6 months.
cookie_name: 'openid_provider',
cookie_path: '/',

img_path: '../images/',
lang: null, // language, is set in openid-jquery-<lang>.js
signin_text: null, // text on submit button on the form
input_id: null,
provider_url: null,
provider_id: null,
all_small: false, // output large providers w/ small icons
no_sprite: false, // don't use sprite image
image_title: '{provider}', // for image title

init: function (input_id) {
    alert("initialising");
    providers = $.extend({}, providers_large, providers_small);

    var openid_btns = $('#openid_btns');

    this.input_id = input_id;

    $('#openid_choice').show();
    $('#openid_input_area').empty();

    var i = 0;
    // add box for each provider
    for (id in providers_large) {
        if (this.all_small) {
            openid_btns.append(this.getBoxHTML(id, providers_large[id], 'small', i++));
        } else
            openid_btns.append(this.getBoxHTML(id, providers_large[id], 'large', i++));
    }
    if (providers_small) {
        openid_btns.append('<br/>');

        for (id in providers_small) {

            openid_btns.append(this.getBoxHTML(id, providers_small[id], 'small', i++));
        }
    }

    $('#openid_form').submit(this.submit);

    var box_id = this.readCookie();
    if (box_id) {
        this.signin(box_id, true);
    }
</code>```

again I added the alert("initialising"); which never seems to be called.

Should it be calling this function?  How can I determine why this function is not being called?  Any ideas?

UPDATE:

in the document ready function i swapped the order of the functions like so:

```<code><script type="text/javascript">
    $(document).ready(function () {
        openid.init('openid_identifier');
        alert("document ready");
    });
</script>
</code>```

and now the alert is not raised.  what does this mean?  is something going wrong in the other function?  how can I tell what it is?

UPDATE 2:

Wierd.  If I rename the openid-jquery.js file to something (seemingly anything) else (like openid-jquery.2.js) then I can see the alert from the open id script.

but it only seems to execute the alert and not the next line as when I add another alter later on (ie after the very next line) the 2nd alert is never seen.  not sure why that would be either.

UPDATE 3:
After debugging in chrome it seems the problem was that providers_large, providers_small were not defined and adding:

```<code>var providers_large;
var providers_small;
</code>```

to the top of the script allowed it to at least run and show the alerts.  but still no images...  further investigation I think.

答:
so it seems that in step 4 of the instructions it needs to be updated to add the english javascript provider information which is where the provider_large is defined, like so:

```<code><script type="text/javascript" src="../../Scripts/jquery-1.4.1.min.js"></script>
<script type="text/javascript" src="../../Scripts/openid-jquery.js"></script>
<script type="text/javascript" src="../../Scripts/openid-jquery-en.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        alert("document ready"); // <- I added this to verfiy that this is being called
        openid.init('openid_identifier');
    });
</script>
</code>```

Body:
I am trying to use the openid selector javascript library to allow OpenId login for a web site.  I'm following the instructions on this site, but I'm not usually a web programmer and its not working and I'm not certain why.  I'm sure its something fairly trivial but I can't see it.

The problem is that no image with the open Id bits on it is rendered in the place where it should go, which is the

 I'm assuming.  This seems to indicate to me that the function which is supposed to set the contents of this div is not being run.

I suspected the scripts.

I have added the script references to the Site.Master as it indicates:

and it seems to call the function on each page (the alert is shown) and it should then, I assume, call the openid.init function.

this is defined in the openid-jquery.js script:

var openid = {
version: '1.2', // version constant
demo: false,
demo_text: null,
cookie_expires: 6 * 30, // 6 months.
cookie_name: 'openid_provider',
cookie_path: '/',

img_path: '../images/',
lang: null, // language, is set in openid-jquery-<lang>.js
signin_text: null, // text on submit button on the form
input_id: null,
provider_url: null,
provider_id: null,
all_small: false, // output large providers w/ small icons
no_sprite: false, // don't use sprite image
image_title: '{provider}', // for image title

init: function (input_id) {
    alert("initialising");
    providers = $.extend({}, providers_large, providers_small);

    var openid_btns = $('#openid_btns');

    this.input_id = input_id;

    $('#openid_choice').show();
    $('#openid_input_area').empty();

    var i = 0;
    // add box for each provider
    for (id in providers_large) {
        if (this.all_small) {
            openid_btns.append(this.getBoxHTML(id, providers_large[id], 'small', i++));
        } else
            openid_btns.append(this.getBoxHTML(id, providers_large[id], 'large', i++));
    }
    if (providers_small) {
        openid_btns.append('
');

        for (id in providers_small) {

            openid_btns.append(this.getBoxHTML(id, providers_small[id], 'small', i++));
        }
    }

    $('#openid_form').submit(this.submit);

    var box_id = this.readCookie();
    if (box_id) {
        this.signin(box_id, true);
    }

again I added the alert("initialising"); which never seems to be called.

Should it be calling this function?  How can I determine why this function is not being called?  Any ideas?

UPDATE:

in the document ready function i swapped the order of the functions like so:

and now the alert is not raised.  what does this mean?  is something going wrong in the other function?  how can I tell what it is?

UPDATE 2:

Wierd.  If I rename the openid-jquery.js file to something (seemingly anything) else (like openid-jquery.2.js) then I can see the alert from the open id script.

but it only seems to execute the alert and not the next line as when I add another alter later on (ie after the very next line) the 2nd alert is never seen.  not sure why that would be either.

UPDATE 3:
After debugging in chrome it seems the problem was that providers_large, providers_small were not defined and adding:

var providers_large;
var providers_small;

to the top of the script allowed it to at least run and show the alerts.  but still no images...  further investigation I think.

Body:
so it seems that in step 4 of the instructions it needs to be updated to add the english javascript provider information which is where the provider_large is defined, like so:

<script type="text/javascript" src="../../Scripts/jquery-1.4.1.min.js"></script>
<script type="text/javascript" src="../../Scripts/openid-jquery.js"></script>
<script type="text/javascript" src="../../Scripts/openid-jquery-en.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        alert("document ready"); // <- I added this to verfiy that this is being called
        openid.init('openid_identifier');
    });
</script>


来源: stackexchange

问:
Read multiple line as input in c# console application
Input:
You should take input up to EOF. First line of each input will hold two numbers separated by a single space. First number will denote the total hours to finish the sprint (0 < CT ≤ 100) and the second one will be number of members in the team (0 < N ≤ 100). Then the N number of lines will hold the total hours a member can work each day (0 < P ≤ 24)

Output:
Print just single line for each test case. If it takes one day to finish the project then print “Project will finish within 1 day.” For more than one days print “Project will finish within D days.”, where D denotes the number of days to finish the project.

Sample Input
10 2
5
5
10 2
5
4
Sample Output
Project will finish within 1 day.
Project will finish within 2 days.

How can i solve this problem in c# console application?

I already create my method to calculate result, but it takes double enter to display result in console window

My Solution

```<code>List<string> lines = new List<string>();
string line;
while ((line = Console.ReadLine()) != null)
{
    lines.Add(line);
}
getResult(lines);
</code>```

enter image description here

答:
I realised that you want to show the result when total members count is reached. So this is your improved code:

```<code>List<string> lines = new List<string>();
string line;
int count = -2; // Current member index;
int totalcount = 0; // Total members count;
while (count < totalcount)
{
    line = Console.ReadLine();
    lines.Add(line);
    if(count == -1) // your app doesn't count first and second line
    {
        totalcount = Convert.ToInt32(line);
    }
    count++;
}
getResult(lines);
</code>```

I hope it helps.

ContentLicense: CC BY-SA 3.0

Body:
Input:
You should take input up to EOF. First line of each input will hold two numbers separated by a single space. First number will denote the total hours to finish the sprint (0 < CT ≤ 100) and the second one will be number of members in the team (0 < N ≤ 100). Then the N number of lines will hold the total hours a member can work each day (0 < P ≤ 24)

Output:
Print just single line for each test case. If it takes one day to finish the project then print “Project will finish within 1 day.” For more than one days print “Project will finish within D days.”, where D denotes the number of days to finish the project.

Sample Input
10 2
5
5
10 2
5
4
Sample Output
Project will finish within 1 day.
Project will finish within 2 days.

How can i solve this problem in c# console application?

I already create my method to calculate result, but it takes double enter to display result in console window

My Solution

List<string> lines = new List<string>();
string line;
while ((line = Console.ReadLine()) != null)
{
    lines.Add(line);
}
getResult(lines);

enter image description here

Body:
I realised that you want to show the result when total members count is reached. So this is your improved code:

List<string> lines = new List<string>();
string line;
int count = -2; // Current member index;
int totalcount = 0; // Total members count;
while (count < totalcount)
{
    line = Console.ReadLine();
    lines.Add(line);
    if(count == -1) // your app doesn't count first and second line
    {
        totalcount = Convert.ToInt32(line);
    }
    count++;
}
getResult(lines);

I hope it helps.


问:
wrapping handlbars string with jQuery distorting the string
I am trying to change an email with jQuery. The email itself is using handlebars. I have a table in it, and inside it I have an each command that renders number or
's.
When I wrap the email with jQuery, it is somehow distorting the structure of the email, and basically making it meaningless.
for example this is before wrapping with jQuery:

{{#each items}}

 item.something

{{/each}}

```
</div>
</div>
</p>

<p>and this is after:</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-html lang-html prettyprint-override"><code>{{#each items}}

{{/each}}
<table>
  <tr> item.something</tr>
</table></code>```

Any idea what could be the issue?
Thanks

答:
I Figured out the issue.
Actually there were two issues:

I didn't have
 tag

The {{#each}} should be outside the table.

So it should actually look like this:

{{#each items}}

 item.something

{{/each}}```

Body:
I am trying to change an email with jQuery. The email itself is using handlebars. I have a table in it, and inside it I have an each command that renders number or
's.
When I wrap the email with jQuery, it is somehow distorting the structure of the email, and basically making it meaningless.
for example this is before wrapping with jQuery:

{{#each items}}

 item.something

{{/each}}

and this is after:

{{#each items}}

{{/each}}

 item.something

Any idea what could be the issue?
Thanks

Body:
I Figured out the issue.
Actually there were two issues:

I didn't have <tbody> tag

The {{#each}} should be outside the table.

So it should actually look like this:

{{#each items}}
<table>
  <tbody>
    <tr> item.something</tr>
  </tbody>
</table>
{{/each}}


问:
static/compile time check for javascript with jquery?
I know javascript (or at least a version of it) can be compiled into .NET provided certain conditions are met. How can i do a compile time or static syntax check on javascript i am writing? The catch is, it must support jquery

Cause someone will ask, to compile (with ms .net) is

```<code>C:\Windows\Microsoft.NET\Framework\v2.0.50727\jsc thefile.js
</code>```

writing package thenamespace { class ClassName{ around where necessary. Then you can add this as a normal reference. From experience the references are not always compatible with mono.

答:
I'm not sure if there are any static analyzers which can check the validity of jQuery code in depth, but for the Javascript syntax itself, there are non-web versions of Javascript Lint and JSLint you could use.

If you're using Visual Studio, you could also give JSLint.VS a try for better integration.

UPDATE: Since I wrote this, JSHint and ESLint have taken over as the most popular members of the JSLint family.

Also, TypeScript is gaining popularity. It's a superset of JavaScript with optional static types which compiles to plain JavaScript. (For those who have used MyPy for Python, it's similar. Valid JavaScript is also valid TypeScript, but you can incrementally add type annotations and the compiler will use them to catch bugs.)

ContentLicense: CC BY-SA 2.5

Body:
I know javascript (or at least a version of it) can be compiled into .NET provided certain conditions are met. How can i do a compile time or static syntax check on javascript i am writing? The catch is, it must support jquery

Cause someone will ask, to compile (with ms .net) is

C:\Windows\Microsoft.NET\Framework\v2.0.50727\jsc thefile.js

writing package thenamespace { class ClassName{ around where necessary. Then you can add this as a normal reference. From experience the references are not always compatible with mono.


问:
Problems reading xml file with Chinese characters using UTF-8 encoding in RStudio
I want to read a .xml file which looks like:

```<code><?xml version="1.0" encoding="UTF-8"?>
<province name="北京市" id="11">
  <city name="市辖区" id="110100000000">
    <county name="东城区" id="110101000000">
      <town name="珍珠泉乡" id="110229214000">
        <village name="珍珠泉乡社区居委会" id="110229214001" type="220"/>
        <village name="珍珠泉村委会" id="110229214200" type="210"/>
        <village name="称沟湾村委会" id="110229214201" type="220"/>
        <village name="庙梁村委会" id="110229214202" type="220"/>
        <village name="下水沟村委会" id="110229214203" type="220"/>
        <village name="上水沟村委会" id="110229214204" type="220"/>
        <village name="下花楼村委会" id="110229214205" type="220"/>
        <village name="八亩地村委会" id="110229214206" type="220"/>
        <village name="转山子村委会" id="110229214207" type="220"/>
        <village name="水泉子村委会" id="110229214208" type="220"/>
        <village name="双金草村委会" id="110229214209" type="220"/>
        <village name="小川村委会" id="110229214210" type="220"/>
        <village name="小铺村委会" id="110229214211" type="220"/>
        <village name="仓米道村委会" id="110229214212" type="220"/>
        <village name="南天门村委会" id="110229214213" type="220"/>
        <village name="桃条沟村委会" id="110229214214" type="220"/>
      </town>
    </county>
  </city>
</province>
</code>```

I set the system locale to be simplified Chinese using Sys.setlocale("LC_ALL", locale="Chinese (Simplified)"), and read the document using XML package with UTF-8 encoding doc = xmlParse(files[i], encoding = "UTF-8", useInternalNodes = TRUE), but when I look at doc, the Chinese characters are not properly displayed:

```<code><village id="110229214001" type="220" name="鐝嶇彔娉変埂绀惧尯灞呭浼?/>
        <village id="110229214200" type="210" name="鐝嶇彔娉夋潙濮斾細"/>
        <village id="110229214201" type="220" name="绉版矡婀炬潙濮斾細"/>
        <village id="110229214202" type="220" name="搴欐鏉戝浼?/>
        <village id="110229214203" type="220" name="涓嬫按娌熸潙濮斾細"/>
        <village id="110229214204" type="220" name="涓婃按娌熸潙濮斾細"/>
        <village id="110229214205" type="220" name="涓嬭姳妤兼潙濮斾細"/>
        <village id="110229214206" type="220" name="鍏憨鍦版潙濮斾細"/>
        <village id="110229214207" type="220" name="杞北瀛愭潙濮斾細"/>
        <village id="110229214208" type="220" name="姘存硥瀛愭潙濮斾細"/>
        <village id="110229214209" type="220" name="鍙岄噾鑽夋潙濮斾細"/>
        <village id="110229214210" type="220" name="灏忓窛鏉戝浼?/>
        <village id="110229214211" type="220" name="灏忛摵鏉戝浼?/>
        <village id="110229214212" type="220" name="浠撶背閬撴潙濮斾細"/>
        <village id="110229214213" type="220" name="鍗楀ぉ闂ㄦ潙濮斾細"/>
        <village id="110229214214" type="220" name="妗冩潯娌熸潙濮斾細"/>
</code>```

I also tried to set the system locale to English_United States.1252, but the problem remains the same.
One strange thing is that, when I use some functions over doc, for example xmlRoot(doc) or getNodeSet(doc,"//village")[1], the Chinese characters are displayed correctly. But not for all functions, if I use xmlAttrs(getNodeSet(doc,"//village")[[1]]), it has problem.

答:
Try xml linq</p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;

namespace ConsoleApplication49
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            StreamReader reader = new StreamReader(FILENAME);
            var z = reader.ReadLine();

            XDocument doc = XDocument.Load(reader);

            var results = doc.Descendants("village").Select(x => new
            {
                name = (string)x.Attribute("name"),
                id = (long)x.Attribute("id"),
                type = (int)x.Attribute("type")
            }).ToList();

        }
    }
}
</code>```

Body:
I want to read a .xml file which looks like:

<?xml version="1.0" encoding="UTF-8"?>
<province name="北京市" id="11">
  <city name="市辖区" id="110100000000">
    <county name="东城区" id="110101000000">
      <town name="珍珠泉乡" id="110229214000">
        <village name="珍珠泉乡社区居委会" id="110229214001" type="220"/>
        <village name="珍珠泉村委会" id="110229214200" type="210"/>
        <village name="称沟湾村委会" id="110229214201" type="220"/>
        <village name="庙梁村委会" id="110229214202" type="220"/>
        <village name="下水沟村委会" id="110229214203" type="220"/>
        <village name="上水沟村委会" id="110229214204" type="220"/>
        <village name="下花楼村委会" id="110229214205" type="220"/>
        <village name="八亩地村委会" id="110229214206" type="220"/>
        <village name="转山子村委会" id="110229214207" type="220"/>
        <village name="水泉子村委会" id="110229214208" type="220"/>
        <village name="双金草村委会" id="110229214209" type="220"/>
        <village name="小川村委会" id="110229214210" type="220"/>
        <village name="小铺村委会" id="110229214211" type="220"/>
        <village name="仓米道村委会" id="110229214212" type="220"/>
        <village name="南天门村委会" id="110229214213" type="220"/>
        <village name="桃条沟村委会" id="110229214214" type="220"/>
      </town>
    </county>
  </city>
</province>

I set the system locale to be simplified Chinese using Sys.setlocale("LC_ALL", locale="Chinese (Simplified)"), and read the document using XML package with UTF-8 encoding doc = xmlParse(files[i], encoding = "UTF-8", useInternalNodes = TRUE), but when I look at doc, the Chinese characters are not properly displayed:

<village id="110229214001" type="220" name="鐝嶇彔娉変埂绀惧尯灞呭浼?/>
        <village id="110229214200" type="210" name="鐝嶇彔娉夋潙濮斾細"/>
        <village id="110229214201" type="220" name="绉版矡婀炬潙濮斾細"/>
        <village id="110229214202" type="220" name="搴欐鏉戝浼?/>
        <village id="110229214203" type="220" name="涓嬫按娌熸潙濮斾細"/>
        <village id="110229214204" type="220" name="涓婃按娌熸潙濮斾細"/>
        <village id="110229214205" type="220" name="涓嬭姳妤兼潙濮斾細"/>
        <village id="110229214206" type="220" name="鍏憨鍦版潙濮斾細"/>
        <village id="110229214207" type="220" name="杞北瀛愭潙濮斾細"/>
        <village id="110229214208" type="220" name="姘存硥瀛愭潙濮斾細"/>
        <village id="110229214209" type="220" name="鍙岄噾鑽夋潙濮斾細"/>
        <village id="110229214210" type="220" name="灏忓窛鏉戝浼?/>
        <village id="110229214211" type="220" name="灏忛摵鏉戝浼?/>
        <village id="110229214212" type="220" name="浠撶背閬撴潙濮斾細"/>
        <village id="110229214213" type="220" name="鍗楀ぉ闂ㄦ潙濮斾細"/>
        <village id="110229214214" type="220" name="妗冩潯娌熸潙濮斾細"/>

I also tried to set the system locale to English_United States.1252, but the problem remains the same.
One strange thing is that, when I use some functions over doc, for example xmlRoot(doc) or getNodeSet(doc,"//village")[1], the Chinese characters are displayed correctly. But not for all functions, if I use xmlAttrs(getNodeSet(doc,"//village")[[1]]), it has problem.

Body:
Try xml linq

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;

namespace ConsoleApplication49
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            StreamReader reader = new StreamReader(FILENAME);
            var z = reader.ReadLine();

            XDocument doc = XDocument.Load(reader);

            var results = doc.Descendants("village").Select(x => new
            {
                name = (string)x.Attribute("name"),
                id = (long)x.Attribute("id"),
                type = (int)x.Attribute("type")
            }).ToList();

        }
    }
}


问:
Re-running scala program in eclipse ide after renaming
first i created a scala class inside a scala project in eclipse ide as below and ran it, it was successful.

```<code>object Test extends App{
  println("hi");
}
</code>```

once i rename the object , i can not find any option to run the program. [The file name is not changed and build automatically was enabled]

```<code>object Test1 extends App{
  println("hi");
}
</code>```

any advice ?

答:
Try to change launch configs for your application. Clean target folder before re-build. For config you can refer to:

Select Run > Run Configurations... or Run > Debug Configurations... from the workbench menu bar.  This opens a dialog
  that lets you create, modify, and delete launch configurations of
  different types.

Body:
first i created a scala class inside a scala project in eclipse ide as below and ran it, it was successful.

object Test extends App{
  println("hi");
}

once i rename the object , i can not find any option to run the program. [The file name is not changed and build automatically was enabled]

object Test1 extends App{
  println("hi");
}

any advice ?


问:
Override onSavedInstanceState: savedInstanceState object is always null
I have two activities (A and B). Activity A calls activity B. Activity B has Back (Up) button like this:

```<code>getSupportActionBar().setDisplayHomeAsUpEnabled(true);
</code>```

Now when this UP button is pressed, onCreate of activity A is again called. In the activity A, there is a classId variable (which I got from an Intent) which I want to retain. For this I have following code in my onCreate of activity A:

```<code>        if (savedInstanceState == null)
        {
            Intent intent = getIntent();
            classId = intent.getIntExtra("CLASS_ID", 0);
        }
        else
        {
            classId = savedInstanceState.getInt("CLASS_ID");
        }
</code>```

I have also overriden the onSavedInstanceState method:

```<code>@Override
protected void onSaveInstanceState(Bundle savedInstanceState)
{
    savedInstanceState.putInt("CLASS_ID", classId);
    super.onSaveInstanceState(savedInstanceState);
}
</code>```

I am following this SO answer:
onCreate being called on Activity A in up navigation

The problem I am facing is that when I come again to activity A by passing back button in activity B, onCreate gets called and I found savedInstanceState to be NULL.

Edit:

Is there any other way to save my classId variable so that when I return again to activity A, I can use that?

Edit 2

If I set launch mode of my activity A to SingleTop in the manifest file, my issue gets resolved. Is it the right approach?

答:
Try this

```<code>public class SingletonHolder {

    //your id here as what data type you want

    private  static SingletonHolder instance;

    public static SingletonHolder getInstance() {
        if (instance == null) {
            instance = new SingletonHolder();
        }
        return instance;
    }

   //set getter setter here
}
</code>```

If not successfull feel free to comment

Body:
I have two activities (A and B). Activity A calls activity B. Activity B has Back (Up) button like this:

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

Now when this UP button is pressed, onCreate of activity A is again called. In the activity A, there is a classId variable (which I got from an Intent) which I want to retain. For this I have following code in my onCreate of activity A:

        if (savedInstanceState == null)
        {
            Intent intent = getIntent();
            classId = intent.getIntExtra("CLASS_ID", 0);
        }
        else
        {
            classId = savedInstanceState.getInt("CLASS_ID");
        }

I have also overriden the onSavedInstanceState method:

@Override
protected void onSaveInstanceState(Bundle savedInstanceState)
{
    savedInstanceState.putInt("CLASS_ID", classId);
    super.onSaveInstanceState(savedInstanceState);
}

I am following this SO answer:
onCreate being called on Activity A in up navigation

The problem I am facing is that when I come again to activity A by passing back button in activity B, onCreate gets called and I found savedInstanceState to be NULL.

Edit:

Is there any other way to save my classId variable so that when I return again to activity A, I can use that?

Edit 2

If I set launch mode of my activity A to SingleTop in the manifest file, my issue gets resolved. Is it the right approach?

Body:
Try this

public class SingletonHolder {

    //your id here as what data type you want

    private  static SingletonHolder instance;

    public static SingletonHolder getInstance() {
        if (instance == null) {
            instance = new SingletonHolder();
        }
        return instance;
    }

   //set getter setter here
}

If not successfull feel free to comment


问:
Weird result in MySQL query
I have this query:

SELECT COUNT(1), name, (@i := @i + 1) AS counter FROM mytbl, (SELECT @i := 0) tmp_tbl GROUP BY counter

For this query, the counter column increases its value with 2.

But if I remove COUNT(1), such as:

SELECT name, (@i := @i + 1) AS counter FROM mytbl, (SELECT @i := 0) tmp_tbl GROUP BY counter

counter column increases its value with 1.

Can anyone explain why this behavior?

Table would be:
create table mytbl (name VARCHAR(20));

With data:

INSERT INTO mytbl VALUES
('a1'),
('a2'),
('a3');

答:
As mentioned in MySQL document, we should not assign a value to a user variable and read the value within the same statement. We might get the expected results, but this is not guaranteed. Changing the statement (for example, by adding a GROUP BY, HAVING, or ORDER BY clause) may cause MySQL to select an execution plan with a different order of evaluation.

In your query, counter field will be evaluated in SELECT statement and then be used in GROUP BY statement. Seem when we add an aggregation function to SELECT statement, the field that be used in GROUP BY statement will be evaluated 2 times.

I've create a demo, you could check it. In the demo, I've this query

```<code>SELECT Count(1),
       name,
       ( @i := @i + 1 ) AS counter,
       ( @j := @j + 1 ) AS group_field
FROM   (SELECT 'A' AS name
        UNION
        SELECT 'B' AS name
        UNION
        SELECT 'C' AS name) mytable,
       (SELECT @i := 0) tmp_tbl,
       (SELECT @j := 0) tmp_tbl1
GROUP  BY group_field;
</code>```

In the execution result, counter field only be increased by 1 and group_field be increased by 2.

To make the counter field only increasing by 1, you could try this

```<code>SELECT Count(1),
       name,
       counter
FROM   (SELECT name,
               ( @i := @i + 1 ) AS counter
        FROM   mytbl,
               (SELECT @i := 0) tmp_tbl) data
GROUP  BY counter;
</code>```

Title: Weird result in MySQL query

Body:
As mentioned in MySQL document, we should not assign a value to a user variable and read the value within the same statement. We might get the expected results, but this is not guaranteed. Changing the statement (for example, by adding a GROUP BY, HAVING, or ORDER BY clause) may cause MySQL to select an execution plan with a different order of evaluation.

In your query, counter field will be evaluated in SELECT statement and then be used in GROUP BY statement. Seem when we add an aggregation function to SELECT statement, the field that be used in GROUP BY statement will be evaluated 2 times.

I've create a demo, you could check it. In the demo, I've this query

SELECT Count(1),
       name,
       ( @i := @i + 1 ) AS counter,
       ( @j := @j + 1 ) AS group_field
FROM   (SELECT 'A' AS name
        UNION
        SELECT 'B' AS name
        UNION
        SELECT 'C' AS name) mytable,
       (SELECT @i := 0) tmp_tbl,
       (SELECT @j := 0) tmp_tbl1
GROUP  BY group_field;

In the execution result, counter field only be increased by 1 and group_field be increased by 2.

To make the counter field only increasing by 1, you could try this

SELECT Count(1),
       name,
       counter
FROM   (SELECT name,
               ( @i := @i + 1 ) AS counter
        FROM   mytbl,
               (SELECT @i := 0) tmp_tbl) data
GROUP  BY counter;


问:
Football (soccer) match processing
I want to implement football match processing and so I spent a lot of time to find good algorithms to do it. I have some data as input - players that have some parameters. Some of parameters are static while the match is processing (skills) and some of them are dynamic (physical state, psycological state) that are changing in process. Also I have external parameters that I can change manually. I don't need it to be so close to the real football (excluding result. 20:0 will be awful anyway). And the last main idea is that the same input will not lead to the same output. Some of middle calculations should return random values.

The algorithm should not be very slow because in the near future it will be necessary to process about 1000 matches at the same time step-by-step. Each step will be calculated once per 3 seconds. And also these steps should be logically linked because I will make graphic match process with all ball and players movements.

What algorithms can you recommend for me? I thought about neural network but I'm not sure that this is a good solution.

You will really help me because I spent about of a half of year to find it so thank you very much!

答:
Let's say you have an "action" every 5 minutes of the game, so 90/5 = 18 actions. To make it more realistic you can choose random number like:

```<code>numberOfActions = round(10,20);
</code>```

This number can appear as a lenght of you for().
Than you have interactions between defense and offence parameters of two sets of your players. Lets say each point of offenceA-defenceB creates ten per cent chance to succeed:

```<code>if((TeamA.Offence-TeamB.Defence)*10 > round(0,100))
{
  TeamA.points++;
}
</code>```

Of course the goalkeeper can decrease this probability, maybe even significantly.

And so on. Of course you can make it more complicated. Like you can compare your stats only for certain players, depending on who's having the ball. Your both offence and defense parameters can be decreased by time and raised by condition:

```<code>TeamA._realOffenceValue =
    TeamA.Offence*
    (1-i/numberOfActions)*
    (TeamA.leftOffencePlayer.Condition);
</code>```

Remember that in games like football manager or Europa Universalis it's everything about cheating the player. Balancing the game is a job for many hours and nobody will make it for you on the forum :)

Title: Football (soccer) match processing

Body:
Let's say you have an "action" every 5 minutes of the game, so 90/5 = 18 actions. To make it more realistic you can choose random number like:

numberOfActions = round(10,20);

This number can appear as a lenght of you for().
Than you have interactions between defense and offence parameters of two sets of your players. Lets say each point of offenceA-defenceB creates ten per cent chance to succeed:

if((TeamA.Offence-TeamB.Defence)*10 > round(0,100))
{
  TeamA.points++;
}

Of course the goalkeeper can decrease this probability, maybe even significantly.

And so on. Of course you can make it more complicated. Like you can compare your stats only for certain players, depending on who's having the ball. Your both offence and defense parameters can be decreased by time and raised by condition:

TeamA._realOffenceValue =
    TeamA.Offence*
    (1-i/numberOfActions)*
    (TeamA.leftOffencePlayer.Condition);

Remember that in games like football manager or Europa Universalis it's everything about cheating the player. Balancing the game is a job for many hours and nobody will make it for you on the forum :)


问:
How can I set a column in the footerdata with a dynamic name?
How can I set a column in the footerdata with a dynamic name?

Instead of doing:

```<code>grid.footerData('set', { Total: total.toFixed(1) });
</code>```

I would like to do something like:

```<code>var colName = 'Total'
grid.footerData('set', { colName: total.toFixed(1) });
</code>```

But this obviously is not working... How can I make this work?

Thanks!

答:
The object

{ Total: total.toFixed(1) }
```

<p>has <code>Total</code> property. You can create the property dynamically by usage <code>[]</code>:</p>

<pre class="lang-js prettyprint-override"><code>var colName = 'Total', options = {};
options[colName] = total.toFixed(1);
grid.footerData('set', options);
</code>```

Body:
How can I set a column in the footerdata with a dynamic name?

Instead of doing:

grid.footerData('set', { Total: total.toFixed(1) });

I would like to do something like:

var colName = 'Total'
grid.footerData('set', { colName: total.toFixed(1) });

But this obviously is not working... How can I make this work?

Thanks!

Body:
The object

{ Total: total.toFixed(1) }

has Total property. You can create the property dynamically by usage []:

var colName = 'Total', options = {};
options[colName] = total.toFixed(1);
grid.footerData('set', options);


问:
Understanding "Too many ancestors" from pylint
example.py:

```<code>'''
demo too many ancestors
'''
from flask_security.forms import RegisterForm
from wtforms.fields import TextField

class ExtendedRegisterForm(RegisterForm):
    '''An extended register form'''
    name = TextField('Name', [])
</code>```

When I run pylint:

```<code>$ pylint -r n example.py
************* Module example
R:  7, 0: Too many ancestors (10/7) (too-many-ancestors)
</code>```

What does this mean and how can I fix it?

答:
In addition to the disabling directives in the source code, you can configure this through the --max-parents= commandline option. You can also specify this in the config file (.pylintrc):

```<code>[DESIGN]
max-parents=15
</code>```

As you can see I set it to 15 as many classes in Django (my project), particularly its view classes, will have hierarchies that are deeper than the default 7.

Body:
example.py:

'''
demo too many ancestors
'''
from flask_security.forms import RegisterForm
from wtforms.fields import TextField

class ExtendedRegisterForm(RegisterForm):
    '''An extended register form'''
    name = TextField('Name', [])

When I run pylint:

$ pylint -r n example.py
************* Module example
R:  7, 0: Too many ancestors (10/7) (too-many-ancestors)

What does this mean and how can I fix it?

Body:
In addition to the disabling directives in the source code, you can configure this through the --max-parents= commandline option. You can also specify this in the config file (.pylintrc):

[DESIGN]
max-parents=15

As you can see I set it to 15 as many classes in Django (my project), particularly its view classes, will have hierarchies that are deeper than the default 7.


问:
SQL - Only show results for one column in first instance of a duplicated record
I am finding it difficult to explain exactly what I am trying to achieve so I think it best to show a visual representation.

Example of how my query results currently look

Example of how I want the results to look

The report I am running shows a list of every product within orders. Each product has its own cost assigned to it. Another column is a delivery charge, but this is a charge assigned to the order; not individual products. I want to be able to show the delivery charge against the first product in each order ONLY.

I have attempted, for far too long, to try and find an answer to this query but have had no luck. I don't know if it is even possible so assistance of any sort, or even just being pointed in the right direction, would be of great help.

Thanks

EDIT.

If it helps here is my query:

```<code>SELECT dbo.Orders.EncryptedOrderId,
       dbo.OrderProduct.ProductID,
       dbo.OrderProduct.QuantityPerRecipient,
       dbo.OrderProduct.NumRecipients,
       dbo.OrderProduct.TotalQuantity,
       dbo.DocType.Name AS [Product Type],
       dbo.ProductGroup_Culture.Name AS [Product Group],
       RIGHT(CatalogNo, CHARINDEX('_', REVERSE('_' + CatalogNo)) -1) AS [HamptonsType],
       FORMAT(dbo.Orders.DateOrderCreated, 'dd/MM/yyyy HH:mm:ss') AS 'DateOrderCreated',
       CAST(REPLACE(dbo.Orders.ClearingResult, 'utf-8', 'utf-16') AS XML ).value('(/UserData//CostCenter/node())[1]', 'nvarchar(max)') AS [Cost Center],
       dbo.Users.FirstName,
       dbo.Users.LastName,
       dbo.Users.CompanyName AS [Branch Name],
       dbo.Users.Department AS Subsidiary,
       dbo.Users.Custom1,
       dbo.Users.Custom2,
       dbo.Users.Custom3,
       dbo.Users.Custom4,
       dbo.Users.Custom5,
       dbo.OrderProduct.TotalPrice,
       dbo.Orders.ShippingCharges,
       dbo.OrderProduct.OrderProductID,
       dbo.FileSubmissionDocument.OriginalFileType,
       COALESCE (dbo.FileSubmissionDocument.Title, dbo.Product_Culture.Name) AS [Product Name],
       OPDV.FriendlyValue AS 'BCard Recipient'
FROM dbo.DocType
INNER JOIN dbo.Doc
    ON dbo.DocType.DocTypeID = dbo.Doc.DocTypeID
INNER JOIN dbo.OrderProduct
    ON dbo.Doc.ProductID = dbo.OrderProduct.ProductID
LEFT JOIN dbo.Product
    ON dbo.Product.ProductID = dbo.Doc.ProductID
LEFT JOIN dbo.ProductGroupMembership
    ON dbo.ProductGroupMembership.ProductID = dbo.Doc.ProductID
LEFT JOIN dbo.ProductGroup_Culture
    ON dbo.ProductGroup_Culture.ProductGroupID = dbo.ProductGroupMembership.ProductGroupID
INNER JOIN dbo.Orders
    ON dbo.OrderProduct.OrderID = dbo.Orders.OrderID
INNER JOIN dbo.Users
    ON dbo.Orders.UserID = dbo.Users.UserID
INNER JOIN dbo.Product_Culture
    ON dbo.OrderProduct.ProductID = dbo.Product_Culture.ProductID
INNER JOIN dbo.Store_Culture
    ON dbo.Store_Culture.StoreID = dbo.Users.AssignedToStoreID FULL OUTER
JOIN dbo.FileSubmissionDocument
    ON dbo.OrderProduct.OrderProductID = dbo.FileSubmissionDocument.SubOrderProductID - 1
LEFT JOIN (SELECT OP.OrderProductID,
                  OP.DialID,
                  OP.FriendlyValue
           FROM OrderProductDialValue OP
           LEFT JOIN Dial DI ON DI.DialID = OP.DialID
           LEFT JOIN OrderProduct OT ON OT.OrderProductID = OP.OrderProductID
           LEFT JOIN Product PR ON PR.ProductID = OT.ProductID
           WHERE PR.ExternalID = 'BCName'
           AND DI.UProduceDialName = 'Name') OPDV ON OPDV.OrderProductID = dbo.OrderProduct.OrderProductID
WHERE ('@CUSTOMERNAME' is null
        OR '@CUSTOMERNAME' = ''
        OR dbo.Store_Culture.Name LIKE '%' + '@CUSTOMERNAME' + '%')
        AND dbo.OrderProduct.IsDraft = 0
        AND dbo.Orders.IsCart=0
        AND dbo.Orders.IsSaveForLater=0
        AND (('@DATE' <= dbo.Orders.DateOrderCreated)
        OR ('@DATE' IS NULL)
        OR ('@DATE'=''))
        AND ((DATEADD(day, 1, '@DATE') >= dbo.Orders.DateOrderCreated)
        OR ('@DATE' IS NULL)
        OR ('@DATE'=''))
AND dbo.Users.LastName NOT LIKE '%TEST%'
ORDER BY  dbo.Orders.OrderID DESC, dbo.OrderProduct.OrderProductID DESC
</code>```

The query runs through a reporting system on an online portal so the values that show as @CUSTOMERNAME or @DATE are variables based on values given at the time when the report is run.

答:
I assume your query looks like

```<code>    select orderID
         , productID
         , productValue
         , DeliveryCharge
      from test_t
  order by orderID
         , productValue desc
         ;
</code>```

and that you want delivery charges listed for the most expensive product of each order.

If supported by your rdbms, you can use the analytic RANK function

```<code>    select orderID
         , productID
         , productValue
         , DeliveryCharge
         , CASE RANK() OVER ( PARTITION BY orderID ORDER BY productValue DESC ) WHEN 1 THEN DeliveryCharge ELSE NULL END r
      from test_t
  order by orderID
         , productValue desc
         ;
</code>```

If your rdbms does not support RANK, you can emulate it using a left join with a suitably aggregated copy of your table:

```<code>    select t.orderID
         , t.productID
         , t.productValue
         , rt.mdc DeliveryCharge
      from test_t t
 left join (
                select orderID
                     , max(productValue)    mp
                     , max(DeliveryCharge)  mdc
                  from test_t
              group by orderID
           ) rt
        on (
                 rt.orderID = t.orderID
             AND rt.mp      = t.productValue
           )
  order by orderID
         , productValue desc
         ;
</code>```

The tacit assumption is that the delivery charge is by order (which seems reasonable as you wouldn't want to selectively drop it otherwise, right ?).

Moreover, both solutions will produce multiple rows containing the delivery charge per order if that order contains multipleproducts with the same productValue.

Tested on oracle 12c1;

Body:
I am finding it difficult to explain exactly what I am trying to achieve so I think it best to show a visual representation.

Example of how my query results currently look

Example of how I want the results to look

The report I am running shows a list of every product within orders. Each product has its own cost assigned to it. Another column is a delivery charge, but this is a charge assigned to the order; not individual products. I want to be able to show the delivery charge against the first product in each order ONLY.

I have attempted, for far too long, to try and find an answer to this query but have had no luck. I don't know if it is even possible so assistance of any sort, or even just being pointed in the right direction, would be of great help.

Thanks

EDIT.

If it helps here is my query:

SELECT dbo.Orders.EncryptedOrderId,
       dbo.OrderProduct.ProductID,
       dbo.OrderProduct.QuantityPerRecipient,
       dbo.OrderProduct.NumRecipients,
       dbo.OrderProduct.TotalQuantity,
       dbo.DocType.Name AS [Product Type],
       dbo.ProductGroup_Culture.Name AS [Product Group],
       RIGHT(CatalogNo, CHARINDEX('_', REVERSE('_' + CatalogNo)) -1) AS [HamptonsType],
       FORMAT(dbo.Orders.DateOrderCreated, 'dd/MM/yyyy HH:mm:ss') AS 'DateOrderCreated',
       CAST(REPLACE(dbo.Orders.ClearingResult, 'utf-8', 'utf-16') AS XML ).value('(/UserData//CostCenter/node())[1]', 'nvarchar(max)') AS [Cost Center],
       dbo.Users.FirstName,
       dbo.Users.LastName,
       dbo.Users.CompanyName AS [Branch Name],
       dbo.Users.Department AS Subsidiary,
       dbo.Users.Custom1,
       dbo.Users.Custom2,
       dbo.Users.Custom3,
       dbo.Users.Custom4,
       dbo.Users.Custom5,
       dbo.OrderProduct.TotalPrice,
       dbo.Orders.ShippingCharges,
       dbo.OrderProduct.OrderProductID,
       dbo.FileSubmissionDocument.OriginalFileType,
       COALESCE (dbo.FileSubmissionDocument.Title, dbo.Product_Culture.Name) AS [Product Name],
       OPDV.FriendlyValue AS 'BCard Recipient'
FROM dbo.DocType
INNER JOIN dbo.Doc
    ON dbo.DocType.DocTypeID = dbo.Doc.DocTypeID
INNER JOIN dbo.OrderProduct
    ON dbo.Doc.ProductID = dbo.OrderProduct.ProductID
LEFT JOIN dbo.Product
    ON dbo.Product.ProductID = dbo.Doc.ProductID
LEFT JOIN dbo.ProductGroupMembership
    ON dbo.ProductGroupMembership.ProductID = dbo.Doc.ProductID
LEFT JOIN dbo.ProductGroup_Culture
    ON dbo.ProductGroup_Culture.ProductGroupID = dbo.ProductGroupMembership.ProductGroupID
INNER JOIN dbo.Orders
    ON dbo.OrderProduct.OrderID = dbo.Orders.OrderID
INNER JOIN dbo.Users
    ON dbo.Orders.UserID = dbo.Users.UserID
INNER JOIN dbo.Product_Culture
    ON dbo.OrderProduct.ProductID = dbo.Product_Culture.ProductID
INNER JOIN dbo.Store_Culture
    ON dbo.Store_Culture.StoreID = dbo.Users.AssignedToStoreID FULL OUTER
JOIN dbo.FileSubmissionDocument
    ON dbo.OrderProduct.OrderProductID = dbo.FileSubmissionDocument.SubOrderProductID - 1
LEFT JOIN (SELECT OP.OrderProductID,
                  OP.DialID,
                  OP.FriendlyValue
           FROM OrderProductDialValue OP
           LEFT JOIN Dial DI ON DI.DialID = OP.DialID
           LEFT JOIN OrderProduct OT ON OT.OrderProductID = OP.OrderProductID
           LEFT JOIN Product PR ON PR.ProductID = OT.ProductID
           WHERE PR.ExternalID = 'BCName'
           AND DI.UProduceDialName = 'Name') OPDV ON OPDV.OrderProductID = dbo.OrderProduct.OrderProductID
WHERE ('@CUSTOMERNAME' is null
        OR '@CUSTOMERNAME' = ''
        OR dbo.Store_Culture.Name LIKE '%' + '@CUSTOMERNAME' + '%')
        AND dbo.OrderProduct.IsDraft = 0
        AND dbo.Orders.IsCart=0
        AND dbo.Orders.IsSaveForLater=0
        AND (('@DATE' <= dbo.Orders.DateOrderCreated)
        OR ('@DATE' IS NULL)
        OR ('@DATE'=''))
        AND ((DATEADD(day, 1, '@DATE') >= dbo.Orders.DateOrderCreated)
        OR ('@DATE' IS NULL)
        OR ('@DATE'=''))
AND dbo.Users.LastName NOT LIKE '%TEST%'
ORDER BY  dbo.Orders.OrderID DESC, dbo.OrderProduct.OrderProductID DESC

The query runs through a reporting system on an online portal so the values that show as @CUSTOMERNAME or @DATE are variables based on values given at the time when the report is run.

Body:
I assume your query looks like

    select orderID
         , productID
         , productValue
         , DeliveryCharge
      from test_t
  order by orderID
         , productValue desc
         ;

and that you want delivery charges listed for the most expensive product of each order.

If supported by your rdbms, you can use the analytic RANK function

    select orderID
         , productID
         , productValue
         , DeliveryCharge
         , CASE RANK() OVER ( PARTITION BY orderID ORDER BY productValue DESC ) WHEN 1 THEN DeliveryCharge ELSE NULL END r
      from test_t
  order by orderID
         , productValue desc
         ;

If your rdbms does not support RANK, you can emulate it using a left join with a suitably aggregated copy of your table:

    select t.orderID
         , t.productID
         , t.productValue
         , rt.mdc DeliveryCharge
      from test_t t
 left join (
                select orderID
                     , max(productValue)    mp
                     , max(DeliveryCharge)  mdc
                  from test_t
              group by orderID
           ) rt
        on (
                 rt.orderID = t.orderID
             AND rt.mp      = t.productValue
           )
  order by orderID
         , productValue desc
         ;

The tacit assumption is that the delivery charge is by order (which seems reasonable as you wouldn't want to selectively drop it otherwise, right ?).

Moreover, both solutions will produce multiple rows containing the delivery charge per order if that order contains multipleproducts with the same productValue.

Tested on oracle 12c1;


问:
How to declare that primary key is both one-to-one field?
If I write this way

```<code>@Id
@OneToOne
@JoinColumn(name="Id")
private Region region;
</code>```

it says

```<code>Composite-id class must implement Serializable: ....InPopulation
</code>```

I don't want it be composite key, I just want id replaced by Region of appropriate id.

答:
You use the MapsId annotation for that (i have assumed how the @Id is declared):

```<code>@Id
private Long id;

@JoinColumn(name = "Id")
@OneToOne
@MapsId
private Region region;
</code>```

Body:
If I write this way

@Id
@OneToOne
@JoinColumn(name="Id")
private Region region;

it says

Composite-id class must implement Serializable: ....InPopulation

I don't want it be composite key, I just want id replaced by Region of appropriate id.

Body:
You use the MapsId annotation for that (i have assumed how the @Id is declared):

@Id
private Long id;

@JoinColumn(name = "Id")
@OneToOne
@MapsId
private Region region;


问:
Jersey with Spring Tomcat doesnot start after adding spring web 4.3.5 jar
I am trying to create a REST service using Jersey and spring.(eclipse IDE with Tomcat 8.0 server)
I have added the "org.springframework.web.context.ContextLoaderListener" as the listener in web.xml.

```<code>  <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
</code>```

I added Spring-Web 4.3.5 jar in the classpath of the Tomcat server in eclipse, but after adding this TomCat does not start.

```<code> Mar 28, 2017 12:52:33 AM org.apache.catalina.core.ContainerBase startInternal
SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[]]
    at java.util.concurrent.FutureTask.report(FutureTask.java:122)
    at java.util.concurrent.FutureTask.get(FutureTask.java:192)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:943)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:871)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:162)
    ... 6 more
Caused by: java.lang.NoClassDefFoundError: javax/servlet/ServletContainerInitializer
    at java.lang.ClassLoader.findBootstrapClass(Native Method)
    at java.lang.ClassLoader.findBootstrapClassOrNull(ClassLoader.java:1015)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:413)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1252)
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1167)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at org.apache.catalina.startup.WebappServiceLoader.loadServices(WebappServiceLoader.java:186)
    at org.apache.catalina.startup.WebappServiceLoader.load(WebappServiceLoader.java:157)
    at org.apache.catalina.startup.ContextConfig.processServletContainerInitializers(ContextConfig.java:1631)
    at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1140)
    at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:783)
    at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:307)
    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:95)
    at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5213)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
    ... 6 more
</code>```

how to get this resolved?

答:
Issue has been resolved:

Solution: Removed the jar from Server Class path
Instead added the jar as part of the Deployment assembly section  for the project.

How to add a jar to the Deployment assembly:
Right click - properties- Deployment assembly- add the jar.

Body:
I am trying to create a REST service using Jersey and spring.(eclipse IDE with Tomcat 8.0 server)
I have added the "org.springframework.web.context.ContextLoaderListener" as the listener in web.xml.

  <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

I added Spring-Web 4.3.5 jar in the classpath of the Tomcat server in eclipse, but after adding this TomCat does not start.

 Mar 28, 2017 12:52:33 AM org.apache.catalina.core.ContainerBase startInternal
SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[]]
    at java.util.concurrent.FutureTask.report(FutureTask.java:122)
    at java.util.concurrent.FutureTask.get(FutureTask.java:192)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:943)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:871)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:162)
    ... 6 more
Caused by: java.lang.NoClassDefFoundError: javax/servlet/ServletContainerInitializer
    at java.lang.ClassLoader.findBootstrapClass(Native Method)
    at java.lang.ClassLoader.findBootstrapClassOrNull(ClassLoader.java:1015)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:413)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1252)
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1167)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at org.apache.catalina.startup.WebappServiceLoader.loadServices(WebappServiceLoader.java:186)
    at org.apache.catalina.startup.WebappServiceLoader.load(WebappServiceLoader.java:157)
    at org.apache.catalina.startup.ContextConfig.processServletContainerInitializers(ContextConfig.java:1631)
    at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1140)
    at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:783)
    at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:307)
    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:95)
    at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5213)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
    ... 6 more

how to get this resolved?


问:
Check if location is on a toll road
I am working on a shipment system and in order to calculate the charge for a shipment I need to know if the driver whas in a toll road during the job so I can add the charge to the shipment.

I get the location of the driver all the time from an android/ios app he is using.

My question is:

Is there a way to send a location (latitude & longitude) to google maps api and get back an answere if the location is on a toll road.

Thank you

答:
Well, there is no API for this particular request, that u send a location and give you true/false for toll!

but you can do one thing, usually when road have toll, in html_instructions of the response, there is "toll road" string. so what you can do is to send the location and get the response, and search for "toll road" in the response. if exist, that mean the location have toll!

I write a example code for you :

```<code>$.get(
"https://maps.googleapis.com/maps/api/directions/json?origin=Milwaukee,WI&destination=Rolling+Meadows,IL&key=YOURAPIKEY",

function(data) {
   var routes = JSON.stringify(data.routes);
   var isToll = routes.search("toll road");
   if(isToll===-1){
    return false;
   }
   else{
   return true;
   }
}
);
</code>```

Remember to replace your API KEY in the URL.

Title: Check if location is on a toll road

Body:
Well, there is no API for this particular request, that u send a location and give you true/false for toll!

but you can do one thing, usually when road have toll, in html_instructions of the response, there is "toll road" string. so what you can do is to send the location and get the response, and search for "toll road" in the response. if exist, that mean the location have toll!

I write a example code for you :

$.get(
"https://maps.googleapis.com/maps/api/directions/json?origin=Milwaukee,WI&destination=Rolling+Meadows,IL&key=YOURAPIKEY",

function(data) {
   var routes = JSON.stringify(data.routes);
   var isToll = routes.search("toll road");
   if(isToll===-1){
    return false;
   }
   else{
   return true;
   }
}
);

Remember to replace your API KEY in the URL.


问:
How to delete last character from a string using jQuery?
How to delete last character from a string for instance in 123-4- when I delete 4 it should display 123- using jQuery.

答:
@skajfes and @GolezTrol provided the best methods to use.  Personally, I prefer using "slice()".  It's less code, and you don't have to know how long a string is. Just use:</p>

```<code>//-----------------------------------------
// @param begin  Required. The index where
//               to begin the extraction.
//               1st character is at index 0
//
// @param end    Optional. Where to end the
//               extraction. If omitted,
//               slice() selects all
//               characters from the begin
//               position to the end of
//               the string.
var str = '123-4';
alert(str.slice(0, -1));
</code>```

Body:
@skajfes and @GolezTrol provided the best methods to use.  Personally, I prefer using "slice()".  It's less code, and you don't have to know how long a string is. Just use:

//-----------------------------------------
// @param begin  Required. The index where
//               to begin the extraction.
//               1st character is at index 0
//
// @param end    Optional. Where to end the
//               extraction. If omitted,
//               slice() selects all
//               characters from the begin
//               position to the end of
//               the string.
var str = '123-4';
alert(str.slice(0, -1));


问:
Use Ajax post call in codeigniter cause Internal Server Error
This is the error message found on google chrome:

POST http://localhost/display/register/registerUser 500 (Internal Server Error)

My project file name is "display".

One controller file named "register" ,it has a function called "registerUser". All it does is getting user's input, and compare it with database to see if the name is used or not, if valid store it into database and give them a success message, if not valid give a error message.

```<code>$username=$this->input->post('name');
    $password=$this->input->post('password');

    $result=$this->user->checkExistUser($username);

    if(!$result){

        $data=array(
            'username'=>$username,
            'password'=>md5($password)
            );

    $this->user->register($data);

    echo "<script>alert('You have success registered');</script>";
    $this->load->view('home_view');
    }
    else{

        echo "<script>alert('Sorry, this email address has been used!');</script>";
        $this->load->view('registerView');
    }
</code>```

This is my view file named registerView

```<code><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Welcome to Stock game</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js">
</script>

</head>
<body>

<div id="container">
<h1>Welcome to Stock game!</h1>

<div id="body">
    <p>This is the register page</p>

</div>

<div>

    <form  name="userform" id="userform" >
    <input type="text" name="name" placeholder="Name"/>
    <input type="text" name="password" placeholder="Password"/>

    <button name="submit" value="submit">Register</button>
    </form>
</div>
    <script type="text/javascript">
    $(document).ready(function(){
        $('form#userform').on('submit',function(e){
            e.preventDefault();

    var name=$("#name").val();
    var password=$("#password").val();
    $.ajax({

        type:'POST',
        url:'register/registerUser',
        data:
        {'name':JSON.stringify(name),'password':JSON.stringify(password)},
        dataType:'JSON',
        success: function(response){
            if(response=="success"){
                alert("Yes login");
            }
        },
       error: function (xhr, ajaxOptions, thrownError) {
       alert(xhr.status);
       alert(xhr.responseText);
       alert(thrownError);
   }
   });
        });
    });
    </script>
    </div>
    <br/>
    </body>
    </html>
</code>```

I have tested the controller and model class with a simple form post(form action=xxx, method=post) and it is no error.
I searched almost every stackoverflow questions about this, but i still cannot fix it, I hope someone can help me.

答:
Append the base url in your ajax</p>

```<code>url:<?php echo base_url(); ?>'register/registerUser',
</code>```

Body:
This is the error message found on google chrome:

POST http://localhost/display/register/registerUser 500 (Internal Server Error)

My project file name is "display".

One controller file named "register" ,it has a function called "registerUser". All it does is getting user's input, and compare it with database to see if the name is used or not, if valid store it into database and give them a success message, if not valid give a error message.

$username=$this->input->post('name');
    $password=$this->input->post('password');

    $result=$this->user->checkExistUser($username);

    if(!$result){

        $data=array(
            'username'=>$username,
            'password'=>md5($password)
            );

    $this->user->register($data);

    echo "";
    $this->load->view('home_view');
    }
    else{

        echo "";
        $this->load->view('registerView');
    }

This is my view file named registerView

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?><!DOCTYPE html>

<meta charset="utf-8">
<title>Welcome to Stock game</title>

Welcome to Stock game!

This is the register page

    <form  name="userform" id="userform" >
    <input type="text" name="name" placeholder="Name"/>
    <input type="text" name="password" placeholder="Password"/>

    <button name="submit" value="submit">Register</button>
    </form>

I have tested the controller and model class with a simple form post(form action=xxx, method=post) and it is no error.
I searched almost every stackoverflow questions about this, but i still cannot fix it, I hope someone can help me.

Body:
Append the base url in your ajax

url:<?php echo base_url(); ?>'register/registerUser',


问:
only include some keys from {...props}
here's a first world problem.. I might be asking for something impossible, but I decided to at least ask the question.

I have a react component like this:

```<code>function TextInput(props) {
  return <input type="text" {...props} />;
}
</code>```

But I don't want people to pass in unexpected values in props because that could break the input. Testing is obviously harder this way too.

So I refactored it to this. Lets say I only want to allow name, value, and placeholder.

```<code>function TextInput({value, name, placeholder}) {
  const inputProps = {value, name, placeholder};

  return <input type="text" {...inputProps} />;
}
</code>```

However I think this looks strange and unnecessarily duplicated, right?

Question: Is there a shorter/better way to keep the spread {...inputProps}, but only include the values I specified, without repeating the keys twice? And without adding more "lines" of code.

Why do I want this?

I know this is pedantic and I could do it in 2 lines and some repeating, but I'm trying to find a short, good pattern that I can reuse in both smaller and bigger components.

Why do I want the spread? Because it makes it so much more readable than listing all props and maybe even having to add line breaks inside the element when there are too many props. This is more notable with inner children though, like this:

```<code><div
  foo="bar"
  bar={foo}
  z={y}
>
  innerChildContent
</div>
</code>```

I think it's just so much easier to read if I can keep the keys to javascript objects or something similar.

答:
this is why some people use react + typescript.
In my case i setup input props in interface:

```<code>interface IUserSideBarProps {
    usersData: {
        FullName: string;
        Login: string;
        [propName: string]: any;
    }[];
    options: ISideBarOptions;
    currentUserLogin: string;
}

export class UserSideBar extends React.Component<IUserSideBarProps, undefined> {
</code>```

but i don't know will it be same in plain javaScript

Title: only include some keys from {...props}

Body:
here's a first world problem.. I might be asking for something impossible, but I decided to at least ask the question.

I have a react component like this:

function TextInput(props) {
  return <input type="text" {...props} />;
}

But I don't want people to pass in unexpected values in props because that could break the input. Testing is obviously harder this way too.

So I refactored it to this. Lets say I only want to allow name, value, and placeholder.

function TextInput({value, name, placeholder}) {
  const inputProps = {value, name, placeholder};

  return <input type="text" {...inputProps} />;
}

However I think this looks strange and unnecessarily duplicated, right?

Question: Is there a shorter/better way to keep the spread {...inputProps}, but only include the values I specified, without repeating the keys twice? And without adding more "lines" of code.

Why do I want this?

I know this is pedantic and I could do it in 2 lines and some repeating, but I'm trying to find a short, good pattern that I can reuse in both smaller and bigger components.

Why do I want the spread? Because it makes it so much more readable than listing all props and maybe even having to add line breaks inside the element when there are too many props. This is more notable with inner children though, like this:

  innerChildContent

I think it's just so much easier to read if I can keep the keys to javascript objects or something similar.

Body:
this is why some people use react + typescript.
In my case i setup input props in interface:

interface IUserSideBarProps {
    usersData: {
        FullName: string;
        Login: string;
        [propName: string]: any;
    }[];
    options: ISideBarOptions;
    currentUserLogin: string;
}

export class UserSideBar extends React.Component<IUserSideBarProps, undefined> {

but i don't know will it be same in plain javaScript


问:
How to grep word from file
I want to grep some word inside a file from another file. My code is able to grep the word on last line of the file but not the word before it. I have no idea why and hope can get help here. Below is the perl script i using:

```<code>open(FILE1,"file1.txt") or die "Error, File1 could not open\n";
open(FILE2,"file2.txt") or die "Error, File2 could not open\n";
open(FILE3, ">file3.txt") or die "Error, File3 could not open\n";

use strict;
use warnings;
use List::MoreUtils qw(uniq);

my @file1=<FILE1>;
my @file2=<FILE2>;
my $j =0;
my $i =0;
my $zone =0;
for ($j=0; $j<=$#file2; $j++){
    $zone = $file2[$j];
    unless ( $zone =~ m/#(.*?)/ ) {
        print "$zone";
        my @fid = grep /$zone/ , @file1;
        @fid = uniq(@fid);
        s{^\s+|\s+$}{}g foreach @fid;                #cancel leading space
        for ($i=0; $i<=$#fid; $i++){
            print FILE3 "$fid[$i]\n";
        }
        #@fid=();

    }
}

close(FILE3);
</code>```

My file1.txt is something like this:

```<code>i am a dog
i am a cat
we are the fish
he is a boy
she is a girl
</code>```

My file2.txt is like this:

```<code>is
am
</code>```

But my file3 can only show those sentence contain am but no is, if i put is in second line and am in first line then my file3 only contain the sentences with is. I not very sure why my code can only grep the last row in my file2. Thanks for the help.

答:
please try this .

```<code>use strict;
use warnings;
use List::MoreUtils qw(uniq);

open(FILE1,"file1.txt") or die "Error, File1 could not open\n";
open(FILE2,"file2.txt") or die "Error, File2 could not open\n";
open(FILE3, ">file3.txt") or die "Error, File3 could not open\n";

my @file1=<FILE1>;
my @file2=<FILE2>;
my $j =0;
my $i =0;

foreach my $main_line(@file1){
    chomp($main_line);
    foreach my $line(@file2){
        chomp($line);
        if ($main_line =~ /$line/i) {
            print FILE3 "$main_line\n";
        }
    }
}

close(FILE3);
</code>```

thanks,
praveenzx~

Title: How to grep word from file

Body:
I want to grep some word inside a file from another file. My code is able to grep the word on last line of the file but not the word before it. I have no idea why and hope can get help here. Below is the perl script i using:

open(FILE1,"file1.txt") or die "Error, File1 could not open\n";
open(FILE2,"file2.txt") or die "Error, File2 could not open\n";
open(FILE3, ">file3.txt") or die "Error, File3 could not open\n";

use strict;
use warnings;
use List::MoreUtils qw(uniq);

my @file1=<FILE1>;
my @file2=<FILE2>;
my $j =0;
my $i =0;
my $zone =0;
for ($j=0; $j<=$#file2; $j++){
    $zone = $file2[$j];
    unless ( $zone =~ m/#(.*?)/ ) {
        print "$zone";
        my @fid = grep /$zone/ , @file1;
        @fid = uniq(@fid);
        s{^\s+|\s+$}{}g foreach @fid;                #cancel leading space
        for ($i=0; $i<=$#fid; $i++){
            print FILE3 "$fid[$i]\n";
        }
        #@fid=();

    }
}

close(FILE3);

My file1.txt is something like this:

i am a dog
i am a cat
we are the fish
he is a boy
she is a girl

My file2.txt is like this:

is
am

But my file3 can only show those sentence contain am but no is, if i put is in second line and am in first line then my file3 only contain the sentences with is. I not very sure why my code can only grep the last row in my file2. Thanks for the help.

Body:
please try this .

use strict;
use warnings;
use List::MoreUtils qw(uniq);

open(FILE1,"file1.txt") or die "Error, File1 could not open\n";
open(FILE2,"file2.txt") or die "Error, File2 could not open\n";
open(FILE3, ">file3.txt") or die "Error, File3 could not open\n";

my @file1=<FILE1>;
my @file2=<FILE2>;
my $j =0;
my $i =0;

foreach my $main_line(@file1){
    chomp($main_line);
    foreach my $line(@file2){
        chomp($line);
        if ($main_line =~ /$line/i) {
            print FILE3 "$main_line\n";
        }
    }
}

close(FILE3);

thanks,
praveenzx~


Title: How to substring a given string with specific rules in java

Body:
This is my code and it is showing error at while.Index out of bound exception is coming.The substrings should be such that

Max 50 characters per string

No number should be broken - for example " 4318, 4466, 486," is acceptable but  " 4318, 4466, 48" is not

Substring should always start with one space and end with comma ","

can someone help me out with this please

 public class MyString {

/**
 * @param args

 */
static String input = " 4318, 4466, 486, 1698, 478, 590, 582, 1594, 486, 1690, 702, 378, 486, 586, 486, 1694, 486, 598, 538, 526, 486, 1694, 486, 622, 434, 630, 462, 1730, 422, 1754, 450, 586, 486, 1690, 498, 1682, 486, 586, 502, 606, 454, 1698, 478, 1694, 486, 1718, 458, 1686, 726, 1458, 646, 426, 486, 1694, 482, 1694, 486, 590, 482, 622, 490, 550, 490, 602, 450, 634, 466, 586, 486, 1730, 426, 1714, 494, 622, 446, 590, 494, 618, 450, 586, 490, 586, 486, 1730, 450, 586, 486, 590, 502, 1674, 530, 1650, 482, 1690, 558, 1622, 486, 1690, 486, 5298, 4306, 4466, 530, 1646, 486, 594, 650, 1502, 546, 1650, 490, 586, 486, 622, 522, 1622, 486, 602, 454, 634, 462, 1694, 482, 590, 486, 590, 486, 1694, 482, 1730, 450, 590, 498, 1638, 526, 1690, 498, 606, 458, 586, 486, 1698, 482, 1694, 482, 1690, 486, 1694, 486, 1698, 574, 494, 486, 1714, 462, 1690, 486, 626, 430, 610, 486, 590, 490, 622, 426, 610, 498, 618, 446, 1690, 486, 1734, 446, 590, 482, 590, 502, 606, 454, 590, 502, 582, 478, 1690, 486, 586, 506, 578, 482, 1686, 558, 1622, 674, 1506, 482, 1698, 590, 1606, 462, 1000";
char space=' ';
 static char comma=',';
public static void main(String[] args) {
    // TODO Auto-generated method stub
    int start=0, end=0;
    while (end-1 < input.length()){

    start=end;
    end= start+ 50;

    String output= input.substring(start,end);
    if(output.charAt(start)==' ' && output.charAt(end-1)==',')
    {
    System.out.println(output);
    }
    else
    {

    while(!(output.charAt(end-1)==','))
    {

    end--;

    }
    output= input.substring(start,end);
    System.out.println(output);

    }
    }
    }

}

Body:
I dont understand the question but I think you are looking for this

  public class Snippet {
    static String input = " 4318, 4466, 486, 1698, 478, 590, 582, 1594, 486,            1690, 702, 378, 486, 586, 486, 1694, 486, 598, 538, 526, 486, 1694, 486, 622, 434, 630, 462, 1730, 422, 1754, 450, 586, 486, 1690, 498, 1682, 486, 586, 502, 606, 454, 1698, 478, 1694, 486, 1718, 458, 1686, 726, 1458, 646, 426, 486, 1694, 482, 1694, 486, 590, 482, 622, 490, 550, 490, 602, 450, 634, 466, 586, 486, 1730, 426, 1714, 494, 622, 446, 590, 494, 618, 450, 586, 490, 586, 486, 1730, 450, 586, 486, 590, 502, 1674, 530, 1650, 482, 1690, 558, 1622, 486, 1690, 486, 5298, 4306, 4466, 530, 1646, 486, 594, 650, 1502, 546, 1650, 490, 586, 486, 622, 522, 1622, 486, 602, 454, 634, 462, 1694, 482, 590, 486, 590, 486, 1694, 482, 1730, 450, 590, 498, 1638, 526, 1690, 498, 606, 458, 586, 486, 1698, 482, 1694, 482, 1690, 486, 1694, 486, 1698, 574, 494, 486, 1714, 462, 1690, 486, 626, 430, 610, 486, 590, 490, 622, 426, 610, 498, 618, 446, 1690, 486, 1734, 446, 590, 482, 590, 502, 606, 454, 590, 502, 582, 478, 1690, 486, 586, 506, 578, 482,
1686, 558, 1622, 674, 1506, 482, 1698, 590, 1606, 462, 1000";
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int start=0, end=0;
        String[] a=input.split(",");
        System.out.println(a);
        for (int i = 0; i < a.length; i++) {

            System.out.print(a[i]);
            if(!(a.length-1==i))
            {
            System.out.print(",");
            }
        }
    }
}


问:
Finding the address range of the data segment
As a programming exercise, I am writing a mark-and-sweep garbage collector in C. I wish to scan the data segment (globals, etc.) for pointers to allocated memory, but I don't know how to get the range of the addresses of this segment. How could I do this?</p>

答: Since you'll probably have to make your garbage collector the environment in which the program runs, you can get it from the elf file directly.</p>


问:
Replace "." with "_" in file name
I am using PowerShell to replace pdf file names:

```<code>Get-ChildItem -Path C:\All -Filter *.pdf | Rename-Item -NewName { $_.Name.Replace('.','_') }
</code>```

It works fine if I replace %20 to _, but if we use "test.one.pdf", I need "test_one.pdf" as output, if I use above syntax it replaces the . before pdf like "test_one_pdf".

答:
Your code will rename name.001.pdf to name_001_pdf, so unless you actually want to remove the extensions of your files you need to replace only within the files name and not the extension.

```<code>Get-ChildItem -Path "C:\All" -Filter "*.pdf" | Rename-Item -NewName { $_.BaseName.Replace(".","_") + $_.Extension }
</code>```

Title: Replace "." with "_" in file name

Body:
I am using PowerShell to replace pdf file names:

Get-ChildItem -Path C:\All -Filter *.pdf | Rename-Item -NewName { $_.Name.Replace('.','_') }

It works fine if I replace %20 to _, but if we use "test.one.pdf", I need "test_one.pdf" as output, if I use above syntax it replaces the . before pdf like "test_one_pdf".

Body:
Your code will rename name.001.pdf to name_001_pdf, so unless you actually want to remove the extensions of your files you need to replace only within the files name and not the extension.

Get-ChildItem -Path "C:\All" -Filter "*.pdf" | Rename-Item -NewName { $_.BaseName.Replace(".","_") + $_.Extension }


问:
App not recreating iCloud Drive folder
I am building an app which saves its files to the user's iCloud Drive folder. Everything has been working great until I deleted the app's folder in iCloud Drive to see what would happen. Since then, every time I open the app, it tries to save my sample file in iCloud but it doesn't work (the reloadiCloud() function is set to run in ViewWillAppear). Is there something else I need to do to create the iCloud Drive folder? My code is below.</p>

```<code>func reloadiCloud() {
    ubiquityURL = filemgr.url(forUbiquityContainerIdentifier: nil)

    guard ubiquityURL != nil else {
        print("Unable to access iCloud Account")
        return
    }

    ubiquityURL = ubiquityURL?.appendingPathComponent("Documents")

    metaDataQuery = NSMetadataQuery()

    metaDataQuery?.predicate = NSPredicate(format: "NOT %K.pathExtension = ''", NSMetadataItemFSNameKey)
    metaDataQuery?.searchScopes = [NSMetadataQueryUbiquitousDocumentsScope]

    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.metadataQueryDidFinishGathering), name: NSNotification.Name.NSMetadataQueryDidFinishGathering, object: metaDataQuery!)

    metaDataQuery!.start()
}

func metadataQueryDidFinishGathering(notification: NSNotification) -> Void {
    let query: NSMetadataQuery = notification.object as! NSMetadataQuery

    query.disableUpdates()

    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.NSMetadataQueryDidFinishGathering, object: query)

    query.stop()

    if query.resultCount > 0 {
        fileList = []
        for var i in (0..<query.resultCount) {
            let currentFileURL = query.value(ofAttribute: NSMetadataItemURLKey, forResultAt: i) as! URL
            fileList.append(currentFileURL.lastPathComponent)
            tableView.reloadData()
        }
        tableView.reloadData()
        print(fileList)
    } else {
        let sampleFile = Bundle.main.url(forResource: "Sample", withExtension: "pdf")!
        movetoiCloud(forURL: sampleFile)
    }
}

func movetoiCloud(forURL: URL) {
    let fileName = forURL.lastPathComponent
    ubiquityURL = filemgr.url(forUbiquityContainerIdentifier: nil)?.appendingPathComponent("Documents/\(fileName)")

    //Check if the filename exists and add "copy" to the new version
    for var i in (0..<fileList.count) {
        if fileList[i] == forURL.lastPathComponent {
            let base = ubiquityURL?.absoluteURL.deletingLastPathComponent()
            let endIndex = fileName.index(fileName.endIndex, offsetBy: -4)

            let truncatedExtension = fileName.substring(from: endIndex)
            let truncatedName = fileName.substring(to: endIndex).appending(" copy").appending(truncatedExtension)

            ubiquityURL = base?.appendingPathComponent(truncatedName)
            print("New ubiquity URL: \(ubiquityURL)")
        }
    }

    do {
        try filemgr.setUbiquitous(true, itemAt: forURL, destinationURL: (ubiquityURL)!)
        reloadiCloud()
        print("Move to iCloud OK")
    } catch let error {
        print("moveToiCloud failed: \(error.localizedDescription)")
    }
}
</code>```

答: Try updating the bundle number and version in the info plist, an increase in these values are needed for the icloud additions to take effect.</p>

Title: App not recreating iCloud Drive folder

Body:
I am building an app which saves its files to the user's iCloud Drive folder. Everything has been working great until I deleted the app's folder in iCloud Drive to see what would happen. Since then, every time I open the app, it tries to save my sample file in iCloud but it doesn't work (the reloadiCloud() function is set to run in ViewWillAppear). Is there something else I need to do to create the iCloud Drive folder? My code is below.

func reloadiCloud() {
    ubiquityURL = filemgr.url(forUbiquityContainerIdentifier: nil)

    guard ubiquityURL != nil else {
        print("Unable to access iCloud Account")
        return
    }

    ubiquityURL = ubiquityURL?.appendingPathComponent("Documents")

    metaDataQuery = NSMetadataQuery()

    metaDataQuery?.predicate = NSPredicate(format: "NOT %K.pathExtension = ''", NSMetadataItemFSNameKey)
    metaDataQuery?.searchScopes = [NSMetadataQueryUbiquitousDocumentsScope]

    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.metadataQueryDidFinishGathering), name: NSNotification.Name.NSMetadataQueryDidFinishGathering, object: metaDataQuery!)

    metaDataQuery!.start()
}

func metadataQueryDidFinishGathering(notification: NSNotification) -> Void {
    let query: NSMetadataQuery = notification.object as! NSMetadataQuery

    query.disableUpdates()

    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.NSMetadataQueryDidFinishGathering, object: query)

    query.stop()

    if query.resultCount > 0 {
        fileList = []
        for var i in (0..<query.resultCount) {
            let currentFileURL = query.value(ofAttribute: NSMetadataItemURLKey, forResultAt: i) as! URL
            fileList.append(currentFileURL.lastPathComponent)
            tableView.reloadData()
        }
        tableView.reloadData()
        print(fileList)
    } else {
        let sampleFile = Bundle.main.url(forResource: "Sample", withExtension: "pdf")!
        movetoiCloud(forURL: sampleFile)
    }
}

func movetoiCloud(forURL: URL) {
    let fileName = forURL.lastPathComponent
    ubiquityURL = filemgr.url(forUbiquityContainerIdentifier: nil)?.appendingPathComponent("Documents/\(fileName)")

    //Check if the filename exists and add "copy" to the new version
    for var i in (0..<fileList.count) {
        if fileList[i] == forURL.lastPathComponent {
            let base = ubiquityURL?.absoluteURL.deletingLastPathComponent()
            let endIndex = fileName.index(fileName.endIndex, offsetBy: -4)

            let truncatedExtension = fileName.substring(from: endIndex)
            let truncatedName = fileName.substring(to: endIndex).appending(" copy").appending(truncatedExtension)

            ubiquityURL = base?.appendingPathComponent(truncatedName)
            print("New ubiquity URL: \(ubiquityURL)")
        }
    }

    do {
        try filemgr.setUbiquitous(true, itemAt: forURL, destinationURL: (ubiquityURL)!)
        reloadiCloud()
        print("Move to iCloud OK")
    } catch let error {
        print("moveToiCloud failed: \(error.localizedDescription)")
    }
}


问:
Swift: "Ambiguous reference to member" init
There are several posts on this subject, but I can't see the answer to this problem in them. The following lines produce the title error:

```<code>let pdf_url = NSURL.fileURL(withPath: inputfile)
let pdf_doc = PDFDocument.init?(url: pdf_url) as! URL
</code>```

I understand that the init method can take a variety of data types, but surely I've made it pretty clear that I want a URL.

Error message is:

```<code>error: ambiguous reference to member 'init(url:)'
</code>```

A problem which may be related is that Xcode occasionally tells me to use URL, not NSURL, in the first line, but then complains that URL doesn't have the fileURL method.
(I also tried CGPDFDocument, but that wanted a CFURL, and wouldn't accept NSURL, even though they are supposed to be "toll-free bridged".)

答:
Use URL:

```<code>let pdf_url = URL(fileURLWithPath: inputfile)
</code>```

Body:
There are several posts on this subject, but I can't see the answer to this problem in them. The following lines produce the title error:

let pdf_url = NSURL.fileURL(withPath: inputfile)
let pdf_doc = PDFDocument.init?(url: pdf_url) as! URL

I understand that the init method can take a variety of data types, but surely I've made it pretty clear that I want a URL.

Error message is:

error: ambiguous reference to member 'init(url:)'

A problem which may be related is that Xcode occasionally tells me to use URL, not NSURL, in the first line, but then complains that URL doesn't have the fileURL method.
(I also tried CGPDFDocument, but that wanted a CFURL, and wouldn't accept NSURL, even though they are supposed to be "toll-free bridged".)

Body:
Use URL:

let pdf_url = URL(fileURLWithPath: inputfile)


问:
Function EXTRACT() does not return the correct result
I'm trying to get the years users with this query using the function EXTRACT:

```<code>SELECT EXTRACT(YEAR FROM SYSDATE) - EXTRACT(YEAR FROM contact.BIRTHDATE) AS CONTACT_YEARS
FROM CONTACT contact
</code>```

but for some dates, for example: contact.BIRTHDATE = '27-AGO-40' the function EXTRACT(YEAR FROM contact.BIRTHDATE) return 2040 and query does not work.

I also tried using to_date(contact.BIRTHDATE, 'dd/mm/yyyy')
but the date format does not change.

Thanks!

答:
You are only displaying the year component of the date with two-digits. If you display the full year then you will likely see that the dates have the incorrect century.

Also, rather than subtracting the years to get the difference in years, you would be better using:

```<code>TRUNC( MONTHS_BETWEEN( sysdate, birthdate ) / 12 )
</code>```

Oracle Setup:

```<code>CREATE TABLE contact( BIRTHDATE DATE );

INSERT INTO contact ( birthdate )
SELECT DATE '1977-03-29' FROM DUAL UNION ALL
SELECT DATE '77-03-29'   FROM DUAL UNION ALL
SELECT DATE '1977-03-30' FROM DUAL;
</code>```

Query:

```<code>SELECT TO_CHAR( birthdate, 'YYYY-MM-DD' ) AS full_year,
       TO_CHAR( birthdate, 'YY-MM-DD' )   AS short_year,
       EXTRACT( YEAR FROM sysdate ) - EXTRACT( YEAR FROM birthdate ) AS age,
       TRUNC( MONTHS_BETWEEN( sysdate, birthdate ) / 12 ) AS actual_age
FROM   contact;
</code>```

Output:

```<code>FULL_YEAR  SHORT_YEAR AGE  ACTUAL_AGE
---------- ---------- ---- ----------
1977-03-29 77-03-29     40         40
0077-03-29 77-03-29   1940       1940
1977-03-30 77-03-30     40         39
</code>```

Body:
I'm trying to get the years users with this query using the function EXTRACT:

SELECT EXTRACT(YEAR FROM SYSDATE) - EXTRACT(YEAR FROM contact.BIRTHDATE) AS CONTACT_YEARS
FROM CONTACT contact

but for some dates, for example: contact.BIRTHDATE = '27-AGO-40' the function EXTRACT(YEAR FROM contact.BIRTHDATE) return 2040 and query does not work.

I also tried using to_date(contact.BIRTHDATE, 'dd/mm/yyyy')
but the date format does not change.

Thanks!

Body:
You are only displaying the year component of the date with two-digits. If you display the full year then you will likely see that the dates have the incorrect century.

Also, rather than subtracting the years to get the difference in years, you would be better using:

TRUNC( MONTHS_BETWEEN( sysdate, birthdate ) / 12 )

Oracle Setup:

CREATE TABLE contact( BIRTHDATE DATE );

INSERT INTO contact ( birthdate )
SELECT DATE '1977-03-29' FROM DUAL UNION ALL
SELECT DATE '77-03-29'   FROM DUAL UNION ALL
SELECT DATE '1977-03-30' FROM DUAL;

Query:

SELECT TO_CHAR( birthdate, 'YYYY-MM-DD' ) AS full_year,
       TO_CHAR( birthdate, 'YY-MM-DD' )   AS short_year,
       EXTRACT( YEAR FROM sysdate ) - EXTRACT( YEAR FROM birthdate ) AS age,
       TRUNC( MONTHS_BETWEEN( sysdate, birthdate ) / 12 ) AS actual_age
FROM   contact;

Output:

FULL_YEAR  SHORT_YEAR AGE  ACTUAL_AGE
---------- ---------- ---- ----------
1977-03-29 77-03-29     40         40
0077-03-29 77-03-29   1940       1940
1977-03-30 77-03-30     40         39


问:
keep layout as it is, but shrink it on mobile
So, i've been struggeling with getting my website to work on phones, i'm using a grid, but once i'm trying to view it on a phone it looks awful.

I just want to scale down the desktop-version to half the size on phones.

I've been trying the old zoom:0.5; and transform:scale(0.5); but neither has yeilded me any acceptable result, does anyone know how i can fix this?

I'm using <meta name="viewport" content="width=device-width, initial-scale=1" /> right now, but i've tried without it also.

Here's a link to the website: http://7b772c72.ngrok.io/wordpress/

My grid: https://github.com/joelfolkesson/jf/blob/master/style.css

答:
Shrinking down the content will most likely result in an illegible website on smaller view ports.

You can try media queries for your CSS to give your website the appropriate scale for the sizes defined in said media queries.

If you have not invested too much time I would suggest using Twitter Bootstrap as it already has decent cross device CSS that allow for quick and easy mobile friendly deployments.

You can check out this site that was build with Twitter Bootstrap.

UPDATE:
You want to keep the layout the same as the desktop view for mobile. But as stated above the text will become illegible on mobile view ports and that is in deed the case.

What I would suggest is that you change the CSS media query that governs your menu and logo and increase its size to be readable on the mobile view, instead of using zoom: 0.5;.

Change your logo sizing for the mobile view to about 75% and either change your menu items to 100% width or try using a different defined style for it and either put them in a grid of 3 with 33.3% width and your menu should split into 2 sections above and below or change the grid to 6 with 16.6% width and fit them next to each other and decrease your padding to allow for bigger text.

Other than that I can't help much further as your stylesheet naming conventions are very confusing to me.


问:
Java 'constructor in class cannot be applied to given types' 'required: no arguments found: String'
I'm working on an assignment where I have to create a linked list from scratch and have come across an error when compiling that the "constructor Node in class Node cannot be applied to given types;"

This is what I'm trying, the error says:

required: no arguments
found: string

Yet I cannot see where I am going wrong as my constructor for Node requires a string?

```<code>public class Node {
    String data;
    Node next;

    public void Node(String x) {
        data = x;
        next = null;
    }
}

public class stringList {
    private Node head;
    private int count;

    public void stringList() {
        head = null;
        count = null;
    }

    public void add(String x) {
        Node temp = new Node(x);
    }
</code>```

This is a screenshot of the error the compiler is showing

答:
Constructors don't have a return type. What you have now is a method named Node, which returns nothing.To fix, replace this

```<code>public void Node(String x){
</code>```

with

```<code>public Node(String x){
</code>```

Body:
I'm working on an assignment where I have to create a linked list from scratch and have come across an error when compiling that the "constructor Node in class Node cannot be applied to given types;"

This is what I'm trying, the error says:

required: no arguments
found: string

Yet I cannot see where I am going wrong as my constructor for Node requires a string?

public class Node {
    String data;
    Node next;

    public void Node(String x) {
        data = x;
        next = null;
    }
}

public class stringList {
    private Node head;
    private int count;

    public void stringList() {
        head = null;
        count = null;
    }

    public void add(String x) {
        Node temp = new Node(x);
    }

This is a screenshot of the error the compiler is showing

Body:
Constructors don't have a return type. What you have now is a method named Node, which returns nothing.To fix, replace this

public void Node(String x){

with

public Node(String x){


问:
Remove 'u' from a python list
I have a python list of list as follows. I want to flatten it to a single list.

```<code>l = [u'[190215]']
</code>```

I am trying.

```<code>l = [item for value in l for item in value]
</code>```

It turns the list to [u'[', u'1', u'9', u'0', u'2', u'1', u'5', u']']

How to remove the u from the list.

答:
use [str(item) for item in list]

example

```<code>>>> li = [u'a', u'b', u'c', u'd']
>>> print li
[u'a', u'b', u'c', u'd']
>>> li_u_removed = [str(i) for i in li]
>>> print li_u_removed
['a', 'b', 'c', 'd']
</code>```

Title: Remove 'u' from a python list

Body:
I have a python list of list as follows. I want to flatten it to a single list.

l = [u'[190215]']

I am trying.

l = [item for value in l for item in value]

It turns the list to [u'[', u'1', u'9', u'0', u'2', u'1', u'5', u']']

How to remove the u from the list.

Body:
use [str(item) for item in list]

example

>>> li = [u'a', u'b', u'c', u'd']
>>> print li
[u'a', u'b', u'c', u'd']
>>> li_u_removed = [str(i) for i in li]
>>> print li_u_removed
['a', 'b', 'c', 'd']


问:
Node.js: Testing with VCR
Is there a VCR testing system for node.js?</p>

答:
Update(2017-03-29):

VCR.js
https://github.com/elcuervo/vcr.js

Nock
https://github.com/node-nock/nock#recording

Sepia
https://github.com/linkedin/sepia

Yakbak
https://github.com/flickr/yakbak

Title: Node.js: Testing with VCR


问:
css masonry grid transfer border to the next column
I have a masonry grid to display products and in some cases the first item's border move to the next column. It doesn't happen always and I can't find the reason for this to happen.
Link to the page:
http://en.naaman.b24online.com/b2c-products/tsb-163746/

Thanks.

答: One solution would be to create a wrapper around each box, so the box with border is inside and cant be breaked</p>


问:
Where to after a year of java?
I've just finished a my first year of programming Java at varsity and I have a three month break.

In terms of my development would it be better to:

Cover Java in more depth to acquire a more intermediate level of ability

Learn a new programming language (if so which) to a similar level as my current Java ability

Spend timing learning introductory discrete maths, algorithms and data structures

I'm also open to any other possibilities that would be beneficial but that could be covered in about 3 months

答:
You should start learning Java EE.

JSP, Servelets, Tomcat is a good start. Spring maybe after.

Remember to write code more than you read. Try editing ready examples.

Title: Where to after a year of java?


问:
PL/SQL procedure to inset data from one table to another table but need to insert those record which column 3 have null
I am trying to create pl/sql procedure to insert data from one table to another table , but i need to  filter those record from one column which is not null in column.

Example :-

```<code>C1 | C2| C3|
------------
1  | 2 |   |
3  | 4 | 5 |
6  | 7 |   |
-------------
</code>```

I want to filter column c3 second record and insert the remaining record to another table.

Please help me

Thanks

答:
I assume there would be a need of procedure for some work and the question you asked is a prototype of actual problem. If not then what @Aleksej suggested is correct.</p>

```<code>CREATE OR REPLACE procedure copyTable is
 cursor source_table is
   select c1, c2, c3
   from table1
   where c3 is null;

  TYPE var_temp  IS TABLE OF source_table%rowtype ;

  v_var var_temp;

begin

open source_table;

 fetch source_table bulk collect into v_var;

 close source_table;

  FORALL i IN v_var.first .. v_var.last
     INSERT INTO table2
   VALUES v_var(i);

end;
/
</code>```

Body:
I am trying to create pl/sql procedure to insert data from one table to another table , but i need to  filter those record from one column which is not null in column.

Example :-

C1 | C2| C3|
------------
1  | 2 |   |
3  | 4 | 5 |
6  | 7 |   |
-------------

I want to filter column c3 second record and insert the remaining record to another table.

Please help me

Thanks

Body:
I assume there would be a need of procedure for some work and the question you asked is a prototype of actual problem. If not then what @Aleksej suggested is correct.

CREATE OR REPLACE procedure copyTable is
 cursor source_table is
   select c1, c2, c3
   from table1
   where c3 is null;

  TYPE var_temp  IS TABLE OF source_table%rowtype ;

  v_var var_temp;

begin

open source_table;

 fetch source_table bulk collect into v_var;

 close source_table;

  FORALL i IN v_var.first .. v_var.last
     INSERT INTO table2
   VALUES v_var(i);

end;
/