答:
Simple method,</p>

```<code>$arr = array("  one", "  two", array("  three"));

function trimAll(&$array) {
  foreach($array as $key => $value) {
    if(gettype($value) !== "array") {
        $array[$key] = trim($value);
    } else {
        $array[$key] = trimAll($value);
    }
  }
  return $array;
}

trimAll($arr);
</code>```

Title: How do I remove surrounding spaces from each value in multidimensional array recursively

Body:
Each string value within my $arr array contains 2 preceeding white spaces. I would like to remove these spaces using the trim() method. Furthermore, I would like to do the same for any arrays within the $arr array assuming an infinite number of arrays within arrays. I attempted to do this recursively with no success.

Although there might be a built in php method to do this for me, I am learning, and would like to know why this code block doesn't work as well as what altercation can be made to fix it.

$arr = array("  one", "  two", array("  three"));

function trimAll(&$array) {
  foreach($array as $key => $value) {
    if(gettype($value) !== "array") {
        $array[$key] = trim($value);
    } else {
        trimAll($value);
    }
  }
}

trimAll($arr);

echo $arr[0];//"one" (worked)
echo $arr[1];//"two" (worked)
echo $arr[2][0];// "  three"(didn't work)

Body:
Simple method,

$arr = array("  one", "  two", array("  three"));

function trimAll(&$array) {
  foreach($array as $key => $value) {
    if(gettype($value) !== "array") {
        $array[$key] = trim($value);
    } else {
        $array[$key] = trimAll($value);
    }
  }
  return $array;
}

trimAll($arr);


来源: stackexchange

问:
Upload an Image from camera or gallery in my WebView
I have done on app convert my website to app with webview
i want to Upload an Image from camera or gallery
i want to add to for example if i want to share on facebook it need to open facebook app or if i click links it need to ask me to go outside
what should i change or add?
Thank you!

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    webview = (WebView) findViewById(R.id.webview);
    webView();
}

//Metodo llamar el webview
private void webView() {
    //Habilitar JavaScript (Videos youtube)
    webview.getSettings().setJavaScriptEnabled(true);

    //Handling Page Navigation
    webview.setWebViewClient(new WebViewClient());

    //Load a URL on WebView
    webview.loadUrl("http://www.nehmen-geben.com/");
}

