问:
Symfony3 routing not working with web root configuration
I am trying to integrate some new Symfony3 apps into an existing web space. At my webroot /html, each app has it's own directory. Each of these apps could be anything- cakePHP, custom PHP, whatever. And each are accessed by a URL like localhost/appname. This structure is not flexible and I am not able to add anymore URL patterns to vhosts or anything like that.

Therefore, I have my Symfony3 install at /symfony which is a sibling directory of /html. Inside of /html I have a landing directory for my Symfony app: /html/symfonyapp.

In /html/symfonyapp/index.php I have one sole line of code:
require_once DIR.'/../../symfony/web/app.php';

In my Symfony set up, I have a bundle called SymfonyappBundle. I have a route configured in src/SymfonyappBundle/Resources/config/routing.yml to redirect calls to /symfonyapp to this particular Bundle.

The routing is not working. Calls to http://localhost/symfonyapp always end up going to the routing for "/" Why? I feel that it has nothing to do with my Symfony setup, but instead something to do with the request coming in through that /html/Symfonyapp/index.php file.

Any help is greatly appreciated!

Edit: I see it's helpful to list out the directory structure so here it is:

- /var/www/html <-- this is your (global) web root
|- cake-app
|- custom-php-app
|-symfonyapp
  |—index.php (which contains only a require for app.php)
-/var/www/symfony  <—symphony standard install here
|- app/
|- vendor/
|- src/
|- web/ <-- the web root for your symfony-app
  |- .htaccess
  |- app.php <-- the "boot"-script similar to index.php

答:
I hope I got this right. Your directory structure looks something like this:

```<code>- /var/www/html   <-- this is your (global) web root
|- cake-app
|- custom-php-app
|- symfony    <-- the project root for you symfony-app
 |- app/
 |- vendor/
 |- src/
 |- web/          <-- the web root for your symfony-app
  |- .htaccess
  |- app.php      <-- the "boot"-script similar to index.php
</code>```

So basically you have a typical Symfony-application, but it sits inside a shared web root. So when accessing it you don't go to http://example.com/, but instead to http://example.com/symfony/web/

This might be the first problem you are having. Your application must be accessed from the web folder, not from the symfony-folder. Depending on for example some rewrite rules in /var/www/html/.htaccess you might not be able to look through files in the symfony-subfolder and there is no entry script, so it will not work. Dependening on your setup you might not even have permission to rewrite the url per .htaccess or in your server's config, this would complicate things a bit further. For now let's assume the .htaccess-file in web/ does work and it's just a matter of the wrong folder your url is pointing at.

There are multiple options you have if you want the url to be accessible at http://example.com/symfony/ (without the web/-part). Symfony's project structure is actually pretty flexible and you could get rid of the symfony/web/-folder and instead use symfony/ as your web root. There might be some gotchas for example with some install scripts that copy resources like css and js into your web-root. You could also run into issues when bundles point to the web-directory, e.g. for storing uploads. You probably have to make a few adjustments but a basic setup should be doable in no time by moving all files from web to the parent folder (including the .htaccess which might be hidden).

Another option might be to create a new .htaccess in symfony's project root that points to web/app.php instead of just app.php. You could take the existing file as a reference. I try to avoid using htaccess-files and don't have a setup right now were I could try it, but it might be worth a shot before moving lots of files around. Although you still might run into issues with assets where the path is not matched correctly.

edit: another option that's probably more work, but might be useful if you want to migrate away from the other existing web apps to just a Symfony app is, to move symfony to the same level as html/ and move all the stuff from web/ into html/. Now your server's web root is also symfony's web root (again you might have to fiddle around with assets expecting to be in a folder called web/). Now you just need to make sure that whenever Symfony does not find a route it will pass the request to your other apps. There are several things to look out for and it's a lot more work than the 2 approaches above, but in can be useful. There was a pretty good talk about it at last year's SymfonyCon in Berlin on how to do this if you are interested in this route:

https://github.com/SymfonyCon/2016-talks#modernizing-with-symfony

https://slidr.io/derrabus/modernizing-with-symfony

Unfortunately the video of the talk is not out yet.

Body:
I hope I got this right. Your directory structure looks something like this:

- /var/www/html   <-- this is your (global) web root
|- cake-app
|- custom-php-app
|- symfony    <-- the project root for you symfony-app
 |- app/
 |- vendor/
 |- src/
 |- web/          <-- the web root for your symfony-app
  |- .htaccess
  |- app.php      <-- the "boot"-script similar to index.php

So basically you have a typical Symfony-application, but it sits inside a shared web root. So when accessing it you don't go to http://example.com/, but instead to http://example.com/symfony/web/

This might be the first problem you are having. Your application must be accessed from the web folder, not from the symfony-folder. Depending on for example some rewrite rules in /var/www/html/.htaccess you might not be able to look through files in the symfony-subfolder and there is no entry script, so it will not work. Dependening on your setup you might not even have permission to rewrite the url per .htaccess or in your server's config, this would complicate things a bit further. For now let's assume the .htaccess-file in web/ does work and it's just a matter of the wrong folder your url is pointing at.

There are multiple options you have if you want the url to be accessible at http://example.com/symfony/ (without the web/-part). Symfony's project structure is actually pretty flexible and you could get rid of the symfony/web/-folder and instead use symfony/ as your web root. There might be some gotchas for example with some install scripts that copy resources like css and js into your web-root. You could also run into issues when bundles point to the web-directory, e.g. for storing uploads. You probably have to make a few adjustments but a basic setup should be doable in no time by moving all files from web to the parent folder (including the .htaccess which might be hidden).

Another option might be to create a new .htaccess in symfony's project root that points to web/app.php instead of just app.php. You could take the existing file as a reference. I try to avoid using htaccess-files and don't have a setup right now were I could try it, but it might be worth a shot before moving lots of files around. Although you still might run into issues with assets where the path is not matched correctly.

edit: another option that's probably more work, but might be useful if you want to migrate away from the other existing web apps to just a Symfony app is, to move symfony to the same level as html/ and move all the stuff from web/ into html/. Now your server's web root is also symfony's web root (again you might have to fiddle around with assets expecting to be in a folder called web/). Now you just need to make sure that whenever Symfony does not find a route it will pass the request to your other apps. There are several things to look out for and it's a lot more work than the 2 approaches above, but in can be useful. There was a pretty good talk about it at last year's SymfonyCon in Berlin on how to do this if you are interested in this route:

https://github.com/SymfonyCon/2016-talks#modernizing-with-symfony

https://slidr.io/derrabus/modernizing-with-symfony

Unfortunately the video of the talk is not out yet.


来源: stackexchange

问:
Why does my CGContext-drawn circle suck?
I have a custom table view cell that is intended to draw a circle like the iPhone’s Mail.app does:

Instead, it draws like this:

Here’s my code:

```<code>CGContextRef context = UIGraphicsGetCurrentContext();
UIColor *grayColor = [UIColor grayColor];

[grayColor set];

CGContextStrokeEllipseInRect(context, CGRectMake(9, 10, 23, 23));
</code>```

How can I make it not suck? :)

Edit: Ignore the fact that I omitted the code that draws the white background color.

What about it sucks? It doesn’t look close to, if not exactly like, the circle from Mail.

答:
I was able to solve this by changing the UIColor to the same color Apple uses, #E5E5E5:

```<code>[UIColor colorWithRed: 0.8980392157 green: 0.8980392157 blue: 0.8980392157 alpha: 1.0]
</code>```

And changing the line width from the default 1.0 to 2.0:

```<code>CGContextSetLineWidth(context, 2.0);
</code>```

Tweaking the size was also necessary:

```<code>CGContextStrokeEllipseInRect(context, CGRectMake(10, 11, 21, 21));
</code>```

The final code looks like this:

```<code>CGContextRef context = UIGraphicsGetCurrentContext();
UIColor *grayColor = [UIColor colorWithRed: 0.8980392157 green: 0.8980392157 blue: 0.8980392157 alpha: 1.0];

[grayColor set];

CGContextSetLineWidth(context, 2.0);
CGContextStrokeEllipseInRect(context, CGRectMake(10, 11, 21, 21));
</code>```

And outputs like this:

ContentLicense: CC BY-SA 2.5

Body:
I have a custom table view cell that is intended to draw a circle like the iPhone’s Mail.app does:

Instead, it draws like this:

Here’s my code:

CGContextRef context = UIGraphicsGetCurrentContext();
UIColor *grayColor = [UIColor grayColor];

[grayColor set];

CGContextStrokeEllipseInRect(context, CGRectMake(9, 10, 23, 23));

How can I make it not suck? :)

Edit: Ignore the fact that I omitted the code that draws the white background color.

What about it sucks? It doesn’t look close to, if not exactly like, the circle from Mail.

Body:
I was able to solve this by changing the UIColor to the same color Apple uses, #E5E5E5:

[UIColor colorWithRed: 0.8980392157 green: 0.8980392157 blue: 0.8980392157 alpha: 1.0]

And changing the line width from the default 1.0 to 2.0:

CGContextSetLineWidth(context, 2.0);

Tweaking the size was also necessary:

CGContextStrokeEllipseInRect(context, CGRectMake(10, 11, 21, 21));

The final code looks like this:

CGContextRef context = UIGraphicsGetCurrentContext();
UIColor *grayColor = [UIColor colorWithRed: 0.8980392157 green: 0.8980392157 blue: 0.8980392157 alpha: 1.0];

[grayColor set];

CGContextSetLineWidth(context, 2.0);
CGContextStrokeEllipseInRect(context, CGRectMake(10, 11, 21, 21));

And outputs like this:


问:
JavaScript import JSON data - Loop to sort by long/lat location
I am reading a json file which looks like this:

```<code>[
    {
        "name":"Mark Brown",
        "location":{
            "lat":50.72423653147234,
            "lon":-0.6552093628538713
            }
    },

    {
        "name":"Nina Wright",
        "location":{
            "lat":51.00351657212984,
            "lon":0.4104543851588729
        }
    }

]
</code>```

Then I have a loop that will display the data in a list on my page.

```<code>$.getJSON(JsonFile, function(List){

  var div = document.getElementById('list');

  for( var i = 0; i < List.length;i++ ) {

      div.innerHTML = div.innerHTML + '<li>'+List[i].name+'</li>';

  }

});
</code>```

This will append the list to the

This all works great but what I need to do is to order the data by location in DESC order before appending the data to my page.

How can I do this?

答:
You need a sorting callback with the delta of the distance.</p>

