问:
CI Active record, Select record from multiple table
I have two table. First is product in which Admin will add the Products and another is product_detail in which vendors will add the detail. Multiple vendors can add same product with the product detail like selling price, offer price etc.

"I want to select products from products table and want to select product detail from product_detail table but only one row of product detail which has less  selling price".

So i want to use CI active records to get the final output as product list with its detail.

答:
Take this for example :

```<code>Create table #Product(id int, name varchar(100));
Create table #Product_detail(id int, product_id int, detail varchar(100));

insert into #Product values
(1,'Item1'),
(2,'Item2')

insert into #Product_detail values
(1,1,20),
(2,1,10),
(3,1,40),
(4,2,70),
(5,2,50)
</code>```

this is your basic query:

```<code>select
a.*, b.price
from
 #product a inner join
 (select product_id, min(price) price
  from #product_detail
  group by product_id
 ) b
on a.id = b.product_id
</code>```

In CI, try to do something like this:

```<code>$var = $this->db->query("select a.*, b.price from #product a
                         inner join
                        (select product_id, min(price) price
                         from #product_detail
                         group by product_id
                         ) b
                        on a.id = b.product_id")->result_array();
</code>```

sample output :

```<code>id          name   price
----------- ------ -----------
1           Item1  10
2           Item2  50
</code>```

Body:
Take this for example :

Create table #Product(id int, name varchar(100));
Create table #Product_detail(id int, product_id int, detail varchar(100));

insert into #Product values
(1,'Item1'),
(2,'Item2')

insert into #Product_detail values
(1,1,20),
(2,1,10),
(3,1,40),
(4,2,70),
(5,2,50)

this is your basic query:

select
a.*, b.price
from
 #product a inner join
 (select product_id, min(price) price
  from #product_detail
  group by product_id
 ) b
on a.id = b.product_id

In CI, try to do something like this:

$var = $this->db->query("select a.*, b.price from #product a
                         inner join
                        (select product_id, min(price) price
                         from #product_detail
                         group by product_id
                         ) b
                        on a.id = b.product_id")->result_array();

sample output :

id          name   price
----------- ------ -----------
1           Item1  10
2           Item2  50


来源: stackexchange

问:
Is there a way to debug the worker processes in pm2 while application is running in Cluster mode
So I have a node.js application which I am running in cluster mode using pm2. I am passing the following options for the web node in my pm2 schema.

```<code>exec-mode : "cluster"
--node-args : ["--inspect=5678"]
</code>```

and for worker node I am passing following configuration

```<code>--node-args=["--inspect=5679"]
</code>```

When I start my application in cluster mode, debugging is not possible as I cannot see the debugging URL printed in pm2 logs. Even if I send the USR1 signal to the web or worker node (as mentioned in node inspector help), I do not see any way to debug the processes.

My guess is that in cluster mode, debugging node.js is not possible. I tried the same process with node-inspector but no luck yet.

答: Pass the node_args as a string instead of array (eg --node-args="--inspect=1234")</p>

ContentLicense: CC BY-SA 3.0

Body:
So I have a node.js application which I am running in cluster mode using pm2. I am passing the following options for the web node in my pm2 schema.

exec-mode : "cluster"
--node-args : ["--inspect=5678"]

and for worker node I am passing following configuration

--node-args=["--inspect=5679"]

When I start my application in cluster mode, debugging is not possible as I cannot see the debugging URL printed in pm2 logs. Even if I send the USR1 signal to the web or worker node (as mentioned in node inspector help), I do not see any way to debug the processes.

My guess is that in cluster mode, debugging node.js is not possible. I tried the same process with node-inspector but no luck yet.


问:
Creation of a timer thread in python
```<code>from threading import Thread, current_thread

def hello():
    print("hello, world")
    t = threading.Timer(3.0, hello)
    t.start()
    print current_thread().name

hello()
</code>```

This will create a new thread periodically every 3 seconds. I want to know whether the created thread be expired and then again new thread will be created.? I can see the thread name as "Thread-1", "Thread-2", "Thread-3" and so on be created. I want to know whether "Thread-1" will eventually exit and then a new thread is created i.e "Thread-2" or still "Thread-1" would remain active. Pls help.

答:
Your threads will exit when they complete. In fact, as your print command is the last line in hello(), it means a thread exits as soon as it has displayed its name.  You can use threading.enumerate() to display all running threads:

```<code>from threading import Thread, current_thread, Timer, enumerate

def hello():
    print("hello, world")
    t = Timer(3.0, hello)
    t.start()
    print enumerate()
    print current_thread().name, "exiting"

hello()
</code>```

The only exception is the main thread, that does not exit but remains in stopped state until your program exits, which would never happen with this code but nevertheless. All other threads do their work and then exit.

Does this answer to your question?

Hannu

Title: Creation of a timer thread in python

Body:
from threading import Thread, current_thread

def hello():
    print("hello, world")
    t = threading.Timer(3.0, hello)
    t.start()
    print current_thread().name

hello()

This will create a new thread periodically every 3 seconds. I want to know whether the created thread be expired and then again new thread will be created.? I can see the thread name as "Thread-1", "Thread-2", "Thread-3" and so on be created. I want to know whether "Thread-1" will eventually exit and then a new thread is created i.e "Thread-2" or still "Thread-1" would remain active. Pls help.

Body:
Your threads will exit when they complete. In fact, as your print command is the last line in hello(), it means a thread exits as soon as it has displayed its name.  You can use threading.enumerate() to display all running threads:

from threading import Thread, current_thread, Timer, enumerate

def hello():
    print("hello, world")
    t = Timer(3.0, hello)
    t.start()
    print enumerate()
    print current_thread().name, "exiting"

hello()

The only exception is the main thread, that does not exit but remains in stopped state until your program exits, which would never happen with this code but nevertheless. All other threads do their work and then exit.

Does this answer to your question?

Hannu


问:
How to get integer values from array based on first digits java
I have int number value and int[] numberArray.

I want to get all values from numberArray that starts with number.

What I am trying to do is

```<code>for (int i=0;i<numbers.length;i++){
    if(numberArray[i] "starts with" number){
        System.out.print(numberArray[i]);
     }
}
</code>```

I also need to use 2 and 3 digit numbers.

Could you help me find a solution for that?

EDIT: Thanks for help, found a solution. At the end code look like that:

```<code>String num = String.valueOf(number);
for (int i =0; i< numberArray.size();i++) {
    String anumber = String.valueOf(numberArray[i]);
    if (anumber.startsWith(num)){
        System.out.print(numberArray[i])
    }
}
</code>```

答:
Use the number of digits in the number. You can also compare String instead of convert back to int. You should also check the number of digits in the number is not bigger the number of digits in the number from the array</p>

```<code>int number;
String stringNumber = String.valueOf(number);

for (int i = 0 ; i < numbers.length ; i++) {
    String num = Integer.toString(numbers[i]);
    if(num.length() >= stringNumber.length() && num.substring(0, stringNumber.length()).equals(stringNumber)) {
        System.out.println(numbers[i]);
    }
}
</code>```

Body:
I have int number value and int[] numberArray.

I want to get all values from numberArray that starts with number.

What I am trying to do is

for (int i=0;i<numbers.length;i++){
    if(numberArray[i] "starts with" number){
        System.out.print(numberArray[i]);
     }
}

I also need to use 2 and 3 digit numbers.

Could you help me find a solution for that?

EDIT: Thanks for help, found a solution. At the end code look like that:

String num = String.valueOf(number);
for (int i =0; i< numberArray.size();i++) {
    String anumber = String.valueOf(numberArray[i]);
    if (anumber.startsWith(num)){
        System.out.print(numberArray[i])
    }
}

Body:
Use the number of digits in the number. You can also compare String instead of convert back to int. You should also check the number of digits in the number is not bigger the number of digits in the number from the array

int number;
String stringNumber = String.valueOf(number);

for (int i = 0 ; i < numbers.length ; i++) {
    String num = Integer.toString(numbers[i]);
    if(num.length() >= stringNumber.length() && num.substring(0, stringNumber.length()).equals(stringNumber)) {
        System.out.println(numbers[i]);
    }
}


问:
Disable the arrow keys while a JAR is executed
The case is as follows:

1) I have a script somescript.sh.

2) At the end of the script, there is an eval statement which triggers the execution of a JAR.

3) When the JAR is executed, it will ask the user to provide an a/b/c option as a possible answer - important fact is that this questions come from the JAR application, so the console "logic" regarding the questions is written in Java and not placed in the script itself.