// Metodo Navigating web page history
@Override
public void onBackPressed() {
    if (webview.canGoBack()) {
        webview.goBack();
    } else {
        super.onBackPressed();
    }
</code>```

AndroidManifest

```<code><?xml version="1.0" encoding="utf-8"?>
</code>```

```<code><uses-permission android:name="android.permission.INTERNET" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">

    </activity>
    <activity android:name=".splash">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
</code>```

答:
Try to use the "WebClientListener" and override the "shouldOverrideUrlLoading".

```<code>webView.setWebViewClient(new WebClientListener());
</code>```

and private class WebClientListener extends WebViewClient {
 //other callback......
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
    //Intercept the url you specified in this method.
    //e.g. Define a specified url like "http://yourhost.com/shareToFacebook"
    //in your html and when you cathch this url, use the facebook's sdk to share,
    //and return "true" to tell the webview to handle such url yourself.
    //
    //If you want to open the browser outside,you can use:
    //Uri uri = Uri.parse(url);
    //Intent intent = new Intent(Intent.ACTION_VIEW, uri);

    //startActivity(intent);

    }
}

If you just want to upload the file like photo in webview, you can try

```<code>webView.setWebChromeClient(new WebChromeClient());
</code>```

override the onShowFileChooser(after lollipop) and openFileChooser(prelolipop) of the interface.

ContentLicense: CC BY-SA 3.0

Body:
I have done on app convert my website to app with webview
i want to Upload an Image from camera or gallery
i want to add to for example if i want to share on facebook it need to open facebook app or if i click links it need to ask me to go outside
what should i change or add?
Thank you!

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    webview = (WebView) findViewById(R.id.webview);
    webView();
}

//Metodo llamar el webview
private void webView() {
    //Habilitar JavaScript (Videos youtube)
    webview.getSettings().setJavaScriptEnabled(true);

    //Handling Page Navigation
    webview.setWebViewClient(new WebViewClient());

    //Load a URL on WebView
    webview.loadUrl("http://www.nehmen-geben.com/");
}

// Metodo Navigating web page history
@Override
public void onBackPressed() {
    if (webview.canGoBack()) {
        webview.goBack();
    } else {
        super.onBackPressed();
    }

AndroidManifest

<?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="android.permission.INTERNET" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">

    </activity>
    <activity android:name=".splash">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

Body:
Try to use the "WebClientListener" and override the "shouldOverrideUrlLoading".

webView.setWebViewClient(new WebClientListener());

and private class WebClientListener extends WebViewClient {
 //other callback......
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
    //Intercept the url you specified in this method.
    //e.g. Define a specified url like "http://yourhost.com/shareToFacebook"
    //in your html and when you cathch this url, use the facebook's sdk to share,
    //and return "true" to tell the webview to handle such url yourself.
    //
    //If you want to open the browser outside,you can use:
    //Uri uri = Uri.parse(url);
    //Intent intent = new Intent(Intent.ACTION_VIEW, uri);

    //startActivity(intent);

    }
}

If you just want to upload the file like photo in webview, you can try

webView.setWebChromeClient(new WebChromeClient());

override the onShowFileChooser(after lollipop) and openFileChooser(prelolipop) of the interface.


问:
How do I get a link in Bootstrap nav bar to disappear/reappear based on window size?
I'm currently building a website using Bootstrap. I have a "Services" link listed in my nav bar, that when hovered over displays a list of services. The user can also click on "Services" itself and they are directed to a link. If the user resizes their screen, or are looking at the website on their mobile device, I need to be able to remove the link from "Services".

The code below sort of works. I am running into a bug when I try to resize the desktop browser multiple times. Once I make the screen smaller, I am unable to recognize a larger browser window and, therefore, get the link in "Services" back. What am I missing?

HTML

```<code><li class="dropdown">
    <a href="#services" class="dropdown-toggle linkedDropDown" data-toggle="dropdown">Services
         <i class="fa fa-angle-down"></i>
    </a>
    <ul class="dropdown-menu">
         <li>
              <a href="">Link 1</a>
         </li>
         <li>
              <a href="">Link 2</a>
         </li>
         <li>
              <a href="">Link 3</a>
         </li>
         <li>
              <a href="">Link 4</a>
         </li>
    </ul>
</li>
</code>```

CSS

```<code>@media (min-width:990px){
    .dropdown:hover .dropdown-menu {
        display: block !important;
        margin-top: 0 !important;
     }
}
</code>```

jQuery

```<code>$(document).ready(function () {
     changeElements();

     $(window).resize(function() {
          changeElements();
     });
 });

function changeElements(){
     if ($(window).width() < 990) {
           $('.linkedDropDown').removeAttr('href');
     }
     else{
           $('.linkedDropDown').attr('href');
     }
 }
</code>```

答: check by removing the data-toggle attribute and change the classes for the screen on which you don't need the dropdown. Hope this should work</p>

Body:
I'm currently building a website using Bootstrap. I have a "Services" link listed in my nav bar, that when hovered over displays a list of services. The user can also click on "Services" itself and they are directed to a link. If the user resizes their screen, or are looking at the website on their mobile device, I need to be able to remove the link from "Services".

The code below sort of works. I am running into a bug when I try to resize the desktop browser multiple times. Once I make the screen smaller, I am unable to recognize a larger browser window and, therefore, get the link in "Services" back. What am I missing?

HTML

    Services

              Link 1

              Link 2

              Link 3

              Link 4

CSS

@media (min-width:990px){
    .dropdown:hover .dropdown-menu {
        display: block !important;
        margin-top: 0 !important;
     }
}

jQuery

$(document).ready(function () {
     changeElements();

     $(window).resize(function() {
          changeElements();
     });
 });

function changeElements(){
     if ($(window).width() < 990) {
           $('.linkedDropDown').removeAttr('href');
     }
     else{
           $('.linkedDropDown').attr('href');
     }
 }


问:
maven / eclipse JPA project and Entity generation?
Im a bit confused about this :

I've setuped a simple maven-archetype-webapp

So far i've been creating entities from a plain POJO, adding annotations as needed

But lately i think that there could be ways to ease this entity creations, so i googled

And found out about eclipse that could help me generate the JPA entities ..

I tried right clicking on my package that contains the entities, and new -> JPA -> Entity, only to find out that i can only make use of this in a JPA project.

In one hand, i have a maven project (which is not a JPA project created by eclipse), and in the other hand, i'd like to give eclipse JPA a try.

And one more thing, i have something in mind that we could design with a GUI tool, creating entities, defining the relations, defining configurations like the id generation sequence, multiple unique columns, compound key, etc and have the JPA entities generated for you.

Does this kind of tool exist ? Perhaps as an eclipse plugin or something else ?

答:
JPA tooling can be added to an existing Eclipse project in a couple of ways, depending on the type of project you are starting with. If you have a Java project, you can right-click on it and use the "Configure" -> "Convert to JPA project..." menu item to add JPA project capabilities to an existing Java project.  If you have a Web project or other WTP based project (known as "faceted" projects), you can simply add the JPA facet to the project in the project properties on the "Facets" node.  If you are starting from scratch you can create a JPA project, which is basically just a Java project with JPA tooling added in.

I'm not sure if you are using m2e, but this is the Eclipse Maven integration tooling.  There are some known issues using Maven with the JPA tooling in Eclipse, but there are workarounds that may work for you.

As for graphical diagramming tools for developing entities, this is coming to the Eclipse Dali Java Persistence Tools project for the next release - 3.0 (Indigo).  You can try this functionality out now by downloading the JPA Diagram Editor.  Check out the youtube video (search JPA Diagram Editor) for a quick demo of the functionality.

Sorry for the lack of links, but I can only post 1 per reply as a new user.

ContentLicense: CC BY-SA 2.5


问:
Scanner doesn't work in Blue J (java)
So I have to create matrix of a certain size specified from the user. To do this I was using a Scanner and was going to take two int values, and use those to create the matrix. Long story short, when I ran it, it opened up the terminal window and said "Enter number: " just like I programmed it to, but it wouldn't let me enter a number. I investigated by making a simple program that should take in an integer and output that number, and the results were the same. Any suggestions?

```<code>import java.util.*;
public class scanner
{
    public void scanner()
    {
        Scanner a = new Scanner(System.in);
        System.out.println("Enter number: ");
        int number = a.nextInt();
        a.close();
        System.out.print(number);
    }
}
</code>```

When I run this, it opens up the terminal window, says "Enter number: " but does not have the blinking cursor indicating that I can type, even when I click on it. I inserted this code into JGrasp and it worked just fine. Any help at all?

答:
the problem might be from having your code inside a method instead of a main method or it could just be a bug

side note though: once you type the integer for a.nextInt() and hit enter, it should set int number to that value so I don't believe that the a.close() is necessary because it will move on to printing the integer regardless

Title: Scanner doesn't work in Blue J (java)

Body:
So I have to create matrix of a certain size specified from the user. To do this I was using a Scanner and was going to take two int values, and use those to create the matrix. Long story short, when I ran it, it opened up the terminal window and said "Enter number: " just like I programmed it to, but it wouldn't let me enter a number. I investigated by making a simple program that should take in an integer and output that number, and the results were the same. Any suggestions?

import java.util.*;
public class scanner
{
    public void scanner()
    {
        Scanner a = new Scanner(System.in);
        System.out.println("Enter number: ");
        int number = a.nextInt();
        a.close();
        System.out.print(number);
    }
}

When I run this, it opens up the terminal window, says "Enter number: " but does not have the blinking cursor indicating that I can type, even when I click on it. I inserted this code into JGrasp and it worked just fine. Any help at all?


问:
Java: How to Count a Character in a String
I have to count the number of times that a character appears in a string.

I know this question has been asked previously.  However, the solutions that I've seen use commands/techniques that I haven't yet covered in class.

Here is my code:

```<code>import java.util.Scanner;
/*
This program counts the number of occourances of a char in a string.
*/

public class LetterCounter
{
public static void main(String[] args)
{
int i, length, count=0;
String input;
char letter1, letter2;

// Create a Scanner object for keyboard input.
Scanner stdin = new Scanner(System.in);

// Get a string from user
System.out.print("Enter a string: ");
input = stdin.nextLine();

// Get a character from user
System.out.print("Enter a character: ");
letter1 = stdin.next().charAt(0);

//Determine the length of the string
length = input.length();

//Count the number of times the user selected character appears in the string
for (i = 0; i <= length; i++)
{
    letter2 = input.charAt(i);
    if (letter1 == letter2)
{
count++;
}
}

System.out.printf("Occurrences of a %s in %s is %d", letter1, input, count);
</code>```

}
}

Here is the output from jgrasp:

----jGRASP exec: java LetterCounter
Enter a string: hello world
Enter a character: l
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 11
    at java.lang.String.charAt(String.java:658)
    at LetterCounter.main(LetterCounter.java:37)

----jGRASP wedge2: exit code for process is 1.
 ----jGRASP: operation complete.

I don't understand the errors.  Any and all help is appreciated.

答:
Error is occurring in the below line of code -

```<code>for (i = 0; i <= length; i++)
</code>```

Here Iteration is longer than input length [exceeds the range].
The revised code will be -

```<code>for (i = 0; i < length; i++)
</code>```

Need anything more? Shoot me a comment please.

Hopefully, it will work fine.

Body:
I have to count the number of times that a character appears in a string.

I know this question has been asked previously.  However, the solutions that I've seen use commands/techniques that I haven't yet covered in class.

Here is my code:

import java.util.Scanner;
/*
This program counts the number of occourances of a char in a string.
*/

public class LetterCounter
{
public static void main(String[] args)
{
int i, length, count=0;
String input;
char letter1, letter2;

// Create a Scanner object for keyboard input.
Scanner stdin = new Scanner(System.in);

// Get a string from user
System.out.print("Enter a string: ");
input = stdin.nextLine();

// Get a character from user
System.out.print("Enter a character: ");
letter1 = stdin.next().charAt(0);

//Determine the length of the string
length = input.length();

//Count the number of times the user selected character appears in the string
for (i = 0; i <= length; i++)
{
    letter2 = input.charAt(i);
    if (letter1 == letter2)
{
count++;
}
}

System.out.printf("Occurrences of a %s in %s is %d", letter1, input, count);

}
}

Here is the output from jgrasp:

----jGRASP exec: java LetterCounter
Enter a string: hello world
Enter a character: l
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 11
    at java.lang.String.charAt(String.java:658)
    at LetterCounter.main(LetterCounter.java:37)

----jGRASP wedge2: exit code for process is 1.
 ----jGRASP: operation complete.

I don't understand the errors.  Any and all help is appreciated.

Body:
Error is occurring in the below line of code -

for (i = 0; i <= length; i++)

Here Iteration is longer than input length [exceeds the range].
The revised code will be -

for (i = 0; i < length; i++)

Need anything more? Shoot me a comment please.

Hopefully, it will work fine.


问:
How to communicate mobile (Xamarin) with a desktop Application (.NET)
Is it possible to send some kind of message from mobile app (developed using Xamarin.forms with C#) to a desktop application (developed using VB.net or C#)? I would like to send messages from mobile to desktop app. I was thinking on using Bluetooth or maybe WIFI protocol

Other idea that I was thinkin is making desktop application to use a rest service, then also make mobile app to use same rest server. In this way It could be possible to create some kind of bridge between these techs.

Do you have any example or any experience on this?

答: You can create a web API https://learn.microsoft.com/en-us/aspnet/web-api/overview/older-versions/build-restful-apis-with-aspnet-web-api then host it on your desktop/laptop. That would be the channel between your mobile app and your desktop app.</p>


问:
Sqlite with hibernate and spring-boot
I'm working on a project using maven, hibernate, spring and sqlite3.For the configuration of the connection and hibernate I use the application.yml file which is:

```<code>spring:
profile: dev
jpa:
hibernate:
ddl-auto: create-drop
properties:
hibernate:
dialect: org.hibernate.dialect.SQLiteDialect
datasource:url: jdbc:sqlite:C:\Users\user pc\Desktop\database\testrest.db
username: username
password: password
driverClassName: org.sqlite.JDBC
</code>```

The problem every time I start the application my sqlite database is overwritten (so I lose all my tables) and a new one of the same name is created.

Hoping to have your help, thank you in advance.

答:
The list of possible values for ddl-auto for Hibernate are:

validate: validates the schema, makes no changes to the database.

update: updates the schema.

create: creates the schema, destroying previous data.

create-drop: create the schema and then drop it when SessionFactory is closed explicitly (application is closed).

You should replace create-drop with update or validate

Title: Sqlite with hibernate and spring-boot

Body:
I'm working on a project using maven, hibernate, spring and sqlite3.For the configuration of the connection and hibernate I use the application.yml file which is:

spring:
profile: dev
jpa:
hibernate:
ddl-auto: create-drop
properties:
hibernate:
dialect: org.hibernate.dialect.SQLiteDialect
datasource:url: jdbc:sqlite:C:\Users\user pc\Desktop\database\testrest.db
username: username
password: password
driverClassName: org.sqlite.JDBC

The problem every time I start the application my sqlite database is overwritten (so I lose all my tables) and a new one of the same name is created.

Hoping to have your help, thank you in advance.

ContentLicense: CC BY-SA 4.0


问:
My Work Items gone in TFS
We use VS2008 with TFS for source control at my workplace and it works fine, however today we experienced a problem when trying to associate our pending changes with a work item.
Usually when I want to associate changes with a work item I just go to the second tab from the top in the "pending changes" window, check the work item that fits the changes and check in. Today however, all my work items were gone from the list. I can select a suitable query from the drop down box and this works fine, so the projects are there.

I think the problem might have something to do with the "My Work Items" query being associated with the wrong TFS project (there are two on our TFS-server) but I don't know how to fix this. The same problem occurred for most of my colleagues with some (possible) variations.

So... how do I restore "My Work Items" to the pending changes window?

EDIT: The problem still persists in a way but I worked my way around it by removing the second project in the Team Explorer. This is acceptable (for now) since that project is not currently active. I am not content with this being a good long term solution, however...

EDIT: I know that I may not have provided enough information for anyone to understand what really is the problem, still, I'll keep it up for now in case someone has had the same problem and knows how to fix it :P

答:
The first time I've seen with this is when I was associating a checkin with a work item and the queries had changed to another Team Project.  Can you check the queries are pulling from the correct team project?

Another thing to check is the Event Log of your TFS server for any oddities.

OwnerDisplayName: Sakkle

Title: My Work Items gone in TFS

LastEditorDisplayName: Sakkle

OwnerDisplayName: Ray Booysen


问:
Is there benefit to using Monit instead of a basic Upstart setup?
I'm configuring my server to run node.js as a daemon. I've setup Upstart to handle startup and shutdown of node, which works wonderfully. The next step is to make sure that node.js is restarted if it dies. A few of the guides have suggested using Monit (or Fugue) to monitor the process (in Monit's case by doing an HTTP request to the server and waiting for a response).

I'm happy to use something like Monit or Fugue, but I'm not sure why one wouldn't (or couldn't) just use Upstart's respawn feature. I assume Upstart will monitor the PID of the launched process and just kick it off again if it dies. What does Monit or Fugue give you that Upstart doesn't?

答:
I highly recommend using both Monit AND upstart.  Upstart makes it easy to deamonize node.js and Monit comes packed with tons of useful app checks including memory usage, http requests, cpu usage, ...

This is an example of the most basic setup you can get.  You could also easily add another monit config (with the same start and stop script) but using the PID file and monitoring process stats.

For the below configuration create a simple local-only request handler in your app that just responds with status 200 if all is well.

Monit config:

```<code>check host app_name with address 127.0.0.1
    start "/sbin/start app_name"
    stop "/sbin/stop app_name"
    if failed port 80 protocol HTTP
        request /ok
        with timeout 5 seconds
        then restart
</code>```

Upstart script (/etc/init/app_name):

```<code>description "app_name"

start on startup
stop on shutdown

script
    # Node needs HOME to be set
    export HOME="path/to/node/app"

    exec sudo -u nodejs /usr/local/bin/node path/to/node/app/server.js production 2>>/var/log/app_name.error.log >>/var/log/app_name.log
end script
</code>```

Body:
I highly recommend using both Monit AND upstart.  Upstart makes it easy to deamonize node.js and Monit comes packed with tons of useful app checks including memory usage, http requests, cpu usage, ...

This is an example of the most basic setup you can get.  You could also easily add another monit config (with the same start and stop script) but using the PID file and monitoring process stats.

For the below configuration create a simple local-only request handler in your app that just responds with status 200 if all is well.

Monit config:

check host app_name with address 127.0.0.1
    start "/sbin/start app_name"
    stop "/sbin/stop app_name"
    if failed port 80 protocol HTTP
        request /ok
        with timeout 5 seconds
        then restart

Upstart script (/etc/init/app_name):

description "app_name"

start on startup
stop on shutdown

script
    # Node needs HOME to be set
    export HOME="path/to/node/app"

    exec sudo -u nodejs /usr/local/bin/node path/to/node/app/server.js production 2>>/var/log/app_name.error.log >>/var/log/app_name.log
end script


问:
Merging branches: Why is git merge --no-ff not merging everything?

working with git for the first time and encountered a problem with merging.  the work flow was something as follows:

created repository on gitlab and each member linked locally

added two text files to master branch - recipe_book.txt and ingredients.txt

edited the two file and they were added, committed and pushed

created two branches from master - vegetarian and pizza-pasta

in pizza-pasta branch both files were re-written (not just slightly modified), added committed and pushed.

in vegetarian branch both files were re-written (not just slightly modified), added committed and pushed.

on master - master and pizza-pasta were merged this resulted in a fast-forward merge (as suggested below)
-reverted to commit pre-merge
-tried no fast-forwarding merge however only parts of the content of files in pizza-pasta were added to the content of the files in master.

the aim of this task is to two files in three different branches (files must retain same name however content must be completely different) in the end all the branches must be merged so that the files in the master branch contain the content that was originally in each of the three branches.

summary of commands used (editing of files was done manually and locally by each participant):

```<code>    git add ingredients.txt
    git commit -m "adding blank file ingredients.txt"
    git add recipe_book.txt
    git commit -m "adding blank file recipe_book.txt"
    git push -u origin master
    git add ingredients.txt
    git commit -m "updating file ingredients.txt with content"
    git add recipe_book.txt
    git commit -m "updating file recipe_book.txt with content"
    git push -u origin master
    git branch vegetarian
    git push origin vegetarian
    git branch pizza-pasta
    git push origin pizza-pasta
    git checkout vegetarian
    git add ingredients.txt
    git commit -m "updating file ingredients.txt with completely new content"
    git add recipe_book.txt
    git commit -m "updating file recipe_book.txt with completely new content"
    git push -u origin vegetarian
    git checkout pizza-pasta
    git add ingredients.txt
    git commit -m "updating file ingredients.txt with completely new content"
    git add recipe_book.txt
    git commit -m "updating file recipe_book.txt with completely new content"
    git push -u origin pizza-pasta
    git checkout master
    git merge master pizza-pasta \\ here i made the fast-forward merge mistake
    git reset --hard fe6fff
    git reset --soft HEAD@{1}
    git commit -m "reverting to pre-merge"
    git push -u origin master
    git merge --no-ff master pizza-pasta \\ here i made the merge with no fast-forward
</code>```

答:
If the vegetarian branch edits the recipe_book.txt by removing/fully changing all lines and then adding back vegetarian lines, then merging back to master will look like an "overwrite" (but really was just a fast-forward merge).

```<code>$ git init
Initialized empty Git repository in /code/test-git/.git/
$ touch recipe_book.txt
$ echo steak > recipe_book.txt
$ cat recipe_book.txt
steak
$ git add recipe_book.txt
$ git commit -m "steak"
[master (root-commit) 25b1f57] steak
 1 file changed, 1 insertion(+)
 create mode 100644 recipe_book.txt
$ git checkout -b veg
Switched to a new branch 'veg'
$ echo tofu > recipe_book.txt
$ cat recipe_book.txt
tofu
$ git commit -am "tofu"
[veg e765cb4] tofu
 1 file changed, 1 insertion(+), 1 deletion(-)
$ git checkout master
Switched to branch 'master'
$ cat recipe_book.txt
steak
$ git merge veg
Updating 25b1f57..e765cb4
Fast-forward
 recipe_book.txt | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
$ cat recipe_book.txt
tofu
</code>```

Body:
working with git for the first time and encountered a problem with merging.  the work flow was something as follows:

created repository on gitlab and each member linked locally

added two text files to master branch - recipe_book.txt and ingredients.txt

edited the two file and they were added, committed and pushed

created two branches from master - vegetarian and pizza-pasta

in pizza-pasta branch both files were re-written (not just slightly modified), added committed and pushed.

in vegetarian branch both files were re-written (not just slightly modified), added committed and pushed.

on master - master and pizza-pasta were merged this resulted in a fast-forward merge (as suggested below)
-reverted to commit pre-merge
-tried no fast-forwarding merge however only parts of the content of files in pizza-pasta were added to the content of the files in master.

the aim of this task is to two files in three different branches (files must retain same name however content must be completely different) in the end all the branches must be merged so that the files in the master branch contain the content that was originally in each of the three branches.

summary of commands used (editing of files was done manually and locally by each participant):

    git add ingredients.txt
    git commit -m "adding blank file ingredients.txt"
    git add recipe_book.txt
    git commit -m "adding blank file recipe_book.txt"
    git push -u origin master
    git add ingredients.txt
    git commit -m "updating file ingredients.txt with content"
    git add recipe_book.txt
    git commit -m "updating file recipe_book.txt with content"
    git push -u origin master
    git branch vegetarian
    git push origin vegetarian
    git branch pizza-pasta
    git push origin pizza-pasta
    git checkout vegetarian
    git add ingredients.txt
    git commit -m "updating file ingredients.txt with completely new content"
    git add recipe_book.txt
    git commit -m "updating file recipe_book.txt with completely new content"
    git push -u origin vegetarian
    git checkout pizza-pasta
    git add ingredients.txt
    git commit -m "updating file ingredients.txt with completely new content"
    git add recipe_book.txt
    git commit -m "updating file recipe_book.txt with completely new content"
    git push -u origin pizza-pasta
    git checkout master
    git merge master pizza-pasta \\ here i made the fast-forward merge mistake
    git reset --hard fe6fff
    git reset --soft HEAD@{1}
    git commit -m "reverting to pre-merge"
    git push -u origin master
    git merge --no-ff master pizza-pasta \\ here i made the merge with no fast-forward

Body:
If the vegetarian branch edits the recipe_book.txt by removing/fully changing all lines and then adding back vegetarian lines, then merging back to master will look like an "overwrite" (but really was just a fast-forward merge).

$ git init
Initialized empty Git repository in /code/test-git/.git/
$ touch recipe_book.txt
$ echo steak > recipe_book.txt
$ cat recipe_book.txt
steak
$ git add recipe_book.txt
$ git commit -m "steak"
[master (root-commit) 25b1f57] steak
 1 file changed, 1 insertion(+)
 create mode 100644 recipe_book.txt
$ git checkout -b veg
Switched to a new branch 'veg'
$ echo tofu > recipe_book.txt
$ cat recipe_book.txt
tofu
$ git commit -am "tofu"
[veg e765cb4] tofu
 1 file changed, 1 insertion(+), 1 deletion(-)
$ git checkout master
Switched to branch 'master'
$ cat recipe_book.txt
steak
$ git merge veg
Updating 25b1f57..e765cb4
Fast-forward
 recipe_book.txt | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
$ cat recipe_book.txt
tofu


答:
This solution doesn't use dplyr but accomplishes what you want.

```<code>library(readr)
df <- read_table('var C400.0   C403.7  C407.1  A399.6  A403.4   A406.4
V1  1.176    1.149   1.111   0.767   0.736    0.699
V2  1.192    1.160   1.127   0.770   0.738    0.707
V3  1.223    1.1918  1.154   0.775   0.744    0.715')
</code>```

No Nasty Side Effects Version (also not looping, all vectorized)

This is thanks to Gregor.  I don't mind side effects when I make them intentionally, but not everybody feels the same way :)

library(stringr)
cNames = grep("^C",names(df),value=T)
aNames = grep("^A",names(df),value=T)

newCols = df[cNames]-df[aNames]
setNames(newCols, paste0("B", str_extract(cNames, "[0-9]+")))
#Alternative solution that doesn't require the stringr library
#setNames(newCols, paste0("B", sub(".*?([0-9]+).*","\\1",cNames)))
df = cbind(df,newCols)
```

<p>First we extract the 'C' names and the 'A' names.  This assumes they're already in order, but the results you showed in your question don't make it clear how A406.4 was matched to C403.7.</p>

<p>Then we can subset df based on column names and do element-wise subtraction of the resulting subset data.frames.  We change the names and do a simple <code>cbind</code>.</p>

<p><b>Original Solution</b></p>

<pre class="lang-R prettyprint-override"><code>mapply(function(x,y){
  num = str_extract(x,"[0-9]+")
  df[[paste0("B",num)]] = df[[x]]-df[[y]]
  assign("df",df,envir=globalenv())
  return(NULL)
},cNames,aNames)
</code>```

Then I wrote a function which takes two inputs and used mapply to loop across the set of 'C' names and 'A' names.  At each combination we extract the numbers of the 'C' name and paste that onto a 'B' and assign it the difference of 'C'-'A'.  Then, because we're building up a set of new columns, I assign the resulting df back to the global environment (big old side effect).  mapply returns a bunch of NULLs but df has been updated to include your B columns.  This preserves your original wide data structure just without using the tidyverse

Title: Calculate new (78) variables based on column input from 78*2 other variables dplyr

Body:
I would like to make a simple subtraction based on a "two column" pair, the a1...n and c1...n series to create a third column b1...n over 78 "pairs" in dplyr. But, I do not know how to call the columns correctly and rund it over each column pair.

df
var C400.0   C403.7  C407.1  A399.6  A403.4   A406.4
V1  1.176    1.149   1.111   0.767   0.736    0.699
V2  1.192    1.160   1.127   0.770   0.738    0.707
V3  1.223    1.1918  1.154   0.775   0.744    0.715

I have tried:

b_names <- c( "B400",   "B403",   "B407")
df_b  <- mutate_at(df,vars(C400.0:C407.1), .funs(b_names= ., vars(C400.0:C407.1)-vars(A399.6:A403.4)))

with no success

The results should look like

df_b
var C400.0   C403.7  C407.1  A399.6  A403.4   A406.4 B400   B403   B407
V1  1.176    1.149   1.111   0.767   0.736    0.699  0.408  0.412  0.412
V2  1.192    1.160   1.127   0.770   0.738    0.707  0.421  0.421  0.420
V3  1.223    1.1918  1.154   0.775   0.744    0.715  0.447  0.447  0.439

Body:
This solution doesn't use dplyr but accomplishes what you want.

library(readr)
df <- read_table('var C400.0   C403.7  C407.1  A399.6  A403.4   A406.4
V1  1.176    1.149   1.111   0.767   0.736    0.699
V2  1.192    1.160   1.127   0.770   0.738    0.707
V3  1.223    1.1918  1.154   0.775   0.744    0.715')

No Nasty Side Effects Version (also not looping, all vectorized)

This is thanks to Gregor.  I don't mind side effects when I make them intentionally, but not everybody feels the same way :)

library(stringr)
cNames = grep("^C",names(df),value=T)
aNames = grep("^A",names(df),value=T)

newCols = df[cNames]-df[aNames]
setNames(newCols, paste0("B", str_extract(cNames, "[0-9]+")))
#Alternative solution that doesn't require the stringr library
#setNames(newCols, paste0("B", sub(".*?([0-9]+).*","\\1",cNames)))
df = cbind(df,newCols)

First we extract the 'C' names and the 'A' names.  This assumes they're already in order, but the results you showed in your question don't make it clear how A406.4 was matched to C403.7.

Then we can subset df based on column names and do element-wise subtraction of the resulting subset data.frames.  We change the names and do a simple cbind.

Original Solution

mapply(function(x,y){
  num = str_extract(x,"[0-9]+")
  df[[paste0("B",num)]] = df[[x]]-df[[y]]
  assign("df",df,envir=globalenv())
  return(NULL)
},cNames,aNames)

Then I wrote a function which takes two inputs and used mapply to loop across the set of 'C' names and 'A' names.  At each combination we extract the numbers of the 'C' name and paste that onto a 'B' and assign it the difference of 'C'-'A'.  Then, because we're building up a set of new columns, I assign the resulting df back to the global environment (big old side effect).  mapply returns a bunch of NULLs but df has been updated to include your B columns.  This preserves your original wide data structure just without using the tidyverse


问:
How do OR statements affect multicolumn indexes in Postgres query
I'm currently querying my customers table in a postgres database when a user signs up (or makes an order as a guest) to see if we have any old records possibly matching the "new" user.
Users also have the option of changing their names. When they do, we change their primary name but keep their old name in alt_fname and alt_lname fields. As a result our where clause (in ActiveRecord) is

Customer.where(["(fname = :fname OR alt_fname = :fname) AND (lname = :lname OR alt_lname = :lname)", {fname: first_name, lname: last_name}])

To speed things up I'd like to add some multi-column indexes (for example  on fname, lname),  but I don't know if they'll even be used given that the query isn't a straightforward AND statement, but two OR's joined by an AND.

答:
@GordonLinoff is generally right.

Having said that try adding 2 sorted indices lname, user_id and alt_lname, user_id. I don't know what postgres' optimizer does but many will try retrieving via index and possibly switch to sequential if the match ratio is not good. If your cardinality is large then indexes will help.

If speed isn't improved try a UNION of two queries one with lname and one with alt_lname and return user_id. As it's not a union ALL there will still be a sort but that should only happen on the result set and not the whole table.


问:
Spring JMS listener - how to read messages based on a condition
I have configured Spring JMS in my project.
Now my requirement is that messages are read only when the flag in a properties file in ON. </p>

<p>what are ways to implement this in Spring? </p>

答:
When asking questions like this, it's always best to show your configuration so people can provide a very specific answer.

The general solution is to use the property to set the autoStartup property to false on the listener container, or listener container factory (if using @JmsListener annotations).

Use a property placeholder, e.g. ${should.start}.

Body:
I have configured Spring JMS in my project.
Now my requirement is that messages are read only when the flag in a properties file in ON.

what are ways to implement this in Spring?


问:
Is this empty loop executing infinitely?
I have this code right here:

```<code>#include <iostream>
using namespace std;

int main() {
  int counter = 0;
  int sum = 0;
  while(counter < 10);
  {
    sum += ++ counter;
  }
  cout << sum << endl;
}
</code>```

I was wondering if the line while(counter < 10); is an infinite loop which results in the rest of the code not being executed.

Another side question, since the while is delimited with ;, that block of code under it is just an inner scope of code?

答:
The code while(counter < 10); causes undefined behaviour due to not making forward progress on a thread.

In practice this might mean that execution hangs, or execution skips over that line, or anything else. The compiler might optimize the whole program to output 1, or 11.

For further reading see Forward progress - progress guarantee

Body:
I have this code right here:

#include <iostream>
using namespace std;

int main() {
  int counter = 0;
  int sum = 0;
  while(counter < 10);
  {
    sum += ++ counter;
  }
  cout << sum << endl;
}

I was wondering if the line while(counter < 10); is an infinite loop which results in the rest of the code not being executed.

Another side question, since the while is delimited with ;, that block of code under it is just an inner scope of code?


问:
Using paintComponent() on a JFrame canvas being altered by a separate GUI
I am trying to make a JComponent application which uses two JFrames, one frame with alterable sliders and textfields for the graphical display of a firework on the second. When the "fire" button is pressed, a rendering of the firework should appear. However, I have found through placing strategic print statements, that my paintComponent() method does not run even though the conditional statement wrapping the code is satisfied. I have also double checked all of my other methods to ensure that correct values are generated at the correct times. After looking through all of the JComponent literature and questions I could find, I'm afraid I cannot get it to work - this problem is most likely derived from my lack of familiarity with the library. That being said, any advice no matter how rudimentary, will be much appreciated. Abridged code is below:

*The swing timer may also be the issue for I am not sure if I have used it correctly

[fireworksCanvas.java]

```<code>    public class fireworkCanvas extends JComponent implements ActionListener{

private static final long serialVersionUID = 1L;
private ArrayList<Ellipse2D> nodes = new ArrayList<Ellipse2D>();
private ArrayList<Line2D> cNodes = new ArrayList<Line2D>();
private ArrayList<QuadCurve2D> bCurves = new ArrayList<QuadCurve2D>();
private int[] arcX;
private int[] arcY;
private Color userColor;
private Random rand = new Random();
private int shellX, shellY, fType, theta, velocity;
private Timer timer;
private int time;
private double g = -9.8; //gravity in m/s
public boolean explosivesSet;

public fireworkCanvas() {
    time = rand.nextInt(3000) + 2000;
    timer = new Timer(time, this); // 5 seconds
    timer.start();
    fType = 0;
}

@Override
public void paintComponent(Graphics g){

    if (explosivesSet) {
        System.out.println("fType" + fType);
        super.paintComponent(g);
        Graphics2D g2D = (Graphics2D) g;

        g.setColor(Color.BLACK);
        g.drawPolyline(arcX, arcY, arcX.length);

        for (Ellipse2D e : nodes) {
            System.out.println("painting nodes"); // NEVER PRINTS
            g.setColor(userColor);
            g.fillOval(shellX + (int) e.getX(), shellY + (int) e.getY(), (int) e.getWidth(), (int) e.getHeight());
        }
        for (Line2D l: cNodes) {
            System.out.println("painting cNodes"); // NEVER PRINTS
            g.setColor(determineColor("l"));
            g.drawLine(shellX + (int) l.getX1(), shellY + (int) l.getY1(), shellX + (int) l.getX2(), shellY + (int) l.getY2());
        }
        for (QuadCurve2D c: bCurves) {
            System.out.println("painting curves"); // NEVER PRINTS
            g.setColor(determineColor("c"));
            g2D.draw(c);
        }
    }
}

public Color determineColor(String type) {

    // returns color
}

public void setExplosives() {

    if (fType != 5 && fType != 0) {

        nodes.clear(); // clears three array lists with FW components
        cNodes.clear(); // these are the components to paint for the
        bCurves.clear(); // firework explosion graphic
        setArc(); // stores path of shell for a polyLine to be drawn

        // builds and generates components for FW based on type chosen (fType)
        setExplosivesSet(true);
        repaint();
    }
}

public void setArc() {
    // builds int[] for shellX, shellY
}

@Override
public void actionPerformed(ActionEvent e) {
     // nothing is here??
     // should I use the action performed in some way?
}
</code>```

[GUI.java]

```<code>    public class GUI extends JFrame implements ActionListener, ChangeListener, ItemListener, MouseListener{

private static JFrame canvasFrame = new JFrame("Canvas");

private fireworkCanvas canvas = new fireworkCanvas();
private Choice fireworkChooser = new Choice();
private JSlider launchAngle = new JSlider();
private JSlider velocity = new JSlider();
private JSlider r = new JSlider();
private JSlider g = new JSlider();
private JSlider b = new JSlider();
private JPanel panel = new JPanel();
private JButton button = new JButton("Fire!");
private JLabel launchLabel = new JLabel("Launch Angle ");
private JLabel velocityLabel = new JLabel("Velocity ");
private JLabel rLabel = new JLabel("Red ");
private JLabel gLabel = new JLabel("Green ");
private JLabel bLabel = new JLabel("Blue ");
public static int fHeight = 500;
public static int fWidth = 500;

public GUI() {

    this.add(panel);
    panel.add(button);
    panel.add(fireworkChooser);
    panel.add(launchAngle);
    panel.add(launchLabel);
    panel.add(velocity);
    panel.add(velocityLabel);
    panel.add(r);
    panel.add(rLabel);
    panel.add(g);
    panel.add(gLabel);
    panel.add(b);
    panel.add(bLabel);

    addActionListener(this);
    BoxLayout bl = new BoxLayout(getContentPane(), BoxLayout.Y_AXIS);
    setLayout(bl);

    fireworkChooser.addItemListener(this);
    launchAngle.addChangeListener(this);
    velocity.addChangeListener(this);
    r.addChangeListener(this);
    g.addChangeListener(this);
    b.addChangeListener(this);
    button.addActionListener(this);

    fireworkChooser.add("Firework 1");
    fireworkChooser.add("Firework 2");
    fireworkChooser.add("Firework 3");
    fireworkChooser.add("Firework 4");
    fireworkChooser.add("Super Firework");

    launchAngle.setMinimum(1);
    launchAngle.setMaximum(90);
    velocity.setMinimum(1);
    velocity.setMaximum(50);
    r.setMinimum(0);
    r.setMaximum(255);
    g.setMinimum(0);
    g.setMaximum(255);
    b.setMinimum(0);
    b.setMaximum(255);

}

@Override
public Dimension getPreferredSize() {
    return new Dimension(600, 200);
}

@Override
public void stateChanged(ChangeEvent e) {

    // sets FW variables
}

@Override
public void actionPerformed(ActionEvent e) {
    if (e.getSource() == button) {
        canvas.setfType(fireworkChooser.getSelectedIndex()+1);
        canvas.setExplosives();
        canvas.repaint();
        canvas.setExplosivesSet(false);
        System.out.println("button fired");
    }
}

public static void createAndShowGUI() {
    GUI gui = new GUI();
    gui.pack();
    gui.setLocationRelativeTo(null);
    gui.setVisible(true);
    gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    fireworkCanvas canvas = new fireworkCanvas();
    canvasFrame.pack();
    canvasFrame.add(canvas);
    canvasFrame.setLocationRelativeTo(null);
    canvasFrame.setVisible(true);
    canvasFrame.setSize(fWidth, fHeight);
    canvasFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowGUI();
        }
    });
}

}
</code>```

答:
First of all:

```<code>public fireworkCanvas()
</code>```

Class names should start with an upper case character. All the other classes in your code follow this rule. Learn by example.

```<code>private Choice fireworkChooser = new Choice();
</code>```

Choice is an AWT component don't mix AWT components in a Swing application. Use a JComboBox.

that my paintComponent() method does not run

```<code>fireworkCanvas canvas = new fireworkCanvas();
canvasFrame.pack();
canvasFrame.add(canvas);
</code>```

You add the canvas to the frame AFTER you pack() the frame, so the size of the canvas is (0, 0) and there is nothing to paint.

The canvas should be added to the frame BEFORE the pack() and you should implement getPreferredSize() in your FireworkCanvas class so the pack() method can work properly.

Read the section from the Swing tutorial on Custom Painting for the basics and working examples to get you started.

Body:
I am trying to make a JComponent application which uses two JFrames, one frame with alterable sliders and textfields for the graphical display of a firework on the second. When the "fire" button is pressed, a rendering of the firework should appear. However, I have found through placing strategic print statements, that my paintComponent() method does not run even though the conditional statement wrapping the code is satisfied. I have also double checked all of my other methods to ensure that correct values are generated at the correct times. After looking through all of the JComponent literature and questions I could find, I'm afraid I cannot get it to work - this problem is most likely derived from my lack of familiarity with the library. That being said, any advice no matter how rudimentary, will be much appreciated. Abridged code is below:

*The swing timer may also be the issue for I am not sure if I have used it correctly

[fireworksCanvas.java]

    public class fireworkCanvas extends JComponent implements ActionListener{

private static final long serialVersionUID = 1L;
private ArrayList<Ellipse2D> nodes = new ArrayList<Ellipse2D>();
private ArrayList<Line2D> cNodes = new ArrayList<Line2D>();
private ArrayList<QuadCurve2D> bCurves = new ArrayList<QuadCurve2D>();
private int[] arcX;
private int[] arcY;
private Color userColor;
private Random rand = new Random();
private int shellX, shellY, fType, theta, velocity;
private Timer timer;
private int time;
private double g = -9.8; //gravity in m/s
public boolean explosivesSet;

public fireworkCanvas() {
    time = rand.nextInt(3000) + 2000;
    timer = new Timer(time, this); // 5 seconds
    timer.start();
    fType = 0;
}

@Override
public void paintComponent(Graphics g){

    if (explosivesSet) {
        System.out.println("fType" + fType);
        super.paintComponent(g);
        Graphics2D g2D = (Graphics2D) g;

        g.setColor(Color.BLACK);
        g.drawPolyline(arcX, arcY, arcX.length);

        for (Ellipse2D e : nodes) {
            System.out.println("painting nodes"); // NEVER PRINTS
            g.setColor(userColor);
            g.fillOval(shellX + (int) e.getX(), shellY + (int) e.getY(), (int) e.getWidth(), (int) e.getHeight());
        }
        for (Line2D l: cNodes) {
            System.out.println("painting cNodes"); // NEVER PRINTS
            g.setColor(determineColor("l"));
            g.drawLine(shellX + (int) l.getX1(), shellY + (int) l.getY1(), shellX + (int) l.getX2(), shellY + (int) l.getY2());
        }
        for (QuadCurve2D c: bCurves) {
            System.out.println("painting curves"); // NEVER PRINTS
            g.setColor(determineColor("c"));
            g2D.draw(c);
        }
    }
}

public Color determineColor(String type) {

    // returns color
}

public void setExplosives() {

    if (fType != 5 && fType != 0) {

        nodes.clear(); // clears three array lists with FW components
        cNodes.clear(); // these are the components to paint for the
        bCurves.clear(); // firework explosion graphic
        setArc(); // stores path of shell for a polyLine to be drawn

        // builds and generates components for FW based on type chosen (fType)
        setExplosivesSet(true);
        repaint();
    }
}

public void setArc() {
    // builds int[] for shellX, shellY
}

@Override
public void actionPerformed(ActionEvent e) {
     // nothing is here??
     // should I use the action performed in some way?
}

[GUI.java]

    public class GUI extends JFrame implements ActionListener, ChangeListener, ItemListener, MouseListener{

private static JFrame canvasFrame = new JFrame("Canvas");

private fireworkCanvas canvas = new fireworkCanvas();
private Choice fireworkChooser = new Choice();
private JSlider launchAngle = new JSlider();
private JSlider velocity = new JSlider();
private JSlider r = new JSlider();
private JSlider g = new JSlider();
private JSlider b = new JSlider();
private JPanel panel = new JPanel();
private JButton button = new JButton("Fire!");
private JLabel launchLabel = new JLabel("Launch Angle ");
private JLabel velocityLabel = new JLabel("Velocity ");
private JLabel rLabel = new JLabel("Red ");
private JLabel gLabel = new JLabel("Green ");
private JLabel bLabel = new JLabel("Blue ");
public static int fHeight = 500;
public static int fWidth = 500;

public GUI() {

    this.add(panel);
    panel.add(button);
    panel.add(fireworkChooser);
    panel.add(launchAngle);
    panel.add(launchLabel);
    panel.add(velocity);
    panel.add(velocityLabel);
    panel.add(r);
    panel.add(rLabel);
    panel.add(g);
    panel.add(gLabel);
    panel.add(b);
    panel.add(bLabel);

    addActionListener(this);
    BoxLayout bl = new BoxLayout(getContentPane(), BoxLayout.Y_AXIS);
    setLayout(bl);

    fireworkChooser.addItemListener(this);
    launchAngle.addChangeListener(this);
    velocity.addChangeListener(this);
    r.addChangeListener(this);
    g.addChangeListener(this);
    b.addChangeListener(this);
    button.addActionListener(this);

    fireworkChooser.add("Firework 1");
    fireworkChooser.add("Firework 2");
    fireworkChooser.add("Firework 3");
    fireworkChooser.add("Firework 4");
    fireworkChooser.add("Super Firework");

    launchAngle.setMinimum(1);
    launchAngle.setMaximum(90);
    velocity.setMinimum(1);
    velocity.setMaximum(50);
    r.setMinimum(0);
    r.setMaximum(255);
    g.setMinimum(0);
    g.setMaximum(255);
    b.setMinimum(0);
    b.setMaximum(255);

}

@Override
public Dimension getPreferredSize() {
    return new Dimension(600, 200);
}

@Override
public void stateChanged(ChangeEvent e) {

    // sets FW variables
}

@Override
public void actionPerformed(ActionEvent e) {
    if (e.getSource() == button) {
        canvas.setfType(fireworkChooser.getSelectedIndex()+1);
        canvas.setExplosives();
        canvas.repaint();
        canvas.setExplosivesSet(false);
        System.out.println("button fired");
    }
}

public static void createAndShowGUI() {
    GUI gui = new GUI();
    gui.pack();
    gui.setLocationRelativeTo(null);
    gui.setVisible(true);
    gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    fireworkCanvas canvas = new fireworkCanvas();
    canvasFrame.pack();
    canvasFrame.add(canvas);
    canvasFrame.setLocationRelativeTo(null);
    canvasFrame.setVisible(true);
    canvasFrame.setSize(fWidth, fHeight);
    canvasFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowGUI();
        }
    });
}

}

Body:
First of all:

public fireworkCanvas()

Class names should start with an upper case character. All the other classes in your code follow this rule. Learn by example.

private Choice fireworkChooser = new Choice();

Choice is an AWT component don't mix AWT components in a Swing application. Use a JComboBox.

that my paintComponent() method does not run

fireworkCanvas canvas = new fireworkCanvas();
canvasFrame.pack();
canvasFrame.add(canvas);

You add the canvas to the frame AFTER you pack() the frame, so the size of the canvas is (0, 0) and there is nothing to paint.

The canvas should be added to the frame BEFORE the pack() and you should implement getPreferredSize() in your FireworkCanvas class so the pack() method can work properly.

Read the section from the Swing tutorial on Custom Painting for the basics and working examples to get you started.


问:
ViewBag property value in DropDownListFor instead of Model property value
We found strange behaviour in DropDownListFor (ASP.NET MVC3 release). It selects ViewBag property value instead of Model property value in dropdown.

Model:

```<code>public class Country {
    public string Name { get; set; }
}
public class User {
    public Country Country { get; set; }
}
</code>```

Controller Index action:

```<code>ViewBag.CountryList = new List<Country> {  /* Dropdown collection */
   new Country() { Name = "Danmark" },
   new Country() { Name = "Russia" } };

var user = new User();
user.Country = new Country(){Name = "Russia"}; /* User value */
ViewBag.Country = new Country() { Name = "Danmark" };  /* It affects user */
return View(user);
</code>```

View:

```<code>@Html.EditorFor(user => user.Country.Name)
@Html.DropDownListFor(user => user.Country.Name,
    new SelectList(ViewBag.CountryList, "Name", "Name", Model.Country), "...")
</code>```

It will show text box with "Russia" value and dropdown with "Danmark" value selected instead of "Russia".

I didn't find any documentation about this behaviour. Is this behaviour normal? And why is it normal? Because it is very hard to control ViewBag and Model properties names.

This sample MVC3 project sources

答:
The following line from your action method is what is confusing the code:

```<code>ViewBag.Country = new Country() { Name = "Danmark" };  /* It affects user */
</code>```

That's because the html helpers look into a few different places to pick up values for the generated controls. In this case ViewData["Country"] is clashing with ModelState["Country"] Rename that property to something else and everything should work.

Body:
We found strange behaviour in DropDownListFor (ASP.NET MVC3 release). It selects ViewBag property value instead of Model property value in dropdown.

Model:

public class Country {
    public string Name { get; set; }
}
public class User {
    public Country Country { get; set; }
}

Controller Index action:

ViewBag.CountryList = new List<Country> {  /* Dropdown collection */
   new Country() { Name = "Danmark" },
   new Country() { Name = "Russia" } };

var user = new User();
user.Country = new Country(){Name = "Russia"}; /* User value */
ViewBag.Country = new Country() { Name = "Danmark" };  /* It affects user */
return View(user);

View:

@Html.EditorFor(user => user.Country.Name)
@Html.DropDownListFor(user => user.Country.Name,
    new SelectList(ViewBag.CountryList, "Name", "Name", Model.Country), "...")

It will show text box with "Russia" value and dropdown with "Danmark" value selected instead of "Russia".

I didn't find any documentation about this behaviour. Is this behaviour normal? And why is it normal? Because it is very hard to control ViewBag and Model properties names.

This sample MVC3 project sources

Body:
The following line from your action method is what is confusing the code:

ViewBag.Country = new Country() { Name = "Danmark" };  /* It affects user */

That's because the html helpers look into a few different places to pick up values for the generated controls. In this case ViewData["Country"] is clashing with ModelState["Country"] Rename that property to something else and everything should work.


问:
jQuery toggle span text not functioning
My Structure is like this : JSFiddle

I have been referring to various similar questions that the other asked but those solutions are not working for me.

So what I wanted is when I clicked on "Show+", the following content will show and the text will change from "Show+" to "Hide-" which they can be toggled.

I am trying to use if function to achieve this but not working...

```<code>if($(this).find('.expand').text()=="Show+"){
  $(this).find('.expand').text("Hide-");
}else{
  $(this).find('.expand').text("Show+");
}
</code>```

Does anyone get any solution with this?? Thank you so much!

答:
I edited from your example. Try this.
JSfiddle</p>

```<code>$('.title .expand').click(function(){
  $(this).closest("div").next(".dropdown").toggle();
  if($(this).text()=="Show+"){
    $(this).text("Hide-");
  }else{
    $(this).text("Show+");
  }
});
</code>```

Title: jQuery toggle span text not functioning

Body:
My Structure is like this : JSFiddle

I have been referring to various similar questions that the other asked but those solutions are not working for me.

So what I wanted is when I clicked on "Show+", the following content will show and the text will change from "Show+" to "Hide-" which they can be toggled.

I am trying to use if function to achieve this but not working...

if($(this).find('.expand').text()=="Show+"){
  $(this).find('.expand').text("Hide-");
}else{
  $(this).find('.expand').text("Show+");
}

Does anyone get any solution with this?? Thank you so much!

Body:
I edited from your example. Try this.
JSfiddle

$('.title .expand').click(function(){
  $(this).closest("div").next(".dropdown").toggle();
  if($(this).text()=="Show+"){
    $(this).text("Hide-");
  }else{
    $(this).text("Show+");
  }
});


问:
std::mutex can't be shared among std::thread
In the following codes I suppose mLooperMutex can't be acquired by the children thread. But the program output is quite surprising. It looks that mLooperMutex captured in the std::thread is not the same one in main thread.

But if I changed the detach() call of std::thread to join(), this will lead to a deadlock since the mLooperMutex has been locked by the main thread.

Are there anything wrong with this program if I'd like to use the mLooperMutex among different threads?

a.out:
    main: wait cond begin

    child: acquiring lock begin

    child: acquiring lock done

    child: notify one begin

    child: notify one done

    main: wait cond done

```<code>#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>

using namespace std;

int main()
{
    std::condition_variable looperSet;
    bool child_done = false;
    std::mutex mLooperMutex;

    cout << "main: acquiring lock begin" << endl;
    std::unique_lock<std::mutex> lock(mLooperMutex);
    cout << "main: acquiring lock done" << endl;

    std::thread{[&mutex=mLooperMutex, &looperSet, &child_done] () {
        cout << "child: acquiring lock begin" << endl;
        std::unique_lock<std::mutex> lock(mutex);
        cout << "child: acquiring lock done" << endl;
        child_done = true;
        lock.unlock();

        cout << "child: notify one begin" << endl;
        looperSet.notify_one();
        cout << "child: notify one done" << endl;

    }}.detach();

    cout << "main: wait cond begin" << endl;
    looperSet.wait(lock, [&child_done]{ return child_done; });
    cout << "main: wait cond done" << endl;

    return 0;
}
</code>```

答:
The reason why the mLooperMutex can be acquired in the child thread is because the lock is released by looperSet.wait:

```<code>// This unlocks "lock", and then locks it again afterwards.
looperSet.wait(lock, [&child_done]{ return child_done; });
</code>```

The reason why this doesn't work with .join() is because .join() waits for the thread to finish before proceeding, and the thread can't finish until the lock is released, and looperSet.wait() which releases the lock won't run until .join() finishes.

Creating a thread and then immediately calling .join() is not very useful, you might as well run the code directly rather than using a thread.

Body:
In the following codes I suppose mLooperMutex can't be acquired by the children thread. But the program output is quite surprising. It looks that mLooperMutex captured in the std::thread is not the same one in main thread.

But if I changed the detach() call of std::thread to join(), this will lead to a deadlock since the mLooperMutex has been locked by the main thread.

Are there anything wrong with this program if I'd like to use the mLooperMutex among different threads?

a.out:
    main: wait cond begin

    child: acquiring lock begin

    child: acquiring lock done

    child: notify one begin

    child: notify one done

    main: wait cond done

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>

using namespace std;

int main()
{
    std::condition_variable looperSet;
    bool child_done = false;
    std::mutex mLooperMutex;

    cout << "main: acquiring lock begin" << endl;
    std::unique_lock<std::mutex> lock(mLooperMutex);
    cout << "main: acquiring lock done" << endl;

    std::thread{[&mutex=mLooperMutex, &looperSet, &child_done] () {
        cout << "child: acquiring lock begin" << endl;
        std::unique_lock<std::mutex> lock(mutex);
        cout << "child: acquiring lock done" << endl;
        child_done = true;
        lock.unlock();

        cout << "child: notify one begin" << endl;
        looperSet.notify_one();
        cout << "child: notify one done" << endl;

    }}.detach();

    cout << "main: wait cond begin" << endl;
    looperSet.wait(lock, [&child_done]{ return child_done; });
    cout << "main: wait cond done" << endl;

    return 0;
}

Body:
The reason why the mLooperMutex can be acquired in the child thread is because the lock is released by looperSet.wait:

// This unlocks "lock", and then locks it again afterwards.
looperSet.wait(lock, [&child_done]{ return child_done; });

The reason why this doesn't work with .join() is because .join() waits for the thread to finish before proceeding, and the thread can't finish until the lock is released, and looperSet.wait() which releases the lock won't run until .join() finishes.

Creating a thread and then immediately calling .join() is not very useful, you might as well run the code directly rather than using a thread.


答:
Looks like you're just iterating for too long:

```<code>for (int i = 0; i <= length; i++) {
    ...
}
</code>```

should be

```<code>for (int i = 0; i < length; i++) {
    ...
}
</code>```

I noticed that you wrote this line of code:

```<code>if (letter1 == letter2)
{
    count++
}
</code>```

I'd avoid using count++, you may end up getting mixed with ++count sometime. Sticking with the following is always good

```<code>if (letter1 == letter2) {
    count + =1;
}
</code>```

Title: Java: How to Count a Character in a String

Body:
I have to count the number of times that a character appears in a string.

I know this question has been asked previously.  However, the solutions that I've seen use commands/techniques that I haven't yet covered in class.

Here is my code:

import java.util.Scanner;
/*
This program counts the number of occourances of a char in a string.
*/

public class LetterCounter
{
public static void main(String[] args)
{
int i, length, count=0;
String input;
char letter1, letter2;

// Create a Scanner object for keyboard input.
Scanner stdin = new Scanner(System.in);

// Get a string from user
System.out.print("Enter a string: ");
input = stdin.nextLine();

// Get a character from user
System.out.print("Enter a character: ");
letter1 = stdin.next().charAt(0);

//Determine the length of the string
length = input.length();

//Count the number of times the user selected character appears in the string
for (i = 0; i <= length; i++)
{
    letter2 = input.charAt(i);
    if (letter1 == letter2)
{
count++;
}
}

System.out.printf("Occurrences of a %s in %s is %d", letter1, input, count);

}
}

Here is the output from jgrasp:

----jGRASP exec: java LetterCounter
Enter a string: hello world
Enter a character: l
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 11
    at java.lang.String.charAt(String.java:658)
    at LetterCounter.main(LetterCounter.java:37)

----jGRASP wedge2: exit code for process is 1.
 ----jGRASP: operation complete.

I don't understand the errors.  Any and all help is appreciated.

Body:
Looks like you're just iterating for too long:

for (int i = 0; i <= length; i++) {
    ...
}

should be

for (int i = 0; i < length; i++) {
    ...
}

I noticed that you wrote this line of code:

if (letter1 == letter2)
{
    count++
}

I'd avoid using count++, you may end up getting mixed with ++count sometime. Sticking with the following is always good

if (letter1 == letter2) {
    count + =1;
}


问:
Smartsheet API Doesn't Return All User's Sheets
I'm using the GET /sheets call to list all of a user's Smartsheets but am having an issue. The response object contains most of the user's sheets, but doesn't contain any sheets where the user's accessLevel is OWNER.

Here is the call I'm making:

```<code>GET https://api.smartsheet.com/2.0/sheets/
</code>```

With a header

```<code>Key: Authorization
Value: Bearer <access token here>
</code>```

Is there a setting or API parameter I'm missing?

I looked through the Smartsheet API docs and FAQ for answers but couldn't find anything related so apologies if this is already answered somewhere.

答:
As described in the API docs, the List Sheets operation should return all of the sheets that the user (access token owner) has access to -- including any sheets that the user owns (accessLevel = OWNER) or has otherwise been granted access to. I've never seen it not work this way. A couple of thoughts / troubleshooting suggestions:

Is it possible that the user to whom the Bearer token belongs does not actually own any sheets (i.e., that they have access to sheets because they've been "shared" to sheets, but aren't actually the owner of the sheets)?

If you have access to an API access token that belongs to user who has Admin rights in Smartsheet (within the same Org as the User for whom you're trying to identify "owned" sheets), you could execute a List Org Sheets request and examine its response (which will contain all sheets owned by members of the organization to which the Admin belongs) for any sheet objects where owner or ownerId corresponds to the user for whom you're trying to identify "owned" sheets. The number of sheets "owned by" userX in the Get Org Sheets response (using the Admin token) should match the number of sheets where accessLevel = OWNER in the Get Sheets response (using UserX's token).

Update (re paging):

Also note that the Get Sheets operation is one of several Smartsheet API operations that support paging of results. If you're not seeing the sheets you expect to see in the API response, it's possible that results are being paged and it just so happens that the objects you're looking for are not contained within the initial page of results (default page size = 100). To see if this is the case, you could try including the includeAll=true querystring parameter on the API request URL (which tells Smartsheet to not page the results -- i.e., all results should be included within the response).

Body:
I'm using the GET /sheets call to list all of a user's Smartsheets but am having an issue. The response object contains most of the user's sheets, but doesn't contain any sheets where the user's accessLevel is OWNER.

Here is the call I'm making:

GET https://api.smartsheet.com/2.0/sheets/

With a header

Key: Authorization
Value: Bearer <access token here>

Is there a setting or API parameter I'm missing?

I looked through the Smartsheet API docs and FAQ for answers but couldn't find anything related so apologies if this is already answered somewhere.


问:
Selecting multiple sub elements at once
So I am trying to write a Stylish style to remove the black background of avatars on a forum I frequent (they put a black background so transparencies are black instead of white so stand out from the forum, which I dislike).

By copying the selector with the Chrome inspect tool I have isolated the needed argument to this

```<code>#mainpostcontent > table > tbody > tr > td > table.forumline > tbody > tr:nth-child(XX) > td:nth-child(1) > span > table > tbody > tr > td {
    background: none !important;
}
</code>```

Where the XX above is a number. Since the numbering changes whether a user has an avatar or not, I have to saturate the style with about 200 individial lines like so

```<code>#mainpostcontent > table > tbody > tr > td > table.forumline > tbody > tr:nth-child(1) > td:nth-child(1) > span > table > tbody > tr > td {
    background: none !important;
}
#mainpostcontent > table > tbody > tr > td > table.forumline > tbody > tr:nth-child(2) > td:nth-child(1) > span > table > tbody > tr > td {
    background: none !important;
}
#mainpostcontent > table > tbody > tr > td > table.forumline > tbody > tr:nth-child(3) > td:nth-child(1) > span > table > tbody > tr > td {
    background: none !important;
}
</code>```

and so on.

Is there a way I can select all of these with a single selector or is it a limitation of CSS that prevents me wildcarding the first tr:nth-child(2) entry?

Edit: I can't find the accept answer button, this was the answer:
"Could you just remove the nth-child argument of > tr:nth-child(3) > so that it becomes > tr >? – S. Walker"

答: it makes more sense to add a class or id to the element for which you want to alter the styles. anyway upload your html for better understanding of the problem</p>

Title: Selecting multiple sub elements at once

Body:
So I am trying to write a Stylish style to remove the black background of avatars on a forum I frequent (they put a black background so transparencies are black instead of white so stand out from the forum, which I dislike).

By copying the selector with the Chrome inspect tool I have isolated the needed argument to this

#mainpostcontent > table > tbody > tr > td > table.forumline > tbody > tr:nth-child(XX) > td:nth-child(1) > span > table > tbody > tr > td {
    background: none !important;
}

Where the XX above is a number. Since the numbering changes whether a user has an avatar or not, I have to saturate the style with about 200 individial lines like so

#mainpostcontent > table > tbody > tr > td > table.forumline > tbody > tr:nth-child(1) > td:nth-child(1) > span > table > tbody > tr > td {
    background: none !important;
}
#mainpostcontent > table > tbody > tr > td > table.forumline > tbody > tr:nth-child(2) > td:nth-child(1) > span > table > tbody > tr > td {
    background: none !important;
}
#mainpostcontent > table > tbody > tr > td > table.forumline > tbody > tr:nth-child(3) > td:nth-child(1) > span > table > tbody > tr > td {
    background: none !important;
}

and so on.

Is there a way I can select all of these with a single selector or is it a limitation of CSS that prevents me wildcarding the first tr:nth-child(2) entry?

Edit: I can't find the accept answer button, this was the answer:
"Could you just remove the nth-child argument of > tr:nth-child(3) > so that it becomes > tr >? – S. Walker"


问:
Detect null reference in an array
I want to detect whether or not a subrange of an array contains the null reference. Somehow like this:

```<code>public static <T> boolean containsNull
(T[] array, int fromInclusive, int toExclusive)
{
    for (int i = fromInclusive; i < toExclusive; ++i)
    {
        if (array[i] == null) return true;
    }
    return false;
}
</code>```

Is there a method like this in the Java library so I don't have to manually loop over the array? Maybe I have been spoiled by C++'s excellent support for algorithmically focused code, where I can just write:

```<code>#include <algorithm>