```<code>data.sort(function (a, b) {
    return (
        checkDistance(fixedlat, fixedlon, a.location.lat, a.location.lon) -
        checkDistance(fixedlat, fixedlon, b.location.lat, b.location.lon)
    );
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am reading a json file which looks like this:

[
    {
        "name":"Mark Brown",
        "location":{
            "lat":50.72423653147234,
            "lon":-0.6552093628538713
            }
    },

    {
        "name":"Nina Wright",
        "location":{
            "lat":51.00351657212984,
            "lon":0.4104543851588729
        }
    }

]

Then I have a loop that will display the data in a list on my page.

$.getJSON(JsonFile, function(List){

  var div = document.getElementById('list');

  for( var i = 0; i < List.length;i++ ) {

      div.innerHTML = div.innerHTML + '
'+List[i].name+'
';

  }

});

This will append the list to the

This all works great but what I need to do is to order the data by location in DESC order before appending the data to my page.

How can I do this?

Body:
You need a sorting callback with the delta of the distance.

data.sort(function (a, b) {
    return (
        checkDistance(fixedlat, fixedlon, a.location.lat, a.location.lon) -
        checkDistance(fixedlat, fixedlon, b.location.lat, b.location.lon)
    );
});


问:
printing summary of results in Python
I have a python script which makes an http request to an API in order to pull "member" data. It then runs a loop to hit several different member ID's (listed in a text file) to see if each of them are "expired" or not. What I would like to do is print out a summary of these results instead of printing out the individual results for each of the members. Here is my Python script:

```<code>import requests
import json

qa_members = open("numbers_members.txt")
arraylist = []
    for line in qa_members.readlines():
    arraylist.extend(line.split())
qa_members.close()

arraylist = map(int, arraylist)

authorization_code = raw_input("please enter your authorization code: ")
members = arraylist
print "Member Check Starting"

for member in members:
    url = "http://api22.wiki.com/v1.12/member?id="+str(member)

    header = {"Authorization": authorization_code}

    response = requests.get(url, headers=header)

    member_check = json.loads(response.text)

    final_member_status = member_check["response"]["member"]
    ["is_expired"]

    print str(member) + " expired status: " + str(final_member_status)

if final_member_status == False:
    print "All Members Passed"
else:
    print "Some members are expired, please refer to log"

print "Member Check Complete"
</code>```

From this, I get several terminal outputs like:

```<code>123 expired status: False
567 expired status: False
</code>```

Is there way to instead, print out a summary of the results? It could be something like:

```<code>"24 members returned False"
"11 members returned True"
</code>```

It would also be helpful to find out the ID of a particular member if the status returned was "true":

```<code>"Member 1234 returned True"
</code>```

Or something similar to that. Any help is greatly appreciated.

Thanks!

答:
create a list and append your results to it:

```<code>results = []

for member in members:
    (...)
    results.append(str(final_member_status))
</code>```

How can I count the occurrences of a list item in Python?

```<code>>>> [1, 2, 3, 4, 1, 4, 1].count(1)
3
</code>```

Title: printing summary of results in Python

Body:
I have a python script which makes an http request to an API in order to pull "member" data. It then runs a loop to hit several different member ID's (listed in a text file) to see if each of them are "expired" or not. What I would like to do is print out a summary of these results instead of printing out the individual results for each of the members. Here is my Python script:

import requests
import json

qa_members = open("numbers_members.txt")
arraylist = []
    for line in qa_members.readlines():
    arraylist.extend(line.split())
qa_members.close()

arraylist = map(int, arraylist)

authorization_code = raw_input("please enter your authorization code: ")
members = arraylist
print "Member Check Starting"

for member in members:
    url = "http://api22.wiki.com/v1.12/member?id="+str(member)

    header = {"Authorization": authorization_code}

    response = requests.get(url, headers=header)

    member_check = json.loads(response.text)

    final_member_status = member_check["response"]["member"]
    ["is_expired"]

    print str(member) + " expired status: " + str(final_member_status)

if final_member_status == False:
    print "All Members Passed"
else:
    print "Some members are expired, please refer to log"

print "Member Check Complete"

From this, I get several terminal outputs like:

123 expired status: False
567 expired status: False

Is there way to instead, print out a summary of the results? It could be something like:

"24 members returned False"
"11 members returned True"

It would also be helpful to find out the ID of a particular member if the status returned was "true":

"Member 1234 returned True"

Or something similar to that. Any help is greatly appreciated.

Thanks!

Body:
create a list and append your results to it:

results = []

for member in members:
    (...)
    results.append(str(final_member_status))

How can I count the occurrences of a list item in Python?

>>> [1, 2, 3, 4, 1, 4, 1].count(1)
3


问:
How to make your desktop Java app looks like Open Office or Eclipse etc.?
How to make your desktop Java app looks like Open Office or Eclipse  etc ?
Installation process looks like any Windpws app. installation. There is no Java logo on the to on a app window. You run it by .exe file. How it is done? Is this jar->exe conversion?
Is there any free tool to do that?</p>

答:
For the native look, you can obviously go the SWT way, like Eclipse does, however it's a painful one. You could/should prefer the Swing look'n'feel, by using, as an example, the Substance Look'n'Feel.

For the installation part, you can use

InstallAnywhere

IzPack

For the exe wrapper, you can use

Launch4J

JSmooth

or others ...

However, I think that, by doing so, you're doing it wrong.
indeed, instead of the classical download/install step, which is cumbersome, you can go the Java Web Start way : user only has to click one webpage link to install application to its machine (with an update mechanism directly integrated in), an install that go as far as potentially including desktop and start menu shortcuts, and an element in the Windows install panel to remove installed software.


问:
Simultaneous reception and sending of datagrams
There are a code that receaving peer-to-peer messages.

```<code> try {
            DatagramSocket ds = new DatagramSocket(1050);
            DatagramPacket pack = new DatagramPacket(new byte[1024], 1024);
            while (true) {
                AscMessage();
                ds.receive(pack);
                System.out.println(new String(pack.getData()));
            }
        }
            catch(Exception e){
        System.out.println(e);
}
</code>```

There is a code that sends a peer-to-peer message.

```<code>public void AscMessage(){
        System.out.print(">");
        final Scanner in = new Scanner (System.in);
        String s1 = in.nextLine ();
        this.sendMessage(s1);
    }

   public void sendMessage(String mes){

    try{

        byte[] data = mes.getBytes();

        InetAddress addr = InetAddress.getByName(host);

        DatagramPacket pack = new DatagramPacket(data, data.length, addr, port);

        DatagramSocket ds = new DatagramSocket();

        ds.send(pack);

        ds.close();

    }catch(IOException e){

        System.err.println(e);

    }

}

public static void main(String[] args){

    Sender sndr = new Sender("localhost", 1050);

    while (true){
        sndr.AscMessage();
    }
    for (int k = 0; k < args.length; k++)
        sndr.sendMessage(args[k]);

}
</code>```

How can they be combined? Wait for a new message, but at the same time send.
Is it necessary to use two ports?

答: No, one port is ok. You either use two threads or you use the features of Java 8 for asynchronous waiting with select.</p>

Body:
There are a code that receaving peer-to-peer messages.

 try {
            DatagramSocket ds = new DatagramSocket(1050);
            DatagramPacket pack = new DatagramPacket(new byte[1024], 1024);
            while (true) {
                AscMessage();
                ds.receive(pack);
                System.out.println(new String(pack.getData()));
            }
        }
            catch(Exception e){
        System.out.println(e);
}

There is a code that sends a peer-to-peer message.

public void AscMessage(){
        System.out.print(">");
        final Scanner in = new Scanner (System.in);
        String s1 = in.nextLine ();
        this.sendMessage(s1);
    }

   public void sendMessage(String mes){

    try{

        byte[] data = mes.getBytes();

        InetAddress addr = InetAddress.getByName(host);

        DatagramPacket pack = new DatagramPacket(data, data.length, addr, port);

        DatagramSocket ds = new DatagramSocket();

        ds.send(pack);

        ds.close();

    }catch(IOException e){

        System.err.println(e);

    }

}

public static void main(String[] args){

    Sender sndr = new Sender("localhost", 1050);

    while (true){
        sndr.AscMessage();
    }
    for (int k = 0; k < args.length; k++)
        sndr.sendMessage(args[k]);

}

How can they be combined? Wait for a new message, but at the same time send.
Is it necessary to use two ports?


答:
You can use two counters outside the for loop and then increase the counters based on True or False, something like this :

```<code># Set both counts to 0 outside the for loop
true_count = 0
false_count = 0

# increment count values based on check inside the for loop
if final_member_status :
    true_count = true_count + 1
else :
    false_count = false_count + 1

# And finally print outside for loop in the desired format
print("{} members returned True".format(str(true_count)))
print("{} members returned False".format(str(false_count)))
</code>```

This will result the aggregated sum of both checks.

Title: printing summary of results in Python

Body:
You can use two counters outside the for loop and then increase the counters based on True or False, something like this :

# Set both counts to 0 outside the for loop
true_count = 0
false_count = 0

# increment count values based on check inside the for loop
if final_member_status :
    true_count = true_count + 1
else :
    false_count = false_count + 1

# And finally print outside for loop in the desired format
print("{} members returned True".format(str(true_count)))
print("{} members returned False".format(str(false_count)))

This will result the aggregated sum of both checks.


问:
multiprocessing.Pool memory allocation error
I am running script that is using multiprocessing Pooling on shared hosting. I am getting following error:

Errno 12] Cannot allocate memory
(<type 'exceptions.OSError'>,
```

<p>Below is my code:</p>

```with closing(Pool(processes=50)) as pool:
 csv_items = pool.map(get_stuff, list_ids)
 pool.terminate()
 pool.join()
```

答:
Ok, you are trying to launch 50 more processes to be used by your pool. Now, this is not the same as threads, this will launch 50 new Python processes with all the python modules and libraries included.

By default, Pool will launch cpu_count() new processes, normally thinking in multicpu-multicores machines. Now every new Worker process will live by default for the complete duration of your Pool's work queue. If i will use a dedicated VPS instance i will go with precaution about create freely Worker Processes in my pool. In your case you are using a shared hosting and on this, the memory limitations will be bigger, showing the error message that you see above.

If you like to use this, then change your deployment from a shared hosting to a dedicated vps/cloud instance.

Body:
I am running script that is using multiprocessing Pooling on shared hosting. I am getting following error:

