问:
Finding the root directory of a multi module Maven reactor project
Is there an easy way to find the root of a multi-module Maven project, like Gradle's rootDir?

Background:

I want to use the maven-dependency-plugin to copy artifacts from all sub-modules of my multi-module project to a directory that is relative to the root directory of the entire project.

That is, my layout looks similar to this, names changed:

```<code>to-deploy/
my-project/
    module-a/
    module-b/
    more-modules-1/
        module-c/
        module-d/
    more-modules-2/
        module-e/
        module-f/
    ...
</code>```

And i want all the artifacts to be copied from the target-directories of their respective modules to my-project/../to-deploy so i end up with

```<code>to-deploy/
    module-a.jar
    module-b.jar
    module-c.jar
    module-d.jar
    module-e.jar
    module-f.jar
my-project/
    ...
</code>```

I could do it with a relative path in each module, like so:

```<code>        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <executions>
                <execution>
                    <id>copy</id>
                    <phase>install</phase>
                    <goals>
                        <goal>copy</goal>
                    </goals>
                    <configuration>
                        <artifactItems>
                            <artifactItem>
                                <groupId>${project.groupId}</groupId>
                                <artifactId>${project.artifactId}</artifactId>
                                <version>${project.version}</version>
                                <type>jar</type>
                                <outputDirectory>../../to-deploy</outputDirectory>
                            </artifactItem>
                        </artifactItems>
                    </configuration>
                </execution>
            </executions>
        </plugin>
</code>```

But i'd rather not specify a relative path in the <outputDirectory> element.
I'd prefer something like ${reactor.root.directory}/../to-deploy, but i can't find anything like this.

Also, i'd prefer if there was some way to inherit this maven-dependency-plugin configuration so i don't have to specify it for each module.

I also tried inheriting a custom property from the root pom:

```<code><properties>
    <myproject.root>${basedir}</myproject.root>
</properties>
</code>```

But when i tried to use ${myproject.root} in the module POM's, the ${basedir} would resolve to the basedir of the module.

Also, i found http://labs.consol.de/lang/de/blog/maven/project-root-path-in-a-maven-multi-module-project/ where it's suggested that each developer and presumably the continuous integration server should configure the root directory in a profiles.xml file, but i don't consider it a solution.

So is there an easy way to find the root of a multi-module project?

答: Another solution would be to use an ant task to write "rootdir=${basedir}" to a target/root.properties in the root project, and then use the Properties Plugin to read that file back in.  I haven't tried it myself, but I guess it should work..?</p>

ContentLicense: CC BY-SA 4.0

Body:
Is there an easy way to find the root of a multi-module Maven project, like Gradle's rootDir?

Background:

I want to use the maven-dependency-plugin to copy artifacts from all sub-modules of my multi-module project to a directory that is relative to the root directory of the entire project.

That is, my layout looks similar to this, names changed:

to-deploy/
my-project/
    module-a/
    module-b/
    more-modules-1/
        module-c/
        module-d/
    more-modules-2/
        module-e/
        module-f/
    ...

And i want all the artifacts to be copied from the target-directories of their respective modules to my-project/../to-deploy so i end up with

to-deploy/
    module-a.jar
    module-b.jar
    module-c.jar
    module-d.jar
    module-e.jar
    module-f.jar
my-project/
    ...

I could do it with a relative path in each module, like so:

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <executions>
                <execution>
                    <id>copy</id>
                    <phase>install</phase>
                    <goals>
                        <goal>copy</goal>
                    </goals>
                    <configuration>
                        <artifactItems>
                            <artifactItem>
                                <groupId>${project.groupId}</groupId>
                                <artifactId>${project.artifactId}</artifactId>
                                <version>${project.version}</version>
                                <type>jar</type>
                                <outputDirectory>../../to-deploy</outputDirectory>
                            </artifactItem>
                        </artifactItems>
                    </configuration>
                </execution>
            </executions>
        </plugin>

But i'd rather not specify a relative path in the <outputDirectory> element.
I'd prefer something like ${reactor.root.directory}/../to-deploy, but i can't find anything like this.

Also, i'd prefer if there was some way to inherit this maven-dependency-plugin configuration so i don't have to specify it for each module.

I also tried inheriting a custom property from the root pom:

<properties>
    <myproject.root>${basedir}</myproject.root>
</properties>

But when i tried to use ${myproject.root} in the module POM's, the ${basedir} would resolve to the basedir of the module.

Also, i found http://labs.consol.de/lang/de/blog/maven/project-root-path-in-a-maven-multi-module-project/ where it's suggested that each developer and presumably the continuous integration server should configure the root directory in a profiles.xml file, but i don't consider it a solution.

So is there an easy way to find the root of a multi-module project?


来源: stackexchange

问:
How to use Voximplant text chatting together with React Natiwe?
Use Voximplant text chatting along with React Native.
Has anyone used it? What ways did you use if there is no plug-in?</p>

答: Voximplant is used mainly for Voice and Video communications. Text messaging is a pretty new addition and it has not yet landed in the React Native SDK (it will, but in some time).</p>

ContentLicense: CC BY-SA 3.0


问:
get numbers from a link html parsing jsoup
I am working on a software and new on Jsoup. I need help. I am parsing a website. getting links like that :

```<code><a href="/?loc=shop_view_item&item=139218679" class="market-name market-link">XXX</a>
</code>```

How can I take numbers "139218679" with Jsoup or regex. Can you help me please?

答:
This code will work for you . What you need is you need to get numbers from the string;</p>

```<code>String html ="<a href=\"/?loc=shop_view_item&item=139218679\" class=\"market-name market-link\">XXX</a>";

        Document document= Jsoup.parse(html);
        Elements elements = document.select("a[href]");

        for (Element element:elements){
            String itemValue = element.attr("href");
            itemValue = itemValue.replaceAll("[^0-9]+", " ");
            System.out.println(itemValue.trim());
        }
</code>```

Body:
I am working on a software and new on Jsoup. I need help. I am parsing a website. getting links like that :

XXX

How can I take numbers "139218679" with Jsoup or regex. Can you help me please?

Body:
This code will work for you . What you need is you need to get numbers from the string;

String html ="<a href=\"/?loc=shop_view_item&amp;item=139218679\" class=\"market-name market-link\">XXX</a>";

        Document document= Jsoup.parse(html);
        Elements elements = document.select("a[href]");

        for (Element element:elements){
            String itemValue = element.attr("href");
            itemValue = itemValue.replaceAll("[^0-9]+", " ");
            System.out.println(itemValue.trim());
        }


问:
efficiency of a program that checks range of variable vs another that checks values one by one?
Let assume that I have a Boolean function that receives a random number as its argument and then return True if the random number is 200, 201 or 202 and return False for other values.

The question is which one of the following functions are more efficient?

f1:

```<code>bool f1(int number) {
    if (number >= 200 && number <= 202)
        return true;
    return false;
}
</code>```

f2:

```<code>bool f2(int number) {
    if (number == 200 || number == 201 || number == 202)
        return true;
    return false;
}
</code>```

答:
Just see the assembly codes and we do some statistics just from if:

```<code>bool f1(int number) {
011D9160  push        ebp
011D9161  mov         ebp,esp
011D9163  sub         esp,0C0h
011D9169  push        ebx
011D916A  push        esi
011D916B  push        edi
011D916C  lea         edi,[ebp-0C0h]
011D9172  mov         ecx,30h
011D9177  mov         eax,0CCCCCCCCh
011D917C  rep stos    dword ptr es:[edi]
        if (number >= 200 && number <= 202)
011D917E  cmp         dword ptr [number],0C8h
011D9185  jl          f1+34h (011D9194h)
011D9187  cmp         dword ptr [number],0CAh
011D918E  jg          f1+34h (011D9194h)
            return true;
011D9190  mov         al,1
011D9192  jmp         f1+36h (011D9196h)
        return false;
011D9194  xor         al,al  }

bool f2(int number) {
011D91B0  push        ebp
011D91B1  mov         ebp,esp
011D91B3  sub         esp,0C0h
011D91B9  push        ebx
011D91BA  push        esi
011D91BB  push        edi
011D91BC  lea         edi,[ebp-0C0h]
011D91C2  mov         ecx,30h
011D91C7  mov         eax,0CCCCCCCCh
011D91CC  rep stos    dword ptr es:[edi]
        if (number == 200 || number == 201 || number == 202)
011D91CE  cmp         dword ptr [number],0C8h
011D91D5  je          f2+39h (011D91E9h)
011D91D7  cmp         dword ptr [number],0C9h
011D91DE  je          f2+39h (011D91E9h)
011D91E0  cmp         dword ptr [number],0CAh
011D91E7  jne         f2+3Dh (011D91EDh)
            return true;
011D91E9  mov         al,1
011D91EB  jmp         f2+3Fh (011D91EFh)
        return false;
011D91ED  xor         al,al
    }
</code>```

For function f1:

When number equals 200,function f1 calls cmp,jl,cmp,jg,mov,jmp 6
logical operation instructions.

When number equals 201,function f1 calls cmp,jl,cmp,jg,mov,jmp 6 logical operation instructions.

When number equals 202,function f1 calls cmp,jl,cmp,jg,mov,jmp 6 logical operation instructions.

When number is less than 200,function f1 calls cmp,jl,xor 3 logical operation instructions.

When number is bigger than 202,function f1 calls cmp,jl,cmp,jg,xor 5 logical operation instructions.

For function f2:

When number equals 200,function f2 calls cmp,je,mov,jmp 4
logical operation instructions.

When number equals 201,function f2 calls cmp,je,cmp,je,mov,jmp 6 logical operation instructions.

When number equals 202,function f2 calls cmp,je,cmp,je,cmp,jne,mov,jmp 8 logical operation instructions.

For other numbers,function f2 calls cmp,je,cmp,je,cmp,jne,xor 7 logical operation instructions.

Seems that when return true,the performance is averagely the same since 6+6+6=4+6+8.
But when return false,f1 is better than f2.

Body:
Let assume that I have a Boolean function that receives a random number as its argument and then return True if the random number is 200, 201 or 202 and return False for other values.

The question is which one of the following functions are more efficient?

f1:

bool f1(int number) {
    if (number >= 200 && number <= 202)
        return true;
    return false;
}

f2:

bool f2(int number) {
    if (number == 200 || number == 201 || number == 202)
        return true;
    return false;
}

Body:
Just see the assembly codes and we do some statistics just from if:

bool f1(int number) {
011D9160  push        ebp
011D9161  mov         ebp,esp
011D9163  sub         esp,0C0h
011D9169  push        ebx
011D916A  push        esi
011D916B  push        edi
011D916C  lea         edi,[ebp-0C0h]
011D9172  mov         ecx,30h
011D9177  mov         eax,0CCCCCCCCh
011D917C  rep stos    dword ptr es:[edi]
        if (number >= 200 && number <= 202)
011D917E  cmp         dword ptr [number],0C8h
011D9185  jl          f1+34h (011D9194h)
011D9187  cmp         dword ptr [number],0CAh
011D918E  jg          f1+34h (011D9194h)
            return true;
011D9190  mov         al,1
011D9192  jmp         f1+36h (011D9196h)
        return false;
011D9194  xor         al,al  }

bool f2(int number) {
011D91B0  push        ebp
011D91B1  mov         ebp,esp
011D91B3  sub         esp,0C0h
011D91B9  push        ebx
011D91BA  push        esi
011D91BB  push        edi
011D91BC  lea         edi,[ebp-0C0h]
011D91C2  mov         ecx,30h
011D91C7  mov         eax,0CCCCCCCCh
011D91CC  rep stos    dword ptr es:[edi]
        if (number == 200 || number == 201 || number == 202)
011D91CE  cmp         dword ptr [number],0C8h
011D91D5  je          f2+39h (011D91E9h)
011D91D7  cmp         dword ptr [number],0C9h
011D91DE  je          f2+39h (011D91E9h)
011D91E0  cmp         dword ptr [number],0CAh
011D91E7  jne         f2+3Dh (011D91EDh)
            return true;
011D91E9  mov         al,1
011D91EB  jmp         f2+3Fh (011D91EFh)
        return false;
011D91ED  xor         al,al
    }

For function f1:

When number equals 200,function f1 calls cmp,jl,cmp,jg,mov,jmp 6
logical operation instructions.

When number equals 201,function f1 calls cmp,jl,cmp,jg,mov,jmp 6 logical operation instructions.

When number equals 202,function f1 calls cmp,jl,cmp,jg,mov,jmp 6 logical operation instructions.

When number is less than 200,function f1 calls cmp,jl,xor 3 logical operation instructions.

When number is bigger than 202,function f1 calls cmp,jl,cmp,jg,xor 5 logical operation instructions.

For function f2:

When number equals 200,function f2 calls cmp,je,mov,jmp 4
logical operation instructions.

When number equals 201,function f2 calls cmp,je,cmp,je,mov,jmp 6 logical operation instructions.

When number equals 202,function f2 calls cmp,je,cmp,je,cmp,jne,mov,jmp 8 logical operation instructions.

For other numbers,function f2 calls cmp,je,cmp,je,cmp,jne,xor 7 logical operation instructions.

Seems that when return true,the performance is averagely the same since 6+6+6=4+6+8.
But when return false,f1 is better than f2.


问:
Highlight child view inside Expandable ListView
I need to highlight the child view of an expandable list view when the user touch an item. I want the color to stay, not just provide a visual feedback. I was able to achieve this with:

```<code>expandablelistview_options.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {

        @Override
        public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
            v.setBackgroundColor(Color.BLUE);
            return false;
        }
    });
</code>```

But my problem is that if I choose another child in the same parent view, the previous selection doesn't get unhighlighted.

How can I solve this problem?

答:
What you can do is follow this approach:

1) Save the reference or position of the latest item clicked as an int or object.

2) Then you can make a function like this and call it on item click and pass the position:

```<code>int lastItem = 0;

public void highlight(int clickedItem){
clickedItem.setBackground(//highlight color);
lastItem.setBackground(//unhighlight color);
lastItem = clickedItem;
}
</code>```

3) This will help you to save the reference and will make it easy to handle last and current item. This is just an approach I use while handling cases like this. You have to use this kind of approach for the same.

Hope this helps.

Body:
I need to highlight the child view of an expandable list view when the user touch an item. I want the color to stay, not just provide a visual feedback. I was able to achieve this with:

expandablelistview_options.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {

        @Override
        public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
            v.setBackgroundColor(Color.BLUE);
            return false;
        }
    });

But my problem is that if I choose another child in the same parent view, the previous selection doesn't get unhighlighted.

How can I solve this problem?

Body:
What you can do is follow this approach:

1) Save the reference or position of the latest item clicked as an int or object.

2) Then you can make a function like this and call it on item click and pass the position:

int lastItem = 0;

public void highlight(int clickedItem){
clickedItem.setBackground(//highlight color);
lastItem.setBackground(//unhighlight color);
lastItem = clickedItem;
}

3) This will help you to save the reference and will make it easy to handle last and current item. This is just an approach I use while handling cases like this. You have to use this kind of approach for the same.

Hope this helps.


问:
Rounded Image Drawable only drawing white
I am following the rounded image tutorial from romain guy,

http://www.curious-creature.com/2012/12/11/android-recipe-1-image-with-rounded-corners/

I extracted the drawable to a class RoundedDrawable but when i try and use it to the bitmap, it will always paints white.

How do i fix this?

答:
Here is one simple way

add this on your build.gradlecompile 'de.hdodenhof:circleimageview:2.1.0'

and on your xml add

```<code>      <de.hdodenhof.circleimageview.CircleImageView
       xmlns:app="http://schemas.android.com/apk/res-auto"
       android:id="@+id/profile_image"
       android:layout_width="your size"
       android:layout_height="your size"
       android:src="@drawable/profile"
       app:civ_border_width="2dp"
       app:civ_border_color="#FF000000"/>
</code>```

Body:
Here is one simple way

add this on your build.gradlecompile 'de.hdodenhof:circleimageview:2.1.0'

and on your xml add

      <de.hdodenhof.circleimageview.CircleImageView
       xmlns:app="http://schemas.android.com/apk/res-auto"
       android:id="@+id/profile_image"
       android:layout_width="your size"
       android:layout_height="your size"
       android:src="@drawable/profile"
       app:civ_border_width="2dp"
       app:civ_border_color="#FF000000"/>


问:
How might I obtain a Snapshot or Thumbnail of a web page using PHP?
I need to create Snapshots / Thumbshots / Site preview a-site.com.

There are some site as thumbshot.org that meets with I need. But I do not want to use an external service, not to depend on others for my project (What would happen if they close the site?)

For this reason, I am looking for some project to let me do this.

Any idea?

答:
On windows you can use GD's imagegrabwindow() function.

Edit: The help page actually shows you how to grab a screenshot from IE.

OwnerDisplayName: diego

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: RoBorg


问:
Error compiler, cannot convert parameter 2 from MyStruct1 to const void*, for memcpy
I am trying to copy the data from on structure to another. The bytes are identical that each struct can handle are the same. My declarations and the memcpy are below:

```<code>    typedef struct{
        CString strNumber;
        CString strAlpha;

    } _Number;

    typedef struct{
        CString strIterration;
        _Number NumberOne;
        _Number NumberTwo;
    } _Store;

_Store Data1;
_Store Data2;
</code>```

Now let's say that the first struct Data1 has data and the second is just declared.

I am using the following code:

```<code>memcpy(&Data2, Data1,   sizeof(_Store));
</code>```

I cannot compile as the error appears. Any ideas? Any other approaches to copy the data?

答:
You need to use & on both structs:

```<code>memcpy(&Data2, &Data1, sizeof(_Store));
</code>```

Beware: _Store contains CString member variable which (if it is like MFC CString) is not bitwise copyable. You should only use memcpy() on types that are bitwise copyable, otherwise you risk running into undefined behavior.

Body:
I am trying to copy the data from on structure to another. The bytes are identical that each struct can handle are the same. My declarations and the memcpy are below:

    typedef struct{
        CString strNumber;
        CString strAlpha;

    } _Number;

    typedef struct{
        CString strIterration;
        _Number NumberOne;
        _Number NumberTwo;
    } _Store;

_Store Data1;
_Store Data2;

Now let's say that the first struct Data1 has data and the second is just declared.

I am using the following code:

memcpy(&Data2, Data1,   sizeof(_Store));

I cannot compile as the error appears. Any ideas? Any other approaches to copy the data?

Body:
You need to use & on both structs:

memcpy(&Data2, &Data1, sizeof(_Store));

Beware: _Store contains CString member variable which (if it is like MFC CString) is not bitwise copyable. You should only use memcpy() on types that are bitwise copyable, otherwise you risk running into undefined behavior.


问:
Radiobutton requires clicking twice when databound
I'm trying to figure out why my radiobuttons act differently once I add a very simple databinding to them.

Consider a super simple form with just two radiobuttons X and Y. Now say I want to persist them, so in the form designer I add a new settings key for the Checked property for both X and Y.
Now I run the program. Neither checkbox is initially checked, so I click on X and it becomes checked. So far so good. Now I click Y, and expect X to become unchecked again and Y to become checked, but what happens is that only X gets unchecked, and Y remains so. Clicking Y again then checks Y.

The bindings look as follows:

```<code>this.rbX.DataBindings.Add("Checked", global::rb.Properties.Settings.Default, "X", true, DataSourceUpdateMode.OnPropertyChanged));
this.rbY.DataBindings.Add("Checked", global::rb.Properties.Settings.Default, "Y", true, DataSourceUpdateMode.OnPropertyChanged));
</code>```

Am I missing something or doing something wrong?

答:
In the click event:</p>

```<code>private void RadioButtonClick(object sender, EventArgs e)
{
    var rb = sender as RadioButton;
    if (rb != null && !rb.Checked)
    {
        rb.Checked = !rb.Checked;
    }
}
</code>```

Body:
I'm trying to figure out why my radiobuttons act differently once I add a very simple databinding to them.

Consider a super simple form with just two radiobuttons X and Y. Now say I want to persist them, so in the form designer I add a new settings key for the Checked property for both X and Y.
Now I run the program. Neither checkbox is initially checked, so I click on X and it becomes checked. So far so good. Now I click Y, and expect X to become unchecked again and Y to become checked, but what happens is that only X gets unchecked, and Y remains so. Clicking Y again then checks Y.

The bindings look as follows:

this.rbX.DataBindings.Add("Checked", global::rb.Properties.Settings.Default, "X", true, DataSourceUpdateMode.OnPropertyChanged));
this.rbY.DataBindings.Add("Checked", global::rb.Properties.Settings.Default, "Y", true, DataSourceUpdateMode.OnPropertyChanged));

Am I missing something or doing something wrong?

Body:
In the click event:

private void RadioButtonClick(object sender, EventArgs e)
{
    var rb = sender as RadioButton;
    if (rb != null && !rb.Checked)
    {
        rb.Checked = !rb.Checked;
    }
}


问:
How to save XML child nodes value to database in PHP
I need help regarding saving XML data into MySQL database. Here is my code:

```<code>    <?xml version="1.0" encoding="UTF-8"?><Response Code="200"><Description>http://sample.net</Description><URL>/Patient/PatientView.aspx?pid=642</URL></Response>
</code>```