bool found_null = (std::find(array + from, array + to, 0) != array + to);
</code>```

答:
Apache commons-lang gives you ArrayUtils.contains(array, null)

For the range: ArrayUtils.contains(Arrays.copyOfRange(array, from, to), null)

Title: Detect null reference in an array

Body:
I want to detect whether or not a subrange of an array contains the null reference. Somehow like this:

public static <T> boolean containsNull
(T[] array, int fromInclusive, int toExclusive)
{
    for (int i = fromInclusive; i < toExclusive; ++i)
    {
        if (array[i] == null) return true;
    }
    return false;
}

Is there a method like this in the Java library so I don't have to manually loop over the array? Maybe I have been spoiled by C++'s excellent support for algorithmically focused code, where I can just write:

#include <algorithm>

bool found_null = (std::find(array + from, array + to, 0) != array + to);


答:
remove .find('.expand') from your code as $(this) is reference of class expand

$(function(){
 $('.title .expand').click(function(){
   $(this).closest("div").next(".dropdown").toggle();

    if($(this).text()=="Show+"){
     $(this).text("Hide-");
    }else{
     $(this).text("Show+");
    }
  })
});```

Title: jQuery toggle span text not functioning


问:
Python inaccurate curve fit
```<code>Temp    k(T)
298   6.66E-63
300   1.48E-62
350   3.58E-55
400   1.25E-49
450   2.57E-45
500   7.30E-42
550   4.90E-39
600   1.12E-36
650   1.11E-34
700   5.72E-33
750   1.75E-31
800   3.49E-30
850   4.92E-29
900   5.17E-28
950   4.24E-25
1000  2.83E-26
</code>```