Errno 12] Cannot allocate memory
(<type 'exceptions.OSError'>,

Below is my code:

with closing(Pool(processes=50)) as pool:
 csv_items = pool.map(get_stuff, list_ids)
 pool.terminate()
 pool.join()


问:
What happens to a promise that's abandoned?
I have the following code defined in a view controller.

```<code>    _ = accountService.getAccount()

      .then { user -> Void in

         self.txtBxUser.text = user.username
         self.txtBxEmail.text = user.email
   }
</code>```

getAccount makes a REST API request.

If the user dismisses the view controller before the call has returned, what happens to the call back chain? Does it still run given that, I presume, it's still referenced?

答:
If the user dismisses the view controller before the call has returned, what happens to the call back chain? Does it still run given that, I presume, it's still referenced?

Yes, it does still run.

Be forewarned that the reference to self in the closure means that it is also keeping a reference to the view controller until that then closure finishes running. For that reason, if there's a chance the view controller could have been dismissed, you might want to use a weak reference:

```<code>_ = accountService.getAccount().then { [weak self] user -> Void in
    self?.txtBxUser.text = user.username
    self?.txtBxEmail.text = user.email
}
</code>```

Ideally, you should also make getAccount cancellable and cancel it in the view controller's deinit.

(Note, in FAQ - Should I be Concerned About Retain Cycles, the PromiseKit documentation points out that you don't need weak references, which is correct. It's just a question of whether or not you mind if the deallocation of the dismissed view controller is deferred until after the promise is fulfilled.)

Body:
I have the following code defined in a view controller.

    _ = accountService.getAccount()

      .then { user -> Void in

         self.txtBxUser.text = user.username
         self.txtBxEmail.text = user.email
   }

getAccount makes a REST API request.

If the user dismisses the view controller before the call has returned, what happens to the call back chain? Does it still run given that, I presume, it's still referenced?

Body:
If the user dismisses the view controller before the call has returned, what happens to the call back chain? Does it still run given that, I presume, it's still referenced?

Yes, it does still run.

Be forewarned that the reference to self in the closure means that it is also keeping a reference to the view controller until that then closure finishes running. For that reason, if there's a chance the view controller could have been dismissed, you might want to use a weak reference:

_ = accountService.getAccount().then { [weak self] user -> Void in
    self?.txtBxUser.text = user.username
    self?.txtBxEmail.text = user.email
}

Ideally, you should also make getAccount cancellable and cancel it in the view controller's deinit.

(Note, in FAQ - Should I be Concerned About Retain Cycles, the PromiseKit documentation points out that you don't need weak references, which is correct. It's just a question of whether or not you mind if the deallocation of the dismissed view controller is deferred until after the promise is fulfilled.)


问:
Is there a way to deploy a jar without restarting in Tomcat 9?
I know this question has came up before here, however this is in regards to tomcat 9.

Is there anything that has changed in latest tomcat releases that allows to deploy a jar file without restarting tomcat ? We have been using tomcat 7 in our development and all developers restarting tomcat has been time consuming. Its application that has 700 java files that gets built in to a .jar file and about 1000 jsp files that rely on those .jar file, we are not using war. Can WatchedResource be used for this ?

答: You can always restart your webapp and not your Tomcat instance as long as the JAR resides in WEB-INF/lib and not in CATALINA_BASE/lib.


问:
Accessing min and max value within JSON array in JavaScript/HTML
I have the following code that gets data from a database and plots a graph using HTML and the FusionCharts library. I'm just having some trouble with the graph formatting. I want the yAxisMin to be 10 values below the minimum value in the data array and the yAxisMax value to be 10 values above.

```<code>function createJSON(name, data){
    return(
        {
            "chart": {
                "caption": String(name),
                "subCaption": "15-Day Prices",
                "xAxisName": "Day",
                "yAxisName": "Price (USD)",
                "anchorRadius": "1",
                "showValues": "0",
                "borderThickness": "3",
                "yAxisMinValue": data.value.min() - 10,
                "yAxisMaxValue": data.value.max() + 10,
                "theme": "fint"
            },
            "data": data,
        }
    );
}

//I'm including this for context. This is the function that returns the data array
var getHistory = function(req,res,next){

    var data = [];
    History.findOne({"Symbol": String(req.params.sym)}, function(err, foundHistory){
        if(foundHistory){
            (foundHistory.Historical).forEach(function(day){
                data.push({
                    "label": day.Date,
                    "value": day.Close
                });
            });
            res.json(createJSON(foundHistory.Name, data));
            next();
        }
        else{
            next();
        }
    });
};

module.exports = getHistory;
</code>```

Everything else works fine. I just need help with the two lines of code:

```<code>"yAxisMinValue": data.value.min() - 10,
"yAxisMaxValue": data.value.max() + 10,
</code>```

How would I do this? This was my attempt but it does not compile.

答:
Try something like that:</p>

```<code>  "yAxisMinValue": getMinValue(data) - 10,
    "yAxisMaxValue": getMaxValue(data) + 10,

 function getMinValue(data)
     {
       var min = Number.MAX_VALUE;
        for (var key in data)
         {
           if(data[key].value < min)
            {
               min = data[key].value;
            }
         }
        return min;
     }

 function getMaxValue(data)
     {
       var max = Number.MIN_VALUE;
        for (var key in data)
         {
           if(data[key].value > max)
            {
               max = data[key].value;
            }
         }
        return max;
     }
</code>```

Body:
I have the following code that gets data from a database and plots a graph using HTML and the FusionCharts library. I'm just having some trouble with the graph formatting. I want the yAxisMin to be 10 values below the minimum value in the data array and the yAxisMax value to be 10 values above.

function createJSON(name, data){
    return(
        {
            "chart": {
                "caption": String(name),
                "subCaption": "15-Day Prices",
                "xAxisName": "Day",
                "yAxisName": "Price (USD)",
                "anchorRadius": "1",
                "showValues": "0",
                "borderThickness": "3",
                "yAxisMinValue": data.value.min() - 10,
                "yAxisMaxValue": data.value.max() + 10,
                "theme": "fint"
            },
            "data": data,
        }
    );
}

//I'm including this for context. This is the function that returns the data array
var getHistory = function(req,res,next){

    var data = [];
    History.findOne({"Symbol": String(req.params.sym)}, function(err, foundHistory){
        if(foundHistory){
            (foundHistory.Historical).forEach(function(day){
                data.push({
                    "label": day.Date,
                    "value": day.Close
                });
            });
            res.json(createJSON(foundHistory.Name, data));
            next();
        }
        else{
            next();
        }
    });
};

module.exports = getHistory;

Everything else works fine. I just need help with the two lines of code:

"yAxisMinValue": data.value.min() - 10,
"yAxisMaxValue": data.value.max() + 10,

How would I do this? This was my attempt but it does not compile.

Body:
Try something like that:

  "yAxisMinValue": getMinValue(data) - 10,
    "yAxisMaxValue": getMaxValue(data) + 10,

 function getMinValue(data)
     {
       var min = Number.MAX_VALUE;
        for (var key in data)
         {
           if(data[key].value < min)
            {
               min = data[key].value;
            }
         }
        return min;
     }

 function getMaxValue(data)
     {
       var max = Number.MIN_VALUE;
        for (var key in data)
         {
           if(data[key].value > max)
            {
               max = data[key].value;
            }
         }
        return max;
     }


问:
Unable to read URL encode in nodeJS
I am using express framework in nodeJS and trying to send the activation link on email but as i am activating the link the url get encoded and express routes is unable to read and sending to 404 error page.

```<code>Url:

xxx.com/#/user/543fe901b43083207ff0f863c07135b6/xxx.x@gmail.com

On click to URL:

xxx.com/#%2Fuser%2F543fe901b43083207ff0f863c07135b6%2Fxxx.x@gmail.com
</code>```

Can you Please help me out what I am doing wrong or something I have missed?

Thanks in advance.

答:
You must not use the hash sign like this in the url. In fact, the hash sign has a special meaning, everything that follows the hash sign is interpreted in the browser only. It is not used to distinguish URLs, but anchors on the page. </p>

<p>Therefore, express will not parse what comes after the hash sign, at least in its default configuration. </p>

Title: Unable to read URL encode in nodeJS

Body:
I am using express framework in nodeJS and trying to send the activation link on email but as i am activating the link the url get encoded and express routes is unable to read and sending to 404 error page.

Url:

xxx.com/#/user/543fe901b43083207ff0f863c07135b6/xxx.x@gmail.com

On click to URL:

xxx.com/#%2Fuser%2F543fe901b43083207ff0f863c07135b6%2Fxxx.x@gmail.com

Can you Please help me out what I am doing wrong or something I have missed?

Thanks in advance.

Body:
You must not use the hash sign like this in the url. In fact, the hash sign has a special meaning, everything that follows the hash sign is interpreted in the browser only. It is not used to distinguish URLs, but anchors on the page.

Therefore, express will not parse what comes after the hash sign, at least in its default configuration.


问:
How to change Java-based configuration in tests for Spring-boot based application?
I’m trying to figure out how to test my code in a proper way and stuck somewhere in the middle.

What I use:

Spring-boot based Java web-application. Java based configuration. Test.

What I want:

I want to manage my testing in a proper way. I have a @RestController annotated class what has two objects what I’d like to change in tests. It’s an entities provider class BooksService and database configuration class DBConfig. I want to change implementations for these classes in my tests in a simple and proper way. I don’t know how to do it correctly.

What kind of help I need:

Working project that implements this approach is most preferable. Don’t spend too many words, the working code is the best way to understand it for me.

If there is no a complete project there, so code snippets with descriptions will be useful too.

Links to some good and simple tutorials about 1) Java based configurations 2) Replacing Java based configuration for tests.

Sorry if my thoughts are little bit messy, I’m pretty new in Java EE development and still didn’t figure out with all basic topics well.

EDIT:

Here is some code

DemoApplication class

```<code>@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
</code>```

BooksController controller class

```<code>@RestController
public class BooksController {

    @Autowired
    BooksProvider booksProvider;

    @CrossOrigin
    @RequestMapping("/books")
    String allBooks() throws Exception {

        return this.booksProvider.fetchAllBooksAsTring();
    }

}
</code>```

BooksProvider service class

```<code>public class BooksProvider {

    public String fetchAllBooksAsTring() {
        return "[\"Marting Iden\", \"Capital\", \"Strong Wind\"]";
    }
}
</code>```

SimpleConfiguration configuration class

```<code>@Configuration
public class SimpleConfiguration {

    @Bean
    public BooksProvider booksProvider() {
        return new BooksProvider();
    }

}
</code>```

