答:
A trigger is something that happens automatically based on an event in the database.  Typically speaking, it’s not a good idea to be creating tables automatically like this.  What was your thinking around wanting a table to be created automatically by an event?   Normally triggers would be adding or changing individual rows in a DB.

Documentation for mysql triggers can be found at https://dev.mysql.com/doc/refman/5.7/en/trigger-syntax.html

Title: Trigger after create table

Body:
I need when I create a new table, insert it with the name of the table in another already existing table. I had planned to use a trigger, but I can not find documentation on how to do this. Do you have any idea?

Thank you!


来源: stackexchange

问:
Can http client cancel the reuqest before whole body is received?
For example,
By an user, a client send GET request for a 1GB size of data, then the client is receiving the data.
But the user decides to cancel previous one and download another data.
At this moment, does the client immediately cancel previous HTTP request before 1GB size of whole data and send a new HTTP GET request with reusing socket?
Because I'd like to avoid TCP slow start by new socket connection in this situation.</p>

答: There is no way to signal canceling of the request inside a HTTP connection, i.e. while keeping the connection open. This means the only way is to close the underlying TCP connection and create a new one and send the new request using the new connection.</p>

ContentLicense: CC BY-SA 3.0


问:
Show recent blog image on home page bigcommerce?
how can I call blog Summary thumbnail image or content image on the home page? I want to show latest blogs on homepage with date and thumbnail is there any way to achieve this:--

There is two part:

one with stencil big commerce Framework
2nd one with classic next or normal theme with bigcommerce

Need the help any of way with stencil framework or normal theme. below both of themes code please review and suggest me.

Normal themes:--need to modify recent blog snippet.

```<code><div class="RecentNews" id="HomeRecentBlogs" style="display:%%GLOBAL_HideHomeRecentBlogsPanel%%">
  <div class="inner">
  <h4>%%LNG_RecentNews%%</h4>
  <ul>
  %%GLOBAL_Thumbnail%%
  %%SNIPPET_BlogRecentPostsContentItem.html%%
  </ul>
  </div>
  </div>
</code>```

stencil framework:--I have called this code on home.html

```<code> {{#if post.thumbnail}}
  <figure class="blog-thumbnail">
  <a href="{{post.url}}">
  <img src="{{getImage post.thumbnail 'blog_size'}}" alt="{{post.thumbnail.alt}}" title="{{post.thumbnail.alt}}">
  </a>
  </figure>
  {{/if}}
</code>```

if i can acchive javascript then how I can do this please suggest?

答:
In stencil, you need to remove post. since the global blog.recent_posts structure if different than blog.posts and for some reason.

```<code>{{#each blog.recent_posts}}
    {{#if thumbnail}}
        <figure class="blog-thumbnail">
            <a href="{{url}}">
                <img src="{{getImage thumbnail 'blog_size'}}" alt="{{thumbnail.alt}}" title="{{thumbnail.alt}}">
            </a>
        </figure>
    {{/if}}
{{/each}}
</code>```

For blueprint themes, you should be able to add the variable %%Panel.HomeRecentBlogs%% anywhere on the home page to load the panel.

Body:
how can I call blog Summary thumbnail image or content image on the home page? I want to show latest blogs on homepage with date and thumbnail is there any way to achieve this:--

There is two part:

one with stencil big commerce Framework
2nd one with classic next or normal theme with bigcommerce

Need the help any of way with stencil framework or normal theme. below both of themes code please review and suggest me.

Normal themes:--need to modify recent blog snippet.

%%LNG_RecentNews%%

  %%GLOBAL_Thumbnail%%
  %%SNIPPET_BlogRecentPostsContentItem.html%%