Above is the given kinetic data, I am trying to fit this data and plot the same.

Curvefitting

```<code>import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import pandas as pd
plt.style.use('ggplot')

#Generate data
df=pd.read_excel('py_curvefit.xlsx')
T=df.Temp  #xdata
def reacKine(T,A,n,Ea):
    return A*((T/298)**n)*np.exp(-Ea/(0.008314*T))
kt=df['k(T)']  #ydata
#rectifying an erroneous value
kt[14]=4.24*10**(-27)
popt,pcov=curve_fit(reacKine,T,kt)
A,n,Ea=popt
plt.plot(T,np.log(kt),'g-',label='given data')
plt.plot(T,np.log(reacKine(T,*popt)),'ro',label='fit')
plt.xlabel('Temperature [K]')
plt.ylabel('log of reaction coefficient')
plt.legend(loc='best')
plt.show()
</code>```

It says optimal parameters not found for the function. How do I rectify this. I am hoping to see a good fit. Is it because of the exponential term?

答:
The (obligatory?) lmfit answer:

You might find lmfit useful.  For the way this problem is framed, it doesn't add too much but gives a better abstraction for curve-fitting and fitting Parameters.  Similar to @WarrenWeskesser's answer, it would look like

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

T = np.array([298, 300, 350, 400, 450, 500, 550, 600, 650, 700, 750, 800,
          850, 900, 950, 1000])