答:
In Spring Boot 1.3.x I have successfully used the following approach:

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration({Application.class, IntegrationTestsConfiguration.class})
@ActiveProfiles({"it"})
@DirtiesContext(classMode = AFTER_EACH_TEST_METHOD)
public class MyIT {
    // tests
}
</code>```

as you can see apart from Application.class (the one annotated with @SpringBootApplication) there is IntergrationTestsConfiguration.class present in @SpringApplicationConfguration. This class is responsible for overwriting beans which behaviour I wanted to change for test purposes.

This is how such class can look like:

```<code>@Configuration
public class IntegrationTestsConfiguration {

    @Bean
    @Primary
    public BooksProvider booksProvider() {
        // your custom instantiation code goes here
    }
}
</code>```

In other words I have used "Primary beans approach".

Since Spring Boot 1.4.x there is @MockBean annotation available, until now I hadn't opportunity to use it but for sure it is worth checking out.

Further reading:

Overriding an Autowired Bean in Unit Tests

Overriding beans in Integration tests

https://dzone.com/articles/mockbean-spring-boots-missing-ingredient

Body:
I’m trying to figure out how to test my code in a proper way and stuck somewhere in the middle.

What I use:

Spring-boot based Java web-application. Java based configuration. Test.

What I want:

I want to manage my testing in a proper way. I have a @RestController annotated class what has two objects what I’d like to change in tests. It’s an entities provider class BooksService and database configuration class DBConfig. I want to change implementations for these classes in my tests in a simple and proper way. I don’t know how to do it correctly.

What kind of help I need:

Working project that implements this approach is most preferable. Don’t spend too many words, the working code is the best way to understand it for me.

If there is no a complete project there, so code snippets with descriptions will be useful too.

Links to some good and simple tutorials about 1) Java based configurations 2) Replacing Java based configuration for tests.

Sorry if my thoughts are little bit messy, I’m pretty new in Java EE development and still didn’t figure out with all basic topics well.

EDIT:

Here is some code

DemoApplication class

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

BooksController controller class

@RestController
public class BooksController {

    @Autowired
    BooksProvider booksProvider;

    @CrossOrigin
    @RequestMapping("/books")
    String allBooks() throws Exception {

        return this.booksProvider.fetchAllBooksAsTring();
    }

}

BooksProvider service class

public class BooksProvider {

    public String fetchAllBooksAsTring() {
        return "[\"Marting Iden\", \"Capital\", \"Strong Wind\"]";
    }
}

SimpleConfiguration configuration class

@Configuration
public class SimpleConfiguration {

    @Bean
    public BooksProvider booksProvider() {
        return new BooksProvider();
    }

}

Body:
In Spring Boot 1.3.x I have successfully used the following approach:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration({Application.class, IntegrationTestsConfiguration.class})
@ActiveProfiles({"it"})
@DirtiesContext(classMode = AFTER_EACH_TEST_METHOD)
public class MyIT {
    // tests
}

as you can see apart from Application.class (the one annotated with @SpringBootApplication) there is IntergrationTestsConfiguration.class present in @SpringApplicationConfguration. This class is responsible for overwriting beans which behaviour I wanted to change for test purposes.

This is how such class can look like:

@Configuration
public class IntegrationTestsConfiguration {

    @Bean
    @Primary
    public BooksProvider booksProvider() {
        // your custom instantiation code goes here
    }
}

In other words I have used "Primary beans approach".

Since Spring Boot 1.4.x there is @MockBean annotation available, until now I hadn't opportunity to use it but for sure it is worth checking out.

Further reading:

Overriding an Autowired Bean in Unit Tests

Overriding beans in Integration tests

https://dzone.com/articles/mockbean-spring-boots-missing-ingredient


问:
Getting values from functions that run as asyncio tasks
I was trying the following code:

```<code>import asyncio

@asyncio.coroutine
def func_normal():
        print("A")
        yield from asyncio.sleep(5)
        print("B")
        return 'saad'

@asyncio.coroutine
def func_infinite():
    i = 0
    while i<10:
        print("--"+str(i))
        i = i+1
    return('saad2')

loop = asyncio.get_event_loop()

tasks = [
    asyncio.async(func_normal()),
    asyncio.async(func_infinite())]

loop.run_until_complete(asyncio.wait(tasks))
loop.close()
</code>```

I can't figure out how to get values in variables from these functions. I can't do this:

```<code>asyncio.async(a = func_infinite())
</code>```

as this would make this a keyword argument. How do I go about accomplishing this?

答:
If you want to use any value returned by coroutine as soon as coroutine ends you can pass future object into the coro and update this future by computed value. As soon as future is updated it passes its future.result() to the callback function which is bound with given future. See code below:

```<code>import asyncio

async def func_normal(future):
    print("A")
    await asyncio.sleep(5)
    print("B")
    # return 'saad'
    future.set_result('saad')

async def func_infinite(future):
    i = 0
    while i<10:
        print("--"+str(i))
        i = i+1
    # return('saad2')
    future.set_result('saad2')

def got_result(future):
    print(future.result())

loop = asyncio.get_event_loop()
future1 = asyncio.Future()
future2 = asyncio.Future()

future1.add_done_callback(got_result)
future2.add_done_callback(got_result)

# Coros are automatically wrapped in Tasks by asyncio.wait()
coros = [
    func_normal(future1),
    func_infinite(future2)]

