问:
Magento changing block titles

I want to change the titles of the Tabs in the Accordian at the bottom. I no longer want "Additional Info" I want "Product specs"

I also want to change where it says "Related" and have it say "Add A Garage Stop"

Magento 1.9.3.3

答:
Tabs on product page are defined in layout xml

/app/design/frontend/base/default/layout/catalog.xml

```<code>            <block type="catalog/product_view_attributes" name="product.attributes" as="additional" template="catalog/product/view/attributes.phtml">
                <action method="addToParentGroup"><group>detailed_info</group></action>
                <action method="setTitle" translate="value"><value>Additional Information</value></action>
            </block>
</code>```

Related products are defined in template
app/design/frontend/base/default/template/catalog/product/list/related.phtml

```<code><div class="block block-related">
    <div class="block-title">
        <strong><span><?php echo $this->__('Related Products') ?></span></strong>
    </div>
</code>```

if you use custom theme replace base/default with your theme path. If files do not exist in custom theme, you can safely copy them over with same paths

UPDATE

You can use local.xml file of your theme to change tab title

/app/design/frontend/(YOUR THEME PATH)/layout/local.xml

```<code><catalog_product_view>
    <reference name="product.info">
         <remove name="product.attributes"/>
         <block type="catalog/product_view_attributes" name="product.attributes" as="additional" template="catalog/product/view/attributes.phtml">
                <action method="addToParentGroup"><group>detailed_info</group></action>
        <action method="setTitle" translate="value"><value>Product specs</value></action>
        </block>
    </reference>
</catalog_product_view>
</code>```

(will only work if your Theme behaves like default magento theme)

Title: Magento changing block titles

Body:
Tabs on product page are defined in layout xml

/app/design/frontend/base/default/layout/catalog.xml

            <block type="catalog/product_view_attributes" name="product.attributes" as="additional" template="catalog/product/view/attributes.phtml">
                <action method="addToParentGroup"><group>detailed_info</group></action>
                <action method="setTitle" translate="value"><value>Additional Information</value></action>
            </block>

Related products are defined in template
app/design/frontend/base/default/template/catalog/product/list/related.phtml

<div class="block block-related">
    <div class="block-title">
        <strong><span><?php echo $this->__('Related Products') ?></span></strong>
    </div>

if you use custom theme replace base/default with your theme path. If files do not exist in custom theme, you can safely copy them over with same paths

UPDATE

You can use local.xml file of your theme to change tab title

/app/design/frontend/(YOUR THEME PATH)/layout/local.xml

<catalog_product_view>
    <reference name="product.info">
         <remove name="product.attributes"/>
         <block type="catalog/product_view_attributes" name="product.attributes" as="additional" template="catalog/product/view/attributes.phtml">
                <action method="addToParentGroup"><group>detailed_info</group></action>
        <action method="setTitle" translate="value"><value>Product specs</value></action>
        </block>
    </reference>
</catalog_product_view>

(will only work if your Theme behaves like default magento theme)


来源: stackexchange

问:
Can I add a Golang Compiler to Visual Studio Team Services
We are going to use Visual Studio Team Services for a project.  We are using VSTS Git as our repository.  A portion of this project is written in Golang.  We want to enable CI and build/test all code at check in.  I have been learning more about extensions, the build agents and build process within VSTS.  I see in the marketplace there are options for Android, iOS and other platforms (but not GoLang).  Can anyone start me on the path to creating a custom extension or build definition for Golang? How can I create a custom extension to enable automated builds at check-in of GoLang code?  Thanks!</p>

答: As far as I know in order to add the Go compiler you need to setup a private agent or install it on the fly using a build task like the tool installer </p>

ContentLicense: CC BY-SA 3.0


问:
Incorporating one code into another
I have an existing python script which contains a function ('function_1') and some other lines of code that execute function_1 at some point. Lets call this script 'code_a.py'.

I now have another larger script ('code_b.py'). Within this script, I want code_a.py to run in its entirety.

I'm trying to learn what the best way to do this would be.

Obviously, I could just copy and paste the whole of code_a.py into the body of code_b.py - which seems like a terrible way of doing things.

So I was thinking that at the beginning of code_b.py, I could do something like:

```<code>import code_a
</code>```

But as I understand it, that would only import function_1 from code_a. So should I re-write the whole of code_a as a big function, so that it can be imported into code_b?

Or am I thinking about this is the wrong way?

Thanks.

答:
If i understand your problem correctly, you dont want to import function_1 from code_a, you actually want to execute the whole code.

One thing you can do is use the os module in python to execute a shell/cmd command from within code_b.py like so:

```<code>import os
os.system('python code_a.py')
</code>```

Title: Incorporating one code into another

Body:
I have an existing python script which contains a function ('function_1') and some other lines of code that execute function_1 at some point. Lets call this script 'code_a.py'.

I now have another larger script ('code_b.py'). Within this script, I want code_a.py to run in its entirety.

I'm trying to learn what the best way to do this would be.

Obviously, I could just copy and paste the whole of code_a.py into the body of code_b.py - which seems like a terrible way of doing things.

So I was thinking that at the beginning of code_b.py, I could do something like:

import code_a

But as I understand it, that would only import function_1 from code_a. So should I re-write the whole of code_a as a big function, so that it can be imported into code_b?

Or am I thinking about this is the wrong way?

Thanks.

Body:
If i understand your problem correctly, you dont want to import function_1 from code_a, you actually want to execute the whole code.

One thing you can do is use the os module in python to execute a shell/cmd command from within code_b.py like so:

import os
os.system('python code_a.py')


问:
mallocing same variable multiple times in c
Can I malloc the same variable multiple times in a loop, will it get a allocate it a new memory address?

```<code>int* var;
int i;
for(i = 0; i < 5; i++)
{
    var = (int*)malloc(sizeof(int));
}
</code>```

Does this allocate a new space, this is not how I would actually use it, I would use in a situation where the address would be reassigned to a linked list so it could be freed and would not cause a memory address.

答:
Yes this is fine as long as you do something with the variable before reassigning.
And with 'do something' I mean: make a copy of the pointer before reassigning it and call free on that copy later.</p>

Body:
Can I malloc the same variable multiple times in a loop, will it get a allocate it a new memory address?

int* var;
int i;
for(i = 0; i < 5; i++)
{
    var = (int*)malloc(sizeof(int));
}

Does this allocate a new space, this is not how I would actually use it, I would use in a situation where the address would be reassigned to a linked list so it could be freed and would not cause a memory address.


问:
Function return empty dataframe
I would like to make a loop to create a dataframe that gathers the lines of an input dataframe, which have common points.
My problem : When I apply the function, the output dataframe is empty...
yet with a print (output) in the loop, we see that the program works .. I do not understand, i tried to change return position but that doesn't work

Thank you in advance for your help !

```<code>def group (dataframe, identifiant, output):
    for i in range(len(identifiant)):
        ident = identifiant.loc[i,"IDCTV"]
        # print(ident)

        for j in range(len(dataframe)):
            if dataframe.loc[j,"IDCONTREVENANT"] == ident:
                di = dataframe.loc[j, "DATE_INFRACTION"]
                nt = dataframe.loc[j,"NOTRAIN"]
                genre = dataframe.loc[j,"CODEETATCIVIL"]
                age = dataframe.loc[j,"AGE"]
                # print(di, nt, genre, age)

            for k in range(len(dataframe)):
                if k != j :
                    if dataframe.loc[k,"DATE_INFRACTION"] == di and dataframe.loc[k,"NOTRAIN"] == nt:
                        idgroup = dataframe.loc[k,"IDCONTREVENANT"]
                        genreidgroup = dataframe.loc[k,"CODEETATCIVIL"]
                        ageidgroup = dataframe.loc[k,"AGE"]
                        output = output.append({ "IDREF" : ident ,"CODEETATCIVILREF" : genre,"AGEREF" : age ,"IDCTV" : idgroup,"CODEETATCIVILCTV" : genreidgroup,"AGECTV" : ageidgroup}, ignore_index = True)
                        print(output)
    return output

group(df,IDCTV,df_groups)

print(df_groups)
</code>```

答:
I think you want to change

```<code>group(df,IDCTV,df_groups)
</code>```

to

```<code>df_groups = group(df,IDCTV,df_groups)
</code>```

Right now you're calling the group funciton and doing all that calculation, but you're not saving the output anywhere. So when you run print(df_groups) it prints out whatever it was before you called the function.

Title: Function return empty dataframe

Body:
I would like to make a loop to create a dataframe that gathers the lines of an input dataframe, which have common points.
My problem : When I apply the function, the output dataframe is empty...
yet with a print (output) in the loop, we see that the program works .. I do not understand, i tried to change return position but that doesn't work

Thank you in advance for your help !

def group (dataframe, identifiant, output):
    for i in range(len(identifiant)):
        ident = identifiant.loc[i,"IDCTV"]
        # print(ident)

        for j in range(len(dataframe)):
            if dataframe.loc[j,"IDCONTREVENANT"] == ident:
                di = dataframe.loc[j, "DATE_INFRACTION"]
                nt = dataframe.loc[j,"NOTRAIN"]
                genre = dataframe.loc[j,"CODEETATCIVIL"]
                age = dataframe.loc[j,"AGE"]
                # print(di, nt, genre, age)

            for k in range(len(dataframe)):
                if k != j :
                    if dataframe.loc[k,"DATE_INFRACTION"] == di and dataframe.loc[k,"NOTRAIN"] == nt:
                        idgroup = dataframe.loc[k,"IDCONTREVENANT"]
                        genreidgroup = dataframe.loc[k,"CODEETATCIVIL"]
                        ageidgroup = dataframe.loc[k,"AGE"]
                        output = output.append({ "IDREF" : ident ,"CODEETATCIVILREF" : genre,"AGEREF" : age ,"IDCTV" : idgroup,"CODEETATCIVILCTV" : genreidgroup,"AGECTV" : ageidgroup}, ignore_index = True)
                        print(output)
    return output

group(df,IDCTV,df_groups)

print(df_groups)

Body:
I think you want to change

group(df,IDCTV,df_groups)

to

df_groups = group(df,IDCTV,df_groups)

Right now you're calling the group funciton and doing all that calculation, but you're not saving the output anywhere. So when you run print(df_groups) it prints out whatever it was before you called the function.


问:
PostgreSQL 9.2 JDBC driver uses client time zone?
I've run into an interesting challenge using a PostgreSQL database with the PostgreSQL JDBC driver. It seems that the latest version of the driver, 9.2, uses the client time zone when performing date/time matches.

This becomes a problem when the server (JasperReports Server) is set to UTC and the database server is set to US/Eastern.

If I run the following query from a client set to the UTC time zone I get different results using the 9.0 JDBC driver and the 9.2 JDBC driver.

```<code>select now(), extract(timezone FROM now()), current_setting('TIMEZONE'), now()-interval '1 hour' as "1HourAgo"
</code>```

Results using 9.0 JDBC driver:

```<code>now                         date_part   current_setting     1HourAgo
2013-08-26 15:33:57.590089  -14,400     US/Eastern          2013-08-26 14:33:57.590089
</code>```