Now what I wanted to do is to get the value of the <Description> tag and the <URL> tag and combine them to become a complete url then save it to mysql database.

答:
See question here How do you parse and process HTML/XML in PHP?

You can use SimpleXML (see http://php.net/manual/en/simplexml.examples-basic.php) for parsing

```<code>$xmlStr = '<?xml version="1.0" encoding="UTF-8"?><Response Code="200"><Description>http://sample.net</Description><URL>/Patient/PatientView.aspx?pid=642</URL></Response>';

$response = new SimpleXMLElement($xmlStr);

$url = (string) $response->Description . (string) $response->URL;
</code>```

$url will contain:

```<code>http://sample.net/Patient/PatientView.aspx?pid=642
</code>```

Then use PDO (http://php.net/manual/en/book.pdo.php) to store data into database:

```<code>try {
    $dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
    $stmt = $dbh->prepare("INSERT INTO sample (url) VALUES (:url)");
    $stmt->bindParam(':url', $url);
    $stmt->execute();
} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}
</code>```

Body:
I need help regarding saving XML data into MySQL database. Here is my code:

    <?xml version="1.0" encoding="UTF-8"?><Response Code="200"><Description>http://sample.net</Description><URL>/Patient/PatientView.aspx?pid=642</URL></Response>

Now what I wanted to do is to get the value of the <Description> tag and the <URL> tag and combine them to become a complete url then save it to mysql database.

Body:
See question here How do you parse and process HTML/XML in PHP?

You can use SimpleXML (see http://php.net/manual/en/simplexml.examples-basic.php) for parsing

$xmlStr = '<?xml version="1.0" encoding="UTF-8"?><Response Code="200"><Description>http://sample.net</Description><URL>/Patient/PatientView.aspx?pid=642</URL></Response>';

$response = new SimpleXMLElement($xmlStr);

$url = (string) $response->Description . (string) $response->URL;

$url will contain:

http://sample.net/Patient/PatientView.aspx?pid=642

Then use PDO (http://php.net/manual/en/book.pdo.php) to store data into database:

try {
    $dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
    $stmt = $dbh->prepare("INSERT INTO sample (url) VALUES (:url)");
    $stmt->bindParam(':url', $url);
    $stmt->execute();
} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}


问:
How to get date & month using date in mysql
I want to get date & month from date. example 2017-06-15 so I want date & month i.e. -06-15. Do u have any idea? Really appreciated.

From Below query I am getting month from date. but I want both date & month

```<code>SELECT MONTHNAME(`date`) AS month_name FROM table_name;
</code>```

答:
you can use this function

```<code>DATEPART(datepart,date)
</code>```

use below query

```<code>SELECT DATEPART(yyyy,datecolumn) AS dateYear,
DATEPART(mm,datecolumn) AS dateMonth,
DATEPART(dd,datecolumn) AS dateDay
FROM table_name
</code>```

Body:
I want to get date & month from date. example 2017-06-15 so I want date & month i.e. -06-15. Do u have any idea? Really appreciated.

From Below query I am getting month from date. but I want both date & month

SELECT MONTHNAME(`date`) AS month_name FROM table_name;

Body:
you can use this function

DATEPART(datepart,date)

use below query

SELECT DATEPART(yyyy,datecolumn) AS dateYear,
DATEPART(mm,datecolumn) AS dateMonth,
DATEPART(dd,datecolumn) AS dateDay
FROM table_name


问:
PARSE.COM: Fetch data at query
When a query is made in Parse, only the ObjectId is downloaded.

Is there any way to download all the columns data in the same call?

If there isn't, which is the quickest way to fetch it al?

This is what I came up with, but since the calls are done 1 after each other, it takes so long to execute.

```<code>// Create query
ParseUser user = ParseUser.getCurrentUser();
ParseQuery<Centro> query = ParseQuery.getQuery("...");
query.include(...);
query.whereEqualTo(...);
query.addAscendingOrder(...);

// Execute query
try {
    CLASS = query.find();
} catch (ParseException e) {
    return false;
}

// Force to fetch all data by reading a single column
for (CLASS class : classes){
    try {
        class.fetch();
        class.getSomething();
    } catch (ParseException e) { }
}
</code>```

Any help is appreciated, thank you.

答:
The include function is used to tell Parse to retrieve the contents of other tables too. I thought I had to type the table name in there, however, I had to type the field name instead.

Linking the docs in case anyone is interested: http://docs.parseplatform.org/android/guide/

I realised in the following example, since Comment (table name) is uppercase, and line query.include("post") specifies post in lowercase, it had to be a field name.

```<code>ParseQuery<ParseObject> query = ParseQuery.getQuery("Comment");

// Retrieve the most recent ones
query.orderByDescending("createdAt");

// Only retrieve the last ten
query.setLimit(10);

// Include the post data with each comment
query.include("post");

query.findInBackground(new FindCallback<ParseObject>() {
  public void done(List<ParseObject> commentList, ParseException e) {
    // commentList now contains the last ten comments, and the "post"
    // field has been populated. For example:
    for (ParseObject comment : commentList) {
      // This does not require a network access.
      ParseObject post = comment.getParseObject("post");
      Log.d("post", "retrieved a related post");
    }
  }
});
</code>```

Title: PARSE.COM: Fetch data at query

Body:
When a query is made in Parse, only the ObjectId is downloaded.

Is there any way to download all the columns data in the same call?

If there isn't, which is the quickest way to fetch it al?

This is what I came up with, but since the calls are done 1 after each other, it takes so long to execute.

// Create query
ParseUser user = ParseUser.getCurrentUser();
ParseQuery<Centro> query = ParseQuery.getQuery("...");
query.include(...);
query.whereEqualTo(...);
query.addAscendingOrder(...);

// Execute query
try {
    CLASS = query.find();
} catch (ParseException e) {
    return false;
}

// Force to fetch all data by reading a single column
for (CLASS class : classes){
    try {
        class.fetch();
        class.getSomething();
    } catch (ParseException e) { }
}

Any help is appreciated, thank you.

Body:
The include function is used to tell Parse to retrieve the contents of other tables too. I thought I had to type the table name in there, however, I had to type the field name instead.

Linking the docs in case anyone is interested: http://docs.parseplatform.org/android/guide/

I realised in the following example, since Comment (table name) is uppercase, and line query.include("post") specifies post in lowercase, it had to be a field name.

ParseQuery<ParseObject> query = ParseQuery.getQuery("Comment");

// Retrieve the most recent ones
query.orderByDescending("createdAt");

// Only retrieve the last ten
query.setLimit(10);

// Include the post data with each comment
query.include("post");

query.findInBackground(new FindCallback<ParseObject>() {
  public void done(List<ParseObject> commentList, ParseException e) {
    // commentList now contains the last ten comments, and the "post"
    // field has been populated. For example:
    for (ParseObject comment : commentList) {
      // This does not require a network access.
      ParseObject post = comment.getParseObject("post");
      Log.d("post", "retrieved a related post");
    }
  }
});


问:
Why does my function need parentheses?
In my framework, the functions are called without parentheses.... (See showErrors)

```<code>(function () {
  'use strict';

  angular
    .module('core')
    .directive('showErrors', showErrors);

  showErrors.$inject = ['$timeout', '$interpolate'];

  function showErrors($timeout, $interpolate) {
    var directive = {
      restrict: 'A',
      require: '^form',
      compile: compile
    };

    return directive;
</code>```

I get how it works... but when I try this, my component won't work. It only works if I change it to  .component('hotkeys', HotkeysComponent()); // adding parenthesis to HotkeysComponent

```<code>  angular
    .module('contacts.components')
    .component('hotkeys', HotkeysComponent);

  function HotkeysComponent() {
    var component = {
      templateUrl: '/my-app/contacts/client/views/ui/hotkeys.ui.html',
      controller: 'AddManagerController',
      controllerAs: 'vm'
    };

    return component;
</code>```

To clarify, it won't work unless I do HotkeysComponent()

```<code>angular
  .module('contacts.components')
  .component('hotkeys', HotkeysComponent()); // why don't the other functions need ()?
</code>```

答:
Components can be registered using the .component() method of an AngularJS module (returned by angular.module()). The method takes two arguments:

The name of the Component (as string).

The Component config object. (Note that, unlike the .directive()
method, this method does not take a factory function.)

As per your question, the second argument must be an object and that happens only when you called the function(second argument)

Components in angular js
read this for more info

Title: Why does my function need parentheses?

Body:
In my framework, the functions are called without parentheses.... (See showErrors)

(function () {
  'use strict';

  angular
    .module('core')
    .directive('showErrors', showErrors);

  showErrors.$inject = ['$timeout', '$interpolate'];

  function showErrors($timeout, $interpolate) {
    var directive = {
      restrict: 'A',
      require: '^form',
      compile: compile
    };

    return directive;

I get how it works... but when I try this, my component won't work. It only works if I change it to  .component('hotkeys', HotkeysComponent()); // adding parenthesis to HotkeysComponent

  angular
    .module('contacts.components')
    .component('hotkeys', HotkeysComponent);

  function HotkeysComponent() {
    var component = {
      templateUrl: '/my-app/contacts/client/views/ui/hotkeys.ui.html',
      controller: 'AddManagerController',
      controllerAs: 'vm'
    };

    return component;

To clarify, it won't work unless I do HotkeysComponent()

angular
  .module('contacts.components')
  .component('hotkeys', HotkeysComponent()); // why don't the other functions need ()?


问:
Splitting a vector of objects in c++
I know my message is not properly formattd, but I'm new so please help me anyway.
I have two classes: Father and Son. In Son I have an int and a string.
In father i have a vector of son objects.
How can I access just the part of the vector composed by integers and/or the part just composed by strings?
Thank you very much!

CLASS SON.H

```<code>#ifndef SON_H
#define SON_H
#include <iostream>
using namespace std;

class Son
{
    public:
        Son() {}
        Son(int first, string second);
        virtual ~Son();
        int getFirst() const;
        string getSecond() const;
    private:
        int _first_parameter;
        string _second_parameter;
};

#endif // SON_H
</code>```

CLASS SON.CPP

```<code>#include "son.h"

Son::Son(int first, string second)
{
    _first_parameter=first;
    _second_parameter=second;
}

Son::~Son()
{
    //dtor
}

int Son::getFirst() const
{
    return _first_parameter;
}

string Son::getSecond() const
{
    return _second_parameter;
}
</code>```

CLASS FATHER.H

```<code>#ifndef FATHER_H
#define FATHER_H
#include <vector>
#include "son.h"

class Father
{
    public:
        Father() {}
        virtual ~Father();
        void filling();
    private:
        vector<Son> _access_vector;
        void _printIntegers(vector<int> v);
        void _printStrings(vector<string> v);
};

#endif // FATHER_H
</code>```

CLASS FATHER.CPP

```<code>#include "father.h"

Father::~Father()
{
    //dtor
}

void Father::filling()
{
    int temp_first_param;
    string temp_second_param;
    cout<<"Insert integer: "<<endl;
    cin>>temp_first_param;
    cout<<"Insert text"<<endl;
    cin>>temp_second_param;
    _access_vector.push_back(Son(temp_first_param, temp_second_param));
    _printIntegers(_access_vector.getFirst());                       /// Here I want to take just the vector of integers
    _printStrings(_access_vector.getSecond());                       /// Here I want to take just the vector of strings
}

void Father::_printIntegers(vector<int> v)
{
    for(unsigned i=0; i<v.size(); ++i)
        cout<<v[i]<<endl;
}

void Father::_printStrings(vector<string> v)
{
    for(unsigned i=0; i<v.size(); ++i)
    {
        cout<<v[i]<<endl;
    }
}
</code>```

COMPILER ERRORS:

||=== Build: Debug in Vector_access_experiment (compiler: GNU GCC Compiler) ===|
  C:\Users\Alessandro\Documents\CodeBlocks\Vector_access_experiment\src\father.cpp||In member function 'void Father::filling()':|
  C:\Users\Alessandro\Documents\CodeBlocks\Vector_access_experiment\src\father.cpp|17|error: 'class std::vector' has no member named 'getFirst'|
  C:\Users\Alessandro\Documents\CodeBlocks\Vector_access_experiment\src\father.cpp|18|error: 'class std::vector' has no member named 'getSecond'|
  ||=== Build failed: 2 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

答:
Actual answer was given in the comments, now how to solve your problem at hand and some explanation:

std::vector wraps an array. Which means, in the memory, the data within the vector is consecutive. vec[6] lies at the position of vec[5] + sizeof(type) in memory.

In your case, since Son stores a string and an int, this means that the memory looks like this:

int of entry 0, string length of entry 0, string char pointer of entry 0, int of entry 1, string length of entry 1...

What you try to get is a structure that looks like this:

int of entry 0, int of entry 1, ...

Which is obviously not in there. Creating it will require computation time, no way around that.

Since your method printIntegers copies some vector anyway (because you don't call by reference), you can simply solve this by creating new vectors that store the partial data by iterating over the original vector, but that is bad design.

I'd propose:

```<code>void Father::_printIntegers(const vector<Son>& v) const
{
    for(unsigned i=0; i<v.size(); ++i){
        cout<<v[i].getFirst()<<endl;
    }
}
</code>```

(also added call by reference and const keyword, use those!)

You could also merge Son into Father, creating two vectors within Father, which might make sense in some scenario, depends on your context.

That said, as for your design - if there is a hard separation of Son into integers and strings, Son might be a weak class. Classes are not meant to be mere data holders. The best thing would be that Son does the printing itself. Father should have no knowledge about what members Son has - understand what I mean? That said, also depends on context, sometimes mere data holders is what you want.

edit: some comment to my answer raised a valid point, here the method without parameters:

```<code>void Father::_printIntegers() const
{
    for(unsigned i=0; i<v.size(); ++i){
        cout<<_access_vector[i].getFirst()<<endl;
    }
}
</code>```

Title: Splitting a vector of objects in c++

Body:
I know my message is not properly formattd, but I'm new so please help me anyway.
I have two classes: Father and Son. In Son I have an int and a string.
In father i have a vector of son objects.
How can I access just the part of the vector composed by integers and/or the part just composed by strings?
Thank you very much!

CLASS SON.H

#ifndef SON_H
#define SON_H
#include <iostream>
using namespace std;

class Son
{
    public:
        Son() {}
        Son(int first, string second);
        virtual ~Son();
        int getFirst() const;
        string getSecond() const;
    private:
        int _first_parameter;
        string _second_parameter;
};

#endif // SON_H

CLASS SON.CPP

#include "son.h"

Son::Son(int first, string second)
{
    _first_parameter=first;
    _second_parameter=second;
}

Son::~Son()
{
    //dtor
}

int Son::getFirst() const
{
    return _first_parameter;
}

string Son::getSecond() const
{
    return _second_parameter;
}

CLASS FATHER.H

#ifndef FATHER_H
#define FATHER_H
#include <vector>
#include "son.h"

class Father
{
    public:
        Father() {}
        virtual ~Father();
        void filling();
    private:
        vector<Son> _access_vector;
        void _printIntegers(vector<int> v);
        void _printStrings(vector<string> v);
};

#endif // FATHER_H

CLASS FATHER.CPP

#include "father.h"

Father::~Father()
{
    //dtor
}

void Father::filling()
{
    int temp_first_param;
    string temp_second_param;
    cout<<"Insert integer: "<<endl;
    cin>>temp_first_param;
    cout<<"Insert text"<<endl;
    cin>>temp_second_param;
    _access_vector.push_back(Son(temp_first_param, temp_second_param));
    _printIntegers(_access_vector.getFirst());                       /// Here I want to take just the vector of integers
    _printStrings(_access_vector.getSecond());                       /// Here I want to take just the vector of strings
}

void Father::_printIntegers(vector<int> v)
{
    for(unsigned i=0; i<v.size(); ++i)
        cout<<v[i]<<endl;
}

void Father::_printStrings(vector<string> v)
{
    for(unsigned i=0; i<v.size(); ++i)
    {
        cout<<v[i]<<endl;
    }
}

COMPILER ERRORS:

||=== Build: Debug in Vector_access_experiment (compiler: GNU GCC Compiler) ===|
  C:\Users\Alessandro\Documents\CodeBlocks\Vector_access_experiment\src\father.cpp||In member function 'void Father::filling()':|
  C:\Users\Alessandro\Documents\CodeBlocks\Vector_access_experiment\src\father.cpp|17|error: 'class std::vector' has no member named 'getFirst'|
  C:\Users\Alessandro\Documents\CodeBlocks\Vector_access_experiment\src\father.cpp|18|error: 'class std::vector' has no member named 'getSecond'|
  ||=== Build failed: 2 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

Body:
Actual answer was given in the comments, now how to solve your problem at hand and some explanation:

std::vector wraps an array. Which means, in the memory, the data within the vector is consecutive. vec[6] lies at the position of vec[5] + sizeof(type) in memory.

In your case, since Son stores a string and an int, this means that the memory looks like this:

int of entry 0, string length of entry 0, string char pointer of entry 0, int of entry 1, string length of entry 1...

What you try to get is a structure that looks like this:

int of entry 0, int of entry 1, ...

Which is obviously not in there. Creating it will require computation time, no way around that.

Since your method printIntegers copies some vector anyway (because you don't call by reference), you can simply solve this by creating new vectors that store the partial data by iterating over the original vector, but that is bad design.

I'd propose:

void Father::_printIntegers(const vector<Son>& v) const
{
    for(unsigned i=0; i<v.size(); ++i){
        cout<<v[i].getFirst()<<endl;
    }
}

(also added call by reference and const keyword, use those!)

You could also merge Son into Father, creating two vectors within Father, which might make sense in some scenario, depends on your context.

That said, as for your design - if there is a hard separation of Son into integers and strings, Son might be a weak class. Classes are not meant to be mere data holders. The best thing would be that Son does the printing itself. Father should have no knowledge about what members Son has - understand what I mean? That said, also depends on context, sometimes mere data holders is what you want.

edit: some comment to my answer raised a valid point, here the method without parameters:

void Father::_printIntegers() const
{
    for(unsigned i=0; i<v.size(); ++i){
        cout<<_access_vector[i].getFirst()<<endl;
    }
}


问:
I am trying to run MYSQL command using SSH on the remote server. Getting the below error
I am trying to run MYSQL command using SSH on the remote server. Getting the below error

```<code>ssh -p 22 root@eseemon63 "mysql --compress --secure-auth --database nacoma --execute 'SELECT time,object_name FROM changelog_history WHERE object_type = 'host' AND oldname = 'New Host' AND time >= DATE_SUB(NOW(), INTERVAL 1 MONTH) ORDER BY time;'"
</code>```

Error is:

```<code>ERROR 1102 (42000): Incorrect database name 'Host AND time >= DATE_SUB(NOW(), INTERVAL 1 MONTH) ORDER BY time;'
</code>```

答:
Its fixed by entering "'" </p>

```<code>ssh -p 22 root@eseemon63 "mysql --compress --secure-auth --database nacoma --execute 'SELECT time,object_name FROM changelog_history WHERE object_type = 'host' AND oldname = 'New Host' AND time >= DATE_SUB(NOW(), INTERVAL 1 MONTH) ORDER BY time;'"
</code>```

Body:
I am trying to run MYSQL command using SSH on the remote server. Getting the below error

ssh -p 22 root@eseemon63 "mysql --compress --secure-auth --database nacoma --execute 'SELECT time,object_name FROM changelog_history WHERE object_type = 'host' AND oldname = 'New Host' AND time >= DATE_SUB(NOW(), INTERVAL 1 MONTH) ORDER BY time;'"

Error is:

ERROR 1102 (42000): Incorrect database name 'Host AND time >= DATE_SUB(NOW(), INTERVAL 1 MONTH) ORDER BY time;'

Body:
Its fixed by entering "'"

ssh -p 22 root@eseemon63 "mysql --compress --secure-auth --database nacoma --execute 'SELECT time,object_name FROM changelog_history WHERE object_type = 'host' AND oldname = 'New Host' AND time >= DATE_SUB(NOW(), INTERVAL 1 MONTH) ORDER BY time;'"


问:
How does the browser render Images with different sizes ( tag in HTML)?
If an HTML document has three images in different sizes (5MB, 50KB and 10MB) then which image will be rendered first in the page? Does the browser process  tags synchronously? That is, will the render sequence  be

5_mb_img.jpg > 50_kb_img.jpg > 10_mb_img.jpg

OR

might 50_kb_img.jpg be rendered first because  it is smallest in size?

```<code><img src="5_mb_img.jpg" /> <!-- a 5MB image file -->
<img src="50_kb_img.jpg" /> <!-- a 50KB image file -->
<img src="10_mb_img.jpg" /> <!-- a 10MB image file -->
</code>```

WHY A BOUNTY? I know the answer but am expecting a very good explanation that helps someone who is searching it in Stack Overflow

答:
Q: If a HTML document has three images in different size (5MB, 50KB and 10MB) then which image will be rendered first in the page. Is browser process  tag synchronously?

A: The image with the less weight(MB or KB) will be the one to load first. As the higher the resolution, the more pixels will have to load on that particular image making it a little bit slower than the other with less resolution.

Title: How does the browser render Images with different sizes (<img> tag in HTML)?

Body:
If an HTML document has three images in different sizes (5MB, 50KB and 10MB) then which image will be rendered first in the page? Does the browser process  tags synchronously? That is, will the render sequence  be

5_mb_img.jpg > 50_kb_img.jpg > 10_mb_img.jpg

OR

might 50_kb_img.jpg be rendered first because  it is smallest in size?

WHY A BOUNTY? I know the answer but am expecting a very good explanation that helps someone who is searching it in Stack Overflow


问:
How to make library for linked-list functions
I want to create static or dynamic library for linked list functions, but when I try to compile function files with gcc to get object file it gives me error ‘struct node’ declared inside parameter list
 int GetNth(struct node* head, int index) & dereferencing pointer to incomplete type ‘struct node’ if(i == index) return head->data;. Not sure what's going on, may be because I haven't declared the structure in the file

```<code>#include <stdlib.h>
int count(struct node* head, int n) //counts the occurrence of n in the list
{
  int c = 0;
  while(head != NULL){
    if(head->data == n) c+=1;
    head = head->next;
  }
  return c;
}
</code>```

But if I'll declare it inside this file, I think it'll violate 1 definition rule. What to do?

structure is declared in the main function as

```<code>struct node{
  int data;
  struct node *next;
}
</code>```

答:
Continuing from the comment, in your code, the compiler does not know what node is because you have not provided its declaration. You can provide a declaration including a typedef for convenience. The following code declares a typedef to struct _node {...} as node; and then declares two nodes (statically for simplicity reasons), iterates over the list, outputting the data values and then ends, e.g.

```<code>#include <stdio.h>

typedef struct _node {
    int data;
    struct _node *next;
} node;

int main (void) {

    node n1 = {.data = 1},
         n2 = {.data = 2, .next = NULL};
    n1.next = &n2;

    /* iterate over list outputting data values */
    for (node *n = &n1; n != NULL; n = n->next)
        printf ("%d\n", n->data);

    return 0;
}
</code>```

Example Use/Output

```<code>$ ./bin/llstatic
1
2
</code>```

As mentioned, you can create a header file for your list and include your declaration of struct _node and the typedef there, or if you simply use node within this source-file, you can declare it here. Let me know if you have further questions.

Body:
I want to create static or dynamic library for linked list functions, but when I try to compile function files with gcc to get object file it gives me error ‘struct node’ declared inside parameter list
 int GetNth(struct node* head, int index) & dereferencing pointer to incomplete type ‘struct node’ if(i == index) return head->data;. Not sure what's going on, may be because I haven't declared the structure in the file

#include <stdlib.h>
int count(struct node* head, int n) //counts the occurrence of n in the list
{
  int c = 0;
  while(head != NULL){
    if(head->data == n) c+=1;
    head = head->next;
  }
  return c;
}

But if I'll declare it inside this file, I think it'll violate 1 definition rule. What to do?

structure is declared in the main function as

struct node{
  int data;
  struct node *next;
}

Body:
Continuing from the comment, in your code, the compiler does not know what node is because you have not provided its declaration. You can provide a declaration including a typedef for convenience. The following code declares a typedef to struct _node {...} as node; and then declares two nodes (statically for simplicity reasons), iterates over the list, outputting the data values and then ends, e.g.

#include <stdio.h>

typedef struct _node {
    int data;
    struct _node *next;
} node;

int main (void) {

    node n1 = {.data = 1},
         n2 = {.data = 2, .next = NULL};
    n1.next = &n2;

    /* iterate over list outputting data values */
    for (node *n = &n1; n != NULL; n = n->next)
        printf ("%d\n", n->data);

    return 0;
}

Example Use/Output

$ ./bin/llstatic
1
2

As mentioned, you can create a header file for your list and include your declaration of struct _node and the typedef there, or if you simply use node within this source-file, you can declare it here. Let me know if you have further questions.


问:
Custom Upload Images using CKEditor, BLOB field and Rails 4
I'm currently using CKEditor in my site. The user may upload some images to the server using the button for Upload Image in the CKEditor.

There is a textarea field with id #article_conteudo on the page that uses the CKEditor, here is the javascript code to configure the editor:

```<code>CKEDITOR.replace('article_conteudo', {
    filebrowserImageUploadUrl: '/article/upload/'
});
</code>```

The URL /article/upload/ points to a method file_upload in an articles_controller:

```<code>def file_upload
    image = ArticlesImage.new

    image.imagem = params[:upload].read

    image.save
end
</code>```

The images are stored in a BLOB field in a MySQL Database.

The images are saved in the database with no problems. But, after saving, nothing happens in the Editor. I'm not sure what is the expected response for the Upload Action of the CKEditor on this case. I'm not sure, also, if CKEditor uploads support the use of BLOBs.

How can I implement this functionality in my project?

If it can't be done with CKEditor, is there any other plugin that can do it?

Thanks for your help

PS: The use of BLOB is MANDATORY for the project, I cannot use other methods

答:
it depends of what you need.

If you want to display images on your browser, you have to create the JSON response involved.

And then, the fileUploadResponse of the CKEditor would be able to display your images (or files) on your editor.

Body:
I'm currently using CKEditor in my site. The user may upload some images to the server using the button for Upload Image in the CKEditor.

There is a textarea field with id #article_conteudo on the page that uses the CKEditor, here is the javascript code to configure the editor:

CKEDITOR.replace('article_conteudo', {
    filebrowserImageUploadUrl: '/article/upload/'
});

The URL /article/upload/ points to a method file_upload in an articles_controller:

def file_upload
    image = ArticlesImage.new

    image.imagem = params[:upload].read

    image.save
end

The images are stored in a BLOB field in a MySQL Database.

The images are saved in the database with no problems. But, after saving, nothing happens in the Editor. I'm not sure what is the expected response for the Upload Action of the CKEditor on this case. I'm not sure, also, if CKEditor uploads support the use of BLOBs.

How can I implement this functionality in my project?

If it can't be done with CKEditor, is there any other plugin that can do it?

Thanks for your help

PS: The use of BLOB is MANDATORY for the project, I cannot use other methods


问:
Make a global dict object in python which can access and edit from any py files
I want keep some global data which can access and edit from any python files. I tried with python classes but it is not working across the files the code is given below.(Note :I am not interested to do any file operations)</p>

```<code>class Settings(object):
    """docstring for Settings"""
    device = None
    def __init__(self, *args, **kwargs):
        if Settings.device is None:
            Settings.device = DeviceSettings()

class DeviceSettings(object):
    def __init__(self, *args, **kwargs):
        self.mode = None
        self.ops = []
        self.phyops = None

Settings()
Settings.device
</code>```

答:
Im not a fan of this but if you really need it just create a global dict in a module and then import it:

```<code>#a.py

MY_GLOBAL_DICT = {}

#b.py

from a import MY_GLOBAL_DICT
MY_GLOBAL_DICT["hey"] = 10
</code>```

Here you have a working example

Body:
I want keep some global data which can access and edit from any python files. I tried with python classes but it is not working across the files the code is given below.(Note :I am not interested to do any file operations)

class Settings(object):
    """docstring for Settings"""
    device = None
    def __init__(self, *args, **kwargs):
        if Settings.device is None:
            Settings.device = DeviceSettings()

class DeviceSettings(object):
    def __init__(self, *args, **kwargs):
        self.mode = None
        self.ops = []
        self.phyops = None

Settings()
Settings.device

Body:
Im not a fan of this but if you really need it just create a global dict in a module and then import it:

#a.py

MY_GLOBAL_DICT = {}

#b.py

from a import MY_GLOBAL_DICT
MY_GLOBAL_DICT["hey"] = 10

Here you have a working example


问:
How to define a function inside a loop
Why is this not working ?

```<code>u = {}
for me in ['foo', 'bar']:
   def callback():
       return 'I am %s' % me
   u[me] = callback
</code>```

The output I get is:

```<code>>>> u['foo']()
'I am bar'
</code>```

It seems the callback is defined once at the latest iteration.

EDIT

As proposed by kawadhiya21, a class approach would work:

```<code>class CallbackFactory():
    def __init__(self, me):
       self.me = me

    def __call__(self):
       return 'I am %s' % self.me

u = {}
for me in ['foo', 'bar']:

   u[me] = CallbackFactory(me)
</code>```

But it is far more complicated than the former approach.

答:
You want to define a family of callbacks, not simply save a bunch of outputs, right? Define a function that binds the parameter you want, like this:</p>

```<code>def make_callback(param):
    def callback():
       return 'I am %s' % param
    return callback

for me in ['foo', 'bar']:
    u[me] = make_callback(me)

>>> u["foo"]()
'I am foo'
</code>```

Title: How to define a function inside a loop

Body:
Why is this not working ?

u = {}
for me in ['foo', 'bar']:
   def callback():
       return 'I am %s' % me
   u[me] = callback

The output I get is:

>>> u['foo']()
'I am bar'

It seems the callback is defined once at the latest iteration.

EDIT

As proposed by kawadhiya21, a class approach would work:

class CallbackFactory():
    def __init__(self, me):
       self.me = me

    def __call__(self):
       return 'I am %s' % self.me

u = {}
for me in ['foo', 'bar']:

   u[me] = CallbackFactory(me)

But it is far more complicated than the former approach.

Body:
You want to define a family of callbacks, not simply save a bunch of outputs, right? Define a function that binds the parameter you want, like this:

def make_callback(param):
    def callback():
       return 'I am %s' % param
    return callback

for me in ['foo', 'bar']:
    u[me] = make_callback(me)

>>> u["foo"]()
'I am foo'


问:
How do I get rid of this border outline for my image map areas when clicked (OS X Chrome Only)
I have this image map

http://corfro.com/projects/charlie-faye-tour-map/

And when you click on the different cities a black border shows up on the area but only happening in Chrome. (you might need to click a few times on different cities but the border will show up - once the bus arrives at the city the borders start showing up)

I've tried the following but to no avail.

```<code>a{outline:none;}
map > area,
map > area:active,
map > area:focus {outline: none; border:0; }
</code>```

Do you guys have any suggestions? Any help is much appreciated as this is driving me crazy!

答:
I'm experiencing exactly the same thing with Chrome on OS X (v 8.0.552.224). I just restarted Chrome and got an automatic upgrade on my Mac for this to start appearing, so must be something in the new release.

I have noted though that the colour of the outline can be changed by altering the "outline-color" attribute of the image, but have been unable to hide it completely even though "outline" is set to "none".

Body:
I have this image map

http://corfro.com/projects/charlie-faye-tour-map/

And when you click on the different cities a black border shows up on the area but only happening in Chrome. (you might need to click a few times on different cities but the border will show up - once the bus arrives at the city the borders start showing up)

I've tried the following but to no avail.

a{outline:none;}
map > area,
map > area:active,
map > area:focus {outline: none; border:0; }

Do you guys have any suggestions? Any help is much appreciated as this is driving me crazy!


问:
TypeLoadException - how to proceed
So I try to load my dependencies into my code, and then I get this:

TypeLoadException: Could not load type
  'System.Data.SqlClient.SqlConnection' from assembly 'System.Data,
  Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.
  System.Reflection.MonoMethodInfo.GetMethodInfo (IntPtr handle) (at
  /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Reflection/MonoMethod.cs:59)
  System.Reflection.MonoMethodInfo.GetAttributes (IntPtr handle) (at
  /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Reflection/MonoMethod.cs:75)
  System.Reflection.MonoMethod.get_Attributes () (at
  /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Reflection/MonoMethod.cs:245)
  System.Reflection.MethodBase.get_IsSpecialName () (at
  /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Reflection/MethodBase.cs:184)
  UnityEditor.Build.BuildPipelineInterfaces.InitializeBuildCallbacks
  (Boolean findBuildProcessors, Boolean findSceneProcessors) (at
  C:/buildslave/unity/build/Editor/Mono/BuildPipeline/BuildPipelineInterfaces.cs:149)y

I'm using mono, so that may be the reason? I don't really know, since it's the first time I try to work with a database on Unity.

What could I do to make it work?

答:
Did you use System.Data.dll from one of {ProgramFilesDir/x86}\Reference Assemblies\Microsoft\Framework.NETFramework\v3.5\Profile\ Unity profiles (e.g., Unity "Subset v3.5") folders?

Did you put it in "Assets/**/Plugins" folder?

Error tells you that you'r developing with other assembly version that you build / run (in other enviroment) your app.

Title: TypeLoadException - how to proceed


问:
How to properly from VBA connection from Excel sheet to another Excel sheet?
I currently have 2 separate Excel worksheets. One is data entry and another is display.

The display uses VBA to connect to data entry to obtain data. Normally, it functions well enough. However I'm required to have the 2 worksheets in separate windows, meaning both can be displayed at the same time in separate windows, in the same screen.

The issue in this scenario is that when I click Execute in display to begin SQL query, the display window opens another data entry worksheet (read-only) and reads that instead of the one I opened initially. Is this issue due to my connection string or my ADODB.Recordset has issues?

Here is the sub which contains the connection string and ADODB.Recordset.
Edit: Full code is included to provide full context for those who need it.

```<code>Public Sub QueryWorksheet(szSQL As String, rgStart As Range, wbWorkBook As String, AB As String)
Dim rsData As ADODB.Recordset
Dim szConnect As String
On Error GoTo ErrHandler

If AB = "1st" Then
wbWorkBook = ThisWorkbook.Sheets("Inner Workings").Range("B9").Text
End If

Application.StatusBar = "Retrieving data ....."
'Set up the connection string to excel - thisworkbook
szConnect = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
            "Data Source=" & wbWorkBook & ";" & _
            "Extended Properties=Excel 8.0;"

Set rsData = New ADODB.Recordset
'Run the query as adCmdText
rsData.Open szSQL, szConnect, adOpenForwardOnly, adLockReadOnly, adCmdText

'Check if data is returned
If Not rsData.EOF Then
    'if the recordset contains data put them on the worksheet
    rgStart.CopyFromRecordset rsData
Else

End If
'Close connection
rsData.Close
'Clean up and get out
Set rsData = Nothing
Application.StatusBar = False
Exit Sub

ErrHandler:
'an error occured in the SQL-statement
MsgBox "Your query could not be executed, the SQL-statement is incorrect."
Set rsData = Nothing
Application.StatusBar = False

End Sub

Sub process()
Call clear
Call testsql("1st")  ' populate 1st Summary
Call testsql("2nd")  ' find Date+Time
Call testsql("3rd")  ' arrange record by newest
Call testsql("4th")  ' show final results
End Sub

Sub testsql(AB As String)

Dim rgPlaceOutput As Range    'first cell for the output of the query
Dim stSQLstring As String     'text of the cell containing the SQL statement
Dim rg As String, SQL As String

If AB = "1st" Then
stSQLstring = ThisWorkbook.Sheets("Inner Workings").Range("B2").Text
Set rgPlaceOutput = ThisWorkbook.Sheets("1st Summary").Range("A2")
End If
If AB = "2nd" Then
stSQLstring = ThisWorkbook.Sheets("Inner Workings").Range("B3").Text
Set rgPlaceOutput = ThisWorkbook.Sheets("2nd Summary").Range("A2")
End If
If AB = "3rd" Then
stSQLstring = ThisWorkbook.Sheets("Inner Workings").Range("B4").Text
Set rgPlaceOutput = ThisWorkbook.Sheets("3rd Summary").Range("A2")
End If
If AB = "4th" Then
stSQLstring = ThisWorkbook.Sheets("Inner Workings").Range("B5").Text
Set rgPlaceOutput = ThisWorkbook.Sheets("Final Summary").Range("A5")
End If

QueryWorksheet stSQLstring, rgPlaceOutput, ThisWorkbook.FullName, AB

End Sub

Sub clear()
ActiveWorkbook.Sheets("1st Summary").Range("A2:BR5000").Value = Empty
ActiveWorkbook.Sheets("2nd Summary").Range("A2:BR5000").Value = Empty
ActiveWorkbook.Sheets("3rd Summary").Range("A2:BR5000").Value = Empty
ActiveWorkbook.Sheets("Final Summary").Range("A5:BR5000").Value = Empty
End Sub
</code>```

Also another thing I noticed. Depending on which file I open first, it can result in both files creating a read-only copy when I click Execute. If I open Display first then Entry form, both in different instances of Excel, it will create read-only copies of both files.

If I open Entry form first, then Display in again, different instances of Excel, only the read-only copy of Display will appear.

The only time a read-only does not appear is when both files are in a single instance of Excel, which is not what I want.

Edit2:

For more info, here is the SQL I used (4 total)

SQL1 - select * from EntryTable

SQL2 - select A.*,[Date + Time] from Summary1 A left join (select [Die No], max (Date + Time) as [Date + Time] from Summary1 group by [Die No]) B on A.[Die No] = B.[Die No]

SQL3 - select * from Summary2 where [Date + Time] = Date + Time

SQL4 - select Project_No, Die_No, Description, Repair_Details, Status from Summary3

Workbook name in cell B9 = V:\Die Maintenance System v2\Die Maintenance Menu.xlsx

Update: My colleague has tested the system on her PC and tested no problems. I've been told its most likely my Excel settings. But for the life of me, I can't figure out what is causing it. What type of setting is used to prevent the read-only file from appearing?

Edit: I can see that this post has gone on too long. I decided to continue this on a new thread right here.

答:
I tired using ACE and it worked just fine. It didn't open a new file.

```<code>szConnect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & _
            wbWorkBook  & "';" & _
            "Extended Properties='Excel 12.0;HDR=Yes;IMEX=1';"
</code>```

Body:
I currently have 2 separate Excel worksheets. One is data entry and another is display.

The display uses VBA to connect to data entry to obtain data. Normally, it functions well enough. However I'm required to have the 2 worksheets in separate windows, meaning both can be displayed at the same time in separate windows, in the same screen.

The issue in this scenario is that when I click Execute in display to begin SQL query, the display window opens another data entry worksheet (read-only) and reads that instead of the one I opened initially. Is this issue due to my connection string or my ADODB.Recordset has issues?

Here is the sub which contains the connection string and ADODB.Recordset.
Edit: Full code is included to provide full context for those who need it.

Public Sub QueryWorksheet(szSQL As String, rgStart As Range, wbWorkBook As String, AB As String)
Dim rsData As ADODB.Recordset
Dim szConnect As String
On Error GoTo ErrHandler

If AB = "1st" Then
wbWorkBook = ThisWorkbook.Sheets("Inner Workings").Range("B9").Text
End If

Application.StatusBar = "Retrieving data ....."
'Set up the connection string to excel - thisworkbook
szConnect = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
            "Data Source=" & wbWorkBook & ";" & _
            "Extended Properties=Excel 8.0;"

Set rsData = New ADODB.Recordset
'Run the query as adCmdText
rsData.Open szSQL, szConnect, adOpenForwardOnly, adLockReadOnly, adCmdText

'Check if data is returned
If Not rsData.EOF Then
    'if the recordset contains data put them on the worksheet
    rgStart.CopyFromRecordset rsData
Else

End If
'Close connection
rsData.Close
'Clean up and get out
Set rsData = Nothing
Application.StatusBar = False
Exit Sub

ErrHandler:
'an error occured in the SQL-statement
MsgBox "Your query could not be executed, the SQL-statement is incorrect."
Set rsData = Nothing
Application.StatusBar = False

End Sub

Sub process()
Call clear
Call testsql("1st")  ' populate 1st Summary
Call testsql("2nd")  ' find Date+Time
Call testsql("3rd")  ' arrange record by newest
Call testsql("4th")  ' show final results
End Sub

Sub testsql(AB As String)

Dim rgPlaceOutput As Range    'first cell for the output of the query
Dim stSQLstring As String     'text of the cell containing the SQL statement
Dim rg As String, SQL As String

If AB = "1st" Then
stSQLstring = ThisWorkbook.Sheets("Inner Workings").Range("B2").Text
Set rgPlaceOutput = ThisWorkbook.Sheets("1st Summary").Range("A2")
End If
If AB = "2nd" Then
stSQLstring = ThisWorkbook.Sheets("Inner Workings").Range("B3").Text
Set rgPlaceOutput = ThisWorkbook.Sheets("2nd Summary").Range("A2")
End If
If AB = "3rd" Then
stSQLstring = ThisWorkbook.Sheets("Inner Workings").Range("B4").Text
Set rgPlaceOutput = ThisWorkbook.Sheets("3rd Summary").Range("A2")
End If
If AB = "4th" Then
stSQLstring = ThisWorkbook.Sheets("Inner Workings").Range("B5").Text
Set rgPlaceOutput = ThisWorkbook.Sheets("Final Summary").Range("A5")
End If

QueryWorksheet stSQLstring, rgPlaceOutput, ThisWorkbook.FullName, AB

End Sub

Sub clear()
ActiveWorkbook.Sheets("1st Summary").Range("A2:BR5000").Value = Empty
ActiveWorkbook.Sheets("2nd Summary").Range("A2:BR5000").Value = Empty
ActiveWorkbook.Sheets("3rd Summary").Range("A2:BR5000").Value = Empty
ActiveWorkbook.Sheets("Final Summary").Range("A5:BR5000").Value = Empty
End Sub

Also another thing I noticed. Depending on which file I open first, it can result in both files creating a read-only copy when I click Execute. If I open Display first then Entry form, both in different instances of Excel, it will create read-only copies of both files.

If I open Entry form first, then Display in again, different instances of Excel, only the read-only copy of Display will appear.

The only time a read-only does not appear is when both files are in a single instance of Excel, which is not what I want.

Edit2:

For more info, here is the SQL I used (4 total)

SQL1 - select * from EntryTable

SQL2 - select A.*,[Date + Time] from Summary1 A left join (select [Die No], max (Date + Time) as [Date + Time] from Summary1 group by [Die No]) B on A.[Die No] = B.[Die No]

SQL3 - select * from Summary2 where [Date + Time] = Date + Time

SQL4 - select Project_No, Die_No, Description, Repair_Details, Status from Summary3

Workbook name in cell B9 = V:\Die Maintenance System v2\Die Maintenance Menu.xlsx

Update: My colleague has tested the system on her PC and tested no problems. I've been told its most likely my Excel settings. But for the life of me, I can't figure out what is causing it. What type of setting is used to prevent the read-only file from appearing?

Edit: I can see that this post has gone on too long. I decided to continue this on a new thread right here.

Body:
I tired using ACE and it worked just fine. It didn't open a new file.

szConnect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & _
            wbWorkBook  & "';" & _
            "Extended Properties='Excel 12.0;HDR=Yes;IMEX=1';"


问:
IssuableSubscriptionVisitor & BaseTreeVisitor
I would like to ask when writing custom rules for java in SonarQube, in which circumstances does the test logic class extends IssuableSubscriptionVisitor and which circumstances is BaseTreeVisitor extended instead?

Thank you.

答: That depends what you are trying to achieve. Ususally the subscription visitor is a bit simpler to implement but the visit of the AST is handled for you and you can't control it which the BaseTreeVisitor allows you to do which can be required when implementing rules with a bit of complexity. </p>


问:
Set a list in a variable in subquery - MYSQL
My problem is the following, I want set a list of ID in a variable, then use this variable in a subquery. The problem is that WorkBench (my GUI) return the following error : "subquery returning multiple rows". It seems to me that's what I want.

 Please explain me where I am wrong.

This is my query :

```<code>set @listID := (select ID_VOIE as ID from voies
    where ORIGINE = 'XXX'
    group by CODE_INSEE, CODE_VOIE
    having count(*) > 1);

select substring(v.CODE_INSEE,1,2), count(*) from voies v
    where v.ID_VOIE in (@listID)
    group by substring(vs.CODE_INSEE,1,2);
</code>```

The thing is I'm blocked with the "group by", I want do a groupd by after a first group by, that's why I can't (or at least i didn't find a way) write the request with a single WHERE clause.

The thing is I know that I can put the whole request directly in my subquery instead of using variable but :

It can let me use this trick in another requests that needed this behaviour (DRY concept !)

I'm not sure but the subquery will be executed in each turn of my loop, and that will be very inefficient

So I seek 2 possible ways : a way that let me use a list in a variable in a subquery OR a way that let me use "group by" twice in a single query.

Thanks you in advance for your answers (oh and sorry for my english, this is not my maternal language).

答:
Unless you need that variable for something else, you should be able to skip it entirely as follows:

```<code>SELECT
    SUBSTRING(v.CODE_INSEE,1,2),
    COUNT(*)
FROM
    voies v
WHERE
    v.ID_VOIE in
    (SELECT
         ID_VOIE as ID
     FROM
         voies
     WHERE
         ORIGINE = 'XXX'
     GROUP BY
         CODE_INSEE,
         CODE_VOIE
     HAVING COUNT(*) > 1)
GROUP BY
    SUBSTRING(vs.CODE_INSEE,1,2);
</code>```

As you say, the subquery will be executed for all rows. To avoid that, a variable would be best, but MySQL doesn't support table variables. Instead, you can use a temporary table:

```<code>IF EXISTS DROP TABLE myTempTable;
CREATE TEMPORARY TABLE myTempTable (ID_VOIE int); -- I don't know the datatype
INSERT INTO myTempTable (ID_VOIE)
SELECT DISTINCT -- using distinct so I can join instead of use IN.
    ID_VOIE as ID from voies
WHERE
    ORIGINE = 'XXX'
GROUP BY
    CODE_INSEE, CODE_VOIE
HAVING COUNT(*) > 1
</code>```

And now you can do this:

```<code>SELECT
    SUBSTRING(v.CODE_INSEE,1,2), COUNT(*)
FROM
   voies v
   JOIN myTempTable tt ON
       v.ID_VOIE = tt.ID_VOIE
GROUP BY SUBSTRING(vs.CODE_INSEE,1,2);
</code>```

Body:
My problem is the following, I want set a list of ID in a variable, then use this variable in a subquery. The problem is that WorkBench (my GUI) return the following error : "subquery returning multiple rows". It seems to me that's what I want.

 Please explain me where I am wrong.

This is my query :

set @listID := (select ID_VOIE as ID from voies
    where ORIGINE = 'XXX'
    group by CODE_INSEE, CODE_VOIE
    having count(*) > 1);

select substring(v.CODE_INSEE,1,2), count(*) from voies v
    where v.ID_VOIE in (@listID)
    group by substring(vs.CODE_INSEE,1,2);

The thing is I'm blocked with the "group by", I want do a groupd by after a first group by, that's why I can't (or at least i didn't find a way) write the request with a single WHERE clause.

The thing is I know that I can put the whole request directly in my subquery instead of using variable but :

It can let me use this trick in another requests that needed this behaviour (DRY concept !)

I'm not sure but the subquery will be executed in each turn of my loop, and that will be very inefficient

So I seek 2 possible ways : a way that let me use a list in a variable in a subquery OR a way that let me use "group by" twice in a single query.

Thanks you in advance for your answers (oh and sorry for my english, this is not my maternal language).

Body:
Unless you need that variable for something else, you should be able to skip it entirely as follows:

SELECT
    SUBSTRING(v.CODE_INSEE,1,2),
    COUNT(*)
FROM
    voies v
WHERE
    v.ID_VOIE in
    (SELECT
         ID_VOIE as ID
     FROM
         voies
     WHERE
         ORIGINE = 'XXX'
     GROUP BY
         CODE_INSEE,
         CODE_VOIE
     HAVING COUNT(*) > 1)
GROUP BY
    SUBSTRING(vs.CODE_INSEE,1,2);

As you say, the subquery will be executed for all rows. To avoid that, a variable would be best, but MySQL doesn't support table variables. Instead, you can use a temporary table:

IF EXISTS DROP TABLE myTempTable;
CREATE TEMPORARY TABLE myTempTable (ID_VOIE int); -- I don't know the datatype
INSERT INTO myTempTable (ID_VOIE)
SELECT DISTINCT -- using distinct so I can join instead of use IN.
    ID_VOIE as ID from voies
WHERE
    ORIGINE = 'XXX'
GROUP BY
    CODE_INSEE, CODE_VOIE
HAVING COUNT(*) > 1

And now you can do this:

SELECT
    SUBSTRING(v.CODE_INSEE,1,2), COUNT(*)
FROM
   voies v
   JOIN myTempTable tt ON
       v.ID_VOIE = tt.ID_VOIE
GROUP BY SUBSTRING(vs.CODE_INSEE,1,2);


问:
add sender's name in the from field of the email in python
I am trying to send email with below code.

```<code>import smtplib
from email.mime.text import MIMEText

sender = 'sender@sender.com'

def mail_me(cont, receiver):
    msg = MIMEText(cont, 'html')
    recipients = ",".join(receiver)
    msg['Subject'] = 'Test-email'
    msg['From'] = "XYZ ABC"
    msg['To'] = recipients
    # Send the message via our own SMTP server.
    try:
        s = smtplib.SMTP('localhost')
        s.sendmail(sender, receiver, msg.as_string())
        print "Successfully sent email"
    except SMTPException:
        print "Error: unable to send email"
    finally:
        s.quit()

cont = """\
   <html>
     <head></head>
     <body>
       <p>Hi!<br>
          How are you?<br>
          Here is the <a href="http://www.google.com">link</a> you wanted.
       </p>
     </body>
   </html>
   """
mail_me(cont,['xyz@xyzcom'])
</code>```

I want "XYZ ABC" to appear as the sender's name when the email is received and its email address as 'sender@sender.com'. but when i receive email i am receiving weird details in "from" fields of the email message.

```<code>[![from:    XYZ@<machine-hostname-appearing-here>
reply-to:   XYZ@<machine-hostname-appearing-here>,
ABC@<machine-hostname-appearing-here>][1]][1]
</code>```

I have attached a screenshot of the email that i receive.

how can i fix this according to my need.

答:
This should fix it:

Replace mail_me(cont,['xyz@xyzcom'])
with

```<code>mail_me(cont,'xyz@xyz.com')
</code>```

Body:
I am trying to send email with below code.

import smtplib
from email.mime.text import MIMEText

sender = 'sender@sender.com'

def mail_me(cont, receiver):
    msg = MIMEText(cont, 'html')
    recipients = ",".join(receiver)
    msg['Subject'] = 'Test-email'
    msg['From'] = "XYZ ABC"
    msg['To'] = recipients
    # Send the message via our own SMTP server.
    try:
        s = smtplib.SMTP('localhost')
        s.sendmail(sender, receiver, msg.as_string())
        print "Successfully sent email"
    except SMTPException:
        print "Error: unable to send email"
    finally:
        s.quit()

cont = """\

Hi!

          How are you?

          Here is the link you wanted.

   """
mail_me(cont,['xyz@xyzcom'])

I want "XYZ ABC" to appear as the sender's name when the email is received and its email address as 'sender@sender.com'. but when i receive email i am receiving weird details in "from" fields of the email message.

[![from:    XYZ@<machine-hostname-appearing-here>
reply-to:   XYZ@<machine-hostname-appearing-here>,
ABC@<machine-hostname-appearing-here>][1]][1]

I have attached a screenshot of the email that i receive.

how can i fix this according to my need.

Body:
This should fix it:

Replace mail_me(cont,['xyz@xyzcom'])
with

mail_me(cont,'xyz@xyz.com')


问:
Silex 2 - Provider needs another service not yet registered
I have a service provider, that wants to call a method of another service from another provider, that is not yet registered. How can i solve this?

Let's say i have a service $app["two"] that has a doStuff() method. Then i have a service $app["one"]. During registration of $app["one"], it's service provider needs to call the $app["two"]->doStuff() method, but since the provider of $app["two"] is registered after $app["one"], that is impossible since silex doesnt know it yet.

The Provideder of $app["one"]:

```<code>class OneServiceProvider implements ServiceProviderInterface {

    public function register(Container $app) {

        $app['one'] = function () use ($app) {
            $app['two']->doStuff(); // <- Error since not yet registered!
            return new OneService();
        };
    }
}
</code>```

The registration part of the main app:

```<code>$app->register(new OneServiceProvider());
$app->register(new TwoServiceProvider());
</code>```

In Silex 1, i think there was this extend method, which could extend/change a service when it is registered. In silex 2, i couldnt find anything similar. Is there any solution to it or should i dispatch an event in $app["two"] and subscribe to it in $app["one"]? Or should i use the boot method to call $app["two"]?

Update

I just tried the $app->extend approach. Sadly it still threw an error calling member function doStuff() on null

class OneServiceProvider implements ServiceProviderInterface {

```<code>public function register(Container $app) {

    $app['one'] = function () use ($app) {
        $one = new OneService();
        $app->extend("two", function($two, $c){
            $two->doStuff();
        })
        return $one;
    };
}
</code>```

}

Solution
Since i can no longer reproduce the original issue in clean test code, i'll have to assume that the problem was unrelated. Silex 2 seems to take care of this problem, no matter how you access services during their registration.
Tnx for your help anyways!

答:
I think your problem is the lazy call. Don't use this :

```<code>$app['one'] = function () use ($app) {
</code>```

but :

```<code>$app['one'] = function (Container $app) {
</code>```

In the first one, the app don't have provider two.

UPDATE

It's working for me :

TwoServiceProvider.php

```<code>class TwoServiceProvider implements ServiceProviderInterface
{
    public function register(Container $app)
    {
        $app['two'] = function() {
            return new Test();
        };
    }
}
</code>```

OneServiceProvider.php

```<code>class OneServiceProvider implements ServiceProviderInterface
{
    public function register(Container $app)
    {
        $app['one'] = function(Container $app) {
            $app['two']->doStuff();
            return new Test2();
        };
    }
}
</code>```

index.php

```<code>$app->register(new OneServiceProvider());
$app->register(new TwoServiceProvider());
$app['one']->doStuff();
</code>```

Body:
I have a service provider, that wants to call a method of another service from another provider, that is not yet registered. How can i solve this?

Let's say i have a service $app["two"] that has a doStuff() method. Then i have a service $app["one"]. During registration of $app["one"], it's service provider needs to call the $app["two"]->doStuff() method, but since the provider of $app["two"] is registered after $app["one"], that is impossible since silex doesnt know it yet.

The Provideder of $app["one"]:

class OneServiceProvider implements ServiceProviderInterface {

    public function register(Container $app) {

        $app['one'] = function () use ($app) {
            $app['two']->doStuff(); // <- Error since not yet registered!
            return new OneService();
        };
    }
}

The registration part of the main app:

$app->register(new OneServiceProvider());
$app->register(new TwoServiceProvider());

In Silex 1, i think there was this extend method, which could extend/change a service when it is registered. In silex 2, i couldnt find anything similar. Is there any solution to it or should i dispatch an event in $app["two"] and subscribe to it in $app["one"]? Or should i use the boot method to call $app["two"]?

Update

I just tried the $app->extend approach. Sadly it still threw an error calling member function doStuff() on null

class OneServiceProvider implements ServiceProviderInterface {

public function register(Container $app) {

    $app['one'] = function () use ($app) {
        $one = new OneService();
        $app->extend("two", function($two, $c){
            $two->doStuff();
        })
        return $one;
    };
}

}

Solution
Since i can no longer reproduce the original issue in clean test code, i'll have to assume that the problem was unrelated. Silex 2 seems to take care of this problem, no matter how you access services during their registration.
Tnx for your help anyways!

Body:
I think your problem is the lazy call. Don't use this :

$app['one'] = function () use ($app) {

but :

$app['one'] = function (Container $app) {

In the first one, the app don't have provider two.

UPDATE

It's working for me :

TwoServiceProvider.php

class TwoServiceProvider implements ServiceProviderInterface
{
    public function register(Container $app)
    {
        $app['two'] = function() {
            return new Test();
        };
    }
}

OneServiceProvider.php

class OneServiceProvider implements ServiceProviderInterface
{
    public function register(Container $app)
    {
        $app['one'] = function(Container $app) {
            $app['two']->doStuff();
            return new Test2();
        };
    }
}

index.php

$app->register(new OneServiceProvider());
$app->register(new TwoServiceProvider());
$app['one']->doStuff();


问:
React how to pass an state to another component
Hello i split my app and would like to pass the state from my <button />
to <menu />   I'm simply trying to do is toggle a function with an onClick.

So the Button.js file will have 1 buttons when clicked will toggle the states to visible or invisible. The menu  component Menu.js will need know about these state changes so they can toggle the function and will show the menu

Button component

```<code>import React, { PureComponent } from 'react';
import CSSTransitionGroup from 'react-addons-css-transition-group';
import { themr } from 'react-css-themr';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import localStyles from './NavButton.scss';

@themr('NavButton', localStyles)

export default class NavButton extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      visible: false,
    };
    this.toggleMenu = this.toggleMenu.bind(this);
  }

  toggleMenu() {
    this.setState({
      visible: !this.state.visible
    })
    console.log('toggle');
  }

  render() {

    const {theme } = this.props;
    return (
      <div className={theme['nav-button']} onClick={this.toggleMenu}>
      <span></span>
      <span></span>
      </div>
    );
  }
}
</code>```

Menu

```<code>import React, { PureComponent } from 'react';
import CSSTransitionGroup from 'react-addons-css-transition-group';
import { themr } from 'react-css-themr';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import localStyles from './Menu.scss';
import { NavButton } from '../../components';

@themr('Menu', localStyles)

export default class Menu extends React.Component {

  render() {

    return (

      <div className="menu-wrapper">
      <CSSTransitionGroup
        transitionName="menu"
        transitionEnterTimeout={300}
        transitionLeaveTimeout={300}>
        {this.state.visible &&
        <Menus alignment="right">
          <MenuItem hash="first-page">First Page</MenuItem>
          <MenuItem hash="second-page">Second Page</MenuItem>
          <MenuItem hash="third-page">Third Page</MenuItem>
        </Menus>}
        </CSSTransitionGroup>
      </div>
    );
  }
}
const Menus = ({alignment, children, theme }) => (
  <div className="menu">
  <div className={alignment}>{children}</div>
  </div>
);
</code>```

答:
It's better to maintain the state of an application at the top most component, so it kinda governs the brains of the app.

If you moved the state into the Menu, you can pass the onClick callback into the Button e.g.

Menu.js

```<code><NavButton toggleClick={this.handleClick} />
</code>```

Then you can move the State information into the Menu as well as the handleClick function.

This allows the Button to be stateless:

```<code>const NavButton = ({theme, toggleClick}) => (
    <div className={theme['nav-button']} onClick={toggleMenu}>
        <span></span>
        <span></span>
    </div>
);
</code>```

Body:
Hello i split my app and would like to pass the state from my <button />
to <menu />   I'm simply trying to do is toggle a function with an onClick.

So the Button.js file will have 1 buttons when clicked will toggle the states to visible or invisible. The menu  component Menu.js will need know about these state changes so they can toggle the function and will show the menu

Button component

import React, { PureComponent } from 'react';
import CSSTransitionGroup from 'react-addons-css-transition-group';
import { themr } from 'react-css-themr';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import localStyles from './NavButton.scss';

@themr('NavButton', localStyles)

export default class NavButton extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      visible: false,
    };
    this.toggleMenu = this.toggleMenu.bind(this);
  }

  toggleMenu() {
    this.setState({
      visible: !this.state.visible
    })
    console.log('toggle');
  }

  render() {

    const {theme } = this.props;
    return (

    );
  }
}

Menu

import React, { PureComponent } from 'react';
import CSSTransitionGroup from 'react-addons-css-transition-group';
import { themr } from 'react-css-themr';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import localStyles from './Menu.scss';
import { NavButton } from '../../components';

@themr('Menu', localStyles)

export default class Menu extends React.Component {

  render() {

    return (

      <CSSTransitionGroup
        transitionName="menu"
        transitionEnterTimeout={300}
        transitionLeaveTimeout={300}>
        {this.state.visible &&
        <Menus alignment="right">
          <MenuItem hash="first-page">First Page</MenuItem>
          <MenuItem hash="second-page">Second Page</MenuItem>
          <MenuItem hash="third-page">Third Page</MenuItem>
        </Menus>}
        </CSSTransitionGroup>

    );
  }
}
const Menus = ({alignment, children, theme }) => (

{children}

);

Body:
It's better to maintain the state of an application at the top most component, so it kinda governs the brains of the app.

If you moved the state into the Menu, you can pass the onClick callback into the Button e.g.

Menu.js

<NavButton toggleClick={this.handleClick} />

Then you can move the State information into the Menu as well as the handleClick function.

This allows the Button to be stateless:

const NavButton = ({theme, toggleClick}) => (
    <div className={theme['nav-button']} onClick={toggleMenu}>
        <span></span>
        <span></span>
    </div>
);


问:
SQL update all records except the last one with a value
I need to make a query where only the last line of each user that has a car gets a license plate number.

```<code>ID    UserId    LicensePlate    HasCar
1     1         ABC123          1
2     1         ABC123          1
3     2         NULL            0
4     3         UVW789          1
5     3         UVW789          1
</code>```

Should become:

```<code>ID    UserId    LicensePlate    HasCar
1     1         NULL            1
2     1         ABC123          1
3     2         NULL            0
4     3         NULL            1
5     3         UVW789          1
</code>```

So I basically need to find all users with a licenseplate and change all but the last one and make the LicensePlate NULL

答:
Assuming the ID column is an identity column so it can provide the ordering, something like this should do the trick:</p>

```<code>;WITH CTE AS
(
    SELECT Id,
           UserId,
           LicensePlate,
           ROW_NUMBER() OVER(PARTITION BY UserId ORDER BY Id DESC) rn
    FROM Table
    WHERE HasCar = 1
)

UPDATE CTE
SET LicensePlate = NULL
WHERE rn > 1
</code>```

Body:
I need to make a query where only the last line of each user that has a car gets a license plate number.

ID    UserId    LicensePlate    HasCar
1     1         ABC123          1
2     1         ABC123          1
3     2         NULL            0
4     3         UVW789          1
5     3         UVW789          1

Should become:

ID    UserId    LicensePlate    HasCar
1     1         NULL            1
2     1         ABC123          1
3     2         NULL            0
4     3         NULL            1
5     3         UVW789          1

So I basically need to find all users with a licenseplate and change all but the last one and make the LicensePlate NULL

Body:
Assuming the ID column is an identity column so it can provide the ordering, something like this should do the trick:

;WITH CTE AS
(
    SELECT Id,
           UserId,
           LicensePlate,
           ROW_NUMBER() OVER(PARTITION BY UserId ORDER BY Id DESC) rn
    FROM Table
    WHERE HasCar = 1
)

UPDATE CTE
SET LicensePlate = NULL
WHERE rn > 1