loop.run_until_complete(asyncio.wait(coros))
loop.close()
</code>```

The callback function is called with a single argument - the future object which it is bound with. If you need to pass more arguments into the callback use partial from functools package:

```<code>future1.add_done_callback(functools.partial(print, "future:", argin))
</code>```

will call

```<code>print("future:", argin)
</code>```

Body:
I was trying the following code:

import asyncio

@asyncio.coroutine
def func_normal():
        print("A")
        yield from asyncio.sleep(5)
        print("B")
        return 'saad'

@asyncio.coroutine
def func_infinite():
    i = 0
    while i<10:
        print("--"+str(i))
        i = i+1
    return('saad2')

loop = asyncio.get_event_loop()

tasks = [
    asyncio.async(func_normal()),
    asyncio.async(func_infinite())]

loop.run_until_complete(asyncio.wait(tasks))
loop.close()

I can't figure out how to get values in variables from these functions. I can't do this:

asyncio.async(a = func_infinite())

as this would make this a keyword argument. How do I go about accomplishing this?

Body:
If you want to use any value returned by coroutine as soon as coroutine ends you can pass future object into the coro and update this future by computed value. As soon as future is updated it passes its future.result() to the callback function which is bound with given future. See code below:

import asyncio

async def func_normal(future):
    print("A")
    await asyncio.sleep(5)
    print("B")
    # return 'saad'
    future.set_result('saad')

async def func_infinite(future):
    i = 0
    while i<10:
        print("--"+str(i))
        i = i+1
    # return('saad2')
    future.set_result('saad2')

def got_result(future):
    print(future.result())

loop = asyncio.get_event_loop()
future1 = asyncio.Future()
future2 = asyncio.Future()

future1.add_done_callback(got_result)
future2.add_done_callback(got_result)

# Coros are automatically wrapped in Tasks by asyncio.wait()
coros = [
    func_normal(future1),
    func_infinite(future2)]

loop.run_until_complete(asyncio.wait(coros))
loop.close()

The callback function is called with a single argument - the future object which it is bound with. If you need to pass more arguments into the callback use partial from functools package:

future1.add_done_callback(functools.partial(print, "future:", argin))

will call

print("future:", argin)


问:
WSO2 Enterprise Integrator 6.0.0 Console not reachable after start
finished WSO2 installation and first time I start the service and try to log into the management console it's not accessible (hosted on a Amazon EC2 unix instance).

Based on the log file the server starts normally:

```<code>[2017-03-31 22:40:29,622] [EI-Core]  INFO - CarbonUIServiceComponent Mgt Console URL  : https://XXX.XXX.XXX.XXX:8243/carbon/
</code>```

When I try logging into mgt console the browser is hang up and won't finish loading the page. On wso2carbon.log I get the log entries below:

```<code>[2017-03-31 22:42:51,456] [EI-Core]  WARN - EndpointContext Endpoint : AnonymousEndpoint with address https://XXX.XXX.XXX.XXX:37045 will be marked SUSPENDED as it failed
[2017-03-31 22:42:51,457] [EI-Core]  WARN - EndpointContext Suspending endpoint : AnonymousEndpoint with address https://XXX.XXX.XXX.XXX:37045 - current suspend duration is : 30000ms - Next retry after : Fri Mar 31 22:43:21 UTC 2017
[2017-03-31 22:43:44,246] [EI-Core]  INFO - SourceHandler Writer null when calling informWriterError
[2017-03-31 22:43:44,247] [EI-Core]  WARN - SourceHandler Connection time out after request is read: http-incoming-1 Socket Timeout : 180000 Remote Address : YYY.YYY.YYY.YYY/179.212.90.90:4529
[2017-03-31 22:45:51,671] [EI-Core]  WARN - ConnectCallback Connection refused or failed for : /XXX.XXX.XXX.XXX:37045
[2017-03-31 22:45:51,672] [EI-Core]  WARN - EndpointContext Endpoint : AnonymousEndpoint with address https://XXX.XXX.XXX.XXX:37045 will be marked SUSPENDED as it failed
[2017-03-31 22:45:51,672] [EI-Core]  WARN - EndpointContext Suspending endpoint : AnonymousEndpoint with address https://XXX.XXX.XXX.XXX:37045 - last suspend duration was : 30000ms and current suspend duration is : 30000ms - Next retry after : Fri Mar 31 22:46:21 UTC 2017
[2017-03-31 22:46:44,662] [EI-Core]  INFO - SourceHandler Writer null when calling informWriterError
[2017-03-31 22:46:44,663] [EI-Core]  WARN - SourceHandler Connection time out after request is read: http-incoming-2 Socket Timeout : 180000 Remote Address : 179.212.90.90/179.212.90.90:4592
[2017-03-31 22:48:52,151] [EI-Core]  WARN - ConnectCallback Connection refused or failed for : /XXX.XXX.XXX.XXX:37045
[2017-03-31 22:48:52,151] [EI-Core]  WARN - EndpointContext Endpoint : AnonymousEndpoint with address https://XXX.XXX.XXX.XXX:37045 will be marked SUSPENDED as it failed
[2017-03-31 22:48:52,151] [EI-Core]  WARN - EndpointContext Suspending endpoint : AnonymousEndpoint with address https://XXX.XXX.XXX.XXX:37045 - last suspend duration was : 30000ms and current suspend duration is : 30000ms - Next retry after : Fri Mar 31 22:49:22 UTC 2017
</code>```

XXX.XXX.XXX.XXX is the local host IP. YYY.YYY.YYY.YYY is my local IP from where I am trying to connect to the Amazon instance.

I am just trying to open mgt console but it seems the ESB is trying to process my request as a regular endpoint request.

The most confusing piece is that I can open the Analytics dashboard (on 9444) and BPEL mgt console (on 9445) that ships inside EI 6.0.0. Only the Enterprise Integrator mgt console accessible under 8243 port is not reachable.

Thanks in advance.

答:
During login into EI console (ESB+DSS+AS console on 8243 port) EI trying to connect some other services. In my cases I've got (in some installations) Name Notification error at this point.
In your case you received timeout. Probably these port (37045) is closed for IP  XXX.XXX.XXX.XXX

Try to configure AWS Security Group to open this port

Body:
finished WSO2 installation and first time I start the service and try to log into the management console it's not accessible (hosted on a Amazon EC2 unix instance).

Based on the log file the server starts normally:

[2017-03-31 22:40:29,622] [EI-Core]  INFO - CarbonUIServiceComponent Mgt Console URL  : https://XXX.XXX.XXX.XXX:8243/carbon/

When I try logging into mgt console the browser is hang up and won't finish loading the page. On wso2carbon.log I get the log entries below:

[2017-03-31 22:42:51,456] [EI-Core]  WARN - EndpointContext Endpoint : AnonymousEndpoint with address https://XXX.XXX.XXX.XXX:37045 will be marked SUSPENDED as it failed
[2017-03-31 22:42:51,457] [EI-Core]  WARN - EndpointContext Suspending endpoint : AnonymousEndpoint with address https://XXX.XXX.XXX.XXX:37045 - current suspend duration is : 30000ms - Next retry after : Fri Mar 31 22:43:21 UTC 2017
[2017-03-31 22:43:44,246] [EI-Core]  INFO - SourceHandler Writer null when calling informWriterError
[2017-03-31 22:43:44,247] [EI-Core]  WARN - SourceHandler Connection time out after request is read: http-incoming-1 Socket Timeout : 180000 Remote Address : YYY.YYY.YYY.YYY/179.212.90.90:4529
[2017-03-31 22:45:51,671] [EI-Core]  WARN - ConnectCallback Connection refused or failed for : /XXX.XXX.XXX.XXX:37045
[2017-03-31 22:45:51,672] [EI-Core]  WARN - EndpointContext Endpoint : AnonymousEndpoint with address https://XXX.XXX.XXX.XXX:37045 will be marked SUSPENDED as it failed
[2017-03-31 22:45:51,672] [EI-Core]  WARN - EndpointContext Suspending endpoint : AnonymousEndpoint with address https://XXX.XXX.XXX.XXX:37045 - last suspend duration was : 30000ms and current suspend duration is : 30000ms - Next retry after : Fri Mar 31 22:46:21 UTC 2017
[2017-03-31 22:46:44,662] [EI-Core]  INFO - SourceHandler Writer null when calling informWriterError
[2017-03-31 22:46:44,663] [EI-Core]  WARN - SourceHandler Connection time out after request is read: http-incoming-2 Socket Timeout : 180000 Remote Address : 179.212.90.90/179.212.90.90:4592
[2017-03-31 22:48:52,151] [EI-Core]  WARN - ConnectCallback Connection refused or failed for : /XXX.XXX.XXX.XXX:37045
[2017-03-31 22:48:52,151] [EI-Core]  WARN - EndpointContext Endpoint : AnonymousEndpoint with address https://XXX.XXX.XXX.XXX:37045 will be marked SUSPENDED as it failed
[2017-03-31 22:48:52,151] [EI-Core]  WARN - EndpointContext Suspending endpoint : AnonymousEndpoint with address https://XXX.XXX.XXX.XXX:37045 - last suspend duration was : 30000ms and current suspend duration is : 30000ms - Next retry after : Fri Mar 31 22:49:22 UTC 2017

XXX.XXX.XXX.XXX is the local host IP. YYY.YYY.YYY.YYY is my local IP from where I am trying to connect to the Amazon instance.

I am just trying to open mgt console but it seems the ESB is trying to process my request as a regular endpoint request.

The most confusing piece is that I can open the Analytics dashboard (on 9444) and BPEL mgt console (on 9445) that ships inside EI 6.0.0. Only the Enterprise Integrator mgt console accessible under 8243 port is not reachable.

Thanks in advance.


问:
Cannot get shared preferences inside custom context wrapper injection
I am trying to get a user's desired language stored in shared preferences, and use that to set the language of the app through this answer.

I have the same MyConxtextWrapper file as that answer but have changed the wrapper injection to:

```<code>    @Override
    protected void attachBaseContext(Context newBase) {
        SharedPreferences sharedPref = getSharedPreferences("userLang", Context.MODE_PRIVATE);
        String lang = sharedPref.getString("lang", "");

        super.attachBaseContext(MyContextWrapper.wrap(newBase,lang));
    }
}
</code>```

This gives me the error:

```<code>04-01 18:35:25.648 25032-25032/com.example.c1629177.cymruniapp E/AndroidRuntime: FATAL EXCEPTION: main
 Process: com.example.c1629177.cymruniapp, PID: 25032
 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.c1629177.cymruniapp/com.example.c1629177.cymruniapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
     at android.app.ActivityThread.-wrap11(ActivityThread.java)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
     at android.os.Handler.dispatchMessage(Handler.java:102)
     at android.os.Looper.loop(Looper.java:148)
     at android.app.ActivityThread.main(ActivityThread.java:5417)
     at java.lang.reflect.Method.invoke(Native Method)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
  Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
     at android.content.ContextWrapper.getSharedPreferences(ContextWrapper.java:171)
     at com.example.c1629177.cymruniapp.MainActivity.attachBaseContext(MainActivity.java:194)
     at android.app.Activity.attach(Activity.java:6175)
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2350)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
     at android.app.ActivityThread.-wrap11(ActivityThread.java)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
     at android.os.Handler.dispatchMessage(Handler.java:102)
     at android.os.Looper.loop(Looper.java:148)
     at android.app.ActivityThread.main(ActivityThread.java:5417)
     at java.lang.reflect.Method.invoke(Native Method)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
</code>```

How can I can pass the shared preference value "lang" into the line super.attachBaseContext(MyContextWrapper.wrap(newBase,lang)); ?

答:
You're overriding attachBaseContext() which is used to attach the base context to your wrapper. At the moment when you're calling getSharedPreferences() the base context is not yet set and thus you're trying to get the NullPointerException.

So instead call this method directly on the newBase context:

```<code>@Override
protected void attachBaseContext(Context newBase) {
    SharedPreferences sharedPref = newBase.getSharedPreferences("userLang", Context.MODE_PRIVATE);
    String lang = sharedPref.getString("lang", "");
    super.attachBaseContext(MyContextWrapper.wrap(newBase, lang));
}
</code>```

And maybe use a useful default for the language; instead of "".

Body:
I am trying to get a user's desired language stored in shared preferences, and use that to set the language of the app through this answer.

I have the same MyConxtextWrapper file as that answer but have changed the wrapper injection to:

    @Override
    protected void attachBaseContext(Context newBase) {
        SharedPreferences sharedPref = getSharedPreferences("userLang", Context.MODE_PRIVATE);
        String lang = sharedPref.getString("lang", "");

        super.attachBaseContext(MyContextWrapper.wrap(newBase,lang));
    }
}

This gives me the error:

04-01 18:35:25.648 25032-25032/com.example.c1629177.cymruniapp E/AndroidRuntime: FATAL EXCEPTION: main
 Process: com.example.c1629177.cymruniapp, PID: 25032
 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.c1629177.cymruniapp/com.example.c1629177.cymruniapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
     at android.app.ActivityThread.-wrap11(ActivityThread.java)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
     at android.os.Handler.dispatchMessage(Handler.java:102)
     at android.os.Looper.loop(Looper.java:148)
     at android.app.ActivityThread.main(ActivityThread.java:5417)
     at java.lang.reflect.Method.invoke(Native Method)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
  Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
     at android.content.ContextWrapper.getSharedPreferences(ContextWrapper.java:171)
     at com.example.c1629177.cymruniapp.MainActivity.attachBaseContext(MainActivity.java:194)
     at android.app.Activity.attach(Activity.java:6175)
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2350)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
     at android.app.ActivityThread.-wrap11(ActivityThread.java)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
     at android.os.Handler.dispatchMessage(Handler.java:102)
     at android.os.Looper.loop(Looper.java:148)
     at android.app.ActivityThread.main(ActivityThread.java:5417)
     at java.lang.reflect.Method.invoke(Native Method)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

How can I can pass the shared preference value "lang" into the line super.attachBaseContext(MyContextWrapper.wrap(newBase,lang)); ?

Body:
You're overriding attachBaseContext() which is used to attach the base context to your wrapper. At the moment when you're calling getSharedPreferences() the base context is not yet set and thus you're trying to get the NullPointerException.

So instead call this method directly on the newBase context:

@Override
protected void attachBaseContext(Context newBase) {
    SharedPreferences sharedPref = newBase.getSharedPreferences("userLang", Context.MODE_PRIVATE);
    String lang = sharedPref.getString("lang", "");
    super.attachBaseContext(MyContextWrapper.wrap(newBase, lang));
}

And maybe use a useful default for the language; instead of "".


问:
HTML upload directly image
I have a page that will allow users to upload their picture that will act as their profile picture. I have this code:

```<code><form method = "post" action = "" enctype="multipart/form-data">
    <input type = "hidden" name = "size" value = "1000000">
    <input type = "file" name = "image">
    <input type = "submit" name = "upload" value = "Upload Image">
</form>
</code>```

My php:

```<code>if(isset($_POST['upload'])) {
    $target = "profileimgs/".$key.basename($_FILES['image']['name']);

    $image = $key.basename($_FILES['image']['name']);

    $sql = "UPDATE users SET img = '$image' WHERE idnumber = $idnumber";
    mysqli_query($con,$sql);

    if(move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
        header("Location:home.php");
    } else {
        header("Location:error_uploading.php");
    }
}
</code>```

By choosing the picture, the only preview that will be shown is the picture's filename. I want to add a "preview" of their chosen image right after they chose the image. Just like when you upload a profile picture on facebook - you choose a picture from your computer, then when you click select picture it automatically upload your picture to the page and gives you a preview to that picture wihout having to click so many buttons.

Is there something I can do to achieve something this?

答:
```<code><form id="form1" runat="server">
   <input type='file' id="imgInp" />
   <img id="blah" src="#" alt="your image" />