Results using 9.2 JDBC driver:

```<code>now                         date_part   current_setting     1HourAgo
2013-08-26 15:41:49.067903  0           UTC                 2013-08-26 14:41:49.067903
</code>```

This is causing a WHERE statement in a query to return incorrect results. For example,

```<code>WHERE end_time between now() - interval '1 hour' and now()
</code>```

works as expected using the 9,0 driver but returns no results using the 9,2 driver as the driver appears to be offsetting the value of end_time to match UTC (the client's time zone). The following is a workaround, but an ugly one:

```<code>WHERE end_time at time zone 'EDT' between now() - interval '1 hour' and now()
</code>```

Questions:

Has anyone else run across this before?

Is there an explanation for this change in behavior? I haven't been able to find anything in the JDBC release notes

Any advice on how to work around this other than rolling back the driver to an older version?

Thanks!

答:
Just in case others struggle with this - you can edit the "conf" file that launches SQLDeveloper and add the following line :

```<code>AddVMOption -Duser.timezone=UTC
</code>```

I found this file on my machine at :

```<code>/opt/sqldeveloper/ide/bin/ide.conf
</code>```

Thanks to @a_horse_with_no_name for pointing me in the right direction with a comment in one of the other answers

Body:
I've run into an interesting challenge using a PostgreSQL database with the PostgreSQL JDBC driver. It seems that the latest version of the driver, 9.2, uses the client time zone when performing date/time matches.

This becomes a problem when the server (JasperReports Server) is set to UTC and the database server is set to US/Eastern.

If I run the following query from a client set to the UTC time zone I get different results using the 9.0 JDBC driver and the 9.2 JDBC driver.

select now(), extract(timezone FROM now()), current_setting('TIMEZONE'), now()-interval '1 hour' as "1HourAgo"

Results using 9.0 JDBC driver:

now                         date_part   current_setting     1HourAgo
2013-08-26 15:33:57.590089  -14,400     US/Eastern          2013-08-26 14:33:57.590089

Results using 9.2 JDBC driver:

now                         date_part   current_setting     1HourAgo
2013-08-26 15:41:49.067903  0           UTC                 2013-08-26 14:41:49.067903

This is causing a WHERE statement in a query to return incorrect results. For example,

WHERE end_time between now() - interval '1 hour' and now()

works as expected using the 9,0 driver but returns no results using the 9,2 driver as the driver appears to be offsetting the value of end_time to match UTC (the client's time zone). The following is a workaround, but an ugly one:

WHERE end_time at time zone 'EDT' between now() - interval '1 hour' and now()

Questions:

Has anyone else run across this before?

Is there an explanation for this change in behavior? I haven't been able to find anything in the JDBC release notes

Any advice on how to work around this other than rolling back the driver to an older version?

Thanks!

Body:
Just in case others struggle with this - you can edit the "conf" file that launches SQLDeveloper and add the following line :

AddVMOption -Duser.timezone=UTC

I found this file on my machine at :

/opt/sqldeveloper/ide/bin/ide.conf

Thanks to @a_horse_with_no_name for pointing me in the right direction with a comment in one of the other answers


问:
C++ bool returns 0 1 instead of true false
I have overloaded equals (including == and !=) that checks if two objects are equals and then returns a boolean.

Unfortunately, it prints 0 or 1. I know it's correct but I can't figure out the way to make it to print true or false for readability purposes.

I've even tried:

```<code>if (a.equals(b))
{
    return true;
}

return false;
</code>```

However, C++ is stubborn enough to output 0 or 1.

Any help would be appreciated.

Edit - Print is done:

```<code>cout << "a == b is " << (a == b) << endl;
</code>```

Desired output is

a == b is true

答:
If you need to do this outside of a stream output <<, it's a simple ternary expression:

```<code>std::string str = (a == b) ? "true" : "false";
</code>```

Body:
I have overloaded equals (including == and !=) that checks if two objects are equals and then returns a boolean.

Unfortunately, it prints 0 or 1. I know it's correct but I can't figure out the way to make it to print true or false for readability purposes.

I've even tried:

if (a.equals(b))
{
    return true;
}

return false;

However, C++ is stubborn enough to output 0 or 1.

Any help would be appreciated.

Edit - Print is done:

cout << "a == b is " << (a == b) << endl;

Desired output is

a == b is true

Body:
If you need to do this outside of a stream output <<, it's a simple ternary expression:

std::string str = (a == b) ? "true" : "false";


问:
Unicode data over socket in C# client & C++ server
I have a C# client and a C++ server. I am sending a user's facebook name via sockets. I write the length of the name at the beginning. For example:
05/*sizeofname*/ getbytes("asdfg")
 I dont get an error. But if I try to do this:
05/*size of name*/ getbytes("İasdf"), it reads only İasd
because İ has two bytes. But other letters have 1 byte. I dont know how to read it correctly in the C++ server.

Server C++:

```<code>byte firstlen = packet.byteread();
                if (firstlen >= 150 || firstlen <= 0) { printf("first %d came\n", firstlen); goto hataver; }
                char * firstname = new char[firstlen];
                firstname = (char*)packet.charread(firstlen);
                printf("income firstname = %s\n", firstname);

char * charread(int idlen)
{
    char * retarray = new char[idlen];
    memcpy(retarray, buffs + marker, idlen);
    marker += idlen;
    retarray[idlen] = 0;
    return retarray;
}
</code>```

Client C#

```<code>yenisi.eklestrlen(firstname, (byte)sizeof(profile.FirstName)); //(byte)firstname.Length);

    public void eklestrlen(string eklenecek,byte uzunluk)
    {
        ekle1(uzunluk);
        ekles(eklenecek);
    }

    public void ekle1(byte eklenecek)
    {
        Paket2[marker] = eklenecek;
        marker++;// eklenecek.Length;
    }

    public void ekles(string eklenecek2)
    {
        byte[] eklenecek = Encoding.UTF8.GetBytes(eklenecek2);
        Array.Copy(eklenecek, 0, Paket2, marker, eklenecek.Length);
        marker += eklenecek.Length;

    }
</code>```

答:
If "İ" has two bytes and the others have one, you're most likely encoding the string value using UTF8 encoding.

You don't share enough of your C++/C# code to know what's exactly going on. On the C side, you should be able to use strlen to get the size of your string.

On the C# side, you can use Encoding.UTF8.GetByteCount and Encoding.UTF8.GetBytes to convert from a string to a byte array, and Encoding.UTF8.GetString to convert from a byte array to a string.

Body:
I have a C# client and a C++ server. I am sending a user's facebook name via sockets. I write the length of the name at the beginning. For example:
05/*sizeofname*/ getbytes("asdfg")
 I dont get an error. But if I try to do this:
05/*size of name*/ getbytes("İasdf"), it reads only İasd
because İ has two bytes. But other letters have 1 byte. I dont know how to read it correctly in the C++ server.

Server C++:

byte firstlen = packet.byteread();
                if (firstlen >= 150 || firstlen <= 0) { printf("first %d came\n", firstlen); goto hataver; }
                char * firstname = new char[firstlen];
                firstname = (char*)packet.charread(firstlen);
                printf("income firstname = %s\n", firstname);

char * charread(int idlen)
{
    char * retarray = new char[idlen];
    memcpy(retarray, buffs + marker, idlen);
    marker += idlen;
    retarray[idlen] = 0;
    return retarray;
}

Client C#

yenisi.eklestrlen(firstname, (byte)sizeof(profile.FirstName)); //(byte)firstname.Length);

    public void eklestrlen(string eklenecek,byte uzunluk)
    {
        ekle1(uzunluk);
        ekles(eklenecek);
    }

    public void ekle1(byte eklenecek)
    {
        Paket2[marker] = eklenecek;
        marker++;// eklenecek.Length;
    }

    public void ekles(string eklenecek2)
    {
        byte[] eklenecek = Encoding.UTF8.GetBytes(eklenecek2);
        Array.Copy(eklenecek, 0, Paket2, marker, eklenecek.Length);
        marker += eklenecek.Length;

    }


问:
Java code style for open stream try/finally block
This is a code style question.  I notice much example code including some examples from Oracle ensure that a stream is closed in the following manner:

```<code>InputStream in = null;
try {
    in = acquireStream();
    ...
} finally {
    if (in != null) in.close();
}
</code>```

Note the initialization to null and check for null in the finally block.

I tend to write code like this:

```<code>InputStream in = acquireStream();
try {
    ...
} finally {
    in.close();
}
</code>```

Are there advantages or disadvantages to either approach?  I like my style because I don't need the null check.  Also I like to avoid null when possible.  But since the Oracle style is so common in online examples, I'm wondering if mine has some hidden error.

I ask the same question for InputStream, OutputStream, java.sql.Connection, java.sql.PreparedStatement, etc.  I tend to acquired the resource outside the try block and then close it in finally without a null check.  Is there anything I am missing other than stylistic differences?

Thanks.

答:
I think it's safer to acquire the stream within the try block.

There's another option for closing - instead of checking for null you can do the following:

```<code>finally {
    IOUtils.closeQuietly(in);
}
</code>```

This does require Apache Commons-IO to do this, but it will do the null check for you.  It's also a nice way stylistically to do this.

ContentLicense: CC BY-SA 2.5

Body:
This is a code style question.  I notice much example code including some examples from Oracle ensure that a stream is closed in the following manner:

InputStream in = null;
try {
    in = acquireStream();
    ...
} finally {
    if (in != null) in.close();
}

Note the initialization to null and check for null in the finally block.

I tend to write code like this:

InputStream in = acquireStream();
try {
    ...
} finally {
    in.close();
}

Are there advantages or disadvantages to either approach?  I like my style because I don't need the null check.  Also I like to avoid null when possible.  But since the Oracle style is so common in online examples, I'm wondering if mine has some hidden error.

I ask the same question for InputStream, OutputStream, java.sql.Connection, java.sql.PreparedStatement, etc.  I tend to acquired the resource outside the try block and then close it in finally without a null check.  Is there anything I am missing other than stylistic differences?

Thanks.

Body:
I think it's safer to acquire the stream within the try block.

There's another option for closing - instead of checking for null you can do the following:

finally {
    IOUtils.closeQuietly(in);
}

This does require Apache Commons-IO to do this, but it will do the null check for you.  It's also a nice way stylistically to do this.


问:
There's a way to add a row in SQLite Cursor in Android to use as separator?
The problem is that I want to build a RecyclerView with sections, so for my specific case it would be good to have a "fake" row in the cursor with the category, and the other rows after it, and so on.

It's possible to do something like this?

I'm not very skilled in SQLite.

答:
It's possible to do something like this?

Not very easily. You could create a CursorWrapper that manages your fake rows, wrapping your real Cursor.

IMHO, it would be simpler to use an existing library for section headers (e.g., this one, this one, or others in the Android Arsenal RecyclerView category), or implement headers yourself, as I show in this sample app.


问:
AWS CodeDeploy Most Recent Revision
I am using AWS CLI for CodeDeploy.
CodeDeploy is not deploying the most recent revision, instead it is deploying the last revision I manually deployed.

I have left the version and etag out of my cli command. As per the documentation:

(Optional) The Amazon S3 version identifier for the revision. (If the
  version identifier is not specified, AWS CodeDeploy will use the most
  recent version.)

```<code>aws deploy create-deployment --application-name MyApp --deployment-config-name CodeDeployDefault.OneAtATime --deployment-group-name MyAppGroup --description "My App" --s3-location bucket=MyAppBucket,bundleType=zip,key=MyApp.zip
</code>```

But it is not working. Any ideas? Is there a way to specifically enforce CodeDeploy to use the latest revision?

There is the S3 lifecycle to make sure the older versions are removed, but that is a hack at best. There needs to be an overwrite, or simply a way to force this.

答:
By default, if you don't specify the version identifier when creating a deployment, CodeDeploy will try to deploy the latest revision by default according to http://docs.aws.amazon.com/codedeploy/latest/userguide/deployments-create-cli.html. But do you know how long do you create a deployment after push the new revision to S3?

Thanks,
Binbin

Title: AWS CodeDeploy Most Recent Revision

Body:
I am using AWS CLI for CodeDeploy.
CodeDeploy is not deploying the most recent revision, instead it is deploying the last revision I manually deployed.

I have left the version and etag out of my cli command. As per the documentation:

(Optional) The Amazon S3 version identifier for the revision. (If the
  version identifier is not specified, AWS CodeDeploy will use the most
  recent version.)

aws deploy create-deployment --application-name MyApp --deployment-config-name CodeDeployDefault.OneAtATime --deployment-group-name MyAppGroup --description "My App" --s3-location bucket=MyAppBucket,bundleType=zip,key=MyApp.zip

But it is not working. Any ideas? Is there a way to specifically enforce CodeDeploy to use the latest revision?

There is the S3 lifecycle to make sure the older versions are removed, but that is a hack at best. There needs to be an overwrite, or simply a way to force this.


问:
ways of resetting Tic Tac Toe in a different component
I'm creating a Tic Tac Toe board in React. I'm trying to rest the board when a person clicks on the rest button that's in my app component. I'm trying to figure out whats the best approach dealing with this situation. I have been reading about uplifting, but if there is an easier way any suggestion would be helpful.
here is my code </p>

```<code>let data = {
    "box":[
        [ "", "", "" ],
        [ "", "", "" ],
        [ "", "", "" ]
    ],
    "players": ['X','O']

}

class DataStore {
    constructor(data, players) {
        //store that data in the object
        this.data = data;
        this.players = players;
        //empty array for our watchers
        //watchers are objects that want to be informed about when the data changes
        this.registeredWatchers = [];
    }
    //add a new watcher to the list
    register(watcher) {
        this.registeredWatchers.push(watcher);
    }
    setCrop(newDataState, row, col) {
        //update data
        this.data[row][col] = newDataState;
        //inform all watching objects..
        this.registeredWatchers.map((watcher) => {
            watcher.dataUpdated();
        })
    }
}
class Dispatcher {
    constructor() {
        this.registeredHandlers = []; //D:
    }
    register(callback) {
        this.registeredHandlers.push(callback);
    }
    dispatch(action) {
        //call every method in our registered handlers array
        //with this action as an input
        this.registeredHandlers.map((handler) => {
            //call that individual function in the array..
            handler(action);
        })
    }
}
class BoxComponent extends React.Component {
    render() {
        return (
            <div
                className="box"
                onClick={this.handleClick.bind(this)}>
                <span>{this.props.type}</span>
            </div>);
    }
    handleClick() {
        //try a test dispatch
        if(this.props.type.length > 0) {
            return false;
        } else {
            boxDispatcher.dispatch({ type: "pick", row: this.props.rowNum, col: this.props.colNum});
        }
    }
}
class GridComponent extends React.Component {
    constructor(props) {
        //make sure this stays a react component
        super(props);
        this.state = {
            turn: boxDataStore.players[0],
            box: this.props.box
        }
        //ensure we're listening to the data store
        boxDataStore.register(this);
    }
    dataUpdated() {
        this.setState(prevState => ({
            box: boxDataStore.data,
            // turn: cropDataStore.players,
            turn: prevState.turn === 'X'
                ? boxDataStore.players[1]
                : boxDataStore.players[0]
        }))
    }
    render() {
        return(
            <div>
                {
                    //loop through all the  rows...
                    this.state.box.map((row, rowNum) => {
                        //and write them out to the page..
                        return (<div className="row">
                            {
                                row.map((cropEntry, colNum) => {
                                    return <BoxComponent type={cropEntry} rowNum={rowNum} colNum={colNum} turn={rowNum}/>
                                })
                            }
                        </div>);
                    })
                }
            </div>
        )
    }
}
class App extends React.Component {
    render() {
        return (
            <div>
                <h1>Tic Tac Toe </h1>

                <button onClick={this.resetBoard.bind(this)}>reset</button>
                <GridComponent box={this.props.data}/>
            </div>
        );
    }
    resetBoard() {

    }
}
//start of app
var boxDispatcher = new Dispatcher();
var boxDataStore = new DataStore(data.box, data.players);
boxDispatcher.register((action) => {
    if(boxDataStore.registeredWatchers["0"].state.turn == "X") {
        //actually waint to handle it

        boxDataStore.setCrop('X', action.row, action.col);
    } else {
        boxDataStore.setCrop('O', action.row, action.col);
    }

})
</code>```

答:
If you are reading about lifting state up you might have already read the page of the React official documentation that talks about it.

There should be a single “source of truth” for any data that changes in a React application. Usually, the state is first added to the component that needs it for rendering. Then, if other components also need it, you can lift it up to their closest common ancestor. Instead of trying to sync the state between different components, you should rely on the top-down data flow.

Basically, if you don't lift your state up, it's more difficult to maintain the single source of truth because you have to sync both states and it just doesn't feel right. I don't think there is "an easier way" to do that since it can cause you a lot of side effects.

ContentLicense: CC BY-SA 4.0

Body:
I'm creating a Tic Tac Toe board in React. I'm trying to rest the board when a person clicks on the rest button that's in my app component. I'm trying to figure out whats the best approach dealing with this situation. I have been reading about uplifting, but if there is an easier way any suggestion would be helpful.
here is my code

let data = {
    "box":[
        [ "", "", "" ],
        [ "", "", "" ],
        [ "", "", "" ]
    ],
    "players": ['X','O']

}

class DataStore {
    constructor(data, players) {
        //store that data in the object
        this.data = data;
        this.players = players;
        //empty array for our watchers
        //watchers are objects that want to be informed about when the data changes
        this.registeredWatchers = [];
    }
    //add a new watcher to the list
    register(watcher) {
        this.registeredWatchers.push(watcher);
    }
    setCrop(newDataState, row, col) {
        //update data
        this.data[row][col] = newDataState;
        //inform all watching objects..
        this.registeredWatchers.map((watcher) => {
            watcher.dataUpdated();
        })
    }
}
class Dispatcher {
    constructor() {
        this.registeredHandlers = []; //D:
    }
    register(callback) {
        this.registeredHandlers.push(callback);
    }
    dispatch(action) {
        //call every method in our registered handlers array
        //with this action as an input
        this.registeredHandlers.map((handler) => {
            //call that individual function in the array..
            handler(action);
        })
    }
}
class BoxComponent extends React.Component {
    render() {
        return (

                {this.props.type}

);
    }
    handleClick() {
        //try a test dispatch
        if(this.props.type.length > 0) {
            return false;
        } else {
            boxDispatcher.dispatch({ type: "pick", row: this.props.rowNum, col: this.props.colNum});
        }
    }
}
class GridComponent extends React.Component {
    constructor(props) {
        //make sure this stays a react component
        super(props);
        this.state = {
            turn: boxDataStore.players[0],
            box: this.props.box
        }
        //ensure we're listening to the data store
        boxDataStore.register(this);
    }
    dataUpdated() {
        this.setState(prevState => ({
            box: boxDataStore.data,
            // turn: cropDataStore.players,
            turn: prevState.turn === 'X'
                ? boxDataStore.players[1]
                : boxDataStore.players[0]
        }))
    }
    render() {
        return(

                {
                    //loop through all the  rows...
                    this.state.box.map((row, rowNum) => {
                        //and write them out to the page..
                        return (

                            {
                                row.map((cropEntry, colNum) => {
                                    return <BoxComponent type={cropEntry} rowNum={rowNum} colNum={colNum} turn={rowNum}/>
                                })
                            }

);
                    })
                }

        )
    }
}
class App extends React.Component {
    render() {
        return (

Tic Tac Toe

                <button onClick={this.resetBoard.bind(this)}>reset</button>
                <GridComponent box={this.props.data}/>

        );
    }
    resetBoard() {

    }
}
//start of app
var boxDispatcher = new Dispatcher();
var boxDataStore = new DataStore(data.box, data.players);
boxDispatcher.register((action) => {
    if(boxDataStore.registeredWatchers["0"].state.turn == "X") {
        //actually waint to handle it

        boxDataStore.setCrop('X', action.row, action.col);
    } else {
        boxDataStore.setCrop('O', action.row, action.col);
    }

})


问:
Mesosphere DC/OS community license
It is legal to use DC/OS community in commercial usage? I cannot decide (set focus for learning) what to use -- Mesos or DC/OS.
Also what pros and cons DC/OS community edition versus Mesos?</p>

答:
There isn't a formal "Community Edition" these days, there's the standard open source version and an Enterprise version which is sold with a license.

The open source version is Apache-licensed and perfectly fine to be used commercially.

Title: Mesosphere DC/OS community license


问:
Need to design a table with loads of attributes which must all be searchable by SQL
I'm in a fix here. I'm building a home reservation site and the client requires a filter search facility to allow visitors to search and filter through properties based upon criteria. The thing is that his list of criteria is exceedingly long, largely boolean values and calculable values stuff like:

Attached bathroom, balcony, smoking, alcoholic, maximum number of occupants, cable TV, Internet, carpeted, airconditioning, central heating, room service, etc., etc., etc...

I'm thinking of having to create a field for each of these, but there's a very strong chance that the number of preferences might even go up. I dished out the idea of storing everying in a serialised object as a string as then it would be impossible to search using an SQL query. Do I have any options apart from setting up individual fields for each preference here?

Thanks. I'm using PHP MySQL.

答: You should read up on database normalization. IMHO the goal is to structure your tables in such a way that allow these queries to be run efficiently and with less logic on the php side. For example, if each of the above mentioned search criteria have a value associated with them, the values should be stored in a separate table, and if there are many options to many values, you will need to setup a different type of relationship. This initial time looking at the database from all angles will save you a lot of make-shift php code and possible prevent an entire rebuild of the database once you realized you've bottlenecked. Hope this was at all helpful. Good luck!</p>


问:
Difference between () and $()
What's the difference between

```<code>Write-Host (Get-Date) # just paren
</code>```

and

```<code>Write-Host $(Get-Date) # dollar-paren
</code>```

Content within the parens could be anything, just going with a simple example. Is there any difference between the two?

I consider myself reasonably experienced with PS, but it's these little things that bug me, especially during code review and the like. Has anyone come across a good source for "here is how the language works" with enough detail to derive answers to these sorts of questions?

答:
Parenthesis are used to group and establish order just as they do in mathematics. Starting in PowerShell v3 you can also use them to evaluate a property of a group, such as getting the file names for the files in the current folder by running:

```<code>(Get-ChildItem).Name
</code>```

A sub-expression $() evaluates the script within it, and then presents the output of that to be used in the command. Often times used within strings to expand a property of an object such as:

```<code>"Hello $($User.Name), would you like to play a game?"
</code>```

It can also be useful when working with ComObjects, such as Excel where you may have a range that you want to test against a property of each item. While this does not work because the Range object does not have a Font property:

```<code>$Range.Font|Where{$_.Bold}
</code>```

This would work, because it would output the Range as a collection of Cell objects, each of which have a Font property:

```<code>$($Range).Font|Where{$_.Bold}
</code>```

You can think of sub-expressions as being a script within your script, since they can be several commands long, and the entire thing is evaluated at once so that the end output can be used for the parent command.

Title: Difference between () and $()

Body:
What's the difference between

Write-Host (Get-Date) # just paren

and

Write-Host $(Get-Date) # dollar-paren

Content within the parens could be anything, just going with a simple example. Is there any difference between the two?

I consider myself reasonably experienced with PS, but it's these little things that bug me, especially during code review and the like. Has anyone come across a good source for "here is how the language works" with enough detail to derive answers to these sorts of questions?

Body:
Parenthesis are used to group and establish order just as they do in mathematics. Starting in PowerShell v3 you can also use them to evaluate a property of a group, such as getting the file names for the files in the current folder by running:

(Get-ChildItem).Name

A sub-expression $() evaluates the script within it, and then presents the output of that to be used in the command. Often times used within strings to expand a property of an object such as:

"Hello $($User.Name), would you like to play a game?"

It can also be useful when working with ComObjects, such as Excel where you may have a range that you want to test against a property of each item. While this does not work because the Range object does not have a Font property:

$Range.Font|Where{$_.Bold}

This would work, because it would output the Range as a collection of Cell objects, each of which have a Font property:

$($Range).Font|Where{$_.Bold}

You can think of sub-expressions as being a script within your script, since they can be several commands long, and the entire thing is evaluated at once so that the end output can be used for the parent command.


问:
Getting error while executing python program to get a caller to conference call from twilio server
I wrote a python program as to [Ph Num 1 <-> Twilio Server <-> Ph Num2 ]
[- Send a Message from my ph number (Num 1) containing another phone number(Num 2) to twilio server
- twilio takes the number (Num2) and calls me back (Num1) (saying as you are about to conference) and
- twilio calls the Num 2 and conferences me (Num1)

Here is my program:

```<code>from flask import Flask, request
from twilio import twiml
from twilio.rest import Client

app = Flask(__name__)

account = "AC7d2a***************"
token = "f83b27**************"
client = Client(account, token)

@app.route("/sms", methods=['GET', 'POST'])
def sms():
    number=request.form["From"]

    call= client.calls.create(from_="+1857*******",to=number,url="https://handler.twilio.com/twiml/EHb330731ab2c9a35fcdc620bef1b88536")

    return str(resp)

if __name__=="__main__":
    app.run()
</code>```

The url="https://handler.twilio.com/twiml/EHb330731ab2c9a35fcdc620bef1b88536 contains

```<code><?xml version="1.0" encoding="UTF-8"?>
<Response>
  <Say>You are about to enter a conference</Say>
  <Dial><Conference>number</Conference></Dial>
</Response>
</code>```

i did Ngrok too and added my Ngrok link in Voice and Message URL in twilio number

I tried many changes and getting all kind of error instead of twilio number calling me after sending a message(with Ph Number (Num2) to conference)

Recent error while executing the above code is
Error:

```<code>[2017-11-13 09:46:41,570] ERROR in app: Exception on /sms [POST]
Traceback (most recent call last):
  File "/home/arif/my_app/local/lib/python2.7/site-packages/flask/app.py", line 1982, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/arif/my_app/local/lib/python2.7/site-packages/flask/app.py", line 1614, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/home/arif/my_app/local/lib/python2.7/site-packages/flask/app.py", line 1517, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/home/arif/my_app/local/lib/python2.7/site-packages/flask/app.py", line 1612, in full_dispatch_request
    rv = self.dispatch_request()
  File "/home/arif/my_app/local/lib/python2.7/site-packages/flask/app.py", line 1598, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "conf.py", line 17, in sms
    return str(resp)
NameError: global name 'resp' is not defined
127.0.0.1 - - [13/Nov/2017 09:46:41] "POST /sms HTTP/1.1" 500 -
</code>```

Does my program get the result what i expected ? Can anyone help me where is the issue is ?

答:
Twilio developer evangelist here.

There are a couple of issues here. First up, you are getting an error in your webhook response. You can see the error at the bottom of your stack trace:

```<code>  File "conf.py", line 17, in sms
    return str(resp)
NameError: global name 'resp' is not defined
127.0.0.1 - - [13/Nov/2017 09:46:41] "POST /sms HTTP/1.1" 500 -
</code>```

It says that resp is not defined.

You can see that within your method, you never define a resp but you try to return the str version of it:

```<code>def sms():
    number=request.form["From"]
    call= client.calls.create(from_="+1857*******",to=number,url="https://handler.twilio.com/twiml/EHb330731ab2c9a35fcdc620bef1b88536")
    return str(resp)
</code>```

You can just return an empty string  to Twilio in this case.

```<code>def sms():
    number=request.form["From"]
    call= client.calls.create(from_="+1857*******",to=number,url="https://handler.twilio.com/twiml/EHb330731ab2c9a35fcdc620bef1b88536")
    return ('', 204)
</code>```

Once that is fixed you'll find you are only making one call, the outgoing call back to yourself. To conference with the number that you want to call, you will need to generate two calls. You say that the body of the message that you are sending will be the other number you want to dial into the conference, so this should work:

```<code>def sms():
    my_number=request.form["From"]
    other_number=request.form["Body"]
    twilio_number="+1857*******"
    conference_url="https://handler.twilio.com/twiml/EHb330731ab2c9a35fcdc620bef1b88536"
    client.calls.create(from_=twilio_number,to=my_number,url=conference_url)
    client.calls.create(from_=twilio_number,to=other_number,url=conference_url)
    return ('', 204)
</code>```

Let me know if that helps.

Body:
I wrote a python program as to [Ph Num 1 <-> Twilio Server <-> Ph Num2 ]
[- Send a Message from my ph number (Num 1) containing another phone number(Num 2) to twilio server
- twilio takes the number (Num2) and calls me back (Num1) (saying as you are about to conference) and
- twilio calls the Num 2 and conferences me (Num1)

Here is my program:

from flask import Flask, request
from twilio import twiml
from twilio.rest import Client

app = Flask(__name__)

account = "AC7d2a***************"
token = "f83b27**************"
client = Client(account, token)

@app.route("/sms", methods=['GET', 'POST'])
def sms():
    number=request.form["From"]

    call= client.calls.create(from_="+1857*******",to=number,url="https://handler.twilio.com/twiml/EHb330731ab2c9a35fcdc620bef1b88536")

    return str(resp)

if __name__=="__main__":
    app.run()

The url="https://handler.twilio.com/twiml/EHb330731ab2c9a35fcdc620bef1b88536 contains

<?xml version="1.0" encoding="UTF-8"?>
<Response>
  <Say>You are about to enter a conference</Say>
  <Dial><Conference>number</Conference></Dial>
</Response>

i did Ngrok too and added my Ngrok link in Voice and Message URL in twilio number

I tried many changes and getting all kind of error instead of twilio number calling me after sending a message(with Ph Number (Num2) to conference)

Recent error while executing the above code is
Error:

[2017-11-13 09:46:41,570] ERROR in app: Exception on /sms [POST]
Traceback (most recent call last):
  File "/home/arif/my_app/local/lib/python2.7/site-packages/flask/app.py", line 1982, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/arif/my_app/local/lib/python2.7/site-packages/flask/app.py", line 1614, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/home/arif/my_app/local/lib/python2.7/site-packages/flask/app.py", line 1517, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/home/arif/my_app/local/lib/python2.7/site-packages/flask/app.py", line 1612, in full_dispatch_request
    rv = self.dispatch_request()
  File "/home/arif/my_app/local/lib/python2.7/site-packages/flask/app.py", line 1598, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "conf.py", line 17, in sms
    return str(resp)
NameError: global name 'resp' is not defined
127.0.0.1 - - [13/Nov/2017 09:46:41] "POST /sms HTTP/1.1" 500 -

Does my program get the result what i expected ? Can anyone help me where is the issue is ?

Body:
Twilio developer evangelist here.

There are a couple of issues here. First up, you are getting an error in your webhook response. You can see the error at the bottom of your stack trace:

  File "conf.py", line 17, in sms
    return str(resp)
NameError: global name 'resp' is not defined
127.0.0.1 - - [13/Nov/2017 09:46:41] "POST /sms HTTP/1.1" 500 -

It says that resp is not defined.

You can see that within your method, you never define a resp but you try to return the str version of it:

def sms():
    number=request.form["From"]
    call= client.calls.create(from_="+1857*******",to=number,url="https://handler.twilio.com/twiml/EHb330731ab2c9a35fcdc620bef1b88536")
    return str(resp)

You can just return an empty string  to Twilio in this case.

def sms():
    number=request.form["From"]
    call= client.calls.create(from_="+1857*******",to=number,url="https://handler.twilio.com/twiml/EHb330731ab2c9a35fcdc620bef1b88536")
    return ('', 204)

Once that is fixed you'll find you are only making one call, the outgoing call back to yourself. To conference with the number that you want to call, you will need to generate two calls. You say that the body of the message that you are sending will be the other number you want to dial into the conference, so this should work:

def sms():
    my_number=request.form["From"]
    other_number=request.form["Body"]
    twilio_number="+1857*******"
    conference_url="https://handler.twilio.com/twiml/EHb330731ab2c9a35fcdc620bef1b88536"
    client.calls.create(from_=twilio_number,to=my_number,url=conference_url)
    client.calls.create(from_=twilio_number,to=other_number,url=conference_url)
    return ('', 204)

Let me know if that helps.


问:
Why is the while loop returning false positives?
I'm trying out Python 3 and been doing a practice with a while loop but the loop doesn't end when the variable is set to another value different from the default Y</p>

```<code>#!/usr/bin/python3

elements = [];
copy = [];
rot=0;
op='y';
ap='y';

while op is 'y' or 'Y':

    elements = [];
    a = int(input("How many elements? "));
    for i in range(a):
        elements.append(input("Enter element " + str(i+1) + " "));

    while ap is 'y' or 'Y':
        rot = int(input("How many element to rotate? "));
        print(elements);
        copy = elements[-rot:] + elements[:-rot];
        elements = copy;
        print(elements);
        ap = input("Rotate again? ");

    op = input("Create a new rotatrix? ");
</code>```

答:
The or operator in your test condition is not working as you intend it to. Try this:

```<code>elements = []
copy = []
rot=0
op='y'
ap='y'

while op == 'y' or op == 'Y':

    elements = []
    a = input("How many elements? ")
    for i in range(a):
        elements.append(input("Enter element " + str(i+1) + " "))

    while ap == 'y' or ap == 'Y':
        rot = input("How many element to rotate? ")
        print(elements)
        copy = elements[-rot:] + elements[:-rot]
        elements = copy
        print(elements)
        ap = raw_input("Rotate again? ")

    op = raw_input("Create a new rotatrix? ")
</code>```

Body:
I'm trying out Python 3 and been doing a practice with a while loop but the loop doesn't end when the variable is set to another value different from the default Y

#!/usr/bin/python3

elements = [];
copy = [];
rot=0;
op='y';
ap='y';

while op is 'y' or 'Y':

    elements = [];
    a = int(input("How many elements? "));
    for i in range(a):
        elements.append(input("Enter element " + str(i+1) + " "));

    while ap is 'y' or 'Y':
        rot = int(input("How many element to rotate? "));
        print(elements);
        copy = elements[-rot:] + elements[:-rot];
        elements = copy;
        print(elements);
        ap = input("Rotate again? ");

    op = input("Create a new rotatrix? ");

Body:
The or operator in your test condition is not working as you intend it to. Try this:

elements = []
copy = []
rot=0
op='y'
ap='y'

while op == 'y' or op == 'Y':

    elements = []
    a = input("How many elements? ")
    for i in range(a):
        elements.append(input("Enter element " + str(i+1) + " "))

    while ap == 'y' or ap == 'Y':
        rot = input("How many element to rotate? ")
        print(elements)
        copy = elements[-rot:] + elements[:-rot]
        elements = copy
        print(elements)
        ap = raw_input("Rotate again? ")

    op = raw_input("Create a new rotatrix? ")


问:
How do you properly include a resource folder in a JAR artifact in IntelliJ IDEA?
I have a project that reads graphics and sound effects from a folder labeled res. This folder is at the same directory level as the src folder. I have res marked as Resources Root.

I configured my artifact to include res as a Content Directory by way of
Project Structure -> Artifacts -> Add (Alt + Insert) -> JAR

Then, in the output layout tab, I pressed the Add dropdown box -> Directory Content -> res

When I run the project in Intellij, it finds the resources just fine. Here is a code snippet showing how I access the resources:

```<code>public static final Sfx VOID_SOUND = new Sfx(TinySound.loadSound(new File("res/audio/sfx/void_sound.wav")));
</code>```

However, when I build the standalone artifact, then run the jar, it looks for the resource by prepending the parent directory of my machine to the file path, all the way to root. Here is how the terminal output looks:

```<code>/home/user/Demo/res/audio/sfx/void_sound.wav (No such file or directory)
Error getting resource stream!
</code>```

Is there a way to configure the artifact build to where it looks in the proper place? I want the resources included inside the jar file so it acts as a standalone jar with no external dependencies.

答: I'm not familiar with Linux so please take this with a grain of salt. But to me, it looks like its trying to access the file from where it doesn't have permission.  Have you tried moving the file or directory to a shared location where any user can access it?</p>

Body:
I have a project that reads graphics and sound effects from a folder labeled res. This folder is at the same directory level as the src folder. I have res marked as Resources Root.

I configured my artifact to include res as a Content Directory by way of
Project Structure -> Artifacts -> Add (Alt + Insert) -> JAR

Then, in the output layout tab, I pressed the Add dropdown box -> Directory Content -> res

When I run the project in Intellij, it finds the resources just fine. Here is a code snippet showing how I access the resources:

public static final Sfx VOID_SOUND = new Sfx(TinySound.loadSound(new File("res/audio/sfx/void_sound.wav")));

However, when I build the standalone artifact, then run the jar, it looks for the resource by prepending the parent directory of my machine to the file path, all the way to root. Here is how the terminal output looks:

/home/user/Demo/res/audio/sfx/void_sound.wav (No such file or directory)
Error getting resource stream!

Is there a way to configure the artifact build to where it looks in the proper place? I want the resources included inside the jar file so it acts as a standalone jar with no external dependencies.


问:
Can't get grid area to fill vertical space
I'm trying to use css-grid to create 3 areas, 2 with fixed height and the bottom one to fill the available space with a grid of buttons that also adapt to the space available. The buttons will adapt horizontally but not vertically. Can you see what silly thing I am doing to stop it working?

* {
  margin: 2px 2px 2px 2px;
  padding: 0;
  border: 0;
  outline: 0;
  font-size: 100%;
  vertical-align: middle;
  background: transparent;
  letter-spacing: normal;
}

body {
  color: #00000;
  background-color: #335155
}

p {
  color: #669990;
  font-size: 50px;
  text-decoration: none;
  font-family: sans-serif;
}

p:after {
  content: "";
  display: inline-block;
  width: 0px;
  height: auto;
}

.panel {
  display: grid;
  grid-template-columns: 1fr;
  grid-template-rows: 80px 80px 1fr;
}

.top-panel {
  display: grid;
  grid-template-columns: 60% 1fr 40px;
  grid-template-rows: 80px;
  grid-row-gap: 20px;
  grid-column-gap: 20px;
  padding: 0px 50px 0px 20px;
}

#paragraph-1 {
  text-align: right;
  padding: 0px 10px 0px 0px;
}

#paragraph-2 {
  border-width: 1px;
  border-style: solid;
  border-color: #669990;
  min-height: 75px;
  max-width: 100px;
  padding: 0px 20px 0px 0px;
  text-align: center;
}

#paragraph-3 {
  min-height: 75px;
  max-width: 100px;
  padding: 0px 10px 0px 0px;
  text-align: center;
}

.middle-panel {
  display: grid;
  grid-template-columns: 1fr;
  grid-template-rows: 1fr;
  grid-row-gap: 20px;
}

button {
  width: 100%;
  height: 100%;
  background-color: #669990;
  border: none;
  color: #335155;
  text-align: center;
  text-decoration: none;
  font-size: 20px;
}

button:hover {
  background-color: white;
}

.button-panel {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(4, minmax(20px, 300px);
  grid-row-gap: 10px;
  grid-column-gap: 10px;
  width: 100vw;
  height: 100vh;
}

.grid-position-1-1 {
  grid-column: 1;
  grid-row: 1;
}

.grid-position-2-1 {
  grid-column: 2;
  grid-row: 1;
}

.grid-position-3-1 {
  grid-column: 3;
  grid-row: 1;
}

.grid-position-1-2 {
  grid-column: 1;
  grid-row: 2;
}

.grid-position-2-2 {
  grid-column: 2;
  grid-row: 2;
}

.grid-position-3-2 {
  grid-column: 3;
  grid-row: 2;
}

.grid-position-1-3 {
  grid-column: 1;
  grid-row: 3;
}

.grid-position-2-3 {
  grid-column: 2;
  grid-row: 3;
}

.grid-position-3-3 {
  grid-column: 3;
  grid-row: 3;
}

.grid-position-1-4 {
  grid-column: 1;
  grid-row: 4;
}

.grid-position-2-4 {
  grid-column: 2;
  grid-row: 4;
}

.grid-position-3-4 {
  grid-column: 3;
  grid-row: 4;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="panel">
  <div class="grid-position-1-1">
    <!-- of panel-->
    <div class="top-panel">
      <div class="grid-position-1-1">
        <!-- of top-panel-->
        <p id="paragraph-1"></p>
      </div>
      <div class="grid-position-2-1">
        <!-- of top-panel-->
        <p id="paragraph-2"></p>
      </div>
      <div class="grid-position-3-1">
        <!-- of top-panel-->
        <p id="paragraph-3"></p>
      </div>
    </div>
    <div class="grid-position-2-1">
      <!-- of panel-->
      <div class="middle-panel">
        <p id="another-paragraph"></p>
      </div>
    </div>
    <div class="grid-position-3-1">
      <!-- of panel-->
      <div class="button-panel">
        <div class="grid-position-1-1">
          <!-- of button-panel-->
          <button id="button-1" class="input-button" value=x>x</button>
        </div>
        <div class="grid-position-2-1">
          <button id="button-2" class="input-button" value=x>x</button>
        </div>
        <div class="grid-position-3-1">
          <button id="button-3" class="input-button" value=x>x</button>
        </div>
        <div class="grid-position-1-2">
          <button id="button-4" class="input-button" value=x>x</button>
        </div>
        <div class="grid-position-2-2">
          <button id="button-5" class="input-button" value=x>x</button>
        </div>
        <div class="grid-position-3-2">
          <button id="button-6" class="input-button" value=x>x</button>
        </div>
        <div class="grid-position-1-3">
          <button id="button-7" class="input-button" value=x>x</button>
        </div>
        <div class="grid-position-2-3">
          <button id="button-8" class="input-button" value=x>x</button>
        </div>
        <div class="grid-position-3-3">
          <button id="button-9" class="input-button" value=x>x</button>
        </div>
        <div class="grid-position-1-4">
          <button id="button-10" class="input-button" value=x>x</button>
        </div>
        <div class="grid-position-2-4">
          <button id="button-10" class="input-button" value=x>x</button>
        </div>
        <div class="grid-position-3-4">
          <button id="button-10" class="input-button" value=x>x</button>
        </div>
      </div>
    </div>
  </div></code>```

Amended code as per advice of Michael_B

* {
    margin: 2px 2px 2px 2px;
    padding: 0;
    border: 0;
    outline: 0;
    font-size: 100%;
    vertical-align: middle;
    background: transparent;
    letter-spacing: normal;
}

body {color: #00000; background-color: #335155}

p {
    color: #669990;
    font-size: 50px;
    text-decoration: none;
    font-family: sans-serif;
}

p:after {
    content:"";
    display:inline-block;
    width:0px;
    height:auto;
}
.panel {
    display: grid;
    grid-template-columns: 1fr;
    grid-template-rows: 80px 80px 1fr;
}

.top-panel {
    grid-column: 1;
    grid-row: 1;
    display: grid;
    grid-template-columns: 60% 1fr 40px;
    grid-template-rows: 80px;
    grid-row-gap: 20px;
    grid-column-gap: 20px;
    padding: 0px 50px 0px 20px;
}

#paragraph-1 {
    text-align: right;
    padding: 0px 10px 0px 0px;
}
#paragraph-2 {
    border-width: 1px;
    border-style: solid;
    border-color: #669990;
    min-height: 75px;
    max-width: 100px;
    padding: 0px 20px 0px 0px;
    text-align: center;
}

#paragraph-3 {
    min-height: 75px;
    max-width: 100px;
    padding: 0px 10px 0px 0px;
    text-align: center;
}

.middle-panel {
    grid-column: 1;
    grid-row: 2;
    display: grid;
    grid-template-columns: 1fr;
    grid-template-rows: 1fr;
    grid-row-gap: 20px;
}
button {
    width: 100%;
    height: 100%;
    background-color: #669990;
    border: none;
    color: #335155;
    text-align: center;
    text-decoration: none;
    font-size: 20px;
}
button:hover {
    background-color: white;
}
.button-panel {
    grid-column: 1;
    grid-row: 3;
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-template-rows: repeat(4, 1fr);
    grid-row-gap: 2px;
    grid-column-gap: 2px;
}

.grid-position-1-1 {
    grid-column: 1;
    grid-row: 1;
}
.grid-position-2-1 {
    grid-column: 2;
    grid-row: 1;
}
.grid-position-3-1 {
    grid-column: 3;
    grid-row: 1;
}
.grid-position-1-2 {
    grid-column: 1;
    grid-row: 2;
}
.grid-position-2-2 {
    grid-column: 2;
    grid-row: 2;
}
.grid-position-3-2 {
    grid-column: 3;
    grid-row: 2;
}
.grid-position-1-3 {
    grid-column: 1;
    grid-row: 3;
}
.grid-position-2-3 {
    grid-column: 2;
    grid-row: 3;
}
.grid-position-3-3 {
    grid-column: 3;
    grid-row: 3;
}
.grid-position-1-4 {
    grid-column: 1;
    grid-row: 4;
}
.grid-position-2-4 {
    grid-column: 2;
    grid-row: 4;
}
.grid-position-3-4 {
    grid-column: 3;
    grid-row: 4;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
    <div class="panel">
        <div class="top-panel">
            <div class="grid-position-1-1"><!-- of top-panel-->
                <p id="paragraph-1"></p>
            </div>
            <div class="grid-position-2-1"><!-- of top-panel-->
                <p id="paragraph-2"></p>
            </div>
            <div class="grid-position-3-1"><!-- of top-panel-->
                <p id="paragraph-3"></p>
            </div>
        </div>
        <div class="middle-panel">
            <p id="another-paragraph"></p>
        </div>
        <div class="button-panel">
            <div class="grid-position-1-1"><!-- of button-panel-->
                <button id="button-1" class="input-button" value=x>x</button>
            </div>
            <div class="grid-position-2-1">
                <button id="button-2" class="input-button" value=x>x</button>
            </div>
            <div class="grid-position-3-1">
                <button id="button-3" class="input-button" value=x>x</button>
            </div>
            <div class="grid-position-1-2">
                <button id="button-4" class="input-button" value=x>x</button>
            </div>
            <div class="grid-position-2-2">
                <button id="button-5" class="input-button" value=x>x</button>
            </div>
            <div class="grid-position-3-2">
                <button id="button-6" class="input-button" value=x>x</button>
            </div>
            <div class="grid-position-1-3">
                <button id="button-7" class="input-button" value=x>x</button>
            </div>
            <div class="grid-position-2-3">
                <button id="button-8" class="input-button" value=x>x</button>
            </div>
            <div class="grid-position-3-3">
                <button id="button-9" class="input-button" value=x>x</button>
            </div>
            <div class="grid-position-1-4">
                <button id="button-10" class="input-button" value=x>x</button>
            </div>
            <div class="grid-position-2-4">
                <button id="button-10" class="input-button" value=x>x</button>
            </div>
            <div class="grid-position-3-4">
                <button id="button-10" class="input-button" value=x>x</button>
            </div>
        </div>
    </div>
</body></code>```

Code also https://github.com/rawcane/panel-example

答:
You grid container is set to
:

```<code>.panel {
    display: grid;
    grid-template-columns: 1fr;
    grid-template-rows: 80px 80px 1fr;
}
</code>```

But the three areas you reference in your question:

.top-panel

.grid-position-2-1

.grid-position-3-1

are not children of the grid container. They are grandchildren of .panel.

Therefore, they are not grid items.

The scope of a grid formatting context is limited to the parent-child relationship.

This means that a grid container is always the parent and a grid item is always the child. Grid properties work only within this relationship.

As stated in the spec:

6. Grid
  Items

Each in-flow child of a grid container becomes a grid item.

Descendants of a grid container beyond the children are not grid items and will not accept grid properties. Also, as implied in the spec language above, children that are out-of-flow (i.e., absolutely positioned) are not grid items, either.

Bottom line: You will always need to apply display: grid or display: inline-grid to a parent in order for grid properties to work on the child.

Body:
I'm trying to use css-grid to create 3 areas, 2 with fixed height and the bottom one to fill the available space with a grid of buttons that also adapt to the space available. The buttons will adapt horizontally but not vertically. Can you see what silly thing I am doing to stop it working?

* {
  margin: 2px 2px 2px 2px;
  padding: 0;
  border: 0;
  outline: 0;
  font-size: 100%;
  vertical-align: middle;
  background: transparent;
  letter-spacing: normal;
}

body {
  color: #00000;
  background-color: #335155
}

p {
  color: #669990;
  font-size: 50px;
  text-decoration: none;
  font-family: sans-serif;
}

p:after {
  content: "";
  display: inline-block;
  width: 0px;
  height: auto;
}

.panel {
  display: grid;
  grid-template-columns: 1fr;
  grid-template-rows: 80px 80px 1fr;
}

.top-panel {
  display: grid;
  grid-template-columns: 60% 1fr 40px;
  grid-template-rows: 80px;
  grid-row-gap: 20px;
  grid-column-gap: 20px;
  padding: 0px 50px 0px 20px;
}

#paragraph-1 {
  text-align: right;
  padding: 0px 10px 0px 0px;
}

#paragraph-2 {
  border-width: 1px;
  border-style: solid;
  border-color: #669990;
  min-height: 75px;
  max-width: 100px;
  padding: 0px 20px 0px 0px;
  text-align: center;
}

#paragraph-3 {
  min-height: 75px;
  max-width: 100px;
  padding: 0px 10px 0px 0px;
  text-align: center;
}