kt = np.array([6.66e-63, 1.48e-62, 3.58e-55, 1.25e-49, 2.57e-45, 7.30e-42,
           4.90e-39, 1.12e-36, 1.11e-34, 5.72e-33, 1.75e-31, 3.49e-30,
           4.92e-29, 5.17e-28, 4.24e-27, 2.83e-26])

def reacKine(T, A, n, Ea):
    return A*((T/298)**n)*np.exp(-Ea/(0.008314*T))

react_model = Model(reacKine)
params = react_model.make_params(A=2.e-11, n=1, Ea=200)
result = react_model.fit(kt, params, T=T)

print(result.fit_report())

plt.plot(T, kt, 'bo', label='data')
plt.plot(T, result.best_fit, 'r--', label='fit')

plt.xlabel('T (K)')
plt.ylabel('k(T)')
plt.legend()
plt.gca().set_yscale('log')
plt.show()
</code>```

When fitting with Python27 and scipy 1.0.0, this will show a fit similar to Warrens (I left out the annotations), and print a fit report of

```<code>[[Model]]
    Model(reacKine)
[[Fit Statistics]]
    # function evals   = 1294
    # data points      = 16
    # variables        = 3
    chi-square         = 0.000
    reduced chi-square = 0.000
    Akaike info crit   = -2219.907
    Bayesian info crit = -2217.590