</form>

<script type="text/javascript">
function readURL(input)
{
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#blah').attr('src', e.target.result);
            }

            reader.readAsDataURL(input.files[0]);
        }
}

$("#imgInp").change(function(){
    readURL(this);
});
</script>
It will show instead image using javascript base encode. your php code work as well as.
</code>```

Title: HTML upload directly image

Body:
I have a page that will allow users to upload their picture that will act as their profile picture. I have this code:

<form method = "post" action = "" enctype="multipart/form-data">
    <input type = "hidden" name = "size" value = "1000000">
    <input type = "file" name = "image">
    <input type = "submit" name = "upload" value = "Upload Image">
</form>

My php:

if(isset($_POST['upload'])) {
    $target = "profileimgs/".$key.basename($_FILES['image']['name']);

    $image = $key.basename($_FILES['image']['name']);

    $sql = "UPDATE users SET img = '$image' WHERE idnumber = $idnumber";
    mysqli_query($con,$sql);

    if(move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
        header("Location:home.php");
    } else {
        header("Location:error_uploading.php");
    }
}

By choosing the picture, the only preview that will be shown is the picture's filename. I want to add a "preview" of their chosen image right after they chose the image. Just like when you upload a profile picture on facebook - you choose a picture from your computer, then when you click select picture it automatically upload your picture to the page and gives you a preview to that picture wihout having to click so many buttons.

Is there something I can do to achieve something this?


答:
For 1-Dimensional Array of Numbers:

JavaScript's Math.max and Math.min will find the maximum or minimum of their arguments respectively, so, using an apply call, we can apply the array of numbers to these functions.

```<code>var values = [ 1, 2, 3, 4, 5 ]
Math.max.apply(null, values) // 5
Math.min.apply(null, values) // 1
</code>```

For Anything Else:

If you want the index of the maximum or are comparing non-numeric values, a custom iterator is needed.

```<code>function getMax (values)
  var maxIndex = -1
  var max = Number.MIN_VALUE // use Number.MAX_VALUE for min

  for (var i = 0; i < values.length; i++) {
    if (value[i] > max) { // do your "greater than" comparison here
      maxIndex = i
      max = value[i]
    }
  }

  // return what it is you need, max or maxIndex
  return max
end
</code>```

Title: Accessing min and max value within JSON array in JavaScript/HTML

Body:
For 1-Dimensional Array of Numbers:

JavaScript's Math.max and Math.min will find the maximum or minimum of their arguments respectively, so, using an apply call, we can apply the array of numbers to these functions.

var values = [ 1, 2, 3, 4, 5 ]
Math.max.apply(null, values) // 5
Math.min.apply(null, values) // 1

For Anything Else:

If you want the index of the maximum or are comparing non-numeric values, a custom iterator is needed.

function getMax (values)
  var maxIndex = -1
  var max = Number.MIN_VALUE // use Number.MAX_VALUE for min

  for (var i = 0; i < values.length; i++) {
    if (value[i] > max) { // do your "greater than" comparison here
      maxIndex = i
      max = value[i]
    }
  }

  // return what it is you need, max or maxIndex
  return max
end


问:
Set and get checked boxes in MultiSelectListPreference
I'm defining the MultiSelectListPreference in my axml file like this:

```<code> <MultiSelectListPreference
        android:title="Title"
        android:summary="Sum"
        android:key="dutyMarks"
        android:entries="@array/array_marks"
        android:entryValues="@array/array_marksValues">
 </MultiSelectListPreference>
</code>```

How can check / read the checked boxes in code?

I tried to get the checked values via the PreferenceChange event:

The checked values appear there, but I have no idea how to get them...

答:
since e.NewValue is a HashSet, you should be able to iterate through it</p>

```<code>foreach (string x in e.NewValue) {
  // do whatever you need to do with each value x here
}
</code>```

Body:
I'm defining the MultiSelectListPreference in my axml file like this:

 <MultiSelectListPreference
        android:title="Title"
        android:summary="Sum"
        android:key="dutyMarks"
        android:entries="@array/array_marks"
        android:entryValues="@array/array_marksValues">
 </MultiSelectListPreference>

How can check / read the checked boxes in code?

I tried to get the checked values via the PreferenceChange event:

The checked values appear there, but I have no idea how to get them...

Body:
since e.NewValue is a HashSet, you should be able to iterate through it

foreach (string x in e.NewValue) {
  // do whatever you need to do with each value x here
}


问:
How to disable the shadow around card view in android
I am working on demo application in which I am using the card view of the support library. By default, it is adding a shadow around it. I want to remove this shadow & should looks like simple.

I tried this (not working for me):

```<code>CardView cardView = (CardView) v.findViewById(R.id.cardView);
cardView.setElevation(0);
</code>```

After doing these I am getting crash

```<code>11-06 15:12:17.018: E/AndroidRuntime(24315): FATAL EXCEPTION: main
11-06 15:12:17.018: E/AndroidRuntime(24315): Process: com.xyz, PID: 24315
11-06 15:12:17.018: E/AndroidRuntime(24315): java.lang.NoSuchMethodError: android.support.v7.widget.CardView.setElevation
11-06 15:12:17.018: E/AndroidRuntime(24315):    at com.xyz.adapters.RecycleViewAdapter.onCreateViewHolder(RecycleViewAdapter.java:85)
11-06 15:12:17.018: E/AndroidRuntime(24315):    at com.xyz.adapters.RecycleViewAdapter.onCreateViewHolder(RecycleViewAdapter.java:1)
11-06 15:12:17.018: E/AndroidRuntime(24315):    at android.support.v7.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:2915)
11-06 15:12:17.018: E/AndroidRuntime(24315):    at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:2511)
11-06 15:12:17.018: E/AndroidRuntime(24315):    at android.support.v7.widget.LinearLayoutManager$RenderState.next(LinearLayoutManager.java:1425)
11-06 15:12:17.018: E/AndroidRuntime(24315):    at android.support.v7.widget.LinearLayoutManager$RenderState.next(LinearLayoutManager.java:1425)
</code>```

layout.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    xmlns:app="http://schemas.android.com/apk/res/com.xyz"
    android:id="@+id/cardView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginBottom="5dp"
    android:layout_marginLeft="5dp"
    android:layout_marginRight="5dp"
    android:orientation="horizontal" >
</code>```

答:
You can have it in XML like:

```<code><android.support.v7.widget.CardView
    android:id="@+id/card_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="2dp"
    android:layout_marginRight="2dp"
    app:cardElevation="0dp"
    app:cardCornerRadius="0.5dp"
    app:cardPreventCornerOverlap="false"
    app:cardUseCompatPadding="true"
    >
   </android.support.v7.widget.CardView>
</code>```

hope it helps you !!!

ContentLicense: CC BY-SA 4.0

Body:
I am working on demo application in which I am using the card view of the support library. By default, it is adding a shadow around it. I want to remove this shadow & should looks like simple.

I tried this (not working for me):

CardView cardView = (CardView) v.findViewById(R.id.cardView);
cardView.setElevation(0);

After doing these I am getting crash

11-06 15:12:17.018: E/AndroidRuntime(24315): FATAL EXCEPTION: main
11-06 15:12:17.018: E/AndroidRuntime(24315): Process: com.xyz, PID: 24315
11-06 15:12:17.018: E/AndroidRuntime(24315): java.lang.NoSuchMethodError: android.support.v7.widget.CardView.setElevation
11-06 15:12:17.018: E/AndroidRuntime(24315):    at com.xyz.adapters.RecycleViewAdapter.onCreateViewHolder(RecycleViewAdapter.java:85)
11-06 15:12:17.018: E/AndroidRuntime(24315):    at com.xyz.adapters.RecycleViewAdapter.onCreateViewHolder(RecycleViewAdapter.java:1)
11-06 15:12:17.018: E/AndroidRuntime(24315):    at android.support.v7.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:2915)
11-06 15:12:17.018: E/AndroidRuntime(24315):    at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:2511)
11-06 15:12:17.018: E/AndroidRuntime(24315):    at android.support.v7.widget.LinearLayoutManager$RenderState.next(LinearLayoutManager.java:1425)
11-06 15:12:17.018: E/AndroidRuntime(24315):    at android.support.v7.widget.LinearLayoutManager$RenderState.next(LinearLayoutManager.java:1425)

layout.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    xmlns:app="http://schemas.android.com/apk/res/com.xyz"
    android:id="@+id/cardView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginBottom="5dp"
    android:layout_marginLeft="5dp"
    android:layout_marginRight="5dp"
    android:orientation="horizontal" >

Body:
You can have it in XML like:

<android.support.v7.widget.CardView
    android:id="@+id/card_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="2dp"
    android:layout_marginRight="2dp"
    app:cardElevation="0dp"
    app:cardCornerRadius="0.5dp"
    app:cardPreventCornerOverlap="false"
    app:cardUseCompatPadding="true"
    >
   </android.support.v7.widget.CardView>

hope it helps you !!!


问:
Where to define C++ class member template function and functors that instantiate it?
I have a class Foo which is used in a small standalone project. It has a class definition in Foo.h with the implementation for the class' member functions in an implementation file Foo.cpp.

First question - one of the member functions of class Foo is a template method Foo::doSomething(), is it correct that the implementation of this method should appear with the declaration of the function in Foo.h ?

The template parameter which Foo::doSomething() will be instantiated with is one of two Functor types - class CalcA and CalcB.

Should I:

(A) put the defintion and implementation of the two Functor classes all together in Foo.cpp (where they are actually used by the implementation of other Foo member functions to call Foo::doSomething).

(B) put the definition and implementation of the two Functor classes in Foo.h.

(C) should I put split the definition and implementation of the two Functors across Foo.h and Foo.cpp as would be done with an ordinary class?

答:
The template method definition should indeed be in the header file of it the class it belongs to.

Like this:

```<code>class MyClass
{
    template <typename T>
    void foo(const T&)
    {
        // Definition
    }
};
</code>```

Or like this (note that the template method definition can be included from separate file after the class declaration)

```<code>class MyClass
{
    template <typename T> void foo(const T&);
};

template <typename T>
void MyClass::foo(const T&)
{
    // Definition
}
</code>```

The rest is depends on the style you agreed on and your needs.