.middle-panel {
  display: grid;
  grid-template-columns: 1fr;
  grid-template-rows: 1fr;
  grid-row-gap: 20px;
}

button {
  width: 100%;
  height: 100%;
  background-color: #669990;
  border: none;
  color: #335155;
  text-align: center;
  text-decoration: none;
  font-size: 20px;
}

button:hover {
  background-color: white;
}

.button-panel {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(4, minmax(20px, 300px);
  grid-row-gap: 10px;
  grid-column-gap: 10px;
  width: 100vw;
  height: 100vh;
}

.grid-position-1-1 {
  grid-column: 1;
  grid-row: 1;
}

.grid-position-2-1 {
  grid-column: 2;
  grid-row: 1;
}

.grid-position-3-1 {
  grid-column: 3;
  grid-row: 1;
}

.grid-position-1-2 {
  grid-column: 1;
  grid-row: 2;
}

.grid-position-2-2 {
  grid-column: 2;
  grid-row: 2;
}

.grid-position-3-2 {
  grid-column: 3;
  grid-row: 2;
}

.grid-position-1-3 {
  grid-column: 1;
  grid-row: 3;
}

.grid-position-2-3 {
  grid-column: 2;
  grid-row: 3;
}

.grid-position-3-3 {
  grid-column: 3;
  grid-row: 3;
}

.grid-position-1-4 {
  grid-column: 1;
  grid-row: 4;
}

.grid-position-2-4 {
  grid-column: 2;
  grid-row: 4;
}

.grid-position-3-4 {
  grid-column: 3;
  grid-row: 4;
}

          <button id="button-1" class="input-button" value=x>x</button>

          <button id="button-2" class="input-button" value=x>x</button>

          <button id="button-3" class="input-button" value=x>x</button>

          <button id="button-4" class="input-button" value=x>x</button>

          <button id="button-5" class="input-button" value=x>x</button>

          <button id="button-6" class="input-button" value=x>x</button>

          <button id="button-7" class="input-button" value=x>x</button>

          <button id="button-8" class="input-button" value=x>x</button>

          <button id="button-9" class="input-button" value=x>x</button>

          <button id="button-10" class="input-button" value=x>x</button>

          <button id="button-10" class="input-button" value=x>x</button>

          <button id="button-10" class="input-button" value=x>x</button>

Amended code as per advice of Michael_B

* {
    margin: 2px 2px 2px 2px;
    padding: 0;
    border: 0;
    outline: 0;
    font-size: 100%;
    vertical-align: middle;
    background: transparent;
    letter-spacing: normal;
}

body {color: #00000; background-color: #335155}

p {
    color: #669990;
    font-size: 50px;
    text-decoration: none;
    font-family: sans-serif;
}

p:after {
    content:"";
    display:inline-block;
    width:0px;
    height:auto;
}
.panel {
    display: grid;
    grid-template-columns: 1fr;
    grid-template-rows: 80px 80px 1fr;
}

.top-panel {
    grid-column: 1;
    grid-row: 1;
    display: grid;
    grid-template-columns: 60% 1fr 40px;
    grid-template-rows: 80px;
    grid-row-gap: 20px;
    grid-column-gap: 20px;
    padding: 0px 50px 0px 20px;
}

#paragraph-1 {
    text-align: right;
    padding: 0px 10px 0px 0px;
}
#paragraph-2 {
    border-width: 1px;
    border-style: solid;
    border-color: #669990;
    min-height: 75px;
    max-width: 100px;
    padding: 0px 20px 0px 0px;
    text-align: center;
}