The problem: while executing the JAR program, the user can press the arrow keys and this will result in an ugly outcome such as ^[[A ^[[B ^[[C ^[[D.

This thread clarifies the ugly outcome: Why the terminal shows "^[[A" "^[[B" "^[[C" "^[[D" when pressing the arrow keys in Ubuntu?

Question: How is it possible to disable the arrow keys while the JAR is executed?

答:
Now this is rather convoluted, but it`s still better than nothing.

The code below is a primitive BASH key filter to bypass cursor keys and halt any input on pressing Enter. Currently it lacks backspace support, but this is also doable if need be.

Requires BASH 4.2 or greater.

```<code>while true; do
    read -s -N1          c1
    read -s -N2 -t 0.001 c2
    read -s -N1 -t 0.001 c3
    case "$c1$c2$c3" in
        $'\x0a' | $'') echo "";
                       break ;; # Enter
        $'\x1b\x5b\x41')     ;; # Up arrow
        $'\x1b\x5b\x42')     ;; # Down arrow
        $'\x1b\x5b\x43')     ;; # Right arrow
        $'\x1b\x5b\x44')     ;; # Left arrow
        *) echo -n $c1$c2$c3 ;; # [guaranteed to be non-empty]
    esac
done | tee >(stdbuf -o0 java -jar your_applet.jar)
</code>```

read is a BASH built-in function that captures keyboard input.

echo is a BASH built-in function that prints what it`s told.

tee redirects the output to both STDOUT and the file provided.

>() is the so-called process substitution; it acts like a file for the writer and passes the resulting file`s contents as input to the command inside its brackets.

stdbuf disables output buffering, just in case.

Both tee and stdbuf are parts of coreutils, so they have to be present almost everywhere (maybe except Android, but that`s another story).

[UPD.] Last line, adapted:

```<code>done | tee >(stdbuf -o0 "$JAVA" $JAVA_OPTS -jar "$JBOSS_HOME/jboss-modules.jar" -mp "$JBOSS_MODULEPATH" org.jboss.as.domain-add-user "$@")
</code>```

Hopefully that`d work.

[UPD2.] FINALLY! A different solution!

Just add this before eval:

```<code>stty=$(stty -g)
stty -ctlecho
trap "stty $stty" HUP INT QUIT PIPE TERM
</code>```

Okay, this is also not perfect (the user is now able to travel the screen by pressing cursor keys…) but that`s still better than ^[[B^[[A^[[D^[[C

Body:
Now this is rather convoluted, but it`s still better than nothing.

The code below is a primitive BASH key filter to bypass cursor keys and halt any input on pressing Enter. Currently it lacks backspace support, but this is also doable if need be.

Requires BASH 4.2 or greater.

while true; do
    read -s -N1          c1
    read -s -N2 -t 0.001 c2
    read -s -N1 -t 0.001 c3
    case "$c1$c2$c3" in
        $'\x0a' | $'') echo "";
                       break ;; # Enter
        $'\x1b\x5b\x41')     ;; # Up arrow
        $'\x1b\x5b\x42')     ;; # Down arrow
        $'\x1b\x5b\x43')     ;; # Right arrow
        $'\x1b\x5b\x44')     ;; # Left arrow
        *) echo -n $c1$c2$c3 ;; # [guaranteed to be non-empty]
    esac
done | tee >(stdbuf -o0 java -jar your_applet.jar)

read is a BASH built-in function that captures keyboard input.

echo is a BASH built-in function that prints what it`s told.

tee redirects the output to both STDOUT and the file provided.

>() is the so-called process substitution; it acts like a file for the writer and passes the resulting file`s contents as input to the command inside its brackets.

stdbuf disables output buffering, just in case.

Both tee and stdbuf are parts of coreutils, so they have to be present almost everywhere (maybe except Android, but that`s another story).

[UPD.] Last line, adapted:

done | tee >(stdbuf -o0 "$JAVA" $JAVA_OPTS -jar "$JBOSS_HOME/jboss-modules.jar" -mp "$JBOSS_MODULEPATH" org.jboss.as.domain-add-user "$@")

Hopefully that`d work.

[UPD2.] FINALLY! A different solution!

Just add this before eval:

stty=$(stty -g)
stty -ctlecho
trap "stty $stty" HUP INT QUIT PIPE TERM

Okay, this is also not perfect (the user is now able to travel the screen by pressing cursor keys…) but that`s still better than ^[[B^[[A^[[D^[[C


问:
'NoneType' object has no attribute 'name' -Attribute Error

views.py

What is wrong in the 7th line

```<code>@login_required
        def user_recommendation_list(request):
            #get request user reviewed wines
            user_reviews = Review.objects.filter(user_name=request.user.username).prefetch_related('wine')
            user_reviews_wine_ids = set(map(lambda x: x.wine.id, user_reviews))
            #get request user cluster name (just the first one righ now)
            user_cluster_name =User.objects.get(username=request.user.username).cluster_set.first().name
</code>```

答:
First, you can directly access the logged in user via request.user

```<code>user_cluster = request.user.cluster_set.first()
</code>```

Then you should check if the user have at least one cluster assigned, as first may return None in that case

```<code>user_cluster_name = user_cluster.name if user_cluser else None
</code>```

user_cluster_name will be None if the user have a cluster assigned otherwise it will be None

Body:
views.py

What is wrong in the 7th line

@login_required
        def user_recommendation_list(request):
            #get request user reviewed wines
            user_reviews = Review.objects.filter(user_name=request.user.username).prefetch_related('wine')
            user_reviews_wine_ids = set(map(lambda x: x.wine.id, user_reviews))
            #get request user cluster name (just the first one righ now)
            user_cluster_name =User.objects.get(username=request.user.username).cluster_set.first().name

Body:
First, you can directly access the logged in user via request.user

user_cluster = request.user.cluster_set.first()

Then you should check if the user have at least one cluster assigned, as first may return None in that case

user_cluster_name = user_cluster.name if user_cluser else None

user_cluster_name will be None if the user have a cluster assigned otherwise it will be None


问:
System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection.'
```<code>protected void getSUM()
{
    // SQL query that gets total of product sales where category id = 1
    string SqlQuery = @"SELECT Price AS TotalSales
  FROM STOCK
  WHERE Barcode = '" + TextBox1 + "'";

    // Declare and open a connection to database

    sqlcon.Open();

    // Creates SqlCommand object
    SqlCommand comm = new SqlCommand(SqlQuery, sqlcon);

    // Gets total sales
    decimal TotalSales = Convert.ToDecimal(comm.ExecuteScalar());

    // Close connection
    sqlcon.Close();

    // Adds formatted output to GridView footer
    GridView1.Columns[3].FooterText = String.Format("{0:c}", TotalSales);
}
</code>```

i just want to add the price at the footer of the gridview. i don't understand what's wrong. the error is in this line GridView1.Columns[3].FooterText = String.Format("{0:c}", TotalSales);

答:
You are probably using AutoGenerateColumns="true" in your GridView. When using this you will only have access to the columns in the RowCreated and RowDataBound events. When the grid is done building the column count will be 0.

Better use TemplateFields. You'll have much more control that way.

```<code><asp:GridView ID="GridView1" runat="server">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <%# Eval("myColumn") %>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
</code>```

Now GridView1.Columns.Count will return 1.

Body:
protected void getSUM()
{
    // SQL query that gets total of product sales where category id = 1
    string SqlQuery = @"SELECT Price AS TotalSales
  FROM STOCK
  WHERE Barcode = '" + TextBox1 + "'";

    // Declare and open a connection to database

    sqlcon.Open();

    // Creates SqlCommand object
    SqlCommand comm = new SqlCommand(SqlQuery, sqlcon);

    // Gets total sales
    decimal TotalSales = Convert.ToDecimal(comm.ExecuteScalar());

    // Close connection
    sqlcon.Close();

    // Adds formatted output to GridView footer
    GridView1.Columns[3].FooterText = String.Format("{0:c}", TotalSales);
}

i just want to add the price at the footer of the gridview. i don't understand what's wrong. the error is in this line GridView1.Columns[3].FooterText = String.Format("{0:c}", TotalSales);

Body:
You are probably using AutoGenerateColumns="true" in your GridView. When using this you will only have access to the columns in the RowCreated and RowDataBound events. When the grid is done building the column count will be 0.

Better use TemplateFields. You'll have much more control that way.

<asp:GridView ID="GridView1" runat="server">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <%# Eval("myColumn") %>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Now GridView1.Columns.Count will return 1.


问:
How to manage multiple calls to Membership.GetUser() efficiently
I have multiple calls to Membership.GetUser() and can't seem to find anything built in to cope with this (without hitting the database multiple times).

I first looked into static variables before realising this was not suitable. I know I can use sessions but I would need to hash/encrypt the userID to make it safe, which is fine but I didn't want to do this without checking if there was a built in way to do this within the .net membership provider

Is there a built in way of remembering a value like the UserID and safely storing that for the current user?

答:
Membership.GetUser() is an indirect call to the class MembershipProvider's method:

```<code>public abstract MembershipUser GetUser(string username, bool userIsOnline);
</code>```

So, you can write a class that derives from the MembershipProvider you're using (for example SqlMembershipProvider or ActiveDirectoryMembershipProvider, or a custom one) and override this method using some clever cache mechanism.

Then you will need to change the web.config to declare this new MembershipProvider class:

```<code><membership defaultProvider="MyProvider">
    <providers>
        <clear/>
        <add name="MyProvider" type="...MyProvider" ... />
    </providers>
</membership>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Membership.GetUser() is an indirect call to the class MembershipProvider's method:

public abstract MembershipUser GetUser(string username, bool userIsOnline);

So, you can write a class that derives from the MembershipProvider you're using (for example SqlMembershipProvider or ActiveDirectoryMembershipProvider, or a custom one) and override this method using some clever cache mechanism.

Then you will need to change the web.config to declare this new MembershipProvider class:

<membership defaultProvider="MyProvider">
    <providers>
        <clear/>
        <add name="MyProvider" type="...MyProvider" ... />
    </providers>
</membership>


问:
Why is the `LIKE` operator not working with integer columns?
I'm trying to receive some ids from my database for an autocomplete search on my CAKEPHP 3.3 site. But my problem is that its only returning the id if I type in the exact id and not part of it.

Here is my function to search the data. The name variable is what is being passed from input.

```<code>public function search()
{
    if ($this->request->is('ajax'))
    {
        $name = $this->request->query['term'];
        $resultArr = $this->Invoices->find('all', [
            'conditions' => ['Invoices.id LIKE' => ($name . '%')]
        ]);
        $resultsArr = [];
        foreach ($resultArr as $result)
        {
             $resultsArr[] = ($result['id']);
        }

        $this->set('resultsArr', $resultsArr);
        // This line is what handles converting your array into json
        // To get this to work you must load the request handler
        $this->set('_serialize', ['resultsArr']);
    }
}
</code>```

For example there is a id in the table '5254' and I type in part of the id '52' nothing is returned but when I type in the whole id '5254' the id is returned.

I'm unsure why this is the case because in my sql query i'm using the percent sign to say any characters after what has been typed into the input.

Here is part of my table

SQL debug when 52 is entered.

```<code>object(Cake\ORM\Query) {

    '(help)' => 'This is a Query object, to get the results execute or iterate it.',
    'sql' => 'SELECT Invoices.id AS `Invoices__id`, Invoices.start_date AS `Invoices__start_date`, Invoices.close_date AS `Invoices__close_date`, Invoices.customer_id AS `Invoices__customer_id`, Invoices.invoice_to_address AS `Invoices__invoice_to_address`, Invoices.ship_to_address AS `Invoices__ship_to_address`, Invoices.customer_contact_id AS `Invoices__customer_contact_id`, Invoices.aircraft_registration_id AS `Invoices__aircraft_registration_id`, Invoices.shipping_company_id AS `Invoices__shipping_company_id`, Invoices.notes AS `Invoices__notes`, Invoices.worksheet_notes AS `Invoices__worksheet_notes`, Invoices.closed AS `Invoices__closed`, Invoices.times_printed AS `Invoices__times_printed`, Invoices.payment_due AS `Invoices__payment_due`, Invoices.GST_rate AS `Invoices__GST_rate`, Invoices.opening_notes AS `Invoices__opening_notes`, Invoices.courier_ticket AS `Invoices__courier_ticket`, Invoices.job_description AS `Invoices__job_description`, Invoices.worksheets_printed AS `Invoices__worksheets_printed`, Invoices.supervising_engineer_id AS `Invoices__supervising_engineer_id`, Invoices.job_type_id AS `Invoices__job_type_id`, Invoices.opened_by_id AS `Invoices__opened_by_id`, Invoices.assigned_to_id AS `Invoices__assigned_to_id`, Invoices.certification_required AS `Invoices__certification_required`, Invoices.currency_id AS `Invoices__currency_id`, Invoices.xero_batch_number AS `Invoices__xero_batch_number`, Invoices.xero_amount AS `Invoices__xero_amount`, Invoices.exchange_rate AS `Invoices__exchange_rate`, Invoices.payment_instructions AS `Invoices__payment_instructions`, Invoices.email AS `Invoices__email`, Invoices.inv_email AS `Invoices__inv_email` FROM invoices Invoices WHERE Invoices.id like :c0',
    'params' => [
        ':c0' => [
            'value' => '52%',
            'type' => 'integer',
            'placeholder' => 'c0'
        ]
</code>```

答:
The id column is of type INTEGER, and therefore the value is being bound as such, as can be seen in your Query dump, it says 'type' => 'integer'. Being bound as an integer will cause it to be casted, and you'll end up with a comparison against 52 only.

You can workaround that by telling the query builder to treat the column as a string type. This can be done via the second argument ($types) of the query builders *where() methods:

```<code>$this->Invoices
    ->find()
    ->where(
        ['Invoices.id LIKE' => ($name . '%')],
        ['Invoices.id' => 'string']
    );
</code>```

See also

API > \Cake\ORM\Query::where()

Body:
I'm trying to receive some ids from my database for an autocomplete search on my CAKEPHP 3.3 site. But my problem is that its only returning the id if I type in the exact id and not part of it.

Here is my function to search the data. The name variable is what is being passed from input.

public function search()
{
    if ($this->request->is('ajax'))
    {
        $name = $this->request->query['term'];
        $resultArr = $this->Invoices->find('all', [
            'conditions' => ['Invoices.id LIKE' => ($name . '%')]
        ]);
        $resultsArr = [];
        foreach ($resultArr as $result)
        {
             $resultsArr[] = ($result['id']);
        }

        $this->set('resultsArr', $resultsArr);
        // This line is what handles converting your array into json
        // To get this to work you must load the request handler
        $this->set('_serialize', ['resultsArr']);
    }
}

For example there is a id in the table '5254' and I type in part of the id '52' nothing is returned but when I type in the whole id '5254' the id is returned.

I'm unsure why this is the case because in my sql query i'm using the percent sign to say any characters after what has been typed into the input.

Here is part of my table

SQL debug when 52 is entered.

object(Cake\ORM\Query) {

    '(help)' => 'This is a Query object, to get the results execute or iterate it.',
    'sql' => 'SELECT Invoices.id AS `Invoices__id`, Invoices.start_date AS `Invoices__start_date`, Invoices.close_date AS `Invoices__close_date`, Invoices.customer_id AS `Invoices__customer_id`, Invoices.invoice_to_address AS `Invoices__invoice_to_address`, Invoices.ship_to_address AS `Invoices__ship_to_address`, Invoices.customer_contact_id AS `Invoices__customer_contact_id`, Invoices.aircraft_registration_id AS `Invoices__aircraft_registration_id`, Invoices.shipping_company_id AS `Invoices__shipping_company_id`, Invoices.notes AS `Invoices__notes`, Invoices.worksheet_notes AS `Invoices__worksheet_notes`, Invoices.closed AS `Invoices__closed`, Invoices.times_printed AS `Invoices__times_printed`, Invoices.payment_due AS `Invoices__payment_due`, Invoices.GST_rate AS `Invoices__GST_rate`, Invoices.opening_notes AS `Invoices__opening_notes`, Invoices.courier_ticket AS `Invoices__courier_ticket`, Invoices.job_description AS `Invoices__job_description`, Invoices.worksheets_printed AS `Invoices__worksheets_printed`, Invoices.supervising_engineer_id AS `Invoices__supervising_engineer_id`, Invoices.job_type_id AS `Invoices__job_type_id`, Invoices.opened_by_id AS `Invoices__opened_by_id`, Invoices.assigned_to_id AS `Invoices__assigned_to_id`, Invoices.certification_required AS `Invoices__certification_required`, Invoices.currency_id AS `Invoices__currency_id`, Invoices.xero_batch_number AS `Invoices__xero_batch_number`, Invoices.xero_amount AS `Invoices__xero_amount`, Invoices.exchange_rate AS `Invoices__exchange_rate`, Invoices.payment_instructions AS `Invoices__payment_instructions`, Invoices.email AS `Invoices__email`, Invoices.inv_email AS `Invoices__inv_email` FROM invoices Invoices WHERE Invoices.id like :c0',
    'params' => [
        ':c0' => [
            'value' => '52%',
            'type' => 'integer',
            'placeholder' => 'c0'
        ]

Body:
The id column is of type INTEGER, and therefore the value is being bound as such, as can be seen in your Query dump, it says 'type' => 'integer'. Being bound as an integer will cause it to be casted, and you'll end up with a comparison against 52 only.

You can workaround that by telling the query builder to treat the column as a string type. This can be done via the second argument ($types) of the query builders *where() methods:

$this->Invoices
    ->find()
    ->where(
        ['Invoices.id LIKE' => ($name . '%')],
        ['Invoices.id' => 'string']
    );

See also

API > \Cake\ORM\Query::where()


问:
Resolve git merge conflict by renaming one of the files
I'm using Flyway to keep track of database changes, and git for version control.

Flyway depends on migration scripts, which are named with increasing numbers for each migration.

Now I have the following situation: two features were developed on two separate branches (let's call them A and B), both requiring database changes. Both developers created a migration script for the database for their branch. As they branched off master at around the same time, they both assigned the same filename to the migration script: V42__migration.sql.

Now branch A was merged into master. When merging branch B, I got into a merge conflict because of the V42__migration.sql file. The correct solution to solve this conflict would be to rename the migration script of the branch B to V43__migration.sql. However, at time of merging git tries to merge both files in to one, where I actually need both of them untouched, but one renamed.

What's the best way to solve this kind of merge conflicts with git?

答:
Once git reports the conflict, you are at a prompt and fully able to edit the index in any way you require, to resolve the conflict.  So if you're merging feature_x in, you could:

1) Get the branch's script and name it V43

```<code>git checkout feature_X -- V42__migration.sql
mv V42__migration.sql V43__migration.sql
</code>```

2) Get the V42 script from the previously merged commit

```<code>git checkout HEAD -- V42__migration.sql
</code>```

3) Make sure the index is updated properly and finish the merge

```<code>git add .
git commit
</code>```

Another thing to consider, going forward, is that you don't really want git attempting to merge these files.  So you could use .gitattributes to either mark the files as binary, or apply a custom merge type to them.  I would assume a pattern like whatever/path/to/V*__migration.sql would identify the files.

The idea is that if git thinks it has to merge such a path, it should automatically flag a conflict and it should pick one or the other version to keep as the tentative resolution.  The person resolving the conflict then just has to put the other version in place.

Logically it makes sense to keep "ours" during the merge, because that's the version that will ultimately get that filename.  This is what would happen if you mark the path as binary.

But pragmatically resolution is simpler if you keep "theirs".

```<code>mv conflicted_file next_filename
git checkout HEAD -- conflicted_file
</code>```

So you might want to look up how to create a custom merge driver in the gitattributes documentation.  (It's not as hard as it sounds; the driver can be something like cp %B %A && false.  So just a couple of config commands.)

Body:
Once git reports the conflict, you are at a prompt and fully able to edit the index in any way you require, to resolve the conflict.  So if you're merging feature_x in, you could:

1) Get the branch's script and name it V43

git checkout feature_X -- V42__migration.sql
mv V42__migration.sql V43__migration.sql

2) Get the V42 script from the previously merged commit

git checkout HEAD -- V42__migration.sql

3) Make sure the index is updated properly and finish the merge

git add .
git commit

Another thing to consider, going forward, is that you don't really want git attempting to merge these files.  So you could use .gitattributes to either mark the files as binary, or apply a custom merge type to them.  I would assume a pattern like whatever/path/to/V*__migration.sql would identify the files.

The idea is that if git thinks it has to merge such a path, it should automatically flag a conflict and it should pick one or the other version to keep as the tentative resolution.  The person resolving the conflict then just has to put the other version in place.

Logically it makes sense to keep "ours" during the merge, because that's the version that will ultimately get that filename.  This is what would happen if you mark the path as binary.

But pragmatically resolution is simpler if you keep "theirs".

mv conflicted_file next_filename
git checkout HEAD -- conflicted_file

So you might want to look up how to create a custom merge driver in the gitattributes documentation.  (It's not as hard as it sounds; the driver can be something like cp %B %A && false.  So just a couple of config commands.)


问:
Java 8 streams do something with an element which has a boolean field
I wanna make streams from a list, and do something with an object if an certain field is true.

Let me show you what have I done till now:

```<code>    List<UserData> userDataList = new ArrayList<>();

    phoneNumbers.forEach(phoneNumber -> {
        if (phoneNumber.getPrimary()) {
            UserData userData = new UserData();
            userData.setDescription(phoneNumber.getType());
            userData.setValue(phoneNumber.getNumber);
            userDataList.add(userData);
        }
    });
</code>```

So if phoneNumber.getPrimary() == true will do the following task, if not -
 ignore it.

答:
There is already answer Accepted . but I am going to add alternative solution with one line code;

```<code> List<UserData> userDataList = phoneNumberList.stream().filter(PhoneNumber::isPrimary)
    .map(UserData::new).collect(Collectors.toList());
</code>```

Let's say Your phone number class have few variables;

```<code>    public class PhoneNumber {

        private String type;
        private String number;
        private boolean isPrimary;

        public PhoneNumber(String type, String number,boolean isPrimary) {
            this.isPrimary = isPrimary;
            this.type = type;
            this.number = number;
        }

//     getter setters
    }
</code>```

Add Your UserData I have added constructor with Phonenumber class.which will make easy of adding your data . since i'm going to use  (::) Method Reference.

```<code>    public class UserData {
        private String description;
        private String value;

        public UserData() {
        }
       //Constructor with PhoneNumber class
        public UserData(PhoneNumber phoneNumber) {
            this.description = phoneNumber.getType();
            this.value = phoneNumber.getNumber();
        }
// getter setter
     }
</code>```

So let say have a list of phonenumers itearaion with one line.

```<code>        List<PhoneNumber> phoneNumberList = new ArrayList<>();
                phoneNumberList.add(new PhoneNumber("Landline","40054638",false));
                phoneNumberList.add(new PhoneNumber("Work","90054638",true));
                phoneNumberList.add(new PhoneNumber("Office","7891432654",false));
                phoneNumberList.add(new PhoneNumber("Personal","40054638",true));
        //PhoneNumber::isPrimary this will check only primary
//UserData::new will set values Phonenumber to UserData
                List<UserData> userDataList = phoneNumberList.stream().filter(PhoneNumber::isPrimary)
    .map(UserData::new).collect(Collectors.toList());

                System.out.println(userDataList);
                System.out.println(userDataList.size());
</code>```

Body:
I wanna make streams from a list, and do something with an object if an certain field is true.

Let me show you what have I done till now:

    List<UserData> userDataList = new ArrayList<>();

    phoneNumbers.forEach(phoneNumber -> {
        if (phoneNumber.getPrimary()) {
            UserData userData = new UserData();
            userData.setDescription(phoneNumber.getType());
            userData.setValue(phoneNumber.getNumber);
            userDataList.add(userData);
        }
    });

So if phoneNumber.getPrimary() == true will do the following task, if not -
 ignore it.

Body:
There is already answer Accepted . but I am going to add alternative solution with one line code;

 List<UserData> userDataList = phoneNumberList.stream().filter(PhoneNumber::isPrimary)
    .map(UserData::new).collect(Collectors.toList());

Let's say Your phone number class have few variables;

    public class PhoneNumber {

        private String type;
        private String number;
        private boolean isPrimary;

        public PhoneNumber(String type, String number,boolean isPrimary) {
            this.isPrimary = isPrimary;
            this.type = type;
            this.number = number;
        }

//     getter setters
    }

Add Your UserData I have added constructor with Phonenumber class.which will make easy of adding your data . since i'm going to use  (::) Method Reference.

    public class UserData {
        private String description;
        private String value;

        public UserData() {
        }
       //Constructor with PhoneNumber class
        public UserData(PhoneNumber phoneNumber) {
            this.description = phoneNumber.getType();
            this.value = phoneNumber.getNumber();
        }
// getter setter
     }

So let say have a list of phonenumers itearaion with one line.

        List<PhoneNumber> phoneNumberList = new ArrayList<>();
                phoneNumberList.add(new PhoneNumber("Landline","40054638",false));
                phoneNumberList.add(new PhoneNumber("Work","90054638",true));
                phoneNumberList.add(new PhoneNumber("Office","7891432654",false));
                phoneNumberList.add(new PhoneNumber("Personal","40054638",true));
        //PhoneNumber::isPrimary this will check only primary
//UserData::new will set values Phonenumber to UserData
                List<UserData> userDataList = phoneNumberList.stream().filter(PhoneNumber::isPrimary)
    .map(UserData::new).collect(Collectors.toList());

                System.out.println(userDataList);
                System.out.println(userDataList.size());


问:
how to configure server Jenkins with github?
In Github i have created webhooks (http://192.168.10.98:8080/github-webhook/) and in Intergration & Services tab,I have added Jenkins (Github Plugin).
In webhooks its showing

```<code> "We couldn’t deliver this payload: Couldn't connect to server".
</code>```

In Jenkins,build trigger (i chooses GitHub hook trigger for GITScm polling)
Code changes are showing in Jenkins dashboard but its not updating in Server.What i need to configure for updating that changed codes through Jenkins?Can anybody help me?

答: Your IP seems to be private, and for webhooks you need to provide Jenkins Public Ip(You can able to access it from anywhere connected with network)</p>

Body:
In Github i have created webhooks (http://192.168.10.98:8080/github-webhook/) and in Intergration & Services tab,I have added Jenkins (Github Plugin).
In webhooks its showing

 "We couldn’t deliver this payload: Couldn't connect to server".

In Jenkins,build trigger (i chooses GitHub hook trigger for GITScm polling)
Code changes are showing in Jenkins dashboard but its not updating in Server.What i need to configure for updating that changed codes through Jenkins?Can anybody help me?


问:
compiling windows screensavers on linux
an customer would like to provide to his website visitors an windows screensaver as download. So far so god, but: The screensavers should be generated on the fly with some meta date which needs to be displayed within the screensaver.

I've found some windows tools which can create screensaver files through an UI (http://www.instantstorm.com/download/) but they provide no documented cli interface if neither. The cli interface could be useful when using DOSBox on ubuntu to compile an screensaver file.

The question is how this could be accomplished?

Best,
Stanislav

答:
You should be able to use mingw32 to cross compile executables for windows, though you will need to make your sources acceptable to GCC in order to do this.

However, have you considered the possibility of patching the binary rather than compiling it?  Perhaps things have changed since I last tried it under XP, but I believe strings included in the program or in a resource come through either unchanged or in an accessible encoding which you could easily patch, provided that you kept the length in memory the same (for something null-terminated, you can always make it shorter by placing a null earlier).  Also you might be able to append data to the end of the executable and read that at runtime.

However, if your binary is expected to be signed in some manner, you'd have to do the signing after the modification.

Title: compiling windows screensavers on linux


问:
Swap using a pointer without referring the array C++
so i need to swap row 2 and row 3 of my array. There is a catch our professor had us use a one dimensional array and use a pointer instead of a 2d array. We cannot reference the array only the pointer. I have no idea how to do this.

```<code>int numbers[25] = { 1,3,5,7,9 , -2,-4,-6, -8, -10 , 3,3,3,3,3 , 55, 77, 99, 22, 33, -15, -250, -350, -450, -550 };
</code>```

this array is supposed to look like this:

```<code> 1     3     5     7     9
   -2    -4    -6    -8   -10   // i need to swap this row
    3     3     3     3     3   // for this row
   55    77    99    22    33
  -15  -250  -350  -450  -550

This is how i need to print it
  1     3     5     7     9
  3     3     3     3     3
 -2    -4    -6    -8   -10
   55    77    99    22    33
  -15  -250  -350  -450  -550
</code>```

Note: this is not my whole HW assignment is just where i am stuck.

答:
Why not try something like:

```<code>constexpr std::size_t rowLength = 5u;
const auto beginRow2 = std::begin(numbers) + (rowLength * 2);
const auto endRow2 = std::begin(numbers) + (rowLength * 3);
const auto beginRow3 = std::begin(numbers) + (rowLength * 3);
std::swap_ranges(beginRow2, endRow2, beginRow3);
</code>```

This is idiomatic C++ and can easily be adapted to provide a generic function that accepts a 1-dimensional container, a row-length and the two rows to swap.

Body:
so i need to swap row 2 and row 3 of my array. There is a catch our professor had us use a one dimensional array and use a pointer instead of a 2d array. We cannot reference the array only the pointer. I have no idea how to do this.

int numbers[25] = { 1,3,5,7,9 , -2,-4,-6, -8, -10 , 3,3,3,3,3 , 55, 77, 99, 22, 33, -15, -250, -350, -450, -550 };

this array is supposed to look like this:

 1     3     5     7     9
   -2    -4    -6    -8   -10   // i need to swap this row
    3     3     3     3     3   // for this row
   55    77    99    22    33
  -15  -250  -350  -450  -550

This is how i need to print it
  1     3     5     7     9
  3     3     3     3     3
 -2    -4    -6    -8   -10
   55    77    99    22    33
  -15  -250  -350  -450  -550

Note: this is not my whole HW assignment is just where i am stuck.

Body:
Why not try something like:

constexpr std::size_t rowLength = 5u;
const auto beginRow2 = std::begin(numbers) + (rowLength * 2);
const auto endRow2 = std::begin(numbers) + (rowLength * 3);
const auto beginRow3 = std::begin(numbers) + (rowLength * 3);
std::swap_ranges(beginRow2, endRow2, beginRow3);

This is idiomatic C++ and can easily be adapted to provide a generic function that accepts a 1-dimensional container, a row-length and the two rows to swap.


问:
Injecting table cell at end of table
I'm completely new to swift and Xcode and everything regarding iOS development. I have a UITableView that populates UITableViewCells, I've been able to graps the fundamentals of that. But what if I wanted to add an extra cell at the bottom upon every visit?

I guess it's a mix of dynamic and static, but I can't find any answers whether this is case as of present date, since information in threads shows discrepancy.

答: You need to use dynamic table view. For example you have an array with some elements and your table view is displaying them. If you want to add a cell on the bottom, simply add another element to your array and then call self.tableView.reloadData()

Title: Injecting table cell at end of table


问:
Questions about jQuery's getScript()
```<code>$.getScript("somescript.js", function() {
    alert('Load Complete');
});
</code>```

Once loaded, is it cached or is it loaded again if referenced more than once?

If an event depends on this file being loaded, will the event be delayed of fail/timeout in case the file takes longer to load or doesn't load?

How do I check and do something in case the file fails to load for some reason?

Thanks in advance for your help.

答:
In addition to Glen's answer I would like to offer another option:

```<code>$.getScript({
    url: "foo.js",
    cache: true // or false, depending on your preference. in most cases you would want it true.
}).done(function(){
    // do something when script was loaded and run
}).fail(function(){
    // do something when script failed to load
});
</code>```

Supported on jQuery 1.12.0+

Title: Questions about jQuery's getScript()

Body:
$.getScript("somescript.js", function() {
    alert('Load Complete');
});

Once loaded, is it cached or is it loaded again if referenced more than once?

If an event depends on this file being loaded, will the event be delayed of fail/timeout in case the file takes longer to load or doesn't load?

How do I check and do something in case the file fails to load for some reason?

Thanks in advance for your help.

Body:
In addition to Glen's answer I would like to offer another option:

$.getScript({
    url: "foo.js",
    cache: true // or false, depending on your preference. in most cases you would want it true.
}).done(function(){
    // do something when script was loaded and run
}).fail(function(){
    // do something when script failed to load
});

Supported on jQuery 1.12.0+


问:
Splash screen react-native
Is there any repo or something that can be used to change the splash screen image automatically without doing a release?

For example 1 week I want to display image X and after that I wanna do Y, but Y its also not on the phone so I have to download it from an api and so on.

答:
You can do that by yourself easily. Just write your api and once a week make your app check that endpoint while opening the app. Save the image to the disk of the device then serve your image on the splash screen from the memory of the device.

If you do not want to write your own api, keep some state and persist it. Again once a week check the api you want if there are any new images, if yes download them to your device then serve them.

This is a broad answer for a broad question, but you can achieve what you want with a little bit react(native) and js.

Title: Splash screen react-native


问:
Best way to pass the value in Some to a function with a default parameter value?
I have a function from a third party library as below :

```<code>def myfunction(input:String = "some constant value")
</code>```

I have a

```<code>myinput:Option[String]
</code>```

with me and I need to pass the function. Right now I am doing this:

```<code>myfunction(myinput.getOrElse("some constant value"))
</code>```

But I dont want to look into the third party library for its default value.
What is the ideal way to do this?

答:
This kind of thing is usually done with .fold:

```<code>myInput.fold(myfunction())(myfunction _)
</code>```

Body:
I have a function from a third party library as below :

def myfunction(input:String = "some constant value")

I have a

myinput:Option[String]

with me and I need to pass the function. Right now I am doing this:

myfunction(myinput.getOrElse("some constant value"))

But I dont want to look into the third party library for its default value.
What is the ideal way to do this?

Body:
This kind of thing is usually done with .fold:

myInput.fold(myfunction())(myfunction _)


问:
SQL Server Conversion Failure when using INSERT
I have an existing table full of data, which can be created using

```<code>CREATE TABLE __EpisodeCost
(
    ActivityRecordID INT NOT NULL,
    ActCstID NVARCHAR(15),
    VolAmt FLOAT,
    ActCnt FLOAT,
    TotCst FLOAT,
    ResCstID NVARCHAR(50)
);
</code>```

This comes from a feed I have no control over and I want to convert this to my own version called EpisodeCost

```<code>CREATE TABLE EpisodeCostCtp
(
    ActivityRecordID INT NOT NULL,
    ActCstID NVARCHAR(6),
    ResCstID NVARCHAR(7),
    ActCnt NVARCHAR(7),
    TotCst DECIMAL(18, 8)
);
</code>```

Now, the problem I am having is with conversions. I can execute the query

```<code>SELECT
    ActivityRecordID,
    Cast(ActCstID AS NVARCHAR(6)),
    Cast(ResCstID AS NVARCHAR(7)),
    Cast(LTRIM(STR(ActCnt, 10)) AS NVARCHAR(7)),
    Cast(TotCst AS DECIMAL(18, 8))
FROM __EpisodeCostCtp;
</code>```

and it provides data, however, when I try to execute

```<code>INSERT INTO EpisodeCostCtp
    (
        ActivityRecordID,
        ActCstID,
        ResCstID,
        ActCnt,
        TotCst
    )
SELECT
    ActivityRecordID,
    Cast(ActCstID AS NVARCHAR(6)),
    Cast(ResCstID AS NVARCHAR(7)),
    Cast(LTRIM(STR(ActCnt, 10)) AS NVARCHAR(7)),
    Cast(TotCst AS DECIMAL(18, 8))
FROM __EpisodeCostCtp;
</code>```

I get

Msg 8115, Level 16, State 8, Line 102
  Arithmetic overflow error converting numeric to data type numeric.
  The statement has been terminated.

Why can I SELECT using the relevant casts, but then cannot INSERT into the target table?

Edit. I still don;t fully know what is occurring here.

As per Serg's recommendations, I have attempted to locate the problematic records but the query

```<code>SELECT
    ActivityRecordID,
    Cast(ActCstID AS NVARCHAR(6)),
    Cast(ResCstID AS NVARCHAR(7)),
    Cast(LTRIM(STR(ActCnt, 10)) AS NVARCHAR(7)),
    Cast(TotCst AS DECIMAL(18, 8))
FROM __EpisodeCostCtp
WHERE TotCst > 9.999999999999999e9;
</code>```

returns zero records. Changing to 9.999999999999999e8 does, and the conversion/cast happens with out error. I have scince changed the INSERT query to use DECIMAL(36, 18) and now the insert succeeds, but I am still none the wiser. Clearly I was hitting a limit on the cast, but why SELECT works and INSERT fails, I still don't know.

答:
To find rows which cause the problem try</p>

```<code>SELECT *
FROM __EpisodeCostCtp
WHERE TotCst > 9.999999999999999e9;
</code>```

Body:
I have an existing table full of data, which can be created using

CREATE TABLE __EpisodeCost
(
    ActivityRecordID INT NOT NULL,
    ActCstID NVARCHAR(15),
    VolAmt FLOAT,
    ActCnt FLOAT,
    TotCst FLOAT,
    ResCstID NVARCHAR(50)
);

This comes from a feed I have no control over and I want to convert this to my own version called EpisodeCost

CREATE TABLE EpisodeCostCtp
(
    ActivityRecordID INT NOT NULL,
    ActCstID NVARCHAR(6),
    ResCstID NVARCHAR(7),
    ActCnt NVARCHAR(7),
    TotCst DECIMAL(18, 8)
);

Now, the problem I am having is with conversions. I can execute the query

SELECT
    ActivityRecordID,
    Cast(ActCstID AS NVARCHAR(6)),
    Cast(ResCstID AS NVARCHAR(7)),
    Cast(LTRIM(STR(ActCnt, 10)) AS NVARCHAR(7)),
    Cast(TotCst AS DECIMAL(18, 8))
FROM __EpisodeCostCtp;

and it provides data, however, when I try to execute

INSERT INTO EpisodeCostCtp
    (
        ActivityRecordID,
        ActCstID,
        ResCstID,
        ActCnt,
        TotCst
    )
SELECT
    ActivityRecordID,
    Cast(ActCstID AS NVARCHAR(6)),
    Cast(ResCstID AS NVARCHAR(7)),
    Cast(LTRIM(STR(ActCnt, 10)) AS NVARCHAR(7)),
    Cast(TotCst AS DECIMAL(18, 8))
FROM __EpisodeCostCtp;

I get

Msg 8115, Level 16, State 8, Line 102
  Arithmetic overflow error converting numeric to data type numeric.
  The statement has been terminated.

Why can I SELECT using the relevant casts, but then cannot INSERT into the target table?

Edit. I still don;t fully know what is occurring here.

As per Serg's recommendations, I have attempted to locate the problematic records but the query

SELECT
    ActivityRecordID,
    Cast(ActCstID AS NVARCHAR(6)),
    Cast(ResCstID AS NVARCHAR(7)),
    Cast(LTRIM(STR(ActCnt, 10)) AS NVARCHAR(7)),
    Cast(TotCst AS DECIMAL(18, 8))
FROM __EpisodeCostCtp
WHERE TotCst > 9.999999999999999e9;

returns zero records. Changing to 9.999999999999999e8 does, and the conversion/cast happens with out error. I have scince changed the INSERT query to use DECIMAL(36, 18) and now the insert succeeds, but I am still none the wiser. Clearly I was hitting a limit on the cast, but why SELECT works and INSERT fails, I still don't know.

Body:
To find rows which cause the problem try

SELECT *
FROM __EpisodeCostCtp
WHERE TotCst > 9.999999999999999e9;


问:
What differs in the destruction of stl::unordered_map and stl::vector
I am looking for a more in detail answer, rather than UB is UB.

I have a piece of legacy code that I know is the culprit of an exception. We previously memset a vector, and once it was changed to an unordered_map it threw an exception on destruction. What in the source code makes memsetting a vector differ from an unordered_map? They both interact with contiguous memory...

In our code we have this. (I apologize for pseudo code, but the point should still be understandable...)

```<code>class B
{
    std::vector<CustomObject> vect;
};

struct STRUCT_A
{
    B b;
};
</code>```

Later on we do this...

```<code>STRUCT_A m_struct_a;
memset(&m_struct_a, 0, sizeof(STRUCT_A));
</code>```

This works perfectly fine even if we memset an stl::container! However, if we change class B to have a map then an exception occurs on the destructor.

```<code>class B
{
    std::map<CustomObject> vect;
};
</code>```

So I thought it had to do with the vector being contiguous, so I changed it to an unordered_map

```<code>class B
{
    std::unordered_map<CustomObject> vect;
};
</code>```

An exception is still thrown on the destructor. I thought it was pretty interesting, and thought it was a good question to ask...

答:
Yes it is indeed an act of absolute insanity to ::memset an instance of a class that contains an STL container.

Thinking more generally, you can only call memset on an object that is trivially copyable. Otherwise the behaviour of your program is undefined.

For more details on that, see http://en.cppreference.com/w/cpp/string/byte/memset and http://en.cppreference.com/w/cpp/types/is_trivially_copyable

Body:
I am looking for a more in detail answer, rather than UB is UB.

I have a piece of legacy code that I know is the culprit of an exception. We previously memset a vector, and once it was changed to an unordered_map it threw an exception on destruction. What in the source code makes memsetting a vector differ from an unordered_map? They both interact with contiguous memory...

In our code we have this. (I apologize for pseudo code, but the point should still be understandable...)

class B
{
    std::vector<CustomObject> vect;
};

struct STRUCT_A
{
    B b;
};

Later on we do this...

STRUCT_A m_struct_a;
memset(&m_struct_a, 0, sizeof(STRUCT_A));

This works perfectly fine even if we memset an stl::container! However, if we change class B to have a map then an exception occurs on the destructor.

class B
{
    std::map<CustomObject> vect;
};

So I thought it had to do with the vector being contiguous, so I changed it to an unordered_map

class B
{
    std::unordered_map<CustomObject> vect;
};

An exception is still thrown on the destructor. I thought it was pretty interesting, and thought it was a good question to ask...


问:
jquery waiting for .ajax() to complete within .each() iteration
Ive a jquery function that obtains text from all nodes of a particular class using the jquery .each() selector:

```<code>function get_text()
            {
              $(".my_class").each(function ()
              {
                $this = $(this);
                node_text = $this.text();
                console.log(node_text);
              })
            }
</code>```

That works as expected. Next, I want to send the text to a php script using .ajax() :

```<code>function get_php_text(node_text)
            {
               let url = `myphp.php?string_text=${node_text}`;
                 $.ajax(
                      {
                        url: url,
                        success: function(result)
                          {
                            console.log(result);
                          }
                      });
            }
</code>```

That function also works as expected.

When I run the following:

```<code>function get_text()
            {
              $(".my_class").each(function ()
              {
                $this = $(this);
                node_text = $this.text();
                get_php_text(node_text);
              })
            }
</code>```

I run into a problem as get_php_text() is not waiting for each .each() iteration to complete.

How can I rewrite the get_text() function so that it waits for the get_php_text() to return before going to the next iteration?

答:
Edit: Removed a promise as pointed out $.each doesn't support it.

Another example is using closures, but it should be used if you want to send data every time an iteration occurs in $.each.

```<code>function get_text() {
    function SampleClosure(node_text) {
        let url = `myphp.php?string_text=${node_text}`;
        $.ajax({
            url: url,
            success: function(result) {
                console.log(result);
            }
        });
    }

    $(".my_class").each(function() {
        $this = $(this);
        node_text = $this.text();
        SampleClosure(node_text);
    })
}
</code>```

So, what happens above is, every element, the text is extracted and passed to a Closure which is an expression that can reference variables within its scope when it was first declared. So even if you change the passed variable before the Ajax call is sent, it'll still use the old passed text and function will execute. I like to (which is wrong) think of it as creating an instance of a function with passed data which once completed is taken care of by GC, and within the loop, multiple instances of the function are created within their own memory allocation. As I said, this is how I see it, and what I said might be wrong, but theoretically this is how the process appears to me and works.

Body:
Ive a jquery function that obtains text from all nodes of a particular class using the jquery .each() selector:

function get_text()
            {
              $(".my_class").each(function ()
              {
                $this = $(this);
                node_text = $this.text();
                console.log(node_text);
              })
            }

That works as expected. Next, I want to send the text to a php script using .ajax() :

function get_php_text(node_text)
            {
               let url = `myphp.php?string_text=${node_text}`;
                 $.ajax(
                      {
                        url: url,
                        success: function(result)
                          {
                            console.log(result);
                          }
                      });
            }

That function also works as expected.

When I run the following:

function get_text()
            {
              $(".my_class").each(function ()
              {
                $this = $(this);
                node_text = $this.text();
                get_php_text(node_text);
              })
            }

I run into a problem as get_php_text() is not waiting for each .each() iteration to complete.

How can I rewrite the get_text() function so that it waits for the get_php_text() to return before going to the next iteration?

Body:
Edit: Removed a promise as pointed out $.each doesn't support it.

Another example is using closures, but it should be used if you want to send data every time an iteration occurs in $.each.

function get_text() {
    function SampleClosure(node_text) {
        let url = `myphp.php?string_text=${node_text}`;
        $.ajax({
            url: url,
            success: function(result) {
                console.log(result);
            }
        });
    }

    $(".my_class").each(function() {
        $this = $(this);
        node_text = $this.text();
        SampleClosure(node_text);
    })
}

So, what happens above is, every element, the text is extracted and passed to a Closure which is an expression that can reference variables within its scope when it was first declared. So even if you change the passed variable before the Ajax call is sent, it'll still use the old passed text and function will execute. I like to (which is wrong) think of it as creating an instance of a function with passed data which once completed is taken care of by GC, and within the loop, multiple instances of the function are created within their own memory allocation. As I said, this is how I see it, and what I said might be wrong, but theoretically this is how the process appears to me and works.


问:
trying to figure out how to add GestureDetectorCompat to my project
I'm reading the android documentation on handling common gestures. I've created an instance of GestureDetectorCompat in my main activity but this particular class doesn't seem to be recognized in the activity. I tried adding this line to my dependencies in build.gradle of my package but still I'm not having any joy.

```<code>compile "com.android.support:support-v4:13.0.+"
</code>```

I'm not too sure what is happening here as I thought when I added this line in the dependencies the option to use GestureDetectorcompat would become available? Also my min SDK is set to  15 and my target SDK is 19. I'm wondering is this preventing me from using GestureDetectorCompat? Any clarification you can provide is much appreciated.

答:
This is how I'd solved the same issue:

In Android Studio, Go to File > Invalidate Caches / Restart, select Invalidate and Restart.

Body:
I'm reading the android documentation on handling common gestures. I've created an instance of GestureDetectorCompat in my main activity but this particular class doesn't seem to be recognized in the activity. I tried adding this line to my dependencies in build.gradle of my package but still I'm not having any joy.

compile "com.android.support:support-v4:13.0.+"

I'm not too sure what is happening here as I thought when I added this line in the dependencies the option to use GestureDetectorcompat would become available? Also my min SDK is set to  15 and my target SDK is 19. I'm wondering is this preventing me from using GestureDetectorCompat? Any clarification you can provide is much appreciated.


问:
Does JSHint support async/await?
I'm using JSHint for the JavaScript project (with the Visual Studio Code). And in this project I use async / await, which JSHint highlights as errors.

I tried to set up jshint, but the it seems like the maxim version of "esversion" is 6.

Does jshint support async/await yet? If it does, how to turn it on? And if not, are there any workarounds?

答:
The OP asked it there were any workarounds.  It's a kludge, but I've replaced all my 'async' or 'await' with 'async /**/' and 'await /**/'.  Then a quick script to swap them into '/*async*/' and '/*await*/' allows me to check with jshint.

It's not pretty, but it feeds the bulldog.

Title: Does JSHint support async/await?


问:
Loading Javascript : HTTP Requests -v- Asynchronous Loading
I'm having difficulty in deciding which approach is better in terms of site performance.

Either to have all required jQuery plugins in one file to be included on every page on the site OR split the plugins out to individual files and use the jQuery.getScript() method to load them as and when required.

Is there any real benefit in loading the scripts asynchronously over one http request?

All my Javascript will be minified and gzipped.

Thanks!

答:
From my poit of view the best solution until now is controljs

Read the complete post http://www.stevesouders.com/blog/2010/12/15/controljs-part-1/


问:
How do I insert random characters into a sql database column?
I want to populate a column of my database table with 253 lines of 'M' and 'F' randomly placed in the column, is this possible?

Example of what it may look like:

```<code>Gender:
M
M
F
M
F
F
M
F
M
</code>```

答:
You can use RAND()function.

Please read the following URL:
[enter link description here][1]

https://learn.microsoft.com/en-us/sql/t-sql/functions/rand-transact-sql

Body:
I want to populate a column of my database table with 253 lines of 'M' and 'F' randomly placed in the column, is this possible?

Example of what it may look like:

Gender:
M
M
F
M
F
F
M
F
M


问:
msbuild fails creating COM wrapper for "Windows Script Host Object Model"

The situation

I just reinstalled windows 10 and my dev tools, while keeping my data

I am using VS2015 update 3.

I have a solution with several projects.

The solution is under version control (git) and I am the only one in my team experiencing this issue.

The problem

Build and Rebuild fail.
In the output I can see that the build of the root project (the one all others depend on directly or indirectly) fails with the following error:

```<code>C:\Program Files (x86)\MSBuild\14.0\bin\Microsoft.Common.CurrentVersion.targets(2399,5): warning MSB3290: Failed to create the wrapper assembly for type library "IWshRuntimeLibrary". Access denied (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
</code>```

IWshRuntimeLibrary is part of the "Windows Script Host Object Model" type library. It resides in the wshom.ocx which can be found in %SYSTEMROOT%\System32 respectivley %SYSTEMROOT%\syswow64.

The reference to IWshRuntimeLibrary is marked with the yellow exclamation mark symbol in visual studio.

What did not work

I re-added the reference but that did not help.

I cloned the source code into a different location

What worked

I started visual studio as an administrator. There where no problems building the solution. Unfortunately this is not an option for daily use but emphasizes that this is a access rights problem

Any help is very appreciated.

答: Readding not the reference, but COM "Windows Script Host Object Model" was helpful for me.

Body:
The situation

I just reinstalled windows 10 and my dev tools, while keeping my data

I am using VS2015 update 3.

I have a solution with several projects.

The solution is under version control (git) and I am the only one in my team experiencing this issue.

The problem

Build and Rebuild fail.
In the output I can see that the build of the root project (the one all others depend on directly or indirectly) fails with the following error:

C:\Program Files (x86)\MSBuild\14.0\bin\Microsoft.Common.CurrentVersion.targets(2399,5): warning MSB3290: Failed to create the wrapper assembly for type library "IWshRuntimeLibrary". Access denied (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))

IWshRuntimeLibrary is part of the "Windows Script Host Object Model" type library. It resides in the wshom.ocx which can be found in %SYSTEMROOT%\System32 respectivley %SYSTEMROOT%\syswow64.

The reference to IWshRuntimeLibrary is marked with the yellow exclamation mark symbol in visual studio.

What did not work

I re-added the reference but that did not help.

I cloned the source code into a different location

What worked

I started visual studio as an administrator. There where no problems building the solution. Unfortunately this is not an option for daily use but emphasizes that this is a access rights problem

Any help is very appreciated.


问:
when will kubernetes service supoort set-based selector?
As the doc says:

Newer resources, such as Job, Deployment, Replica Set, and Daemon Set, support set-based requirements as well.

Why does the resource service not support set-based requirements? When will it support that?

I want to create a service that select pods with key = v1 or v2. How can I achieve this goal?

答: Services belong to the v1 API group (which is stable). By that time, the set-based selector was not implemented. In order to allow that kind of selector, they would need to create a new type of Service that would belong to the alpha/beta API group. In this sense, this would likely take time in order to be production ready. I did not find any information about plans on working on that. I would not expect it in the short term for this to be available.


问:
Persist login/Authentication info on Android?
What is the best way to persist a users info in an android app?  I have a login screen that uses a web service to authenticate the user and return basic user info.

I don't care about saving the username/password, but I do need things like a couple of integer ID fields (patientID and personID) and a first and last name.

I don't want the user to have to login every time they load the app.  Someone suggested I use SQL lite to store the info, is this the best way or is there a more light weight solution?

答: Take a look at the answers and comments to this question: Android: Storing username and password?</p>


问:
Redirect Specific non-existing URL to an existing
I have a simple need to redirect:

mypage.com/myurl (which doesn't not exist; meening that returns a 404 error)

To

mypage.com/newurl/myurl (which is an exitsing page with content).

I saw a tons of forum post about this, but didn't find an awnser. I tried lot of thinks but with internal server error, infinitive loops etc.

Please note that I have a www to non www permanent redirect, like this:

```<code>RewriteCond %{HTTP_HOST} ^www\.mypage\.si [NC]
RewriteRule ^(.*)$ http://mypage.si/$1 [L,R=301]
</code>```

UPDATE:

I will be specific:

This URL doesn't exist:  http://domodom.si/sl/nepremicnine

and needs to be redirected here: http://domodom.si/sl/nepremicnine/nepremicnine-ponudba

Hope this will offer more insights about the problem.

Thanks

答:
Add this to your .htaccess file

```<code>RewriteBase /
RewriteRule ^(.*)$ newurl/$1 [NC,L]
</code>```

Body:
I have a simple need to redirect:

mypage.com/myurl (which doesn't not exist; meening that returns a 404 error)

To

mypage.com/newurl/myurl (which is an exitsing page with content).

I saw a tons of forum post about this, but didn't find an awnser. I tried lot of thinks but with internal server error, infinitive loops etc.

Please note that I have a www to non www permanent redirect, like this:

RewriteCond %{HTTP_HOST} ^www\.mypage\.si [NC]
RewriteRule ^(.*)$ http://mypage.si/$1 [L,R=301]

UPDATE:

I will be specific:

This URL doesn't exist:  http://domodom.si/sl/nepremicnine

and needs to be redirected here: http://domodom.si/sl/nepremicnine/nepremicnine-ponudba

Hope this will offer more insights about the problem.

Thanks

Body:
Add this to your .htaccess file

RewriteBase /
RewriteRule ^(.*)$ newurl/$1 [NC,L]


问:
Replace array-values through a Function
I have some trouble which I have no clue how to solve this. What I need is to replace values in non-associative array with a function and print out as variable.</p>

```<code>function Confirm($var1)
{
    switch ($var1)
    {
        case 1:
            return "Gas";
            break;
        case 2:
            return "Soda";
            break;
        case 3:
            return "Air";
            break;
        case 4:
            return "Ice";
            break;
        case 5:
            return "Soft";
            break;

    }
}

$db_field_data = "1,2,3,5";

what i need is:

$field_data_trough_function = "Gas,Soda,Air,Soft";
</code>```

答:
See coments inside code I have explained the steps</p>

```<code><?php

    function Confirm($var1)
    {
        switch ($var1)
        {
            case 1:
                return "Gas";
                break;
            case 2:
                return "Soda";
                break;
            case 3:
                return "Air";
                break;
            case 4:
                return "Ice";
                break;
            case 5:
                return "Soft";
                break;

        }
    }

    //array declaration can be $variable_name = []; or $variable_name = array() and not $variable_name = ""; that last is for string;

    //If you receive $db_field_data as string then you need first to convert an array with explode function on PHP
    //$db_field_data = "1,2,3,4,5";
    //$db_field_data = explode(",", $db_field_data);

    //if is array it need to be like this;
    $db_field_data = [1,2,3,4,5];

    //declare another array to store results inside
    $field_data_trough_function = [];

    //loop trough
    foreach( $db_field_data as $index => $val){
        //put to result array what function Confirm() returns
        $field_data_trough_function[] = Confirm($val);
    }

    //array
    echo "```";
    print_r($field_data_trough_function);
    echo "```";

    //or string
    echo implode(",", $field_data_trough_function);
?>
</code>```

ContentLicense: CC BY-SA 4.0

Title: Replace array-values through a Function

Body:
I have some trouble which I have no clue how to solve this. What I need is to replace values in non-associative array with a function and print out as variable.

function Confirm($var1)
{
    switch ($var1)
    {
        case 1:
            return "Gas";
            break;
        case 2:
            return "Soda";
            break;
        case 3:
            return "Air";
            break;
        case 4:
            return "Ice";
            break;
        case 5:
            return "Soft";
            break;

    }
}

$db_field_data = "1,2,3,5";

what i need is:

$field_data_trough_function = "Gas,Soda,Air,Soft";

Body:
See coments inside code I have explained the steps

<?php

    function Confirm($var1)
    {
        switch ($var1)
        {
            case 1:
                return "Gas";
                break;
            case 2:
                return "Soda";
                break;
            case 3:
                return "Air";
                break;
            case 4:
                return "Ice";
                break;
            case 5:
                return "Soft";
                break;

        }
    }

    //array declaration can be $variable_name = []; or $variable_name = array() and not $variable_name = ""; that last is for string;

    //If you receive $db_field_data as string then you need first to convert an array with explode function on PHP
    //$db_field_data = "1,2,3,4,5";
    //$db_field_data = explode(",", $db_field_data);

    //if is array it need to be like this;
    $db_field_data = [1,2,3,4,5];

    //declare another array to store results inside
    $field_data_trough_function = [];

    //loop trough
    foreach( $db_field_data as $index => $val){
        //put to result array what function Confirm() returns
        $field_data_trough_function[] = Confirm($val);
    }

    //array
    echo "<pre>";
    print_r($field_data_trough_function);
    echo "</pre>";

    //or string
    echo implode(",", $field_data_trough_function);
?>


问:
check for empty cel and then count the value in the column and paste it to another sheet
I am having two sht, sht1 as BW and sht2 as result.

I want to Count the number of 1's in column T and U of sht1, according to the week in column AX and print the Counted values in the result sheet, looking into the same week.

I took the advice of an expert in the Forum and completed till this.

I want an if condition, in such a way that, if the column AA is empty, then i should not Count the 1's in column T and U, it should be skipped.

I introduced this code of line in my existing code after j=2;  and got an error

error Label not defined`,

```<code> If ws.Range("AA" & i) = "" Then
GoTo nextrow
</code>```

could someone help, how i should execute this condition ?
here is my code;

```<code>Sub results()

Dim i As Integer, j As Integer, cntT As Integer, cntu As Integer, ws As Worksheet
Set ws = Sheets("Result")
Sheets("BW").Select
For i = 2 To WorksheetFunction.CountA(ws.Columns(1))
cntT = 0
cntu = 0
If ws.Range("A" & i) = Val(Format(Now, "ww")) Then Exit For
Next i

For j = 2 To WorksheetFunction.CountA(Columns(50))

If ws.Range("A" & i) = Range("AX" & j) And Range("T" & j) = 1 Then cntT = cntT + 1
If ws.Range("A" & i) = Range("AX" & j) And Range("U" & j) = 1 Then cntu = cntu + 1

Next j
If cntT <> 0 Then ws.Range("B" & i) = cntT
If cntu <> 0 Then ws.Range("C" & i) = cntu
If cntT + cntu <> 0 Then
ws.Range("D" & i) = cntT + cntu
ws.Range("E" & i) = cntT / (cntT + cntu)
ws.Range("F" & i) = cntu / (cntT + cntu)
End If
ws.Range("E" & i & ":F" & i).NumberFormat = "0%"
End Sub
</code>```

答:
The GoTo nextrow is looking for a line label titled nextrow.  That's how the GoTo command is built and operates.  For what you are trying to accomplish, try this instead:

```<code>If ws.Range("AA" & i) <> "" Then
    If ws.Range("A" & i) = Range("AX" & j) And Range("T" & j) = 1 Then cntT = cntT + 1
    If ws.Range("A" & i) = Range("AX" & j) And Range("U" & j) = 1 Then cntu = cntu + 1
End If
</code>```

This way it says, if the column is NOT blank, then do stuff, otherwise go to next j

If you want to use the GoTo Command in the future you can use line numbers (like GoTo 0 which should take you back to the beginning of the code) or you can create a line label by placing nextrow: on an empty line.  Then when you call GoTo nextrow it will go to that line, and proceed from there.

Body:
I am having two sht, sht1 as BW and sht2 as result.

I want to Count the number of 1's in column T and U of sht1, according to the week in column AX and print the Counted values in the result sheet, looking into the same week.

I took the advice of an expert in the Forum and completed till this.

I want an if condition, in such a way that, if the column AA is empty, then i should not Count the 1's in column T and U, it should be skipped.

I introduced this code of line in my existing code after j=2;  and got an error

error Label not defined`,

 If ws.Range("AA" & i) = "" Then
GoTo nextrow

could someone help, how i should execute this condition ?
here is my code;

Sub results()

Dim i As Integer, j As Integer, cntT As Integer, cntu As Integer, ws As Worksheet
Set ws = Sheets("Result")
Sheets("BW").Select
For i = 2 To WorksheetFunction.CountA(ws.Columns(1))
cntT = 0
cntu = 0
If ws.Range("A" & i) = Val(Format(Now, "ww")) Then Exit For
Next i

For j = 2 To WorksheetFunction.CountA(Columns(50))

If ws.Range("A" & i) = Range("AX" & j) And Range("T" & j) = 1 Then cntT = cntT + 1
If ws.Range("A" & i) = Range("AX" & j) And Range("U" & j) = 1 Then cntu = cntu + 1

Next j
If cntT <> 0 Then ws.Range("B" & i) = cntT
If cntu <> 0 Then ws.Range("C" & i) = cntu
If cntT + cntu <> 0 Then
ws.Range("D" & i) = cntT + cntu
ws.Range("E" & i) = cntT / (cntT + cntu)
ws.Range("F" & i) = cntu / (cntT + cntu)
End If
ws.Range("E" & i & ":F" & i).NumberFormat = "0%"
End Sub

Body:
The GoTo nextrow is looking for a line label titled nextrow.  That's how the GoTo command is built and operates.  For what you are trying to accomplish, try this instead:

If ws.Range("AA" & i) <> "" Then
    If ws.Range("A" & i) = Range("AX" & j) And Range("T" & j) = 1 Then cntT = cntT + 1
    If ws.Range("A" & i) = Range("AX" & j) And Range("U" & j) = 1 Then cntu = cntu + 1
End If

This way it says, if the column is NOT blank, then do stuff, otherwise go to next j

If you want to use the GoTo Command in the future you can use line numbers (like GoTo 0 which should take you back to the beginning of the code) or you can create a line label by placing nextrow: on an empty line.  Then when you call GoTo nextrow it will go to that line, and proceed from there.


问:
Calculating Outdegree and Indegree of Adjacency list

Question

Calculate time complexity in calculating Outdegree and Indegree of Adjacency list.

My Approach/Doubt

Let Adj[] be an array of size V where V=No. of vertices  in a directed graph
for representing adjacency list.

I know that ,

Outdegree of vertex u (u belongs to V) is actually the length of Adj[u]

and

Indegree of vertex u (u belongs to V) is actually the count of u in list Adj.

In both the cases , i think the time complexity should be theta (V*E)

Where V=no. of vertices

```<code>  E=no. of edges
</code>```

because for calculating outdegree,we scan all vertices and under each vertices we scan all the edges of that vertices.

Then why it is Thrta (V+E)

Please correct me where i am wrong?

Thanks!

答:
Okay, lets say we have V vertices and E edges.

In both bidirectional and unidirectional graph, for each edge Ei, we get two Vertices V1, V2. We can easily get the direction of the edge and update the outdegree and indegree counter of a certain vertex.

Example:

Vertices: 1, 2, 3, 4

Edges: 1 -> 2, 2 -> 4, 3 -> 1, 2 -> 3

Outdegree: 0 0 0 0

Indegree: 0 0 0 0

Pass 1:

Edge 1 -> 2

Outdegree: 1 0 0 0

Indegree: 0 1 0 0

Pass 2:

Edge 2 -> 4

Outdegree: 1 1 0 0

Indegree: 0 1 0 1

Pass 3:

Edge 3 -> 1

Outdegree: 1 1 1 0

Indegree: 1 1 0 1

Pass 4:

Edge 2 -> 3

Outdegree: 1 2 1 0

Indegree: 1 1 1 1

So here, we need to run a loop through each edge and each vertex exactly once thus resulting in complexity (V + E).

Body:
Question

Calculate time complexity in calculating Outdegree and Indegree of Adjacency list.

My Approach/Doubt

Let Adj[] be an array of size V where V=No. of vertices  in a directed graph
for representing adjacency list.

I know that ,

Outdegree of vertex u (u belongs to V) is actually the length of Adj[u]

and

Indegree of vertex u (u belongs to V) is actually the count of u in list Adj.

In both the cases , i think the time complexity should be theta (V*E)

Where V=no. of vertices

  E=no. of edges

because for calculating outdegree,we scan all vertices and under each vertices we scan all the edges of that vertices.

Then why it is Thrta (V+E)

Please correct me where i am wrong?

Thanks!


问:
Tensorflow with poets
I have questions to ask about why tensorflow with poets was not able to classify the image i want. I am using Ubuntu 14.04 with tensorflow installed using docker. Here is my story:

After a successful retrained on flower category following this link here. I wish to train on my own category as well, I have 10 classes of images and they are well organized according to the tutorial. My photos were also stored in the tf_files directory and following the guide i retrain the inception model on my category.

Everything on the retraining went well. However, as I tired to classify the image I want, I was unable to do so and I have this error. I also tried to look for py file in /usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/errors_impl.py but my dist-packages were empty! Can someone help me in this! Where can I find the py files? Thank you!

答:
Your error indicates that it is unable to locate the file. I would suggest you to execute the following command in the directory where you have the graph and label files</p>

```<code>python label_image.py exact_path_to_your_testimage_file.jpg
</code>```

Title: Tensorflow with poets

Body:
Your error indicates that it is unable to locate the file. I would suggest you to execute the following command in the directory where you have the graph and label files

python label_image.py exact_path_to_your_testimage_file.jpg


问:
Sum of variable got with a Radiobutton = 0
I'm trying to do a simple program using python but it doesn't work. In the penultimate string I don't know how to get the variable from the Radiobutton.</p>

```<code>from tkinter import*
import tkinter.messagebox

finestra = Tk()
finestra.geometry("1000x800+100+0")
finestra.title("Consumo PC")
var = IntVar()
ivar = IntVar()
cpu = Label(text="Seleziona la generazione del tuo processore:").pack()
kaby = Radiobutton(finestra,text="Kabylake",value=1, variable=var).pack()
sky = Radiobutton(finestra,text="SkyLake",value=2, variable=var).pack()
ivy = Radiobutton(finestra,text="IvyBridge",value=3, variable=var).pack()

serie = Label(text="Seleziona il tuo processore:").pack()
i3 = Radiobutton(finestra,text="i3 xxxx",value=6, variable=ivar).pack()
i5 = Radiobutton(finestra,text="i5 xxxx",value=4, variable=ivar).pack()
i7 = Radiobutton(finestra,text="i7 xxxx",value=5, variable=ivar).pack()

brand = Label(text="Seleziona il brand della tua scheda video:").pack()
amd = Radiobutton(finestra,text="AMD", value=7,variable=3).pack()
nvidia = Radiobutton(finestra,text="Nvidia", value=8,variable=3).pack()

kaby = 1
sky = 1
ivy = 11/10
i3 = 51
i5 = 65
i7 = 75

tdp = Label(text=var.get()+ivar.get()).pack()

finestra.mainloop()
</code>```

答:
Right now, you are changing text of label only as soon as you create your UI and since none of those selected, you are getting 0. That text should update on every var/ivar change.

That can be achieved by adding trace for var and ivar.

```<code>def callback(*args):
    print(var.get()+ivar.get())

var.trace("w", callback)
ivar.trace("w", callback)
</code>```

With this, on every button selection, you will get your desired value.

Now one thing left, which is updating the resul label. There are couple ways to update the text of label but since we are using variable classes, let's do it using StringVar.

```<code>def callback(*args):
    result.set(var.get()+ivar.get())

result = StringVar()

tdp = Label(textvariable=result).pack()
                ^^^^^^^^ note that this not text but textvariable!
</code>```

Also, there are couple things you should be aware.

One of them is wildcard import (from tkinter import * usage).

About this one, you can read answers from this question.

Other one is, using pack() at the same line. That will assign None to all of your variables(cpu, kaby, sky etc.).

About this one, you can read answers from this question.

Body:
I'm trying to do a simple program using python but it doesn't work. In the penultimate string I don't know how to get the variable from the Radiobutton.

from tkinter import*
import tkinter.messagebox

finestra = Tk()
finestra.geometry("1000x800+100+0")
finestra.title("Consumo PC")
var = IntVar()
ivar = IntVar()
cpu = Label(text="Seleziona la generazione del tuo processore:").pack()
kaby = Radiobutton(finestra,text="Kabylake",value=1, variable=var).pack()
sky = Radiobutton(finestra,text="SkyLake",value=2, variable=var).pack()
ivy = Radiobutton(finestra,text="IvyBridge",value=3, variable=var).pack()

serie = Label(text="Seleziona il tuo processore:").pack()
i3 = Radiobutton(finestra,text="i3 xxxx",value=6, variable=ivar).pack()
i5 = Radiobutton(finestra,text="i5 xxxx",value=4, variable=ivar).pack()
i7 = Radiobutton(finestra,text="i7 xxxx",value=5, variable=ivar).pack()

brand = Label(text="Seleziona il brand della tua scheda video:").pack()
amd = Radiobutton(finestra,text="AMD", value=7,variable=3).pack()
nvidia = Radiobutton(finestra,text="Nvidia", value=8,variable=3).pack()

kaby = 1
sky = 1
ivy = 11/10
i3 = 51
i5 = 65
i7 = 75

tdp = Label(text=var.get()+ivar.get()).pack()

finestra.mainloop()

Body:
Right now, you are changing text of label only as soon as you create your UI and since none of those selected, you are getting 0. That text should update on every var/ivar change.

That can be achieved by adding trace for var and ivar.

def callback(*args):
    print(var.get()+ivar.get())

var.trace("w", callback)
ivar.trace("w", callback)

With this, on every button selection, you will get your desired value.

Now one thing left, which is updating the resul label. There are couple ways to update the text of label but since we are using variable classes, let's do it using StringVar.

def callback(*args):
    result.set(var.get()+ivar.get())

result = StringVar()

tdp = Label(textvariable=result).pack()
                ^^^^^^^^ note that this not text but textvariable!

Also, there are couple things you should be aware.

One of them is wildcard import (from tkinter import * usage).

About this one, you can read answers from this question.

Other one is, using pack() at the same line. That will assign None to all of your variables(cpu, kaby, sky etc.).

About this one, you can read answers from this question.


问:
Horizontal scroller in CSS
I have been trying to add a scroller to my context section that will only allow the box to scroll horizontally within the visible of the viewer's screen, not vertical.

Does anyone know any code to have scrollable content in a div in a fluid css layout design?

Also, here is a link to a website that has the exact scroll effect I am trying to recreate: http://patrickhoelck.com/home.html

答:
Does anyone know any code to have scrollable content in a div in a fluid css layout design?

'overflow: auto' will add the scroll bar when necessary.

The trick is to make sure the content inside the scrollable element exceeds the normal width of the element, instead of simply reflowing onto a new row in which case it'll never trigger a scroll bar. One way to do this is by using 'white-space: nowrap'.

OwnerDisplayName: R Herod

Title: Horizontal scroller in CSS

LastEditorDisplayName: R Herod

OwnerDisplayName: bobince


问:
What's the benefit of Scala (singleton) object vs. typical class level artifacts
I understand one of the main benefits from using object is, they are real objects instead of system wide functionality.  But finally those objects are also system wide accessible.

Beside of being more "pure"  what additional benefit does scala "objects" offer.

I bet there are a number but I can't really figure out which.

答:
As far as I can tell the advantage is economy of syntax. Now you don't need any static invocation and field referencing nonsense. They are also cleaner than a single element enum for implementing a strategy (that is, a stateless class implementing an interface).

You might argue that they separate out the static parts too.

The other side of that is that mutable statics are already too easy in Java. Scala hides and legitimatises them.


问:
How to sum tuple values outputted by an API in Python
So a fairly simple problem which I'm trying to solve in the most efficient way possible.

I am querying an API which outputs a series of namedtuples, and I want to accumulate and sum the value of each outputted tuple.

i.e i'm doing something like the following:

```<code>for time_series in api_query:
    for ts_tuple in time_series.header:
        print(ts_tuple)
</code>```

which would output something like:

```<code>Point(end_time='2017-07-05T12:12:24.471Z', start_time='2017-07-05T12:11:24.471Z', value=0)
Point(end_time='2017-07-05T12:13:24.471Z', start_time='2017-07-05T12:12:24.471Z', value=48)
Point(end_time='2017-07-05T12:14:24.471Z', start_time='2017-07-05T12:13:24.471Z', value=11)
Point(end_time='2017-07-05T12:15:24.471Z', start_time='2017-07-05T12:14:24.471Z', value=0)
Point(end_time='2017-07-05T11:52:24.471Z', start_time='2017-07-05T11:51:24.471Z', value=0)
</code>```

I need to grab the value in each namedtuple, and sum the total.

What I've got is:

```<code>   total_foo = []

   for time_series in api_query:
        for ts_tuple in time_series.header:
            total_foo.append(ts_tuple.value)
</code>```

then just call a sum on total_foo.

I was wondering whether anyone can suggest a more pythonic way? I'm trying to get away from just using for loops and appending to lists all the time.

NB: for some background the api is querying a Stackdriver metric via the google-cloud-python library.

答:
You may use a generator expression with a nested loop, like this:</p>

```<code>total = sum(ts_tuple.value for time_series in api_query for ts_tuple in time_series.header)
</code>```

Body:
So a fairly simple problem which I'm trying to solve in the most efficient way possible.

I am querying an API which outputs a series of namedtuples, and I want to accumulate and sum the value of each outputted tuple.

i.e i'm doing something like the following:

for time_series in api_query:
    for ts_tuple in time_series.header:
        print(ts_tuple)

which would output something like:

Point(end_time='2017-07-05T12:12:24.471Z', start_time='2017-07-05T12:11:24.471Z', value=0)
Point(end_time='2017-07-05T12:13:24.471Z', start_time='2017-07-05T12:12:24.471Z', value=48)
Point(end_time='2017-07-05T12:14:24.471Z', start_time='2017-07-05T12:13:24.471Z', value=11)
Point(end_time='2017-07-05T12:15:24.471Z', start_time='2017-07-05T12:14:24.471Z', value=0)
Point(end_time='2017-07-05T11:52:24.471Z', start_time='2017-07-05T11:51:24.471Z', value=0)

I need to grab the value in each namedtuple, and sum the total.

What I've got is:

   total_foo = []

   for time_series in api_query:
        for ts_tuple in time_series.header:
            total_foo.append(ts_tuple.value)

then just call a sum on total_foo.

I was wondering whether anyone can suggest a more pythonic way? I'm trying to get away from just using for loops and appending to lists all the time.

NB: for some background the api is querying a Stackdriver metric via the google-cloud-python library.

Body:
You may use a generator expression with a nested loop, like this:

total = sum(ts_tuple.value for time_series in api_query for ts_tuple in time_series.header)


问:
Loading QDialog is blank when showed
I am working on a code that allows the user to control a piezo (PZ193E) in a MainWindow created with Qt Designer form.

However, when I call the function designed to connect the piezo to the computer (from an external library given by the constructor) my UI freeze until the connection is established.

I am trying to display a QDialog with a QLabel in it, telling the user to wait while the connection is processing, but when I do so, the QDialog shows up but without the label. It is only displayed when the connection is established and when the QDialog can close.

Here is how I coded my dialog :

```<code>In the .h :
QDialog *_waitQD = new QDialog;
QVBoxLayout *_waitQVBL = new QVBoxLayout;
QLabel *_waitQL = new QLabel("Loading...");

In the .cpp :
_waitQD->setMinimumSize(QSize(95,35));
_waitQVBL->addWidget(_waitQL);
_waitQD->setLayout(_waitQVBL);
</code>```

And then I call :

```<code>_waitQD->show();
if (_piezo.connected()) // bool funtion that return true if the connection is established
      _waitQD->close();
</code>```

This is what it looks like:

答:
you need to call app.exec()</p>

```<code>#include <QApplication>

#include <QDialog>
#include <QVBoxLayout>
#include <QLabel>
int main(int argc, char *argv[])
{

    QApplication app(argc, argv);

    QDialog *_waitQD = new QDialog;
    QVBoxLayout *_waitQVBL = new QVBoxLayout;
    QLabel *_waitQL = new QLabel("Loading...");

    _waitQD->setMinimumSize(QSize(95,35));
    _waitQVBL->addWidget(_waitQL);
    _waitQD->setLayout(_waitQVBL);

    _waitQD->show();

    return app.exec();
}
</code>```

Title: Loading QDialog is blank when showed

Body:
I am working on a code that allows the user to control a piezo (PZ193E) in a MainWindow created with Qt Designer form.

However, when I call the function designed to connect the piezo to the computer (from an external library given by the constructor) my UI freeze until the connection is established.

I am trying to display a QDialog with a QLabel in it, telling the user to wait while the connection is processing, but when I do so, the QDialog shows up but without the label. It is only displayed when the connection is established and when the QDialog can close.

Here is how I coded my dialog :

In the .h :
QDialog *_waitQD = new QDialog;
QVBoxLayout *_waitQVBL = new QVBoxLayout;
QLabel *_waitQL = new QLabel("Loading...");

In the .cpp :
_waitQD->setMinimumSize(QSize(95,35));
_waitQVBL->addWidget(_waitQL);
_waitQD->setLayout(_waitQVBL);

And then I call :

_waitQD->show();
if (_piezo.connected()) // bool funtion that return true if the connection is established
      _waitQD->close();

This is what it looks like:

Body:
you need to call app.exec()

#include <QApplication>

#include <QDialog>
#include <QVBoxLayout>
#include <QLabel>
int main(int argc, char *argv[])
{

    QApplication app(argc, argv);

    QDialog *_waitQD = new QDialog;
    QVBoxLayout *_waitQVBL = new QVBoxLayout;
    QLabel *_waitQL = new QLabel("Loading...");

    _waitQD->setMinimumSize(QSize(95,35));
    _waitQVBL->addWidget(_waitQL);
    _waitQD->setLayout(_waitQVBL);

    _waitQD->show();

    return app.exec();
}