stencil framework:--I have called this code on home.html

 {{#if post.thumbnail}}

  {{/if}}

if i can acchive javascript then how I can do this please suggest?

Body:
In stencil, you need to remove post. since the global blog.recent_posts structure if different than blog.posts and for some reason.

{{#each blog.recent_posts}}
    {{#if thumbnail}}
        <figure class="blog-thumbnail">
            <a href="{{url}}">
                <img src="{{getImage thumbnail 'blog_size'}}" alt="{{thumbnail.alt}}" title="{{thumbnail.alt}}">
            </a>
        </figure>
    {{/if}}
{{/each}}

For blueprint themes, you should be able to add the variable %%Panel.HomeRecentBlogs%% anywhere on the home page to load the panel.


问:
Cannot expand all nodes in Kendo TreeView
I want to show my Kendo UI TreeView expanded at all time, but it will only show collapsed. When reloading the datasource, I can see a flash of the expanded tree, but then it collapses.</p>

```<code>var locationTreeView = $("#treeViewLocations").kendoTreeView({
checkboxes: {
    checkChildren: false,
    template: "# if(item.showCheckbox){# <input type='checkbox' name='selectedLocations' value='#= item.value #' />#}#"
},
dataTextField: "text",
dataSource: {
    transport: {
        read: {
            url: window.location.origin + "/api/v1/bookingrequestlocation",
            dataType: "json",
            type: "GET",
            data: { bookingSeasonPeriodId: bookingSeasonPeriod.value() },
        }
    },
    schema: {
        model: {
            id: "value",
            children: "items",
            hasChildren: "hasChildren",
        }
    }
}}).data("kendoTreeView");

expandTreeView();

function changeSeason() {
    locationTreeView.dataSource.read();
    expandTreeView();}

function expandTreeView() {
    locationTreeView.expand(".k-item");}
</code>```

答:
```<code>Add the following code right after creating the treeview

 var tree = $("#TREEVIEWID").data("kendoTreeView");
        function expandTreeNodes() {
            if ($('.k-item').length) {
                var expandedLength = $('.k-item').length;
                tree.expand(".k-item");
                if (expandedLength < $('.k-item').length) {
                    expandTreeNodes();
                }
            }
        }
</code>```

Body:
I want to show my Kendo UI TreeView expanded at all time, but it will only show collapsed. When reloading the datasource, I can see a flash of the expanded tree, but then it collapses.

var locationTreeView = $("#treeViewLocations").kendoTreeView({
checkboxes: {
    checkChildren: false,
    template: "# if(item.showCheckbox){# <input type='checkbox' name='selectedLocations' value='#= item.value #' />#}#"
},
dataTextField: "text",
dataSource: {
    transport: {
        read: {
            url: window.location.origin + "/api/v1/bookingrequestlocation",
            dataType: "json",
            type: "GET",
            data: { bookingSeasonPeriodId: bookingSeasonPeriod.value() },
        }
    },
    schema: {
        model: {
            id: "value",
            children: "items",
            hasChildren: "hasChildren",
        }
    }
}}).data("kendoTreeView");

expandTreeView();

function changeSeason() {
    locationTreeView.dataSource.read();
    expandTreeView();}

function expandTreeView() {
    locationTreeView.expand(".k-item");}


问:
How can i convert my already exist array to a new specific array?
Here is my Array of canada post shipping rate:

```<code>Array(
[Priority] => Array
    (
        [num] => 388.98
        [str] => Can$ 388.98
    )

[Xpresspost] => Array
    (
        [num] => 294.98
        [str] => Can$ 294.98
    )

[Regular] => Array
    (
        [num] => 97.14
        [str] => Can$ 97.14
    ))
</code>```

Now i want to subtract the value of num by it's half and want's to make a new array from above array like this :

```<code>Array(
[Priority] => Array
    (
        [num] => 194.49
        [str] => Can$ 194.49
    )

[Xpresspost] => Array
    (
        [num] => 147.49
        [str] => Can$ 147.49
    )

[Regular] => Array
    (
        [num] => 48.57
        [str] => Can$ 48.57
    ))
</code>```

So how can i do that ?

答:
You just need to itterate through your array ($inputArray):

```<code>$outputArray = array();
foreach($inputArray as $key => $value){
    $sum = $value['num']/2;
    $outputArray[$key] = array(
        'num' => $sum,
        'str' => 'Can$ '.$sum,
    );
}
</code>```

Your output will be in $outputArray variable.

Body:
Here is my Array of canada post shipping rate:

Array(
[Priority] => Array
    (
        [num] => 388.98
        [str] => Can$ 388.98
    )

[Xpresspost] => Array
    (
        [num] => 294.98
        [str] => Can$ 294.98
    )

[Regular] => Array
    (
        [num] => 97.14
        [str] => Can$ 97.14
    ))

Now i want to subtract the value of num by it's half and want's to make a new array from above array like this :

Array(
[Priority] => Array
    (
        [num] => 194.49
        [str] => Can$ 194.49
    )

[Xpresspost] => Array
    (
        [num] => 147.49
        [str] => Can$ 147.49
    )

[Regular] => Array
    (
        [num] => 48.57
        [str] => Can$ 48.57
    ))

So how can i do that ?

Body:
You just need to itterate through your array ($inputArray):

$outputArray = array();
foreach($inputArray as $key => $value){
    $sum = $value['num']/2;
    $outputArray[$key] = array(
        'num' => $sum,
        'str' => 'Can$ '.$sum,
    );
}

Your output will be in $outputArray variable.


问:
SQL Server 2005 - How to take a record from one table and loop through another table looking for match
I have 2 tables. for this example I will use only one users records.
The first table has the user name and an evaluation date as such:

```<code>USER  EVALDATE
--------------
bobr  6/7/2010
bobr  9/20/2010
bobr  9/21/2010
</code>```

The above table needs to be joined against this user history table, which has the history of the ID's and the dates they were valid, to look for a match (the NULL date means current):

```<code>USER   STARTDATE   ENDDATE
----------------------------
bobr   2/20/2006   4/18/2010
bobr2  4/19/2010   9/7/2010
bobr   9/8/2010    null
</code>```

What I'm trying to do in SQL Server 2005 is take the first record from the first table, loop it through the second table and when(if) the EVALDATE is within one of these date ranges and the IDs match, then flag that record from the first table as valid.

The current code takes the record from the first table and runs against all rows of the second table and kicks out a record for each invalid evaldate, so it kicks out a record when joined against the second table because the evaldate is not between the dates of the first record on the history table, even though the record is fine because the evaldate is between the start and end dates of the third record in the history table.

I hope this makes sense! In something like SAS I can create an array and loop through checking against each record in the history table. How do I do this in SQL? What I was trying to do was just update the first table with a flag if the records dates are invalid. Any ideas? Thanks!!!

答:
You can try something like

```<code>Select  *
FROM    Users u INNER JOIN
        UserHistory uh  ON  u.User = uh.User
                        AND u.EvalDate BETWEEN  uh.StartDate
                                        AND     ISNULL(uh.EndDate, u.EvalDate)
</code>```

EDIT

Try this for all values from User

```<code>Select  u.*,
        CASE
            WHEN uh.User IS NULL
                THEN 'Invalid'
            ELSE 'Valid'
        END Validity
FROM    Users u LEFT JOIN
        UserHistory uh  ON  u.User = uh.User
                        AND u.EvalDate BETWEEN  uh.StartDate
                                        AND     ISNULL(uh.EndDate, u.EvalDate)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have 2 tables. for this example I will use only one users records.
The first table has the user name and an evaluation date as such:

USER  EVALDATE
--------------
bobr  6/7/2010
bobr  9/20/2010
bobr  9/21/2010

The above table needs to be joined against this user history table, which has the history of the ID's and the dates they were valid, to look for a match (the NULL date means current):

USER   STARTDATE   ENDDATE
----------------------------
bobr   2/20/2006   4/18/2010
bobr2  4/19/2010   9/7/2010
bobr   9/8/2010    null

What I'm trying to do in SQL Server 2005 is take the first record from the first table, loop it through the second table and when(if) the EVALDATE is within one of these date ranges and the IDs match, then flag that record from the first table as valid.

The current code takes the record from the first table and runs against all rows of the second table and kicks out a record for each invalid evaldate, so it kicks out a record when joined against the second table because the evaldate is not between the dates of the first record on the history table, even though the record is fine because the evaldate is between the start and end dates of the third record in the history table.

I hope this makes sense! In something like SAS I can create an array and loop through checking against each record in the history table. How do I do this in SQL? What I was trying to do was just update the first table with a flag if the records dates are invalid. Any ideas? Thanks!!!

Body:
You can try something like

Select  *
FROM    Users u INNER JOIN
        UserHistory uh  ON  u.User = uh.User
                        AND u.EvalDate BETWEEN  uh.StartDate
                                        AND     ISNULL(uh.EndDate, u.EvalDate)

EDIT

Try this for all values from User

Select  u.*,
        CASE
            WHEN uh.User IS NULL
                THEN 'Invalid'
            ELSE 'Valid'
        END Validity
FROM    Users u LEFT JOIN
        UserHistory uh  ON  u.User = uh.User
                        AND u.EvalDate BETWEEN  uh.StartDate
                                        AND     ISNULL(uh.EndDate, u.EvalDate)


问:
Projects created at console.firebase.google.com must use the new Firebase Authentication SDKx available from firebase.google.com/dosc/auth
I am trying to enable GoogleSignIn for my android app and trying to run this code. I have created the json file from firebase console and pasted it in app. Enabled the google login from firebase but after running app on my phone it gives me error.

```<code>firebaseError: Projects created at console.firebase.google.com must use the new Firebase Authentication SDKx available from firebase.google.com/dosc/auth
</code>```

Similar threads said to remove firebase client dependency but if I remove it I have compilation error. I also have tried to add latest dependency from the docs but no luck.

my gradle file

```<code>buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.0.0'
    }
}
apply plugin: 'com.android.application'

repositories {
    mavenCentral()
}

android {
    compileSdkVersion Integer.parseInt(project.ANDROID_BUILD_SDK_VERSION)
    buildToolsVersion project.ANDROID_BUILD_TOOLS_VERSION

    defaultConfig {
        minSdkVersion Integer.parseInt(project.ANDROID_BUILD_MIN_SDK_VERSION)
        targetSdkVersion Integer.parseInt(project.ANDROID_BUILD_TARGET_SDK_VERSION)
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
    packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/LICENSE-FIREBASE.txt'
    }
}

dependencies {
    compile 'com.firebase:firebase-client-android:2.0.3+'
    compile 'com.android.support:appcompat-v7:20.0.0'
    compile 'com.google.android.gms:play-services:5.0.89'
    compile 'org.twitter4j:twitter4j-core:4.0.2'
    compile 'com.facebook.android:facebook-android-sdk:4.1.0'
}
</code>```

What am I missing? What dependency I have to add other than firebase -client because if I add the latest the code still doesnt work.

Edit: After removing

```<code>compile 'com.firebase:firebase-client-android:2.0.3+'
compile 'com.google.android.gms:play-services:5.0.89'
</code>```

And adding

```<code>  compile 'com.google.firebase:firebase-auth:10.2.0'
  compile 'com.google.android.gms:play-services-auth:10.2.0'
</code>```

So my dependency looks like this

```<code>dependencies {
    compile 'com.google.firebase:firebase-auth:10.2.0'
    compile 'com.google.android.gms:play-services-auth:10.2.0'
    compile 'com.android.support:appcompat-v7:20.0.0'
    compile 'org.twitter4j:twitter4j-core:4.0.2'
    compile 'com.facebook.android:facebook-android-sdk:4.1.0'
}
</code>```

But for Above dependency now I have compilation issues in my code like.

```<code>For import com.firebase.client.Firebase; Cannot find the symbol client
import com.google.android.gms.plus.Plus; Cannot find the symbol plus
</code>```

答:
I have just created new project from  link. It 's really easy to follow and sign in. Firebase did all work. You can discover the link below to know which configuration you missed.

Link to test sing in Google project

Body:
I am trying to enable GoogleSignIn for my android app and trying to run this code. I have created the json file from firebase console and pasted it in app. Enabled the google login from firebase but after running app on my phone it gives me error.

firebaseError: Projects created at console.firebase.google.com must use the new Firebase Authentication SDKx available from firebase.google.com/dosc/auth

Similar threads said to remove firebase client dependency but if I remove it I have compilation error. I also have tried to add latest dependency from the docs but no luck.

my gradle file

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.0.0'
    }
}
apply plugin: 'com.android.application'

repositories {
    mavenCentral()
}

android {
    compileSdkVersion Integer.parseInt(project.ANDROID_BUILD_SDK_VERSION)
    buildToolsVersion project.ANDROID_BUILD_TOOLS_VERSION

    defaultConfig {
        minSdkVersion Integer.parseInt(project.ANDROID_BUILD_MIN_SDK_VERSION)
        targetSdkVersion Integer.parseInt(project.ANDROID_BUILD_TARGET_SDK_VERSION)
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
    packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/LICENSE-FIREBASE.txt'
    }
}

dependencies {
    compile 'com.firebase:firebase-client-android:2.0.3+'
    compile 'com.android.support:appcompat-v7:20.0.0'
    compile 'com.google.android.gms:play-services:5.0.89'
    compile 'org.twitter4j:twitter4j-core:4.0.2'
    compile 'com.facebook.android:facebook-android-sdk:4.1.0'
}

What am I missing? What dependency I have to add other than firebase -client because if I add the latest the code still doesnt work.

Edit: After removing

compile 'com.firebase:firebase-client-android:2.0.3+'
compile 'com.google.android.gms:play-services:5.0.89'

And adding

  compile 'com.google.firebase:firebase-auth:10.2.0'
  compile 'com.google.android.gms:play-services-auth:10.2.0'

So my dependency looks like this

dependencies {
    compile 'com.google.firebase:firebase-auth:10.2.0'
    compile 'com.google.android.gms:play-services-auth:10.2.0'
    compile 'com.android.support:appcompat-v7:20.0.0'
    compile 'org.twitter4j:twitter4j-core:4.0.2'
    compile 'com.facebook.android:facebook-android-sdk:4.1.0'
}

But for Above dependency now I have compilation issues in my code like.

For import com.firebase.client.Firebase; Cannot find the symbol client
import com.google.android.gms.plus.Plus; Cannot find the symbol plus


问:
How to setup private constructor?
How do I setup the unit test if the constructor is private (.NET)?

This is my class:

```<code>public class Class2
{
    // Private constructor.
    private Class2()
    {
    }

    public static Class2 getInstance()
    {

        if (x == null)
        {
            x= new Class2();
        }

        return x;
    }
}
</code>```

This is my unit test:

```<code>[TestFixture]
public class Class2Tester
{
    private Class2 test;

    [SetUp()]
    public void SetUp()
    {
        // I cant do this. How should I setup this up?
        test = new Class2();
    }
}
</code>```

答:
Depends on what you are doing in the private constructor.
If you are using a private constructor to disallow creating of an instance of a utility class then I suggest that you throw an illegalaccesserror similar to what you see in EJ2.
In that case you can simply test it via reflections that it won't be bypassed.

```<code>@Test(expected = InvocationTargetException.class)
public void privateConstructor() throws Exception {
    final Constructor<Keys> myConstructor = Keys.class.getDeclaredConstructor();
    myConstructor.setAccessible(true);
    myConstructor.newInstance();
}
</code>```

I don't disagree with this type of testing. It can help find places that are accidentally creating an instance of your util class where you didn't mean for it to (serialization/deserialization etc).

It could mean for some nasty surprises too if they were (highly not recommended) stateful.

OwnerDisplayName: lala

LastEditorDisplayName: moocha

Title: How to setup private constructor?

Body:
How do I setup the unit test if the constructor is private (.NET)?

This is my class:

public class Class2
{
    // Private constructor.
    private Class2()
    {
    }

    public static Class2 getInstance()
    {

        if (x == null)
        {
            x= new Class2();
        }

        return x;
    }
}

This is my unit test:

[TestFixture]
public class Class2Tester
{
    private Class2 test;

    [SetUp()]
    public void SetUp()
    {
        // I cant do this. How should I setup this up?
        test = new Class2();
    }
}

Body:
Depends on what you are doing in the private constructor.
If you are using a private constructor to disallow creating of an instance of a utility class then I suggest that you throw an illegalaccesserror similar to what you see in EJ2.
In that case you can simply test it via reflections that it won't be bypassed.

@Test(expected = InvocationTargetException.class)
public void privateConstructor() throws Exception {
    final Constructor<Keys> myConstructor = Keys.class.getDeclaredConstructor();
    myConstructor.setAccessible(true);
    myConstructor.newInstance();
}

I don't disagree with this type of testing. It can help find places that are accidentally creating an instance of your util class where you didn't mean for it to (serialization/deserialization etc).

It could mean for some nasty surprises too if they were (highly not recommended) stateful.


问:
Some images not showing in mobile browser (but showing in desktop browser)
I am having an issue where some images are not displayed in the mobile browsers on my iPhone, but I see them in all my desktop browsers. On my phone, I just see a blank box with a grey border where the image should be.

A couple notes:

It seems to happen randomly because some images are displayed one day, and then will stop displaying the next day

I noticed if I scroll through the page while it is still loading, I can often see the image, and then it disappears.

All the images are placed in IMG tags and are not
background-images.  All the links and file names are correct.

I have been able to fix some of these in the past by re-saving the image and then re-uploading, but it will then often revert to the same disappearing behavior

答:
Something that happened to me was that I was using background images and I was missing the closing ");" on the url. So images would still show in my computer but they would not show on any mobile browser. So, just for those crazies like me that might be too tired to figure this out. Don't forget to make sure the url is correct:

My mistake

```<code>url(resoures-services-dedicated-support.jpg
</code>```

The correct way

```<code>url(resoures-services-dedicated-support.jpg);
</code>```

Disclaimer, even though this might not be the right answer, believe me guys, seeing this would have saved me a couple of neurons.

Body:
Something that happened to me was that I was using background images and I was missing the closing ");" on the url. So images would still show in my computer but they would not show on any mobile browser. So, just for those crazies like me that might be too tired to figure this out. Don't forget to make sure the url is correct:

My mistake

url(resoures-services-dedicated-support.jpg

The correct way

url(resoures-services-dedicated-support.jpg);

Disclaimer, even though this might not be the right answer, believe me guys, seeing this would have saved me a couple of neurons.


问:
Reading lines in a file and avoiding lines with # with Bash
I tried this:

```<code>file="myfile"
while read -r line
do
    [[ $line = \#* ]] && continue
    "address=\$line\127.0.0.1"
done < "$file"
</code>```

This code doesn't avoid the lines that begin with comments. Even if I don't have any comments, dnsmasq tells that there are errors.

Its going to be a dnsmasq conf file, and it will read and insert domain names like so: address=\mydomain.com\127.0.0.1.

EDIT:1

Input file:

```<code>domain1.com
domain2.com
domain3.com
#domain4.com
domain5.com
</code>```

Output should be:

```<code>address=/domain1.com/127.0.0.1
address=/domain2.com/127.0.0.1
address=/domain3.com/127.0.0.1
address=/domain5.com/127.0.0.1
</code>```

I will drop the script in /etc/dnsmasq.d/ directory so that dnsmaq.conf can  process it when dnsmasq is started.

答:
```<code>[ "${line:0:1}" = "#" ] && continue
</code>```

This takes the string, gets the substring at offset 0, length 1:

```<code>"${line:0:1}"
</code>```

and checks if it is equal to #

```<code>= "#"
</code>```

and continues looping if so

```<code>&& continue
</code>```

http://www.tldp.org/LDP/abs/html/string-manipulation.html

ContentLicense: CC BY-SA 4.0

Body:
I tried this:

file="myfile"
while read -r line
do
    [[ $line = \#* ]] && continue
    "address=\$line\127.0.0.1"
done < "$file"

This code doesn't avoid the lines that begin with comments. Even if I don't have any comments, dnsmasq tells that there are errors.

Its going to be a dnsmasq conf file, and it will read and insert domain names like so: address=\mydomain.com\127.0.0.1.

EDIT:1

Input file:

domain1.com
domain2.com
domain3.com
#domain4.com
domain5.com

Output should be:

address=/domain1.com/127.0.0.1
address=/domain2.com/127.0.0.1
address=/domain3.com/127.0.0.1
address=/domain5.com/127.0.0.1

I will drop the script in /etc/dnsmasq.d/ directory so that dnsmaq.conf can  process it when dnsmasq is started.

Body:
[ "${line:0:1}" = "#" ] && continue

This takes the string, gets the substring at offset 0, length 1:

"${line:0:1}"

and checks if it is equal to #

= "#"

and continues looping if so

&& continue

http://www.tldp.org/LDP/abs/html/string-manipulation.html


问:
How to convert InputStream to virtual File
I have a method which expects the one of the input variable to be of java.io.File type but what I get is only InputStream. Also, I cannot change the signature of the method.

How can I convert the InputStream into File type with out actually writing the file on to the filesystem?

答: You can't. The input stream is just a generic stream of data and there is no guarantee that it actually originates from a File. If someone created an InputStream from reading a web service or just converted a String into an InputStream, there would be no way to link this to a file. So the only thing you can do is actually write data from the stream to a temporary file (e.g. using the File.createTempFile method) and feed this file into your method. </p>


问:
Python integer to letter grade issue
I am attempting to troubleshoot the errors in this piece of code:

```<code>import time

while1 = True

def grader (z):
    if   z >= 0 or z <= 59:
        return "F"
    elif z >= 60 or z <= 62:
        return "D-"
    elif z >= 62 or z <= 66:
        return "D"
    elif z >= 67 or z <= 69:
        return "D+"
    elif z >= 70 or z <= 62:
        return "C-"
    elif z >= 73 or z <= 76:
        return "C"
    elif z >= 77 or z <= 79:
        return "C+"
    elif z >= 80 or z <= 82:
        return "B-"
    elif z >= 83 or z <= 86:
        return "B"
    elif z >= 87 or z <= 89:
        return "B+"
    elif z >= 90 or z <= 92:
        return "A-"
    else:
        return "A"

while while1:
    z = int(input("I will tell you the grade of this number, enter from 1 - 100\n"))
    if z < 0 or z > 100:
        print "Between 1 and 100 PLEASE!\n"
        while1 = True
    print grader(z)
    print "New number now\n"
    time.sleep(100)
    while1 = True
</code>```

The argument in this situation is the integer z. z's value is set by the user and then the function should swing in and determine what letter grade z is worth, no matter what though it always returns 'F.'

This is rather befuddling to me (I am a novice) and I could use some assistance.

答:
This has long since been solved, but a few points remain:

no need to set while1 = True again and again.

0 is a valid input in your code, but the text says that valid grades start at 1.

A complete solution, combined with @Jon Clement's great answer, would be

```<code>import time
from bisect import bisect

def grader(score,
           breakpoints=[60, 62, 67, 70, 73, 77, 80, 83, 87, 90, 93],
           grades=['F', 'D-', 'D', 'D+', 'C-', 'C', 'C+', 'B-', 'B', 'B+', 'A-',
                   'A']):
        i = bisect(breakpoints, score)
        return grades[i]

while True:
    z = int(input("I will tell you the grade of this number, enter from 1 - 100\n"))
    if z < 0 or z > 100:
        print "Between 0 and 100 PLEASE!\n"
        continue
    print grader(z)
    time.sleep(100)
    print "New number now\n"
</code>```

Title: Python integer to letter grade issue

Body:
I am attempting to troubleshoot the errors in this piece of code:

import time

while1 = True

def grader (z):
    if   z >= 0 or z <= 59:
        return "F"
    elif z >= 60 or z <= 62:
        return "D-"
    elif z >= 62 or z <= 66:
        return "D"
    elif z >= 67 or z <= 69:
        return "D+"
    elif z >= 70 or z <= 62:
        return "C-"
    elif z >= 73 or z <= 76:
        return "C"
    elif z >= 77 or z <= 79:
        return "C+"
    elif z >= 80 or z <= 82:
        return "B-"
    elif z >= 83 or z <= 86:
        return "B"
    elif z >= 87 or z <= 89:
        return "B+"
    elif z >= 90 or z <= 92:
        return "A-"
    else:
        return "A"

while while1:
    z = int(input("I will tell you the grade of this number, enter from 1 - 100\n"))
    if z < 0 or z > 100:
        print "Between 1 and 100 PLEASE!\n"
        while1 = True
    print grader(z)
    print "New number now\n"
    time.sleep(100)
    while1 = True

The argument in this situation is the integer z. z's value is set by the user and then the function should swing in and determine what letter grade z is worth, no matter what though it always returns 'F.'

This is rather befuddling to me (I am a novice) and I could use some assistance.

Body:
This has long since been solved, but a few points remain:

no need to set while1 = True again and again.

0 is a valid input in your code, but the text says that valid grades start at 1.

A complete solution, combined with @Jon Clement's great answer, would be

import time
from bisect import bisect

def grader(score,
           breakpoints=[60, 62, 67, 70, 73, 77, 80, 83, 87, 90, 93],
           grades=['F', 'D-', 'D', 'D+', 'C-', 'C', 'C+', 'B-', 'B', 'B+', 'A-',
                   'A']):
        i = bisect(breakpoints, score)
        return grades[i]

while True:
    z = int(input("I will tell you the grade of this number, enter from 1 - 100\n"))
    if z < 0 or z > 100:
        print "Between 0 and 100 PLEASE!\n"
        continue
    print grader(z)
    time.sleep(100)
    print "New number now\n"


问:
I did not get to receive post data in json
From javascript on the client side I send 3 variables per ajax post, and on the server I try to view the json content of the client and it shows me undefined, I do not know where the problem is, I attach the code (refactored):

file : ./routes/index.js

```<code>'use strict'

const express = require('express')
const user_controller = require('../controller/user')

const api = express.Router()

// pagina de Inicio
api.get('/index',function(req,res){

    res.render('index')
})

// Gestion de usuarios
api.get('/usuarios',user_controller.getAllUsers)
api.post('/usuarios',user_controller.newUser)
api.get('/usuario',user_controller.getUser)
api.post('/logear',user_controller.logear)
api.post('/registrar',user_controller.registrar)

module.exports = api
</code>```

file : ./controller/user.js

```<code>function registrar(req,res){

var bcrypt = require('bcrypt');
var BCRYPT_SALT_ROUNDS = 12;

var user = req.body.user;
var email = req.body.email;
var pass = req.body.pass;

console.log('info: ' + user + ' ' + email + ' ' +pass);
//console.log('perro: ' + req.body);

// encriptamos la contraseña
bcrypt.genSalt(10, function(err, salt) {

    if(error) throw error;

    else{

        bcrypt.hash(pass, BCRYPT_SALT_ROUNDS, function(err, hash) {
            pass = hash;
        });
    }

});

//bcrypt.hash(pass, BCRYPT_SALT_ROUNDS).then(function(hashedPassword) {pass = hashedPassword});

conexion_db.query({ ... etc
</code>```

file: ./app.js

```<code>'use strict'

//configuracion del servidor
const express = require('express');
const bodyParser = require('body-parser');
const app = express();

app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
app.set('view engine','jade');
app.set('views', __dirname + '/views');
app.use(express.static(__dirname + '/public'));

const api = require('./routes');
app.use('/api',api);

module.exports = app
</code>```

file: client.js

```<code>$.ajax({
            url:    'http://localhost:3000/api/registrar',
            data: JSON.stringify({'user': $('#nick').val(),'email': $('#email').val(),'pass': $('#pass').val()}),
            type: "POST",
            dataType: 'json',
            success: function(json) {
                console.log("json: " + json.estado);
                console.log("json: " + json.user);
                console.log("json: " + json.pass);
</code>```

I get on cmd server, this: info: undefined undefined undefined

答:
The bodyParser middleware can not handle the json data because you have not set the ContentType.jQuery ajax default value of contentType parameter is "application/x-www-form-urlencoded; charset=UTF-8".But you are sending data in json type.You need to set ContentType to application/json.

You can also give PlainObject to the data parameter.

Body:
From javascript on the client side I send 3 variables per ajax post, and on the server I try to view the json content of the client and it shows me undefined, I do not know where the problem is, I attach the code (refactored):

file : ./routes/index.js

'use strict'

const express = require('express')
const user_controller = require('../controller/user')

const api = express.Router()

// pagina de Inicio
api.get('/index',function(req,res){

    res.render('index')
})

// Gestion de usuarios
api.get('/usuarios',user_controller.getAllUsers)
api.post('/usuarios',user_controller.newUser)
api.get('/usuario',user_controller.getUser)
api.post('/logear',user_controller.logear)
api.post('/registrar',user_controller.registrar)

module.exports = api

file : ./controller/user.js

function registrar(req,res){

var bcrypt = require('bcrypt');
var BCRYPT_SALT_ROUNDS = 12;

var user = req.body.user;
var email = req.body.email;
var pass = req.body.pass;

console.log('info: ' + user + ' ' + email + ' ' +pass);
//console.log('perro: ' + req.body);

// encriptamos la contraseña
bcrypt.genSalt(10, function(err, salt) {

    if(error) throw error;

    else{

        bcrypt.hash(pass, BCRYPT_SALT_ROUNDS, function(err, hash) {
            pass = hash;
        });
    }

});

//bcrypt.hash(pass, BCRYPT_SALT_ROUNDS).then(function(hashedPassword) {pass = hashedPassword});

conexion_db.query({ ... etc

file: ./app.js

'use strict'

//configuracion del servidor
const express = require('express');
const bodyParser = require('body-parser');
const app = express();

app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
app.set('view engine','jade');
app.set('views', __dirname + '/views');
app.use(express.static(__dirname + '/public'));

const api = require('./routes');
app.use('/api',api);

module.exports = app

file: client.js

$.ajax({
            url:    'http://localhost:3000/api/registrar',
            data: JSON.stringify({'user': $('#nick').val(),'email': $('#email').val(),'pass': $('#pass').val()}),
            type: "POST",
            dataType: 'json',
            success: function(json) {
                console.log("json: " + json.estado);
                console.log("json: " + json.user);
                console.log("json: " + json.pass);

I get on cmd server, this: info: undefined undefined undefined


问:
Merge multiple arrays based on their index using javascript
I need to merge two arrays into a single array.  I have code but it is not working as expected-- it is merging them one after another, but I need to interlock the values.

    <title></title>

```

答:
You can use a combination of reduce and concat (source):

var array1 = [1, 2, 3, 4];
var array2 = ["a", "b", "c", "d"];
var newArray = array1.reduce(function(prev, curr) {
  return prev.concat(curr, array2[prev.length / 2]);
}, []);
$("#result").html(newArray);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div></code>```

Body:
You can use a combination of reduce and concat (source):

var array1 = [1, 2, 3, 4];
var array2 = ["a", "b", "c", "d"];
var newArray = array1.reduce(function(prev, curr) {
  return prev.concat(curr, array2[prev.length / 2]);
}, []);
$("#result").html(newArray);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>


问:
What algorithm can generate Round-Robin "pairings" for rounds with more than two contestants?
I'd like to be able to generate a set of tournament match-ups such that each player faces each other player at least once, each player plays the same number of games. Think of it as an abstraction of round-robin matchups to Mario Kart.

In my case, I have 17 contestants, and would like them to play in rounds of 3 or 4 players. I'd like to have a way to generate S, a set of subsets of P (players) such that each element of P occurs in at least one element of S with each other element of P.

At first I thought a Balanced Tournament Design would answer, but it doesn't seem to have any way to match multiple contestants per round, just multiple additional face-offs for each pair.

It also smacks of an exact cover problem, but not quite.

This would be applicable to games such as four-player chess, icehouse, various card and dice games, and the like as well.

答:
I was trying to do something similar for 12 players/4 per game where each player has to play all other players over 5 rounds. Unfortunately, my solution only worked for 7 rounds. I'm interested in solving this myself for N players and M per game.

https://gist.github.com/anonymous/e3372d1e61b01cf453dc26a488c9e345

```<code>(ns tournament-gen.core)

(defn rotate [n ps]
  (concat (drop n ps) (take n ps)))

(defn round [size ps]
  (apply mapcat vector (partition (Math/floorDiv (count ps) size) ps)))

(defn rounds [size n ps]
  (take n (iterate #(rotate 2 (round size %)) ps)))

(defn set->map [gset]
  (into {}
        (for [k gset]
          [k gset])))

(defn verify [size gs]
  (apply merge-with
         clojure.set/union
         (for [game (mapcat (partial partition size) gs)]
           (set->map (set game)))))

; I got it to work in 7 rounds for 12, but it seems like 5 should be possible
(map (partial partition 4) (rounds 4 7 (range 0 12)))

;result
(((0 1 2 3) (4 5 6 7) (8 9 10 11))
 ((6 9 1 4) (7 10 2 5) (8 11 0 3))
 ((2 11 9 7) (5 0 1 10) (8 3 6 4))
 ((1 3 11 5) (10 6 9 0) (8 4 2 7))
 ((9 4 3 10) (0 2 11 6) (8 7 1 5))
 ((11 7 4 0) (6 1 3 2) (8 5 9 10))
 ((3 5 7 6) (2 9 4 1) (8 10 11 0)))

(sort-by first (into {} (for [[k v] (verify 4 (rounds 4 5 (range 0 12)))]
    [(str "Player " k) (count v)])))
=>
(["Player 0" 10]
 ["Player 1" 12]
 ["Player 10" 12]
 ["Player 11" 11]
 ["Player 2" 12]
 ["Player 3" 11]
 ["Player 4" 10]
 ["Player 5" 11]
 ["Player 6" 12]
 ["Player 7" 10]
 ["Player 8" 12]
 ["Player 9" 11])
</code>```

Body:
I was trying to do something similar for 12 players/4 per game where each player has to play all other players over 5 rounds. Unfortunately, my solution only worked for 7 rounds. I'm interested in solving this myself for N players and M per game.

https://gist.github.com/anonymous/e3372d1e61b01cf453dc26a488c9e345

(ns tournament-gen.core)

(defn rotate [n ps]
  (concat (drop n ps) (take n ps)))

(defn round [size ps]
  (apply mapcat vector (partition (Math/floorDiv (count ps) size) ps)))

(defn rounds [size n ps]
  (take n (iterate #(rotate 2 (round size %)) ps)))

(defn set->map [gset]
  (into {}
        (for [k gset]
          [k gset])))

(defn verify [size gs]
  (apply merge-with
         clojure.set/union
         (for [game (mapcat (partial partition size) gs)]
           (set->map (set game)))))

; I got it to work in 7 rounds for 12, but it seems like 5 should be possible
(map (partial partition 4) (rounds 4 7 (range 0 12)))

;result
(((0 1 2 3) (4 5 6 7) (8 9 10 11))
 ((6 9 1 4) (7 10 2 5) (8 11 0 3))
 ((2 11 9 7) (5 0 1 10) (8 3 6 4))
 ((1 3 11 5) (10 6 9 0) (8 4 2 7))
 ((9 4 3 10) (0 2 11 6) (8 7 1 5))
 ((11 7 4 0) (6 1 3 2) (8 5 9 10))
 ((3 5 7 6) (2 9 4 1) (8 10 11 0)))

(sort-by first (into {} (for [[k v] (verify 4 (rounds 4 5 (range 0 12)))]
    [(str "Player " k) (count v)])))
=>
(["Player 0" 10]
 ["Player 1" 12]
 ["Player 10" 12]
 ["Player 11" 11]
 ["Player 2" 12]
 ["Player 3" 11]
 ["Player 4" 10]
 ["Player 5" 11]
 ["Player 6" 12]
 ["Player 7" 10]
 ["Player 8" 12]
 ["Player 9" 11])


问:
Low frame rate during UINavigationController push transition
I have a UINavigationController, and push from the root view controller to the next view controller. This second view controller is fairly "heavy", in that it has a great deal of initialization and subviews.

My issue is this: the transition animation performs terribly. Basically, the animation suffers from a very low frame rate (I get maybe 3-4 frames in total out of the "push" animation).

I've tried a variety of different techniques, including two different methods to manually animate the transition. In all cases, the first 0.4-0.7 seconds of the animation suffers from this poor framerate. If I set the transition to take 5 seconds, for example, the first half second or so performs poorly, but the remainder of the animation is nice and smooth.

This leads me to believe that "something" is happening at the beginning of the transition -- something which causes the device to animate at a very low framerate.

After injecting a lot of NSLog statements into my code, I saw two things happen. First, obviously the second view is being lazy-loaded during the push. I fixed this by accessing the getter on the view property before executing the push. I can confirm that this results in all the initialization happening before the push animation begins.

Second, my app most of the time receives a low memory warning during the transition. However, even in cases when I don't get the memory warning, the animation still performs just as poorly -- leading me to believe that neither of these things is the cause.

My question: Has anyone else experienced a low framerate on a UINavigationController push transition animation, but only for the first 0.4-0.7 seconds of the animation? Is there something else going on behind the scenes that causes it, and can anything be done?

For reference, here's my current code that loads and pushes to the next view. I'm purposefully accessing the view getter in order to force the view to load and initialize before the transition (mostly to rule out that as the issue). This code is executed on the main thread using performSelectorOnMainThread::: in response to a web service callback.

```<code>PlayingFieldViewController *v = [[PlayingFieldViewController alloc] initWithNibName:@"PlayingFieldView" bundle:[NSBundle mainBundle]];
UIView *lazy = v.view;
[appDelegate.navigationController pushViewController:v animated:YES];
[v release];
</code>```

I've also tried a few other animation techniques, all with the same result:

```<code>CATransition *transition = [CATransition animation];
transition.duration = 1.0;
transition.type = kCATransitionPush;
transition.subtype = kCATransitionFromRight;
[appDelegate.navigationController.view.layer addAnimation:transition forKey:kCATransition];
[appDelegate.navigationController pushViewController:v animated:NO];
</code>```

and:

```<code>[UIView
  transitionWithView:appDelegate.navigationController.view
  duration:1.0
  options:UIViewAnimationOptionTransitionCurlUp
  animations:^{
   [appDelegate.navigationController pushViewController:v animated:NO];
  }
  completion:NULL];
</code>```

答:
After further testing, I was able to diagnose the problem. The second view involved includes many UIImageViews. Removing those views or hiding them fixes the problem.

What threw me off was the fact that only the first portion of the animation suffered from frame rate issues, while the remainder of the animation was perfectly smooth (in the case of longer animations). This shows me that the device is quite capable of animating the transition smoothly, even with all the subviews present.

I'm still not an expert on iOS compositing, but I'm guessing the various layers are being laid out and cached, leading to the slowdown. The workaround is to push to the view with most of the subviews hidden, then show them using another animation once the view is visible.

Body:
I have a UINavigationController, and push from the root view controller to the next view controller. This second view controller is fairly "heavy", in that it has a great deal of initialization and subviews.

My issue is this: the transition animation performs terribly. Basically, the animation suffers from a very low frame rate (I get maybe 3-4 frames in total out of the "push" animation).

I've tried a variety of different techniques, including two different methods to manually animate the transition. In all cases, the first 0.4-0.7 seconds of the animation suffers from this poor framerate. If I set the transition to take 5 seconds, for example, the first half second or so performs poorly, but the remainder of the animation is nice and smooth.

This leads me to believe that "something" is happening at the beginning of the transition -- something which causes the device to animate at a very low framerate.

After injecting a lot of NSLog statements into my code, I saw two things happen. First, obviously the second view is being lazy-loaded during the push. I fixed this by accessing the getter on the view property before executing the push. I can confirm that this results in all the initialization happening before the push animation begins.

Second, my app most of the time receives a low memory warning during the transition. However, even in cases when I don't get the memory warning, the animation still performs just as poorly -- leading me to believe that neither of these things is the cause.

My question: Has anyone else experienced a low framerate on a UINavigationController push transition animation, but only for the first 0.4-0.7 seconds of the animation? Is there something else going on behind the scenes that causes it, and can anything be done?

For reference, here's my current code that loads and pushes to the next view. I'm purposefully accessing the view getter in order to force the view to load and initialize before the transition (mostly to rule out that as the issue). This code is executed on the main thread using performSelectorOnMainThread::: in response to a web service callback.

PlayingFieldViewController *v = [[PlayingFieldViewController alloc] initWithNibName:@"PlayingFieldView" bundle:[NSBundle mainBundle]];
UIView *lazy = v.view;
[appDelegate.navigationController pushViewController:v animated:YES];
[v release];

I've also tried a few other animation techniques, all with the same result:

CATransition *transition = [CATransition animation];
transition.duration = 1.0;
transition.type = kCATransitionPush;
transition.subtype = kCATransitionFromRight;
[appDelegate.navigationController.view.layer addAnimation:transition forKey:kCATransition];
[appDelegate.navigationController pushViewController:v animated:NO];

and:

[UIView
  transitionWithView:appDelegate.navigationController.view
  duration:1.0
  options:UIViewAnimationOptionTransitionCurlUp
  animations:^{
   [appDelegate.navigationController pushViewController:v animated:NO];
  }
  completion:NULL];


问:
Handling ARGF.read in ruby
I am using following lines of code in my ruby program on ubuntu:

```<code>data=ARGF.read

if data.length != 0

      .....

end
</code>```

The program runs fine when I run as "cat file.txt | ruby test.rb", however, I am unable to handle following issues:

When run as "cat | ruby test.rb", the program goes into endless loop.

When run as "ruby test.rb", the program goes into endless loop.

When run as "cat file1.txt | ruby test.rb", the program gives "cat: file1.txt: No such file or directory" error.

Any input will be highly appreciated.

答:
I think you misunderstand what ARGF is used for. ARGF.read gives all the data of all the files passed as arguments.

When you don't give any input file, it is waiting for you to give the input through stdin. Since, you are in Ubuntu, you could just press (Control + D) which would end the stream and then you could process the data normally.

Title: Handling ARGF.read in ruby

Body:
I am using following lines of code in my ruby program on ubuntu:

data=ARGF.read

if data.length != 0

      .....

end

The program runs fine when I run as "cat file.txt | ruby test.rb", however, I am unable to handle following issues:

When run as "cat | ruby test.rb", the program goes into endless loop.

When run as "ruby test.rb", the program goes into endless loop.

When run as "cat file1.txt | ruby test.rb", the program gives "cat: file1.txt: No such file or directory" error.

Any input will be highly appreciated.


问:
Drawing in a video
I am doing an exercise in which the program has to follow that routine: when the user clicks on any point of a video, it gets that pixel and turns all pixels in a range of 5% into red. Since it is a video, I am saving the points (x,y) the user clicks in a list and making the retangle for every point. Here is the code: import numpy as np import cv2

```<code>import numpy as np
import cv2

cap =cv2.VideoCapture(-1)

 #creates list

lista= []

    #mouse callback function

def getpixel(event,x,y,flags,param):

       #adds point (x,y) in pixels ont the current list

if event == cv2.EVENT_LBUTTONDOWN:
    lista.append([x,y])
    print (x,y),img[x][y]

  while(cap.isOpened()):

 ret,img= cap.read()
 if ret:
    cv2.imshow('image',img)
    cv2.setMouseCallback('image',getpixel)
 i=0
 #draw the retangle
 while i<lista.__len__():
       img[int(0.95*lista[i][0]):int(1.05*lista[i][0]),int(0.95*lista[i][1]):int(1.05*lista[i][1])]=(0,0,255)
       i+=1
 if cv2.waitKey(20) & 0xFF == 27:
    break

    cap.release()

    cv2.destroyAllWindows()
</code>```

I have already checked and it is creating the list, adding the points and entering in the "while" part of the code. However, I can't see the retangles. What am I missing?

答:
Note: For a quick fix read this answer from bottom.

In your code you calculate percentage NOT frow width / hight of the captured picture but from the points themselves:

```<code>img[int(0.95*lista[i][0]):int(1.05*lista[i][0]), ....
</code>```

So you need to obtain the width and hight - something as

```<code>width  = cap.get( CAP_PROP_FRAME_WIDTH )
height = cap.get( CAP_PROP_FRAME_HEIGHT )
</code>```

and then the vertices of your rectangle adjust to these values:

```<code>int( lista[i][0] - 0.95 * width )
int( lista[i][0] + 1.05 * width )
int( lista[i][1] - 0.95 * hight )
int( lista[i][1] + 1.95 * hight )
</code>```

To be specific and more elegant:

Instead of this part of your code

```<code>i=0
#draw the retangle
while i<lista.__len__():
    img[int(0.95*lista[i][0]):int(1.05*lista[i][0]),int(0.95*lista[i][1]):int(1.05*lista[i][1])]=(0,0,255)
    i+=1
</code>```

write this:

```<code>width  = cap.get( CAP_PROP_FRAME_WIDTH )
height = cap.get( CAP_PROP_FRAME_HEIGHT )

deltaX = 0.05 * width
deltaY = 0.05 * hight

while point in lista:
    ltX = int (point[0] - deltaX)        # Left top X coordinate
    ltY = int (point[1] - deltaY)        # Left top Y coordinate
    rbX = int (point[0] + deltaX)        #   --- and so on ---
    rbY = int (point[1] + deltaX)

    img[ltX:rbX, ltY:rbY] = (0,0,255)
</code>```

Title: Drawing in a video

Body:
I am doing an exercise in which the program has to follow that routine: when the user clicks on any point of a video, it gets that pixel and turns all pixels in a range of 5% into red. Since it is a video, I am saving the points (x,y) the user clicks in a list and making the retangle for every point. Here is the code: import numpy as np import cv2

import numpy as np
import cv2

cap =cv2.VideoCapture(-1)

 #creates list

lista= []

    #mouse callback function

def getpixel(event,x,y,flags,param):

       #adds point (x,y) in pixels ont the current list

if event == cv2.EVENT_LBUTTONDOWN:
    lista.append([x,y])
    print (x,y),img[x][y]

  while(cap.isOpened()):

 ret,img= cap.read()
 if ret:
    cv2.imshow('image',img)
    cv2.setMouseCallback('image',getpixel)
 i=0
 #draw the retangle
 while i<lista.__len__():
       img[int(0.95*lista[i][0]):int(1.05*lista[i][0]),int(0.95*lista[i][1]):int(1.05*lista[i][1])]=(0,0,255)
       i+=1
 if cv2.waitKey(20) & 0xFF == 27:
    break

    cap.release()

    cv2.destroyAllWindows()

I have already checked and it is creating the list, adding the points and entering in the "while" part of the code. However, I can't see the retangles. What am I missing?

Body:
Note: For a quick fix read this answer from bottom.

In your code you calculate percentage NOT frow width / hight of the captured picture but from the points themselves:

img[int(0.95*lista[i][0]):int(1.05*lista[i][0]), ....

So you need to obtain the width and hight - something as

width  = cap.get( CAP_PROP_FRAME_WIDTH )
height = cap.get( CAP_PROP_FRAME_HEIGHT )

and then the vertices of your rectangle adjust to these values:

int( lista[i][0] - 0.95 * width )
int( lista[i][0] + 1.05 * width )
int( lista[i][1] - 0.95 * hight )
int( lista[i][1] + 1.95 * hight )

To be specific and more elegant:

Instead of this part of your code

i=0
#draw the retangle
while i<lista.__len__():
    img[int(0.95*lista[i][0]):int(1.05*lista[i][0]),int(0.95*lista[i][1]):int(1.05*lista[i][1])]=(0,0,255)
    i+=1

write this:

width  = cap.get( CAP_PROP_FRAME_WIDTH )
height = cap.get( CAP_PROP_FRAME_HEIGHT )

deltaX = 0.05 * width
deltaY = 0.05 * hight

while point in lista:
    ltX = int (point[0] - deltaX)        # Left top X coordinate
    ltY = int (point[1] - deltaY)        # Left top Y coordinate
    rbX = int (point[0] + deltaX)        #   --- and so on ---
    rbY = int (point[1] + deltaX)

    img[ltX:rbX, ltY:rbY] = (0,0,255)


问:
How to append an image to a specific class
I have multiple classes with the same tag (.offer) I am going through a loop and it adds the image to all my .offer divs. I just want to add the image specific to the user who posted. How can I do this? Assume the backend is working completely fine

jQuery (1st function)

```<code>    function getOffers(key) {
            dict = {
                'key': key// pk value of post sent to retrieve offers to it
            };

            generateCSRFToken();
            $.ajax({
                url: "/retrieve_offers/",
                method: "POST",
                data: JSON.stringify(dict),
                success: function (data) {
                    data = JSON.parse(data);

                    console.log(appendUserImage(38));
                    $("#offercontainer").empty();
                    $(".offer").empty();
                    for (var i = 0; i < data.length; i++) {

                        var string = data[i].fields.author_name;
                        $("#offercontainer").append(
                            "<div class='offer'>" +
                            "<p class=offername>" + string + "</p>" +
                            "<p class=offertext> offered his " + " " + data[i].fields.item_name +  "</p>" +
                            "</div>"
                        );
                        appendUserImage(data[i].fields.author);
                    }
                },
                error: function () {
                }

            })
        }
</code>```

jQuery (2nd function)

```<code>  function appendUserImage(key) {
        dict = {
            'key': key// pk value of post sent to retrieve offers to it
        };
        generateCSRFToken();
        $.ajax({
            url: "/get_user/",
            method: "POST",
            data: JSON.stringify(dict),
            success: function (data) {
                $('<img />', {
                    src: data["image"],
                    class: "offer_user_image"
                }).appendTo($('.offer'))

            },
            error: function () {
            }

        });

    }
</code>```

I just want to append the image to its respective offer div pls help

答:
you can pass to appendUserImage the div getOffers function creates  or do something like this, add an unique key selector to the created .offer container and targeting it in the appendUserImage function.

in function getOffers(key) {

```<code>$("#offercontainer").append(
  "<div class='offer' data-author-key='" + data[i].fields.author +"'>" +
  "<p class=offername>" + string + "</p>" +
  "<p class=offertext> offered his " + " " + data[i].fields.item_name +  "</p>" +
  "</div>");
  appendUserImage(data[i].fields.author);
</code>```

in function appendUserImage(key) {

```<code>$('<img />', {
 src: data["image"],
 class: "offer_user_image"
 }).appendTo($('.offer[data-author-key="' + key + '"]'))
</code>```

Body:
I have multiple classes with the same tag (.offer) I am going through a loop and it adds the image to all my .offer divs. I just want to add the image specific to the user who posted. How can I do this? Assume the backend is working completely fine

jQuery (1st function)

    function getOffers(key) {
            dict = {
                'key': key// pk value of post sent to retrieve offers to it
            };

            generateCSRFToken();
            $.ajax({
                url: "/retrieve_offers/",
                method: "POST",
                data: JSON.stringify(dict),
                success: function (data) {
                    data = JSON.parse(data);

                    console.log(appendUserImage(38));
                    $("#offercontainer").empty();
                    $(".offer").empty();
                    for (var i = 0; i < data.length; i++) {

                        var string = data[i].fields.author_name;
                        $("#offercontainer").append(
                            "
" +
                            "
" + string + "
" +
                            "
 offered his " + " " + data[i].fields.item_name +  "
" +
                            "
"
                        );
                        appendUserImage(data[i].fields.author);
                    }
                },
                error: function () {
                }

            })
        }

jQuery (2nd function)

  function appendUserImage(key) {
        dict = {
            'key': key// pk value of post sent to retrieve offers to it
        };
        generateCSRFToken();
        $.ajax({
            url: "/get_user/",
            method: "POST",
            data: JSON.stringify(dict),
            success: function (data) {
                $('', {
                    src: data["image"],
                    class: "offer_user_image"
                }).appendTo($('.offer'))

            },
            error: function () {
            }

        });

    }

I just want to append the image to its respective offer div pls help

Body:
you can pass to appendUserImage the div getOffers function creates  or do something like this, add an unique key selector to the created .offer container and targeting it in the appendUserImage function.

in function getOffers(key) {

$("#offercontainer").append(
  "<div class='offer' data-author-key='" + data[i].fields.author +"'>" +
  "<p class=offername>" + string + "</p>" +
  "<p class=offertext> offered his " + " " + data[i].fields.item_name +  "</p>" +
  "</div>");
  appendUserImage(data[i].fields.author);

in function appendUserImage(key) {

$('<img />', {
 src: data["image"],
 class: "offer_user_image"
 }).appendTo($('.offer[data-author-key="' + key + '"]'))


问:
Rearrange lines to tabular format
I would like to grab the part after "-" and combine it with the following letter-string into a tab-output.  I tried something like cut -d "*-" -f 2 <<< "$your_str" but I am not sure how to do the whole shuffling.

Input:

```<code>>1-395652
TATTGCACTTGTCCCGGCCTGT
>2-369990
TATTGCACTCGTCCCGGCCTCC
>3-132234
TATTGCACTCGTCCCGGCCTC
>4-122014
TATTGCACTTGTCCCGGCCTGTAA
>5-118616
</code>```

Output:

```<code>TATTGCACTTGTCCCGGCCTGT 395652
TATTGCACTCGTCCCGGCCTCC 369990
</code>```

答:
awk to the rescue!

```<code>awk -F- '/^>/{k=$2; next} {print $0, k}' file
</code>```

Title: Rearrange lines to tabular format

Body:
I would like to grab the part after "-" and combine it with the following letter-string into a tab-output.  I tried something like cut -d "*-" -f 2 <<< "$your_str" but I am not sure how to do the whole shuffling.

Input:

>1-395652
TATTGCACTTGTCCCGGCCTGT
>2-369990
TATTGCACTCGTCCCGGCCTCC
>3-132234
TATTGCACTCGTCCCGGCCTC
>4-122014
TATTGCACTTGTCCCGGCCTGTAA
>5-118616

Output:

TATTGCACTTGTCCCGGCCTGT 395652
TATTGCACTCGTCCCGGCCTCC 369990

Body:
awk to the rescue!

awk -F- '/^>/{k=$2; next} {print $0, k}' file


问:
Looping through each attribute and downcasing
I am trying to loop through each attribute of datum and downcase the values in the model method below. If I push values into the check[] array, the downcase works, but if I try to datum.attr_name = datum.attr_value.downcase the downcasing does not take.

How do I actually downcase each attribute value and get this downcasing to save?

```<code>check = [] #used to troubleshoot
datum.attributes.each do |attr_name, attr_value|
  begin
    check.push(attr_name) #just used to troubleshoot
    check.push(attr_value.downcase) #just used to troubleshoot

    datum.attr_name = datum.attr_value.downcase #need help here

   rescue
   end
end
datum.save
return check
</code>```

Bonus: I am currently using an array to troubleshoot, and printing that array out through an error message. What is a better way to troubleshoot model code like this?

答:
You can do it like this, and also get rid of the begin...rescue by checking if the attribute can be downcased.

```<code>datum.attributes.each do |attr_name, attr_value|
  datum[attr_name] = attr_value.downcase if attr_value.respond_to?(:downcase)
end
datum.save
</code>```

Body:
I am trying to loop through each attribute of datum and downcase the values in the model method below. If I push values into the check[] array, the downcase works, but if I try to datum.attr_name = datum.attr_value.downcase the downcasing does not take.

How do I actually downcase each attribute value and get this downcasing to save?

check = [] #used to troubleshoot
datum.attributes.each do |attr_name, attr_value|
  begin
    check.push(attr_name) #just used to troubleshoot
    check.push(attr_value.downcase) #just used to troubleshoot

    datum.attr_name = datum.attr_value.downcase #need help here

   rescue
   end
end
datum.save
return check

Bonus: I am currently using an array to troubleshoot, and printing that array out through an error message. What is a better way to troubleshoot model code like this?

Body:
You can do it like this, and also get rid of the begin...rescue by checking if the attribute can be downcased.

datum.attributes.each do |attr_name, attr_value|
  datum[attr_name] = attr_value.downcase if attr_value.respond_to?(:downcase)
end
datum.save


问:
VBA log in failing with getElementsByClassName
I am trying to login to a website using VBA but I can't get it to click the submit button even though I do the things that I have found recommended. Any help would be greatly appreciated.

Below is the HTML of the form:

```<code><div class="pdForm login">
  <div class="pdLoginBox">
    <div class="pdLoginBoxInner">

    <div class="pdLoginFieldTitle">
        <div>Email Address</div>
        <div class="register"></div>
    </div>
    <input type="email" name="email" value="" class="pdInput text" id="pdLogin-email">

    <br>
    <div class="pdLoginFieldTitle">
        <div>Password</div>
        <div class="forgot"><a href="http://myaccount.asdf.com/retrievePassword.php" onclick="pdRetrievePasswordCopyEmail(this);"> Forgot your Password?</a></div>
    </div>
    <input type="password" name="password" value=""  class="pdInput text" id="pdLogin-password">

    <div class="pdLoginBtn">
        <input type="image" src="http://myaccount.asdf.com/skins/standard_custom/butLogin.gif" border="0" vspace="4">
    </div>
        <div class="pdRegisterBtn">
    </div>

    </div>
  </div>
</div>
</code>```

Here is the VBA that I have tried and it fills in the name and password but will not submit even through it runs the code without error.

```<code>Sub Login()
    Dim lr As Long, a

    Set IE = CreateObject("InternetExplorer.Application")

    my_url = "http://myaccount.asdf.com/login.php"

    With IE
        .Visible = True
        .Navigate my_url
        .Top = 50
        .Left = 530
        .Height = 1200
        .Width = 1200

        Do Until Not IE.Busy And IE.READYSTATE = 4
            DoEvents
        Loop

    End With

    ' Input the userid and password
    IE.Document.GetElementById("pdLogin-email").Value = "asdf@asdf.com"
    IE.Document.GetElementById("pdLogin-password").Value = "xxxxxx"

    Set ElementCol = IE.Document.getElementsByClassName("pdLoginBtn")

    For Each btnInput In ElementCol
        btnInput.Click
    Next btnInput

End Sub
</code>```

Any ideas? Thanks in advance for your time.

答:
Does this work for you?</p>

```<code>Set ElementCol = IE.document.getElementsByClassName("pdLoginBtn").Children(0)
ElementCol.Click
</code>```

Body:
I am trying to login to a website using VBA but I can't get it to click the submit button even though I do the things that I have found recommended. Any help would be greatly appreciated.

Below is the HTML of the form:

Email Address

    <input type="email" name="email" value="" class="pdInput text" id="pdLogin-email">

Password

 Forgot your Password?

    <input type="password" name="password" value=""  class="pdInput text" id="pdLogin-password">

        <input type="image" src="http://myaccount.asdf.com/skins/standard_custom/butLogin.gif" border="0" vspace="4">

Here is the VBA that I have tried and it fills in the name and password but will not submit even through it runs the code without error.

Sub Login()
    Dim lr As Long, a

    Set IE = CreateObject("InternetExplorer.Application")

    my_url = "http://myaccount.asdf.com/login.php"

    With IE
        .Visible = True
        .Navigate my_url
        .Top = 50
        .Left = 530
        .Height = 1200
        .Width = 1200

        Do Until Not IE.Busy And IE.READYSTATE = 4
            DoEvents
        Loop

    End With

    ' Input the userid and password
    IE.Document.GetElementById("pdLogin-email").Value = "asdf@asdf.com"
    IE.Document.GetElementById("pdLogin-password").Value = "xxxxxx"

    Set ElementCol = IE.Document.getElementsByClassName("pdLoginBtn")

    For Each btnInput In ElementCol
        btnInput.Click
    Next btnInput

End Sub

Any ideas? Thanks in advance for your time.

Body:
Does this work for you?

Set ElementCol = IE.document.getElementsByClassName("pdLoginBtn").Children(0)
ElementCol.Click


问:
How to export an Excel sheet range to a picture, from within R
We are trying to automate the creation of some picture files within an R Script.

We have the Excel files looking the way that we want them to, but now need to make a JPG or PNG picture-copy of those excel tables for easier web posting.

We've been using the library(xlsx) package for most of our interactions between R and Excel, and it looks like we should be able to send specific java commands through something like ?.jmethods but it's unclear how we would pass as many lines as we need to.

In an R session, here's a minimal reproducible example...

Here's an example Excel file with a range to print

```<code>library(xlsx)
file <- system.file("tests", "test_import.xlsx", package = "xlsx")
file
</code>```

And here's the Excel macro that exports the Excel range to a picture file

```<code>Sub Tester()

    Worksheets("deletedFields").Range("A8:J36").CopyPicture xlScreen, xlBitmap

    Application.DisplayAlerts = False
    Set oCht = Charts.Add
    With oCht
        .Paste
        .Export Filename:="C:\temp\SavedRange.jpg", Filtername:="JPG"
        .Delete
    End With

End Sub
</code>```

Any help automating this would be much appreciated!

答:
Consider having R do exactly as VBA does in your macro: making a COM interface to the Excel object library. You can do so with the RDCOMClient package, retaining nearly same code as macro in the R syntax.

```<code>library(RDCOMClient)

xlApp <- COMCreate("Excel.Application")
xlWbk <- xlApp$Workbooks()$Open("C:\\Path\\To\\test_import.xlsx")
xlScreen = 1
xlBitmap = 2

xlWbk$Worksheets("deletedFields")$Range("A8:J36")$CopyPicture(xlScreen, xlBitmap)

xlApp[['DisplayAlerts']] <- FALSE

oCht <- xlApp[['Charts']]$Add()
oCht$Paste()
oCht$Export("C:\\Temp\\SavedRange.jpg", "JPG")
oCht$Delete()

# CLOSE WORKBOOK AND APP
xlWbk$Close(FALSE)
xlApp$Quit()

# RELEASE RESOURCES
oCht <- xlWbk <- xlApp <- NULL
rm(oCht, xlWbk, xlApp)
gc()
</code>```

Output (random data/chart)

Body:
We are trying to automate the creation of some picture files within an R Script.

We have the Excel files looking the way that we want them to, but now need to make a JPG or PNG picture-copy of those excel tables for easier web posting.

We've been using the library(xlsx) package for most of our interactions between R and Excel, and it looks like we should be able to send specific java commands through something like ?.jmethods but it's unclear how we would pass as many lines as we need to.

In an R session, here's a minimal reproducible example...

Here's an example Excel file with a range to print

library(xlsx)
file <- system.file("tests", "test_import.xlsx", package = "xlsx")
file

And here's the Excel macro that exports the Excel range to a picture file

Sub Tester()

    Worksheets("deletedFields").Range("A8:J36").CopyPicture xlScreen, xlBitmap

    Application.DisplayAlerts = False
    Set oCht = Charts.Add
    With oCht
        .Paste
        .Export Filename:="C:\temp\SavedRange.jpg", Filtername:="JPG"
        .Delete
    End With

End Sub

Any help automating this would be much appreciated!

Body:
Consider having R do exactly as VBA does in your macro: making a COM interface to the Excel object library. You can do so with the RDCOMClient package, retaining nearly same code as macro in the R syntax.

library(RDCOMClient)

xlApp <- COMCreate("Excel.Application")
xlWbk <- xlApp$Workbooks()$Open("C:\\Path\\To\\test_import.xlsx")
xlScreen = 1
xlBitmap = 2

xlWbk$Worksheets("deletedFields")$Range("A8:J36")$CopyPicture(xlScreen, xlBitmap)

xlApp[['DisplayAlerts']] <- FALSE

oCht <- xlApp[['Charts']]$Add()
oCht$Paste()
oCht$Export("C:\\Temp\\SavedRange.jpg", "JPG")
oCht$Delete()

# CLOSE WORKBOOK AND APP
xlWbk$Close(FALSE)
xlApp$Quit()

# RELEASE RESOURCES
oCht <- xlWbk <- xlApp <- NULL
rm(oCht, xlWbk, xlApp)
gc()

Output (random data/chart)


问:
Will F# perform well when writing math functions for a C# program?
Does anyone know how well F# measures with regards to performance, compared to C#. I have a C# raytracer with a lot of vector manipulations, ray-collission algorithms etc. and thought they might be more easily expressed in F#. I'm not asking for how well F# is at expressing math problems, something which has been answered here, but rather if I should expect better or worse performance? As raytracing is very performance intensive, even small cases of poor performance can be a problem in the wrong places.

Edit:

It seems that there are already a lot of questions on the subject that I couldn't find (there are no results if you actually search for anything with the term 'F#'). One good point here was the following answer:

F# provides some performance-related
  features that can make a difference.

Firstly, the implementation of
  delegates on .NET is currently quite
  inefficient and, consequently, F# uses
  its own FastFunc type for
  high-performance first-class
  functions.

Secondly, F# uses .NET metadata to
  convey inline functions so that they
  can be exported across APIs and, of
  course, that can dramatically improve
  performance in certain circumstances.

Finally, pattern matching can be
  extremely laborious to express in C#
  because the language lacks pattern
  matching but it is almost impossible
  to maintain optimized C# code
  equivalent to many non-trivial pattern
  matches. In contrast, the F# compiler
  aggressively optimizes pattern matches
  during compilation.

Conversely, the C# compiler is better
  at optimizing loops using IEnumerables
  and is better at optimizing
  computations over value types (e.g.
  complex arithmetic).

Cheers, Jon Harrop.

答:
F# is better suited for parallel programming. So out-of-the box it can be faster as C# (on multi-cores/cpu).

But then again, you can optimize C# to use this as wel, but it will be a lot more work.

OwnerDisplayName: Morten Christiansen

LastEditorDisplayName: Norman Ramsey

OwnerDisplayName: GvS


问:
Is there a vim command to select pasted text?
I find myself often repeating the following pattern of operations.

I usually go into visual mode, select some lines or block. Then I yank them using y, and paste them using p or P. The next step is to select the pasted text, to replace a variable or function name or change indentation.

I know that I can use gvto reselect the "origin" but what I would like is a similar command to select the "destination".

:help gv mentions :

After using "p" or "P" in Visual mode the text that was put will be selected.

but it is only useful when you are replacing a selection by the content of register, not when you are inserting a whole new block.

答:
I prefer the following simple mapping to Benoit's function

```<code>nnoremap <expr> g<c-v> '`[' . strpart(getregtype(), 0, 1) . '`]'
</code>```

Learn more about expression maps:

```<code>:h :map-expression
</code>```

As @ZyX pointed out the strpart is not needed and can be rewritten as:

```<code>nnoremap <expr> g<c-v> '`[' . getregtype()[0] . '`]'
</code>```

Body:
I prefer the following simple mapping to Benoit's function

nnoremap <expr> g<c-v> '`[' . strpart(getregtype(), 0, 1) . '`]'

Learn more about expression maps:

:h :map-expression

As @ZyX pointed out the strpart is not needed and can be rewritten as:

nnoremap <expr> g<c-v> '`[' . getregtype()[0] . '`]'


问:
Making the sidebars\page of even size
So, I'm making a page with 2 simple sidebars, one on the left and one on the right. The problem is, the sidebar have an height depending on its content, same is for the page. So, if the page content is shorter than the sidebar content, it will not display a single rectangle\square but it will display a sidebar rectangle longer than the page. On the other side, if the page content is longer than the sidebar, it will extend the rectangle and also "extends" the sidebar whitespace, but, that whitespace is of the page and not of the sidebar. The struct of the page is like that:</p>

```<code><div id="page">
    <div id="sidebar1">
    </div>
    <div id="sidebar2">
    </div>
    <div id="pageContent">
    </div>
</div>
</code>```

答:
Use display:inline-block; and Width
Demo Here

#sidebar1{
  display:inline-block;
  width:24%;
  background:red;
  height: 300px;
}

#sidebar2{
   display:inline-block;
   width:24%;
    background:blue;
  height: 300px;
}

#pageContent{
   display:inline-block;
   width:50%;
    background:green;
  height: 300px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="page">
    <div id="sidebar1">
    </div>
    <div id="sidebar2">
    </div>
    <div id="pageContent">
    </div>
</div></code>```

Title: Making the sidebars\page of even size

Body:
Use display:inline-block; and Width
Demo Here

#sidebar1{
  display:inline-block;
  width:24%;
  background:red;
  height: 300px;
}

#sidebar2{
   display:inline-block;
   width:24%;
    background:blue;
  height: 300px;
}

#pageContent{
   display:inline-block;
   width:50%;
    background:green;
  height: 300px;
}

<div id="page">
    <div id="sidebar1">
    </div>
    <div id="sidebar2">
    </div>
    <div id="pageContent">
    </div>
</div>


问:
How to define a JSON format for an object with nested generic types?
I have a case class with this definition:

```<code>case class EndpointResponse[A](timestamp: Instant, uuid: UUID, content: A)
</code>```

and

```<code>case class User(id: UUID, username: String, email: String)
</code>```

And a JsonFormat with the following definition:

```<code>trait EndpointsJsonProtocol extends DefaultJsonProtocol {

  implicit def endpointResponseJsonFormat[A: JsonFormat] = new RootJsonFormat[EndpointResponse[A]] {
    val dtFormatter = DateTimeFormatter.ISO_INSTANT

    override def write(response: EndpointResponse[A]): JsValue = response match {
      case _: EndpointResponse[_] => JsObject(
        "timestamp" -> JsString(dtFormatter.format(response.timestamp)),
        "uuid" -> JsString(response.uuid.toString), // note we don't encode to slug on purpose
        "content" -> response.content.toJson
      )
      case x => deserializationError("Deserialization not supported " + x)
    }

    override def read(value: JsValue): EndpointResponse[A] = value match {
      case JsObject(encoded) =>
        value.asJsObject.getFields("timestamp", "uuid", "content") match {
          case Seq(JsString(timestamp), JsString(uuid), content) =>
            EndpointResponse(Instant.from(dtFormatter.parse(timestamp)), UUID.fromString(uuid), content.convertTo[A])
          case x => deserializationError("Unable to deserialize from " + x)
        }
      case x => deserializationError("Unable to deserialize from " + x)
    }
  }

  implicit def userResponseFormat: JsonFormat[User] = jsonFormat3(User.apply)
}
</code>```

/** Singleton of the JsonProtocol */
object EndpointsJsonProtocol extends EndpointsJsonProtocol

Now when I try to convert to json with a simple type as content it works fine.

```<code>EndpointResponse(uuid, user).toJson
</code>```

But when I try it with a nested generic it wont compile.

```<code>val records: List[User] = // not relevant
EndpointResponse(uuid, records).toJson
</code>```

Any idea what I am doing wrong here? Thanks in advance. I have imported the spray.json._ and the my custom protocol so that isn't the issue.

Edit: I wasn't importing the protocol but a class with a similar name. Welcome to programming! :) At least someone maybe can benefit from this.

答: Silly Me, I had imported the wrong type. Once I imported the right type, this works. Hope the code helps someone else. </p>

Body:
I have a case class with this definition:

case class EndpointResponse[A](timestamp: Instant, uuid: UUID, content: A)

and

case class User(id: UUID, username: String, email: String)

And a JsonFormat with the following definition:

trait EndpointsJsonProtocol extends DefaultJsonProtocol {

  implicit def endpointResponseJsonFormat[A: JsonFormat] = new RootJsonFormat[EndpointResponse[A]] {
    val dtFormatter = DateTimeFormatter.ISO_INSTANT

    override def write(response: EndpointResponse[A]): JsValue = response match {
      case _: EndpointResponse[_] => JsObject(
        "timestamp" -> JsString(dtFormatter.format(response.timestamp)),
        "uuid" -> JsString(response.uuid.toString), // note we don't encode to slug on purpose
        "content" -> response.content.toJson
      )
      case x => deserializationError("Deserialization not supported " + x)
    }

    override def read(value: JsValue): EndpointResponse[A] = value match {
      case JsObject(encoded) =>
        value.asJsObject.getFields("timestamp", "uuid", "content") match {
          case Seq(JsString(timestamp), JsString(uuid), content) =>
            EndpointResponse(Instant.from(dtFormatter.parse(timestamp)), UUID.fromString(uuid), content.convertTo[A])
          case x => deserializationError("Unable to deserialize from " + x)
        }
      case x => deserializationError("Unable to deserialize from " + x)
    }
  }

  implicit def userResponseFormat: JsonFormat[User] = jsonFormat3(User.apply)
}

/** Singleton of the JsonProtocol */
object EndpointsJsonProtocol extends EndpointsJsonProtocol

Now when I try to convert to json with a simple type as content it works fine.

EndpointResponse(uuid, user).toJson

But when I try it with a nested generic it wont compile.

val records: List[User] = // not relevant
EndpointResponse(uuid, records).toJson

Any idea what I am doing wrong here? Thanks in advance. I have imported the spray.json._ and the my custom protocol so that isn't the issue.

Edit: I wasn't importing the protocol but a class with a similar name. Welcome to programming! :) At least someone maybe can benefit from this.


问:
Maven clean - delete target folder what leads to unresolved imports
I am generating classes from WSDL using maven apache.cxf plugin. It will generate classes to "target" folder.

I am using these classes in my project (import generated.wsdlclass...) but when I run mvn clean install it will delete target folder completely which leads to unresolved imports in my project and maven will crash regenerating target folder. It complains I have errors in my project (because it deletes my generated classes I was using)...

How should I solve this problem ? At first of all I thought maybe I should tell maven don't delete my generated classes in my target folder but I've read it's against maven policy and it is not good practice to do it. What's the best approach to solve this problem ? How should I generate classes from wsdl and how should I use them ?

Thanks

答:
The classes must be generated before the compile phase. To achieve that bind the maven-plugin to the generate-sources phase.

```<code><plugin>
    <groupId>...</groupId>
    <artifactId>...</artifactId>
    <version>...</version>
    <executions>
        <execution>
            <phase>generate-sources</phase>
            <goals>
                <goal>...</goal>
            </goals>
        </execution>
    </executions>
</plugin>
</code>```

See also the Maven Lifecycle Reference.

Body:
The classes must be generated before the compile phase. To achieve that bind the maven-plugin to the generate-sources phase.

<plugin>
    <groupId>...</groupId>
    <artifactId>...</artifactId>
    <version>...</version>
    <executions>
        <execution>
            <phase>generate-sources</phase>
            <goals>
                <goal>...</goal>
            </goals>
        </execution>
    </executions>
</plugin>

See also the Maven Lifecycle Reference.


问:
Python class and array interaction
So the basic idea is to make a "phonebook" type deal using classes and I'm not sure how it would interact with arrays.

```<code>class Person:
name = None
b_year = None
phone = None
</code>```

So that is supposed to be the base. Then I want to be able to use

```<code>array[0].name #The name of the first person
array[1].phone #Number of the second person etc.
</code>```

What I'm not sure about is how the get this interaction between the two. Any tips would be appreciated.
Thanks in advance!

答:
```<code>class Person:

    def __init__(self, name, b_year, phone):
        self.name = name
        self.b_year = b_year
        self.phone = phone

p1 = Person(name="Jedrzej", b_year="1882", phone="321432555")
p2 = Person(name="Michael", b_year="1282", phone="321432553")
arr = [p1, p2]
print(arr[0].name)
</code>```

This prints Jedrzej for me.

I think you should read about classes in Python, for example here:
http://www.diveintopython.net/object_oriented_framework/defining_classes.html

Title: Python class and array interaction

Body:
So the basic idea is to make a "phonebook" type deal using classes and I'm not sure how it would interact with arrays.

class Person:
name = None
b_year = None
phone = None

So that is supposed to be the base. Then I want to be able to use

array[0].name #The name of the first person
array[1].phone #Number of the second person etc.

What I'm not sure about is how the get this interaction between the two. Any tips would be appreciated.
Thanks in advance!

Body:
class Person:

    def __init__(self, name, b_year, phone):
        self.name = name
        self.b_year = b_year
        self.phone = phone

p1 = Person(name="Jedrzej", b_year="1882", phone="321432555")
p2 = Person(name="Michael", b_year="1282", phone="321432553")
arr = [p1, p2]
print(arr[0].name)

This prints Jedrzej for me.

I think you should read about classes in Python, for example here:
http://www.diveintopython.net/object_oriented_framework/defining_classes.html


问:
problems between database and website. I can't access my website
I uploaded online all my prestashop website files and database but when I try to open the website I get this error  "Link to database cannot be established: SQLSTATE[28000] [1045] Access denied for user 'lt27mhfc_dkddb'@'localhost' (using password: YES)".

I read somewhere on-line that when you upload the website files and the database the connection between those gets lost so I modified the setting.inc.php file changing db_name, db_user, db_password to match my new credentials.

I made a second new user and I choose a second new password and I even tried with those, the strange thing is that the message stays the same instead of saying “…for user newuser@’localhost’…”; like I never changed the user and password the second time.

I am working online with cpanel.

Can anyone help?

答:
so i solved it,
i moved all the website files in the root folder which is "public_html" (it's not a must step, you can have those files where you want)

i modified these voices in the table ps_shop_url in the database connected to my website:

domain: www.example.com

domain ssl: www.example.com

phisical uri: the name of the foler in which you have your website; mine was the root folder so i wrote "/"

saved and now it works


问:
Why coroutine stops working/executing
I have a 3 second countdown timer which is activated when game is unpaused.
I had it working correctly a couple of days ago but now it doesn't work anymore. It gets blocked on the number 3. This is the code:

```<code>IEnumerator Timer() {

    Time.timeScale = 0;

    objectWithGSScript.scoreText.fontSize = 300;

    objectWithGSScript.scoreText.text = "" + 3;
    yield return WaitOneSecond();

    objectWithGSScript.scoreText.text = "" + 2;
    yield return WaitOneSecond();

    objectWithGSScript.scoreText.text = "" + 1;
    yield return WaitOneSecond();

    objectWithGSScript.scoreText.text = "Go!";
    yield return WaitOneSecond();

    Time.timeScale = 1f;

    objectWithGSScript.scoreText.text = objectWithGSScript.score.ToString();

}

IEnumerator WaitOneSecond() {
    float start = Time.realtimeSinceStartup;
    while (Time.realtimeSinceStartup < start + 1f) {
        print("entered");
        yield return null;
    }
}
</code>```

It prints "entered" only once, it seems it exit from the coroutine, like it's returning null forever.

What could be the problem?

Any help would be appreciated.

答:
The function in your code is perfectly fine. No, it does not and should not stop at the number 3.

These are the possible reasons why it is behaving like it is getting stopped at the number 3.

1.You are calling StopCoroutine or or StopAllCoroutines. Please check that you are not stopping the coroutines. If you are when it is running, then it will behave this way.

2.You are destroying the script or GameObject this script is attached to. Check where you call the Destroy(gameObject);, Destroy(this); or something similar. If the script is destroyed, the coroutine should stop running.

Remember that you can destroy a script from another script so check all scripts.

3.You disabled the GameObject that his script is attached to. When you disable a GameObject, the coroutine stops working. Check that you don't have  gameObject.SetActive(false); or anything with SetActive(false); that disables that GameObject.

4.If you have a coroutine function in ScriptA and then starts that coroutine from ScriptB, if you destroy ScriptB, the coroutine from ScriptA will freeze at the yield return statement. It is important that you know this.

5. Null problem...

Maybe the objectWithGSScript.scoreText.text is not null. You must check each variable and make sure that they are not null. The if stametement is fine but a good shortcut is this:

```<code>UnityEngine.Debug.Log(objectWithGSScript);
UnityEngine.Debug.Log(objectWithGSScript.scoreText);
UnityEngine.Debug.Log(objectWithGSScript.scoreText.text);
</code>```

then you can do:

```<code>objectWithGSScript.scoreText.fontSize = 300;
objectWithGSScript.scoreText.text = "" + 3;
</code>```

I can't think of any other possible reason why this is happening but check all those five things mentioned above.

Title: Why coroutine stops working/executing

Body:
I have a 3 second countdown timer which is activated when game is unpaused.
I had it working correctly a couple of days ago but now it doesn't work anymore. It gets blocked on the number 3. This is the code:

IEnumerator Timer() {

    Time.timeScale = 0;

    objectWithGSScript.scoreText.fontSize = 300;

    objectWithGSScript.scoreText.text = "" + 3;
    yield return WaitOneSecond();

    objectWithGSScript.scoreText.text = "" + 2;
    yield return WaitOneSecond();

    objectWithGSScript.scoreText.text = "" + 1;
    yield return WaitOneSecond();

    objectWithGSScript.scoreText.text = "Go!";
    yield return WaitOneSecond();

    Time.timeScale = 1f;

    objectWithGSScript.scoreText.text = objectWithGSScript.score.ToString();

}

IEnumerator WaitOneSecond() {
    float start = Time.realtimeSinceStartup;
    while (Time.realtimeSinceStartup < start + 1f) {
        print("entered");
        yield return null;
    }
}

It prints "entered" only once, it seems it exit from the coroutine, like it's returning null forever.

What could be the problem?

Any help would be appreciated.

Body:
The function in your code is perfectly fine. No, it does not and should not stop at the number 3.

These are the possible reasons why it is behaving like it is getting stopped at the number 3.

1.You are calling StopCoroutine or or StopAllCoroutines. Please check that you are not stopping the coroutines. If you are when it is running, then it will behave this way.

2.You are destroying the script or GameObject this script is attached to. Check where you call the Destroy(gameObject);, Destroy(this); or something similar. If the script is destroyed, the coroutine should stop running.

Remember that you can destroy a script from another script so check all scripts.

3.You disabled the GameObject that his script is attached to. When you disable a GameObject, the coroutine stops working. Check that you don't have  gameObject.SetActive(false); or anything with SetActive(false); that disables that GameObject.

4.If you have a coroutine function in ScriptA and then starts that coroutine from ScriptB, if you destroy ScriptB, the coroutine from ScriptA will freeze at the yield return statement. It is important that you know this.

5. Null problem...

Maybe the objectWithGSScript.scoreText.text is not null. You must check each variable and make sure that they are not null. The if stametement is fine but a good shortcut is this:

UnityEngine.Debug.Log(objectWithGSScript);
UnityEngine.Debug.Log(objectWithGSScript.scoreText);
UnityEngine.Debug.Log(objectWithGSScript.scoreText.text);

then you can do:

objectWithGSScript.scoreText.fontSize = 300;
objectWithGSScript.scoreText.text = "" + 3;

I can't think of any other possible reason why this is happening but check all those five things mentioned above.


问:
missing ionic bash commands
I am not sure if this is the right place to ask this, I have an ionic 2 project that I have compiled and run many times using ionic serve and ionic run.

However, the next day after pulling my latest codes from github, I could not run any ionic/npm commands anymore. It will show bash: ionic command not found. I am pulling from a windows environment to OSX.

I do not think this as a possibility but is there any chance that pulling my code base actually messes with anything on my command line?

Cheers

答: I am still not sure why this is happening and my deadline is holding my curiosity back. But for those who have the same issue, search for clean uninstall and reinstall node and nvm. </p>

Title: missing ionic bash commands


问:
List all files changed in a pull request in Git/GitHub
Is there a way (from the command line) to list the names of all files changed in a PR in Git/GitHub? This would be used to find what tests need to be run in a Travis CI build for that PR.

The CI build runs these commands before it calls our script:

```<code>git clone --depth=50 git://github.com/jekyll/jekyll.git jekyll/jekyll
cd jekyll/jekyll
git fetch origin +refs/pull/2615/merge
git checkout -qf FETCH_HEAD
</code>```

答:
Google search sent me here though it is slightly different question.

This question [details] has command-line.
However, I needed the list of files, its ok if I can see in GUI

Here a way to see list of files in GUI:

open the pull request

click on the [Files changed] tab

Conversation 0   Commits 3   [Files changed] 8

click on drop down after 'n files' in the below line of [Files changed]

Changes from all commits v ... [8 files v] ... +638 −266

(click on the v, drop down, after files in the above line)

Body:
Is there a way (from the command line) to list the names of all files changed in a PR in Git/GitHub? This would be used to find what tests need to be run in a Travis CI build for that PR.

The CI build runs these commands before it calls our script:

git clone --depth=50 git://github.com/jekyll/jekyll.git jekyll/jekyll
cd jekyll/jekyll
git fetch origin +refs/pull/2615/merge
git checkout -qf FETCH_HEAD


问:
AWS reading mysql replicas instances keeps gettin Too Many Connections error
I've purchased a single VPC on AWS and initiated there 6 MySql databases, and foreach one I've created a reading replica, so that I can always run queries on the reading replicas quickly.

Most of the day, my writing instances (original instances) are fully loaded and their CPUs percentage is mostly 99%. However, the reading replicas shows something ~7-10% CPU usage, but sometimes I get an error when I run a service connecting to the reading replica "TOO MANY CONNECTIONS".

I'm not that expert with AWS, but is this happening because the writing replicas are fully loaded and they're on the same VPC?

答:
this happening because the writing replicas are fully loaded and they're on the same VPC?

No, it isn't.  This is unrelated to replication.  In replication, the replica counts as exactly 1 connection on the master, but replication does not consume any connections on the replica itself.  There is no impact on connections related to the intensity of the total workload from replication.

This issue simply means you have more clients connecting to the replica than are allowed by the parameter group based on your RDS instance type.  Use the query SELECT @@MAX_CONNECTIONS; to see what this limit is.  Use SHOW STATUS LIKE 'THREADS_CONNECTED'; to see how many connections exist currently, and use SHOW PROCESSLIST; (as the administrative user, or any user holding the PROCESS privilege) in order to see what all of these connections are doing.

If many of them show Sleep and have long values in Time (seconds spent in the current state) then the problem is that your application is somehow abandoning connections, rather than properly closing them after use or when they are otherwise no longer needed.