#paragraph-3 {
    min-height: 75px;
    max-width: 100px;
    padding: 0px 10px 0px 0px;
    text-align: center;
}

.middle-panel {
    grid-column: 1;
    grid-row: 2;
    display: grid;
    grid-template-columns: 1fr;
    grid-template-rows: 1fr;
    grid-row-gap: 20px;
}
button {
    width: 100%;
    height: 100%;
    background-color: #669990;
    border: none;
    color: #335155;
    text-align: center;
    text-decoration: none;
    font-size: 20px;
}
button:hover {
    background-color: white;
}
.button-panel {
    grid-column: 1;
    grid-row: 3;
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-template-rows: repeat(4, 1fr);
    grid-row-gap: 2px;
    grid-column-gap: 2px;
}

.grid-position-1-1 {
    grid-column: 1;
    grid-row: 1;
}
.grid-position-2-1 {
    grid-column: 2;
    grid-row: 1;
}
.grid-position-3-1 {
    grid-column: 3;
    grid-row: 1;
}
.grid-position-1-2 {
    grid-column: 1;
    grid-row: 2;
}
.grid-position-2-2 {
    grid-column: 2;
    grid-row: 2;
}
.grid-position-3-2 {
    grid-column: 3;
    grid-row: 2;
}
.grid-position-1-3 {
    grid-column: 1;
    grid-row: 3;
}
.grid-position-2-3 {
    grid-column: 2;
    grid-row: 3;
}
.grid-position-3-3 {
    grid-column: 3;
    grid-row: 3;
}
.grid-position-1-4 {
    grid-column: 1;
    grid-row: 4;
}
.grid-position-2-4 {
    grid-column: 2;
    grid-row: 4;
}
.grid-position-3-4 {
    grid-column: 3;
    grid-row: 4;
}

                <button id="button-1" class="input-button" value=x>x</button>

                <button id="button-2" class="input-button" value=x>x</button>

                <button id="button-3" class="input-button" value=x>x</button>

                <button id="button-4" class="input-button" value=x>x</button>

                <button id="button-5" class="input-button" value=x>x</button>

                <button id="button-6" class="input-button" value=x>x</button>

                <button id="button-7" class="input-button" value=x>x</button>

                <button id="button-8" class="input-button" value=x>x</button>

                <button id="button-9" class="input-button" value=x>x</button>

                <button id="button-10" class="input-button" value=x>x</button>

                <button id="button-10" class="input-button" value=x>x</button>

                <button id="button-10" class="input-button" value=x>x</button>