[[Variables]]
    A:    1.3365e-10 +/- 5.06e-12 (3.79%) (init= 2e-11)
    n:   -0.02392420 +/- 0.034279 (143.28%) (init= 1)
    Ea:   299.843529 +/- 0.024996 (0.01%) (init= 200)
[[Correlations]] (unreported correlations are <  0.100)
    C(A, n)                      = -0.997
    C(A, Ea)                     =  0.117
</code>```

When fitting with Python36 and scipy 1.0.0 the report will be

```<code>[[Model]]
    Model(reacKine)
[[Fit Statistics]]
    # function evals   = 1618
    # data points      = 16
    # variables        = 3
    chi-square         = 0.000
    reduced chi-square = 0.000
    Akaike info crit   = -2289.381
    Bayesian info crit = -2287.063
[[Variables]]
    A:    3.6814e-12 +/- 4.09e-13 (11.12%) (init= 2e-11)
    n:    1.63296239 +/- 0.050923 (3.12%) (init= 1)
    Ea:   286.634973 +/- 0.411890 (0.14%) (init= 200)
[[Correlations]] (unreported correlations are <  0.100)
    C(A, n)                      = -1.000
    C(A, Ea)                     =  1.000
    C(n, Ea)                     = -1.000
</code>```

These values are consistent with what Warren and James show.

I don't have a great explanation for why the results differ with Python version and especially why the correlations are > 0.999 for all variables in the Python36 version of the fit. But, with the parameters almost perfectly correlated and so many fit evaluations compared to data points, I would not be surprised if there were false minima and a complex correlation space.

Title: Python inaccurate curve fit

Body:
Temp    k(T)
298   6.66E-63
300   1.48E-62
350   3.58E-55
400   1.25E-49
450   2.57E-45
500   7.30E-42
550   4.90E-39
600   1.12E-36
650   1.11E-34
700   5.72E-33
750   1.75E-31
800   3.49E-30
850   4.92E-29
900   5.17E-28
950   4.24E-25
1000  2.83E-26

Above is the given kinetic data, I am trying to fit this data and plot the same.

Curvefitting

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import pandas as pd
plt.style.use('ggplot')

#Generate data
df=pd.read_excel('py_curvefit.xlsx')
T=df.Temp  #xdata
def reacKine(T,A,n,Ea):
    return A*((T/298)**n)*np.exp(-Ea/(0.008314*T))
kt=df['k(T)']  #ydata
#rectifying an erroneous value
kt[14]=4.24*10**(-27)
popt,pcov=curve_fit(reacKine,T,kt)
A,n,Ea=popt
plt.plot(T,np.log(kt),'g-',label='given data')
plt.plot(T,np.log(reacKine(T,*popt)),'ro',label='fit')
plt.xlabel('Temperature [K]')
plt.ylabel('log of reaction coefficient')
plt.legend(loc='best')
plt.show()

It says optimal parameters not found for the function. How do I rectify this. I am hoping to see a good fit. Is it because of the exponential term?

Body:
The (obligatory?) lmfit answer:

You might find lmfit useful.  For the way this problem is framed, it doesn't add too much but gives a better abstraction for curve-fitting and fitting Parameters.  Similar to @WarrenWeskesser's answer, it would look like

import numpy as np
import matplotlib.pyplot as plt
from lmfit import Model

T = np.array([298, 300, 350, 400, 450, 500, 550, 600, 650, 700, 750, 800,
          850, 900, 950, 1000])
kt = np.array([6.66e-63, 1.48e-62, 3.58e-55, 1.25e-49, 2.57e-45, 7.30e-42,
           4.90e-39, 1.12e-36, 1.11e-34, 5.72e-33, 1.75e-31, 3.49e-30,
           4.92e-29, 5.17e-28, 4.24e-27, 2.83e-26])

def reacKine(T, A, n, Ea):
    return A*((T/298)**n)*np.exp(-Ea/(0.008314*T))

react_model = Model(reacKine)
params = react_model.make_params(A=2.e-11, n=1, Ea=200)
result = react_model.fit(kt, params, T=T)

print(result.fit_report())

plt.plot(T, kt, 'bo', label='data')
plt.plot(T, result.best_fit, 'r--', label='fit')

plt.xlabel('T (K)')
plt.ylabel('k(T)')
plt.legend()
plt.gca().set_yscale('log')
plt.show()

When fitting with Python27 and scipy 1.0.0, this will show a fit similar to Warrens (I left out the annotations), and print a fit report of

[[Model]]
    Model(reacKine)
[[Fit Statistics]]
    # function evals   = 1294
    # data points      = 16
    # variables        = 3
    chi-square         = 0.000
    reduced chi-square = 0.000
    Akaike info crit   = -2219.907
    Bayesian info crit = -2217.590
[[Variables]]
    A:    1.3365e-10 +/- 5.06e-12 (3.79%) (init= 2e-11)
    n:   -0.02392420 +/- 0.034279 (143.28%) (init= 1)
    Ea:   299.843529 +/- 0.024996 (0.01%) (init= 200)
[[Correlations]] (unreported correlations are <  0.100)
    C(A, n)                      = -0.997
    C(A, Ea)                     =  0.117

When fitting with Python36 and scipy 1.0.0 the report will be

[[Model]]
    Model(reacKine)
[[Fit Statistics]]
    # function evals   = 1618
    # data points      = 16
    # variables        = 3
    chi-square         = 0.000
    reduced chi-square = 0.000
    Akaike info crit   = -2289.381
    Bayesian info crit = -2287.063
[[Variables]]
    A:    3.6814e-12 +/- 4.09e-13 (11.12%) (init= 2e-11)
    n:    1.63296239 +/- 0.050923 (3.12%) (init= 1)
    Ea:   286.634973 +/- 0.411890 (0.14%) (init= 200)
[[Correlations]] (unreported correlations are <  0.100)
    C(A, n)                      = -1.000
    C(A, Ea)                     =  1.000
    C(n, Ea)                     = -1.000

These values are consistent with what Warren and James show.

I don't have a great explanation for why the results differ with Python version and especially why the correlations are > 0.999 for all variables in the Python36 version of the fit. But, with the parameters almost perfectly correlated and so many fit evaluations compared to data points, I would not be surprised if there were false minima and a complex correlation space.


问:
Python Drawing a Circle with X Radius Using Forward()
I'm using Python Turtles to draw a circle using forward() and right().

I have a for loop counting from 0 to 359, and each time it triggers, it moves the turtle forward 1 and right 1.

But the problem is I need specific diameters. I am nearly 100% sure I'll need to use trig, but I've tried to no avail.

I can't figure out the math how to do it. We're supposed to use forward() and right(), NOT circle().

Thanks!

答:
This is one of the exercises in "Think Python," in chapter 4. It really is a horrible exercise to have this early in the book, especially with the "hint" given. I'm using forward and left here, but you can switch left with right.

You should have the polygon function:

```<code>def polygon(t, length, n):
    for i in range(n):
        bob.fd(length)
        bob.lt(360 / n)