I would put the functor declaration (or even the definition if they are simple) into the header if I use them not only in Foo or if Foo has them as class member.

Body:
The template method definition should indeed be in the header file of it the class it belongs to.

Like this:

class MyClass
{
    template <typename T>
    void foo(const T&)
    {
        // Definition
    }
};

Or like this (note that the template method definition can be included from separate file after the class declaration)

class MyClass
{
    template <typename T> void foo(const T&);
};

template <typename T>
void MyClass::foo(const T&)
{
    // Definition
}

The rest is depends on the style you agreed on and your needs.

I would put the functor declaration (or even the definition if they are simple) into the header if I use them not only in Foo or if Foo has them as class member.


问:
Request are not evaluated correctly in async.forEach
I want to request multiple pages with request in async.forEach. I have several links, and I want to go to each link and get the sublinks from it. Then I want to evaluate each sublink and push results to dataarray. But only the first one sublink is evaluated multiple times, for each links array element. But I want to evaluate each sublink. Here is my code:

```<code>var dataarray = [];
var links = ["www.mysite.com/1","www.mysite.com/2","www.mysite.com/3"];

async.whilst(
    function() { console.log("Number of links left: " + links.length); return links.length > 0; },
    function(innerCallback){
        var i1 = getRandomInt(1, links.length); //getRandomInt is a function that gives a random integer in array.
        var Theurl = links[i1-1];
        request({
            url: Theurl,
            //More paramaters to request here...
        }, function(error, response, body) {
            if (response) {
                //Evaluate some jquery to get a variable allsublinks used later on.
                //So I get several sub-links in each element in links array.
                var allsublinks =  stuff;

                //Now I define a function to be used in async.forEach. I basically need to
                //loop over allsublinks array that contains different url links.
                function getInfo(name, thiscallback) {
                    console.log("Online");
                    console.log("Current url: "+name);
                    request({
                    url: name,
                    //Other parameters to request.
                    }, function(error, response, body) {
                        if (response) {
                        //Here I evaluate some jquery again to get the datafromthislink variable
                        dataarray.push(datafromthislink);
                        setTimeout(function() { thiscallback(); });
                    }
                    })
                }

                //Now I use async.forEach to loop over allstorelinks.
                async.forEach(allsublinks, getInfo, function(err, results) {
                    console.log("dataarray: ",dataarray);
                    setTimeout(function() { links.splice(i1-1, 1); innerCallback(); });
                });
            }
        })
    },
    function(err){
        console.log("All Done");
})
</code>```

What am I doing wrong?

Best Regards

答:
This could be the cleaner version of what you are trying to achieve, which clear your concept of using callbacks properly.</p>

```<code>var dataarray = [];
var links = ["www.mysite.com/1", "www.mysite.com/2", "www.mysite.com/3"];

//Now I define a function to be used in async.forEach. I basically need to
//loop over allsublinks array that contains different url links.
function getInfo(link, infoCallback) {
    console.log("Online");
    console.log("Current url: " + link);
    request({
        url: link,
        //Other parameters to request.
    }, function (error, response, body) {
        if (error) console.log(error);
        if (response) {
            //Here I evaluate some jquery again to get the datafromthislink variable
            dataarray.push(body.datafromthislink);
        }
        infoCallback();
    })
}

function getLink(link, linkCallback) {
    console.log('checking link: ' + link);
    request({
        url: link,
        //More paramaters to request here...
    }, function (error, response, body) {
        if (error) console.log(error);
        if (response) {
            //Evaluate some jquery to get a variable allsublinks used later on.
            //So I get several sub-links in each element in links array.
            var allsublinks = body.stuff;
            //Now I use async.forEach to loop over allstorelinks.
            async.forEach(allsublinks, getInfo, linkCallback);
        } else {
            linkCallback();
        }
    })
}

async.each(links, getLink, function (err) {
    if (error) console.log(error);
    console.log("All Done");
    console.log(dataarray);
});
</code>```

Body:
I want to request multiple pages with request in async.forEach. I have several links, and I want to go to each link and get the sublinks from it. Then I want to evaluate each sublink and push results to dataarray. But only the first one sublink is evaluated multiple times, for each links array element. But I want to evaluate each sublink. Here is my code:

var dataarray = [];
var links = ["www.mysite.com/1","www.mysite.com/2","www.mysite.com/3"];

async.whilst(
    function() { console.log("Number of links left: " + links.length); return links.length > 0; },
    function(innerCallback){
        var i1 = getRandomInt(1, links.length); //getRandomInt is a function that gives a random integer in array.
        var Theurl = links[i1-1];
        request({
            url: Theurl,
            //More paramaters to request here...
        }, function(error, response, body) {
            if (response) {
                //Evaluate some jquery to get a variable allsublinks used later on.
                //So I get several sub-links in each element in links array.
                var allsublinks =  stuff;

                //Now I define a function to be used in async.forEach. I basically need to
                //loop over allsublinks array that contains different url links.
                function getInfo(name, thiscallback) {
                    console.log("Online");
                    console.log("Current url: "+name);
                    request({
                    url: name,
                    //Other parameters to request.
                    }, function(error, response, body) {
                        if (response) {
                        //Here I evaluate some jquery again to get the datafromthislink variable
                        dataarray.push(datafromthislink);
                        setTimeout(function() { thiscallback(); });
                    }
                    })
                }

                //Now I use async.forEach to loop over allstorelinks.
                async.forEach(allsublinks, getInfo, function(err, results) {
                    console.log("dataarray: ",dataarray);
                    setTimeout(function() { links.splice(i1-1, 1); innerCallback(); });
                });
            }
        })
    },
    function(err){
        console.log("All Done");
})

What am I doing wrong?

Best Regards

Body:
This could be the cleaner version of what you are trying to achieve, which clear your concept of using callbacks properly.

var dataarray = [];
var links = ["www.mysite.com/1", "www.mysite.com/2", "www.mysite.com/3"];

//Now I define a function to be used in async.forEach. I basically need to
//loop over allsublinks array that contains different url links.
function getInfo(link, infoCallback) {
    console.log("Online");
    console.log("Current url: " + link);
    request({
        url: link,
        //Other parameters to request.
    }, function (error, response, body) {
        if (error) console.log(error);
        if (response) {
            //Here I evaluate some jquery again to get the datafromthislink variable
            dataarray.push(body.datafromthislink);
        }
        infoCallback();
    })
}

function getLink(link, linkCallback) {
    console.log('checking link: ' + link);
    request({
        url: link,
        //More paramaters to request here...
    }, function (error, response, body) {
        if (error) console.log(error);
        if (response) {
            //Evaluate some jquery to get a variable allsublinks used later on.
            //So I get several sub-links in each element in links array.
            var allsublinks = body.stuff;
            //Now I use async.forEach to loop over allstorelinks.
            async.forEach(allsublinks, getInfo, linkCallback);
        } else {
            linkCallback();
        }
    })
}

async.each(links, getLink, function (err) {
    if (error) console.log(error);
    console.log("All Done");
    console.log(dataarray);
});


问:
sorting and load balancing
I read about parallel quicksort ( but no load balancing ).
who can give good algorithm for using on 2, 4, 8 cores?</p>

答: For Intel multicore CPUs, there's this paper.</p>

Title: sorting and load balancing


问:
Large memory usage for sqlite3
I have been using sqlite3 in my python2 project to speed up some tasks while leaving a small memory footprint. However, I have stumbled upon a curious issue where using the ORDER BY clause in a database query consumes lots of RAM memory. I'm really not sure about the cause and how to circumvent this issue. I have found nothing in the python docs for sqlite3. An example follows.

I can create a simple table and insert some dummy data

```<code>import sqlite3
from memory_profiler import memory_usage

con = sqlite3.connect("order_mem.db")
cur = con.cursor()

cur.execute("CREATE TABLE ordertest (idx INT, slice INT, seq TEXT)")

def load_data():

    for i in range(20):
        for p in xrange(50000):
            cur.execute("INSERT INTO ordertest VALUES (?, ?, ?)",
                        (p, i, "A" * 1000))
</code>```

If I want to fetch the data using a normal or ordered query, I get wildly different memory usages.

Unordered:

```<code>def iterate_unordered():

    for i in cur.execute("SELECT idx, seq FROM ordertest"):
        pass

load_data()
mem_usage = memory_usage(iterate_unordered)
print(max(mem_usage))
# 33.99609375
</code>```

Ordered:

```<code>def iterate_ordered():

    for i in cur.execute("SELECT idx, seq FROM ordertest ORDER BY slice"):

        pass

load_data()
mem_usage = memory_usage(iterate_ordered)
print(max(mem_usage))
# 1028.78515625
</code>```

Is there a way to perform this ordered query without grabbing so much memory?

EDIT: As per CL. answer, creating an index on the column that will be sorted greatly reduces RAM consumption during the sorting of that column. For comparative purposes, the result with the index:

```<code>cur.execute("CREATE TABLE ordertest (idx INT, slice INT, seq TEXT)")
cur.execute("CREATE INDEX test ON ordertest(slice)")

def iterate_ordered():

    for i in cur.execute("SELECT idx, slice, seq FROM ordertest ORDER BY slice"):
        pass

load_data()

mem_usage = memory_usage(iterate_ordered)
print(max(mem_usage))
#33.9296875
</code>```

答:
SQLite computes result rows on demand. But when you use ORDER BY, the database must sort all rows and keep that temporary list in memory.

To avoid the sorting, you have to keep a sorted list in the database, i.e., create an index on the slice column. (It is important not only that the rows are actually sorted, but that the query optimizer is able to prove that they are sorted.)

Title: Large memory usage for sqlite3

Body:
I have been using sqlite3 in my python2 project to speed up some tasks while leaving a small memory footprint. However, I have stumbled upon a curious issue where using the ORDER BY clause in a database query consumes lots of RAM memory. I'm really not sure about the cause and how to circumvent this issue. I have found nothing in the python docs for sqlite3. An example follows.

I can create a simple table and insert some dummy data

import sqlite3
from memory_profiler import memory_usage

con = sqlite3.connect("order_mem.db")
cur = con.cursor()

cur.execute("CREATE TABLE ordertest (idx INT, slice INT, seq TEXT)")

def load_data():

    for i in range(20):
        for p in xrange(50000):
            cur.execute("INSERT INTO ordertest VALUES (?, ?, ?)",
                        (p, i, "A" * 1000))

If I want to fetch the data using a normal or ordered query, I get wildly different memory usages.

Unordered:

def iterate_unordered():

    for i in cur.execute("SELECT idx, seq FROM ordertest"):
        pass

load_data()
mem_usage = memory_usage(iterate_unordered)
print(max(mem_usage))
# 33.99609375

Ordered:

def iterate_ordered():

    for i in cur.execute("SELECT idx, seq FROM ordertest ORDER BY slice"):

        pass

load_data()
mem_usage = memory_usage(iterate_ordered)
print(max(mem_usage))
# 1028.78515625

Is there a way to perform this ordered query without grabbing so much memory?

EDIT: As per CL. answer, creating an index on the column that will be sorted greatly reduces RAM consumption during the sorting of that column. For comparative purposes, the result with the index:

cur.execute("CREATE TABLE ordertest (idx INT, slice INT, seq TEXT)")
cur.execute("CREATE INDEX test ON ordertest(slice)")

def iterate_ordered():

    for i in cur.execute("SELECT idx, slice, seq FROM ordertest ORDER BY slice"):
        pass

load_data()

mem_usage = memory_usage(iterate_ordered)
print(max(mem_usage))
#33.9296875


问:
Combine x rows based on key in pandas
I'm new to learning pandas and ran across this problem today:

I'm building a simple df that collects health statistics, and each row represents one day of data per user. I want to see each individual user's weight loss in the data frame.

Here is a sample of my dataframe:

```<code>_id     _rev    body_mass   calories    date    name    sleep   steps   team    token   ua_id
xxxx    yyyy    60          3100    4/1/2017    user1   7        2800   t2      xxxx    123423
xxxx    yyyy    58          3300    4/1/2017    user2   6        2900   t1      xxxx    123439
xxxx    yyyy    45          3300    4/2/2017    user2   6        3300   t1      xxxx    123439
</code>```

What I would like is a new df created with this information:

```<code>weight loss      name
0             user1
13            user2
</code>```

答:
Start by sorting the dataframe by user name and date, so that for each user the first line refers to the earliest measurement:

```<code>df_sorted = df.sort_values(['name','date'])
</code>```

Then group the rows by user name and get the first (earliest) and last (most recent) measurement:

```<code>start = df_sorted.groupby('name').first()['body_mass']
end   = df_sorted.groupby('name').last()['body_mass']
</code>```

Now, get the difference:

```<code>end - start
</code>```

That's your result.

```<code>#name
#user1     0
#user2   -13
#Name: body_mass, dtype: int64
</code>```

Title: Combine x rows based on key in pandas

Body:
I'm new to learning pandas and ran across this problem today:

I'm building a simple df that collects health statistics, and each row represents one day of data per user. I want to see each individual user's weight loss in the data frame.

Here is a sample of my dataframe:

_id     _rev    body_mass   calories    date    name    sleep   steps   team    token   ua_id
xxxx    yyyy    60          3100    4/1/2017    user1   7        2800   t2      xxxx    123423
xxxx    yyyy    58          3300    4/1/2017    user2   6        2900   t1      xxxx    123439
xxxx    yyyy    45          3300    4/2/2017    user2   6        3300   t1      xxxx    123439

What I would like is a new df created with this information:

weight loss      name
0             user1
13            user2

Body:
Start by sorting the dataframe by user name and date, so that for each user the first line refers to the earliest measurement:

df_sorted = df.sort_values(['name','date'])

Then group the rows by user name and get the first (earliest) and last (most recent) measurement:

start = df_sorted.groupby('name').first()['body_mass']
end   = df_sorted.groupby('name').last()['body_mass']

Now, get the difference:

end - start

That's your result.

#name
#user1     0
#user2   -13
#Name: body_mass, dtype: int64


问:
How to declare an array of JComboBox in Java
I need to use an array of ComboBox, I try to declare in different way, but I can't.

Can someone help me?

Last way is:

```<code>final String[] comString = {"aa", "bb", "cc", "dd", "ee" };
private JComboBox<String> comList[]= new JComboBox[10];
</code>```

答:
With this declaration it works:</p>

```<code>private JComboBox comList[]={null,null,null,null,null,null,null,null,null,null};
</code>```

Body:
I need to use an array of ComboBox, I try to declare in different way, but I can't.

Can someone help me?

Last way is:

final String[] comString = {"aa", "bb", "cc", "dd", "ee" };
private JComboBox<String> comList[]= new JComboBox[10];

Body:
With this declaration it works:

private JComboBox comList[]={null,null,null,null,null,null,null,null,null,null};


问:
Mixed Model [in place of Repeated Measures ANOVA], but need RANKED Tukey results PER sampling date (NOT overall)

I have data from 6 different treatments, with sampling repeated 8
  times over 3 years (no missing data points). My individual bins from
  each treatment are equally split in 7 randomly distributed blocks. To
  analyze, I am using a Mixed Model (nlme package).

Example of the data :

```<code>bin     treatment   Bloc        date        CONTAM
b1      TR_A            1       t0      4.753038458
b2      TR_A            2       t0      4.709589136
b3      TR_A            3       t0      4.72668357
b4      TR_A            4       t0      4.647430928
b5      TR_A            5       t0      4.670129151
b6      TR_A            6       t0      4.647430928
b7      TR_A            7       t0      4.811256762
b8      TR_B            1       t0      4.551238194
b9      TR_B            2       t0      4.662660293
b10     TR_B            3       t0      4.753038458
b11     TR_B            4       t0      4.69554541
b12     TR_B            5       t0      4.69554541
</code>```

Packages used:

```<code>nlme ; lattice ; nortest ; multcomp
</code>```

Here is the script I am currently using:

```<code>mod.lme=lme(CONTAM~Treatment*date,random=~1|bloc/bin,data=data)
summary(mod.lme)
anova(mod.lme)
summary(glht(mod.lme, linfct=mcp(Treatment = "Tukey")), test = adjusted(type = "bonferroni"))
</code>```

This works just fine (ANOVA<0.001) but is not giving me the information I need.

-> I obtain an overall Tukey, but since I am dealing with degradation data I expect the treatments to be similar at the beginning and end, but DIFFERENT in the middle.

----> Therefore, I am seeking a test that will give me the RANKED (a, ab,
  bc...) Tukey results PER sampling date, while taking in consideration
  that this is a repeated measures model.

Any ideas? :)

Thanks!

FYI, I've attempted the solutions from this question: post hoc test for a two way mixed model anova

1

```<code>library(GAD)
snk.test(mod.lme, term="Treatment*date", among="Treatment", within="date")
</code>```

My inconclusive result : #  Error in object$model[, 2:(length(object$x) + 1)] : incorrect number of dimensions

2

This second one gives me a huge output, but not the one I need.

```<code>library(lsmeans)
summary(lsmeans(mod.lme, pairwise~Treatment*date), infer=TRUE)
</code>```

答:
Try this:

Obtain the LS means:

```<code>library("lsmeans")
mod.lsm <- lsmeans::lsmeans(mod.lme, ~ Treatment * date)
</code>```

(Calling lsmeans::lsmeans prevents it from using the same function in the lmerTest package, if it happens to be loaded.)

List the LS means:

```<code>mod.lsm
</code>```

Do pairwise comparisons, separately for each date:

```<code>pairs(mod.lsm, by = "date")
</code>```

(The default result shows $t$ tests and adjusted $P$ values using the Tukey method.)

Body:
I have data from 6 different treatments, with sampling repeated 8
  times over 3 years (no missing data points). My individual bins from
  each treatment are equally split in 7 randomly distributed blocks. To
  analyze, I am using a Mixed Model (nlme package).

Example of the data :

bin     treatment   Bloc        date        CONTAM
b1      TR_A            1       t0      4.753038458
b2      TR_A            2       t0      4.709589136
b3      TR_A            3       t0      4.72668357
b4      TR_A            4       t0      4.647430928
b5      TR_A            5       t0      4.670129151
b6      TR_A            6       t0      4.647430928
b7      TR_A            7       t0      4.811256762
b8      TR_B            1       t0      4.551238194
b9      TR_B            2       t0      4.662660293
b10     TR_B            3       t0      4.753038458
b11     TR_B            4       t0      4.69554541
b12     TR_B            5       t0      4.69554541

Packages used:

nlme ; lattice ; nortest ; multcomp

Here is the script I am currently using:

mod.lme=lme(CONTAM~Treatment*date,random=~1|bloc/bin,data=data)
summary(mod.lme)
anova(mod.lme)
summary(glht(mod.lme, linfct=mcp(Treatment = "Tukey")), test = adjusted(type = "bonferroni"))

This works just fine (ANOVA<0.001) but is not giving me the information I need.

-> I obtain an overall Tukey, but since I am dealing with degradation data I expect the treatments to be similar at the beginning and end, but DIFFERENT in the middle.

----> Therefore, I am seeking a test that will give me the RANKED (a, ab,
  bc...) Tukey results PER sampling date, while taking in consideration
  that this is a repeated measures model.

Any ideas? :)

Thanks!

FYI, I've attempted the solutions from this question: post hoc test for a two way mixed model anova

1

library(GAD)
snk.test(mod.lme, term="Treatment*date", among="Treatment", within="date")

My inconclusive result : #  Error in object$model[, 2:(length(object$x) + 1)] : incorrect number of dimensions

2

This second one gives me a huge output, but not the one I need.

library(lsmeans)
summary(lsmeans(mod.lme, pairwise~Treatment*date), infer=TRUE)

Body:
Try this:

Obtain the LS means:

library("lsmeans")
mod.lsm <- lsmeans::lsmeans(mod.lme, ~ Treatment * date)

(Calling lsmeans::lsmeans prevents it from using the same function in the lmerTest package, if it happens to be loaded.)

List the LS means:

mod.lsm

Do pairwise comparisons, separately for each date:

pairs(mod.lsm, by = "date")

(The default result shows $t$ tests and adjusted $P$ values using the Tukey method.)


问:
Why do these two images not wanna go on top of each other?
http://lucasdebelder.be/googledoodle/

I want to have the planet (bottom image) on top of the top image (the blue background/space). I have a main div class:"center" set on 'position: absolute' and around both of those images is separately a div wrapped with position: relative; but somehow they don't want to go and sit on top of each other, I've also tried it with z-index but that doesn't work either.

Thanks in advance.

答:
Use these properties the planeet_achtergrond class:</p>

```<code>.planeet_achtergrond{
  position: absolute;
  bottom: 150px;
}
</code>```

Body:
Use these properties the planeet_achtergrond class:

.planeet_achtergrond{
  position: absolute;
  bottom: 150px;
}