Code also https://github.com/rawcane/panel-example

Body:
You grid container is set to <div class="panel">:

.panel {
    display: grid;
    grid-template-columns: 1fr;
    grid-template-rows: 80px 80px 1fr;
}

But the three areas you reference in your question:

.top-panel

.grid-position-2-1

.grid-position-3-1

are not children of the grid container. They are grandchildren of .panel.

Therefore, they are not grid items.

The scope of a grid formatting context is limited to the parent-child relationship.

This means that a grid container is always the parent and a grid item is always the child. Grid properties work only within this relationship.

As stated in the spec:

6. Grid
  Items

Each in-flow child of a grid container becomes a grid item.

Descendants of a grid container beyond the children are not grid items and will not accept grid properties. Also, as implied in the spec language above, children that are out-of-flow (i.e., absolutely positioned) are not grid items, either.

Bottom line: You will always need to apply display: grid or display: inline-grid to a parent in order for grid properties to work on the child.


问:
Haskell - manipulating/extending an ADT that isn’t under your control
What is the best way to go about manipulating/extending an ADT that isn’t under your control? (ie from a dependency)

Here is the data type that relates to my problem:

I want to maintain the structure of the data, but add additional data (ie adding another type), but the structure itself is not under my control. Do I have to map the data over to my own version of this definition?