</code>```

Then you create a circle function:

```<code>def circle(t):
    polygon(t, 1, 360)
</code>```

That will draw a circle, no radius needed. The turtle goes forward 1, then left 1 (360 / 360), 360 times.

Then, if you want to make the circle bigger, you calculate the circumference of the circle. The hint says:

Hint:  figure out the circumference of the circle and make sure that
length * n = circumference.

Ok, so the formula for circumference = 2 * pi * radius. And the hint says length * n = circumference. n = 360 (number of sides/degrees). We have circumference, so we need to solve for length.

So:

```<code>def circle(t, r):
    circumference = 2 * 3.14 * r
    length = circumference / 360
    polygon(t, length, 360)
</code>```

Now, call the function with whatever radius you want:

```<code>circle(bob, 200)
</code>```

Body:
This is one of the exercises in "Think Python," in chapter 4. It really is a horrible exercise to have this early in the book, especially with the "hint" given. I'm using forward and left here, but you can switch left with right.

You should have the polygon function:

def polygon(t, length, n):
    for i in range(n):
        bob.fd(length)
        bob.lt(360 / n)

Then you create a circle function:

def circle(t):
    polygon(t, 1, 360)

That will draw a circle, no radius needed. The turtle goes forward 1, then left 1 (360 / 360), 360 times.

Then, if you want to make the circle bigger, you calculate the circumference of the circle. The hint says:

Hint:  figure out the circumference of the circle and make sure that
length * n = circumference.

Ok, so the formula for circumference = 2 * pi * radius. And the hint says length * n = circumference. n = 360 (number of sides/degrees). We have circumference, so we need to solve for length.

So:

def circle(t, r):
    circumference = 2 * 3.14 * r
    length = circumference / 360
    polygon(t, length, 360)

Now, call the function with whatever radius you want:

circle(bob, 200)


问:
get List of values exist more than once in array
I have to get a list of values that exist more than once in an array.
This is current code , but as you can see it's too complicated.

var arr = [1, 2, 3, 4, 2, 3];
var flag = {}
var exist2arr = [];

for(var i = 0; i < arr.length; i++){
  for(var j = 0 ; j < arr.length; j ++){
     if(i !=j && arr[i] == arr[j]){
       if(!flag[arr[i]])
         exist2arr.push(arr[i]);
       flag[arr[i]] = 1;
     }
  }
}
console.log(exist2arr);```

Is there any other way (simple code using javascript built-in function) to achieve this?  Any kind of help appreciate.

答:
It could be done like:

function timesInArray(v, a){
  var n = 0;
  for(var i=0,l=a.length; i<l; i++){
    if(a[i] === v){
      n++;
    }
  }
  return n;
}
function dups(dupArray, num){
  var n = num === undefined ? 2 : num;
  var r = [];
  for(var i=0,d,l=dupArray.length; i<l; i++){
    d = dupArray[i];
    if(!timesInArray(d, r) && timesInArray(d, dupArray) >= n){
      r.push(d);
    }
  }
  return r;
}
var testArray = [4, 5, 2, 5, 7, 7, 2, 1, 3, 7, 7, 7, 25, 77, 4, 2];
console.log(dups(testArray)); console.log(dups(testArray, 3));```

Body:
I have to get a list of values that exist more than once in an array.
This is current code , but as you can see it's too complicated.

var arr = [1, 2, 3, 4, 2, 3];
var flag = {}
var exist2arr = [];

for(var i = 0; i < arr.length; i++){
  for(var j = 0 ; j < arr.length; j ++){
     if(i !=j && arr[i] == arr[j]){
       if(!flag[arr[i]])
         exist2arr.push(arr[i]);
       flag[arr[i]] = 1;
     }
  }
}
console.log(exist2arr);

Is there any other way (simple code using javascript built-in function) to achieve this?  Any kind of help appreciate.


问:
qsort does nothing with cmpstr
I'm not sure why qsort doesn't change my array because the elements aren't in alphabetical order. Can someone help me figure out what I'm doing wrong.</p>

```<code>char **wordlist = malloc(sizeof(char*));
int i, numwords = 0;
wordlist[0] = strdup(words[0]);

for(i = 0; i < wcount; i++)
{
    wordlist = realloc(wordlist, (numwords+1)*sizeof(char *));
    wordlist[numwords] = strdup(words[i]);
    numwords++;
}

printf("Added %d words to the array and they are:\n", numwords);
for(i = 0; i < numwords; i++)
{
    printf("%s\n", wordlist[i]);
}

qsort(wordlist, numwords, sizeof(char *), cmpstr);

for(i = 0; i < numwords; i++)
{
    printf("%s\n", wordlist[i]);
}

int cmpstr(const void* a, const void* b)
{
   const char* aa = (const char*)a;
   const char* bb = (const char*)b;
   return strcmp(aa, bb);
}
</code>```

答:
Your comparison is wrong:

```<code>int cmpstr(const void* a, const void* b) {
    char *aa = * (char * const *)a;
    char *bb = * (char * const *)b;
//             ^
//       asterisk here!
//
    return strcmp(aa, bb);
}
</code>```

a and b are pointer-to-pointers.

Or alternatively:

```<code>int cmpstr(const void* a, const void* b) {
    char * const * aa = a;
    char * const * bb = b;
    return strcmp(*aa, *bb);
}
</code>```

Also, there's a potential memory leak because you didn't free() what strdup() gives. You should remove Line 3 in your given code:

```<code>wordlist[0] = strdup(words[0]);
</code>```

Title: qsort does nothing with cmpstr

Body:
I'm not sure why qsort doesn't change my array because the elements aren't in alphabetical order. Can someone help me figure out what I'm doing wrong.

char **wordlist = malloc(sizeof(char*));
int i, numwords = 0;
wordlist[0] = strdup(words[0]);

for(i = 0; i < wcount; i++)
{
    wordlist = realloc(wordlist, (numwords+1)*sizeof(char *));
    wordlist[numwords] = strdup(words[i]);
    numwords++;
}

printf("Added %d words to the array and they are:\n", numwords);
for(i = 0; i < numwords; i++)
{
    printf("%s\n", wordlist[i]);
}

qsort(wordlist, numwords, sizeof(char *), cmpstr);

for(i = 0; i < numwords; i++)
{
    printf("%s\n", wordlist[i]);
}

int cmpstr(const void* a, const void* b)
{
   const char* aa = (const char*)a;
   const char* bb = (const char*)b;
   return strcmp(aa, bb);
}

Body:
Your comparison is wrong:

int cmpstr(const void* a, const void* b) {
    char *aa = * (char * const *)a;
    char *bb = * (char * const *)b;
//             ^
//       asterisk here!
//
    return strcmp(aa, bb);
}

a and b are pointer-to-pointers.

Or alternatively:

int cmpstr(const void* a, const void* b) {
    char * const * aa = a;
    char * const * bb = b;
    return strcmp(*aa, *bb);
}

Also, there's a potential memory leak because you didn't free() what strdup() gives. You should remove Line 3 in your given code:

wordlist[0] = strdup(words[0]);


问:
Handle too many textures Unity
At present one of my quiz game require, many images of flowers based on questions asked.
I can say total 250+ images with resolution of 512x435 each.
Plus other games textures get loaded at a time.

So when game screen get opened which showing all these images, its on the spot get crashed.
I am testing this on iPhone devices. So how to handle these many textures? I was stuck in this point.

Here is overview of flowers textures.

I was displaying all these in grid view so in one scrollable screen all get displayed.
Now I hope, you understand my side point of view.

答: You need to reduce the amount of these images that are loaded at once, try keeping most of those images rendering components disabled using some sort of managing script when you are not seeing them, rather than simply putting them off camera and try to moderate the amount that are rendered at once. If this does not work the problem might be that the total size of the images is bigger then the amount of ram your device has. Even the IPhone X has only 3GB of ram, check if your images in total are bigger than or close to the 1GB-3GB range, unity remote 5 is probably storing these images in ram or temporary memory. It is always a good idea to try to compress your images when working with a mobile device anyway, try to put them into a texture atlas or lower the quality of them until the iphone can handle it, you should never rely on mobile devices to render tons of images at once.</p>

Title: Handle too many textures Unity


问:
Can't set innerHTML on tbody in IE
I have a table like this:

```<code><table>
<thead>
    <tr>
        <th colspan="1">a</th>
        <th colspan="3">b</th>
    </tr>
</thead>
<tbody id="replaceMe">
    <tr>
        <td>data 1</td>
        <td>data 2</td>
        <td>data 3</td>
        <td>data 4</td>
    </tr>
</tbody>
</table>
</code>```

and a method returns me the following after an ajax request:

```<code><tr>
    <td>data 1 new</td>
    <td>data 2 new</td>
    <td>data 3 new</td>
    <td>data 4 new</td>
</tr>
</code>```

I want to change the innerHTML like

```<code>document.getElementById('replaceMe').innerHTML = data.responseText;
</code>```

However, it seems that IE can't set innerHTML on
. Can anyone help me with a simple workaround for this issue?

答:
Create a temp node to store a table in, then copy them to the tbody</p>

```<code>  var tempNode = document.createElement('div');
  tempNode.innerHTML = "<table>" + responseText+ "</table>";

  var tempTable = tempNode.firstChild;
  var tbody = // get a reference to the tbody
  for (var i=0, tr; tr = tempTable.rows[i]; i++) {
    tbody.appendChild(tr);
  }
</code>```

Title: Can't set innerHTML on tbody in IE

Body:
I have a table like this:

        a
        b

        data 1
        data 2
        data 3
        data 4

and a method returns me the following after an ajax request:

    data 1 new
    data 2 new
    data 3 new
    data 4 new

I want to change the innerHTML like

document.getElementById('replaceMe').innerHTML = data.responseText;

However, it seems that IE can't set innerHTML on
. Can anyone help me with a simple workaround for this issue?

Body:
Create a temp node to store a table in, then copy them to the tbody

  var tempNode = document.createElement('div');
  tempNode.innerHTML = "<table>" + responseText+ "</table>";

  var tempTable = tempNode.firstChild;
  var tbody = // get a reference to the tbody
  for (var i=0, tr; tr = tempTable.rows[i]; i++) {
    tbody.appendChild(tr);
  }