For example, for all the paragraphs in the structure, I would like Para to become Para [Inline] [String] where [String] is a list of words contained in the paragraph (as it's own data structure).

I am serving this data up as JSON via an endpoint, I thought one way I could get around this would be to define my own ToJSON instance, and perform this translation on Para there, however I am unable to override the instance as it is already defined! I am willing to accept a solution that does not actually touch the Para type itself, I just need a way to couple more data to Para without losing any of the structure of full Pandoc document.

答:
however I am unable to override the instance as it is already defined!

You could define newtype that wraps a Pandoc, and then define a custom ToJSON instance for that.  query from Text.Pandoc.Walk could easily and efficiently extract the strings from the Para.

Another thing you might consider is creating a function that wraps each Para inside a Div with the strings stored in one of its attributes.  It wasn't clear from what you said whether this would work for your purposes, but it would be easy to define a function that did this transformation.


问:
keystroke generation
I have a scenario where i need to generate all possible keystrokes using numbers 2 to 9. The possible keystrokes should generate 2-git, 3-digit etc upto 32-digit numbers. can anybody tell me what is the best way to solve this problem.

Thanks,
Pdit

答:
You're looking at quite a bit of computation towards the higher end of that.

One possible way to do it would be to have an array as a place-holder for your digit sequence, increment either the highest or lowest index, check if it overflows and then "carry" it to the next index and do that until you overflow the poistion "at the other end". Start with the array filled with 2.

OwnerDisplayName: Pdit

Title: keystroke generation


问:
Insert into code
So I was trying to run this code it didn't work.
Can anyone please tell me what's wrong with it?</p>

```<code>INSERT INTO (LocationID,LocationLatitude, LocationLongitude)
VALUES (1,39.7392° N,104.9903° W),
(2,39.6172° N,104.9508° W),
(3,39.5807° N,104.8772° W),
(4,38.8339° N,104.8214° W),
(5,40.5853° N,105.0844° W)
</code>```

答:
Assuming LocationID is an Indentity Column that automatically increments and the other columns are VARCHAR :

EDIT: OP's comment indicated LocationID is not an Identity

```<code>INSERT INTO Location (LocatioNID, LocationLatitude, LocationLongitude)
VALUES (1, '39.7392° N', '104.9903° W'),
(2, '39.6172° N', '104.9508° W'),
(3, '39.5807° N', '104.8772° W'),
(4, '38.8339° N', '104.8214° W'),
(5, '40.5853° N', '105.0844° W')
</code>```

The problem with your current SQL is the missing table, invalid data types, too many columns/too few data values, too small VARCHAR(10) cols, etc.

Additionally, you may want to read about Spacial Data: https://www.red-gate.com/simple-talk/sql/t-sql-programming/introduction-to-sql-server-spatial-data/

Title: Insert into code

Body:
So I was trying to run this code it didn't work.
Can anyone please tell me what's wrong with it?

INSERT INTO (LocationID,LocationLatitude, LocationLongitude)
VALUES (1,39.7392° N,104.9903° W),
(2,39.6172° N,104.9508° W),
(3,39.5807° N,104.8772° W),
(4,38.8339° N,104.8214° W),
(5,40.5853° N,105.0844° W)

Body:
Assuming LocationID is an Indentity Column that automatically increments and the other columns are VARCHAR :

EDIT: OP's comment indicated LocationID is not an Identity

INSERT INTO Location (LocatioNID, LocationLatitude, LocationLongitude)
VALUES (1, '39.7392° N', '104.9903° W'),
(2, '39.6172° N', '104.9508° W'),
(3, '39.5807° N', '104.8772° W'),
(4, '38.8339° N', '104.8214° W'),
(5, '40.5853° N', '105.0844° W')

The problem with your current SQL is the missing table, invalid data types, too many columns/too few data values, too small VARCHAR(10) cols, etc.

Additionally, you may want to read about Spacial Data: https://www.red-gate.com/simple-talk/sql/t-sql-programming/introduction-to-sql-server-spatial-data/


问:
Display images in Neo4J brower using file name property
How could i display the image.jpg corresponding to a node by clicking on the name of the file (property of the node) in the Neo4j CE 3.2.6 browser. The file being stored locally or on a server? Is there any simple alternative?</p>

答:
The neo4j browser does not support clickable links directly.

However, your browser may have that ability built in, or it may have a plugin that can do that. For this to work, your image links would have to be complete URLs, though.

For example, the Chrome browser has a Text Url Linker extension that can turn http URL strings into clickable links. (That extension does not support file URLs, but there may be other extensions that do.) To see the image, you would select the node of interest in the neo4j browser, and click on the URL value for that node in the bottom of the current pane. You can also right-click on the URL if you want to use the Open Link in New Tab option.


问:
Celery workers unable to connect to redis on docker instances
I have a dockerized setup running a Django app within which I use Celery tasks. Celery uses Redis as the broker.

Versioning:

Docker version 17.09.0-ce, build afdb6d4

docker-compose version 1.15.0, build e12f3b9

Django==1.9.6

django-celery-beat==1.0.1

celery==4.1.0

celery[redis]

redis==2.10.5

Problem:

My celery workers appear to be unable to connect to the redis container located at localhost:6379. I am able to telnet into the redis server on the specified port. I am able to verify redis-server is running on the container.

When I manually connect to the Celery docker instance and attempt to create a worker using the command celery -A backend worker -l info I get the notice:

[2017-11-13 18:07:50,937: ERROR/MainProcess] consumer: Cannot connect to redis://localhost:6379/0: Error 99 connecting to localhost:6379. Cannot assign requested address..
Trying again in 4.00 seconds...

Notes:

I am able to telnet in to the redis container on port 6379. On the redis container, redis-server is running.

Is there anything else that I'm missing? I've gone pretty far down the rabbit hole, but feel like I'm missing something really simple.

DOCKER CONFIG FILES:

docker-compose.common.yml here

docker-compose.dev.yml here

答:
You may need to add the link and depends_on sections to your docker compose file, and then reference the containers by their hostname.

Updated docker-compose.yml:

```<code>version: '2.1'
services:
    db:
        image: postgres
    memcached:
        image: memcached
    redis:
        image: redis
        ports:
          - '6379:6379'
    backend-base:
        build:
            context: .
            dockerfile: backend/Dockerfile-base
        image: "/backend:base"
    backend:
        build:
            context: .
            dockerfile: backend/Dockerfile
        image: "/backend:${ENV:-local}"
        command: ./wait-for-it.sh db:5432 -- gunicorn backend.wsgi:application -b 0.0.0.0:8000 -k gevent -w 3
        ports:
            - 8000
        links:
            - db
            - redis
            - memcached
        depends_on:
            - db
            - redis
            - memcached
    celery:
        image: "/backend:${ENV:-local}"
        command: ./wait-for-it.sh db:5432 -- celery worker -E -B --loglevel=INFO --concurrency=1
        environment:
            C_FORCE_ROOT: "yes"
        links:
            - db
            - redis
            - memcached
        depends_on:
            - db
            - redis
            - memcached
    frontend-base:
        build:
            context: .
            dockerfile: frontend/Dockerfile-base
            args:
                NPM_REGISTRY: http://.view.build
                PACKAGE_INSTALLER: yarn
        image: "/frontend:base"
        links:
            - db
            - redis
            - memcached
        depends_on:
            - db
            - redis
            - memcached
    frontend:
        build:
            context: .
            dockerfile: frontend/Dockerfile
        image: "/frontend:${ENV:-local}"
        command: 'bash -c ''gulp'''
        working_dir: /app/user
        environment:
            PORT: 3000
        links:
            - db
            - redis
            - memcached
        depends_on:
            - db
            - redis
            - memcached
</code>```

Then configure the urls to redis, postgres, memcached, etc. with:

redis://redis:6379/0

postgres://user:pass@db:5432/database

Body:
You may need to add the link and depends_on sections to your docker compose file, and then reference the containers by their hostname.

Updated docker-compose.yml:

version: '2.1'
services:
    db:
        image: postgres
    memcached:
        image: memcached
    redis:
        image: redis
        ports:
          - '6379:6379'
    backend-base:
        build:
            context: .
            dockerfile: backend/Dockerfile-base
        image: "/backend:base"
    backend:
        build:
            context: .
            dockerfile: backend/Dockerfile
        image: "/backend:${ENV:-local}"
        command: ./wait-for-it.sh db:5432 -- gunicorn backend.wsgi:application -b 0.0.0.0:8000 -k gevent -w 3
        ports:
            - 8000
        links:
            - db
            - redis
            - memcached
        depends_on:
            - db
            - redis
            - memcached
    celery:
        image: "/backend:${ENV:-local}"
        command: ./wait-for-it.sh db:5432 -- celery worker -E -B --loglevel=INFO --concurrency=1
        environment:
            C_FORCE_ROOT: "yes"
        links:
            - db
            - redis
            - memcached
        depends_on:
            - db
            - redis
            - memcached
    frontend-base:
        build:
            context: .
            dockerfile: frontend/Dockerfile-base
            args:
                NPM_REGISTRY: http://.view.build
                PACKAGE_INSTALLER: yarn
        image: "/frontend:base"
        links:
            - db
            - redis
            - memcached
        depends_on:
            - db
            - redis
            - memcached
    frontend:
        build:
            context: .
            dockerfile: frontend/Dockerfile
        image: "/frontend:${ENV:-local}"
        command: 'bash -c ''gulp'''
        working_dir: /app/user
        environment:
            PORT: 3000
        links:
            - db
            - redis
            - memcached
        depends_on:
            - db
            - redis
            - memcached

Then configure the urls to redis, postgres, memcached, etc. with:

redis://redis:6379/0

postgres://user:pass@db:5432/database


问:
Overfitting with random forest though very successful cross validation results
I have moderate experience with data science. I have a data set with 9500 observations and more than 4500 features most of which are highly correlated. Here is briefly what I have tried: I have dropped columns where there are less than 6000 non-NAs and have imputed NAs with their corresponding columns' median values when there are at least 6000 non-NAs. As for correlation, I have kept only features having at most 0.7 correlation with others. By doing so, I have reduced the number of features to about 750. Then I have used those features in my binary classification task in random forest.

My data set is highly unbalanced where ratio of (0:1) is (10:1). So when I apply RF with 10-fold cv, I observe too good results in each cv (AUC of 99%) which is to good to be true and in my test set I got way worse results such as 0.7. Here is my code:

```<code>import h2o
from h2o.estimators import H2ORandomForestEstimator

h2o.init(port=23, nthreads=4)

train = fs_rf[fs_rf['Year'] <= '201705']
test = fs_rf[fs_rf['Year'] > '201705']
train = train.drop('Year',axis=1)
test = test.drop('Year',axis=1)
test.head()

train = h2o.H2OFrame(train)
train['BestWorst2'] = train['BestWorst2'].asfactor()

test = h2o.H2OFrame(test)
test['BestWorst2'] = test['BestWorst2'].asfactor()

training_columns = train.drop('BestWorst2',axis=1).col_names
response_column = 'BestWorst2'

model = H2ORandomForestEstimator(ntrees=100, max_depth=20, nfolds=10, balance_classes=True)

model.train(x=training_columns, y=response_column, training_frame=train)

performance = model.model_performance(test_data=test)

print(performance)
</code>```

How could I avoid this over-fitting? I have tried many different parameters in grid search but none of them improved the results.

答:
This is not what I would call "overfitting".  The reason you are seeing really good cross-validation metrics compared to your test metrics is that you have time-series data and so you can't use k-fold cross-validation to give you an accurate estimate of performance.

Performing k-fold cross-validation on a time-series dataset will give you overly-optimistic performance metrics because you are not respecting the time-series component in your data. Regular k-fold cross-validation will randomly sample from your whole dataset to create a train & validation set. Essentially, your validation strategy is "cheating" because you have "future" data included in your CV training sets (if that makes any sense).

I can see by your code that you understand that you need to train with "past" data and predict on "future" data, but if you want to read more about this topic, I'd recommend this article or this article.

One solution is to simply look at test set performance as way to evaluate your model.  Another option is to use what's called "rolling" or "time-series" cross-validation, but H2O does not currently support that (though it seems like it might be added soon).  Here's a ticket for this if you want to keep track of the progress.

Body:
I have moderate experience with data science. I have a data set with 9500 observations and more than 4500 features most of which are highly correlated. Here is briefly what I have tried: I have dropped columns where there are less than 6000 non-NAs and have imputed NAs with their corresponding columns' median values when there are at least 6000 non-NAs. As for correlation, I have kept only features having at most 0.7 correlation with others. By doing so, I have reduced the number of features to about 750. Then I have used those features in my binary classification task in random forest.

My data set is highly unbalanced where ratio of (0:1) is (10:1). So when I apply RF with 10-fold cv, I observe too good results in each cv (AUC of 99%) which is to good to be true and in my test set I got way worse results such as 0.7. Here is my code:

import h2o
from h2o.estimators import H2ORandomForestEstimator

h2o.init(port=23, nthreads=4)

train = fs_rf[fs_rf['Year'] <= '201705']
test = fs_rf[fs_rf['Year'] > '201705']
train = train.drop('Year',axis=1)
test = test.drop('Year',axis=1)
test.head()

train = h2o.H2OFrame(train)
train['BestWorst2'] = train['BestWorst2'].asfactor()

test = h2o.H2OFrame(test)
test['BestWorst2'] = test['BestWorst2'].asfactor()

training_columns = train.drop('BestWorst2',axis=1).col_names
response_column = 'BestWorst2'

model = H2ORandomForestEstimator(ntrees=100, max_depth=20, nfolds=10, balance_classes=True)

model.train(x=training_columns, y=response_column, training_frame=train)

performance = model.model_performance(test_data=test)

print(performance)

How could I avoid this over-fitting? I have tried many different parameters in grid search but none of them improved the results.


问:
I am trying to move the first two letters of the string to the end if it starts with two consonants. It just returns Not a number, or NaN
Here is my javascript code:

```<code>function lattify(id) {
  var inputTextStr = document.getElementById(id).value;
  var lattiStr = "";
  for (var i = 0; i < inputTextStr.length; i++) {
    console.log(inputTextStr[i]);
    var inputText = inputTextStr[i];
    if (inputTextStr[i + 1] !== "a" || "e" || "i" || "o" || "u") {
      lattiStr = inputTextStr.substr(2) +
        inputTextStr.substr(0, inputTextStr.length);
    }

  }
  console.log(lattiStr);
}
</code>```

Here is my html code:

```<code><form>
  <input type="text" id="latin">
  <button type="button" onclick="lattify('latin'.toString())">Submit</button>
</form>
</code>```

What this program is supposed to do is take the text input from the form into the function 'lattify'. That part works. The part that does not work is the part where the first two letters are added to the end if they are both of them are consonants.

答:
You are not explicitly converting the input text into a char array.

From another post you can do it this way:

```<code>var strChars = myString.split("");
</code>```

If in the same loop you are addressing [i] and [i+1], the loop needs to end in length - 1, otherwise you go out of bounds on the last loop.

The condition should be checked for each letter:

```<code>inputTextStr[i+1]!=="a"||
inputTextStr[i+1]!=="e"||
inputTextStr[i+1]!=="i"||
inputTextStr[i+1]!=="o"||
inputTextStr[i+1]!=="u"
</code>```

The second parameter of substr should be 2, which is the number of characters you want to copy to the end.

```<code>inputTextStr.substr(0,2);
</code>```

instead of

```<code>inputTextStr.substr(0,inputTextStr.length);
</code>```

Body:
Here is my javascript code:

function lattify(id) {
  var inputTextStr = document.getElementById(id).value;
  var lattiStr = "";
  for (var i = 0; i < inputTextStr.length; i++) {
    console.log(inputTextStr[i]);
    var inputText = inputTextStr[i];
    if (inputTextStr[i + 1] !== "a" || "e" || "i" || "o" || "u") {
      lattiStr = inputTextStr.substr(2) +
        inputTextStr.substr(0, inputTextStr.length);
    }

  }
  console.log(lattiStr);
}

Here is my html code:

<form>
  <input type="text" id="latin">
  <button type="button" onclick="lattify('latin'.toString())">Submit</button>
</form>

What this program is supposed to do is take the text input from the form into the function 'lattify'. That part works. The part that does not work is the part where the first two letters are added to the end if they are both of them are consonants.

Body:
You are not explicitly converting the input text into a char array.

From another post you can do it this way:

var strChars = myString.split("");

If in the same loop you are addressing [i] and [i+1], the loop needs to end in length - 1, otherwise you go out of bounds on the last loop.

The condition should be checked for each letter:

inputTextStr[i+1]!=="a"||
inputTextStr[i+1]!=="e"||
inputTextStr[i+1]!=="i"||
inputTextStr[i+1]!=="o"||
inputTextStr[i+1]!=="u"

The second parameter of substr should be 2, which is the number of characters you want to copy to the end.

inputTextStr.substr(0,2);

instead of

inputTextStr.substr(0,inputTextStr.length);


答:
You can't check multiple values in an if statement by appending multiple ||s.  The left part of the condition needs to be included each time.

You could check against an array of vowels to avoid such redundant code.

array.indexOf(val) will check for val inside of array and return -1 if it is not found.

The loop isn't necessary, you can manually check the first and second characters, moving them to the end if necessary.  substr(0, 2) to get the first two chars, substr(2, [str.length]) to get everything else.

```<code>function lattify(id) {
  var vowels = ['a', 'e', 'i', 'o', 'u'];
  var inputTextStr = document.getElementById(id).value;
  var lattiStr = "";
  var ret = inputTextStr;

  if(inputTextStr.length > 2 && vowels.indexOf(inputTextStr[0]) === -1 && vowels.indexOf(inputTextStr[1]) === -1) {
    //first and second characters in the string are consonants.
    ret = inputTextStr.substr(2, inputTextStr.length) + inputTextStr.substr(0,2);
  }

  console.log('returning: ' + ret);
  return ret;
}
</code>```

Title: I am trying to move the first two letters of the string to the end if it starts with two consonants. It just returns Not a number, or NaN

Body:
You can't check multiple values in an if statement by appending multiple ||s.  The left part of the condition needs to be included each time.

You could check against an array of vowels to avoid such redundant code.

array.indexOf(val) will check for val inside of array and return -1 if it is not found.

The loop isn't necessary, you can manually check the first and second characters, moving them to the end if necessary.  substr(0, 2) to get the first two chars, substr(2, [str.length]) to get everything else.

function lattify(id) {
  var vowels = ['a', 'e', 'i', 'o', 'u'];
  var inputTextStr = document.getElementById(id).value;
  var lattiStr = "";
  var ret = inputTextStr;

  if(inputTextStr.length > 2 && vowels.indexOf(inputTextStr[0]) === -1 && vowels.indexOf(inputTextStr[1]) === -1) {
    //first and second characters in the string are consonants.
    ret = inputTextStr.substr(2, inputTextStr.length) + inputTextStr.substr(0,2);
  }

  console.log('returning: ' + ret);
  return ret;
}


问:
Iterate through a list, divide values, store in new list
In the code I have series of lists, each one containing the same number of entries. What I want to do now is iterate through the list and divide one list index by the other.

```<code>threads = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
dsk_indpt_PI = [99, 197, 295, 387, 391, 406, 407, 416, 424, 426, 425, 439]

avg_val = []
for x in threads:
    result = dsk_indpt_PI[x]/threads[x]
    avg_val.append(result[x])
</code>```

I am unsure if the above method works, previous methods I ran into the issue where it could not do division between type int and type list. Would the above example work better? If not, what should be changed to have it function as desired? Thank you.

Body:
In the code I have series of lists, each one containing the same number of entries. What I want to do now is iterate through the list and divide one list index by the other.

threads = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
dsk_indpt_PI = [99, 197, 295, 387, 391, 406, 407, 416, 424, 426, 425, 439]

avg_val = []
for x in threads:
    result = dsk_indpt_PI[x]/threads[x]
    avg_val.append(result[x])

I am unsure if the above method works, previous methods I ran into the issue where it could not do division between type int and type list. Would the above example work better? If not, what should be changed to have it function as desired? Thank you.

Body:
Use pythonic way , One line solution:

print([item[1]/item[0] for item in zip(threads,dsk_indpt_PI)])

output:

[99.0, 98.5, 98.33333333333333, 96.75, 78.2, 67.66666666666667, 58.142857142857146, 52.0, 47.111111111111114, 42.6, 38.63636363636363, 36.583333333333336]

above list comprehension is same as:

divide=[]
for item in zip(threads,dsk_indpt_PI):
    divide.append(item[1]/item[0])

print(divide)