问:
Exception: cvc-complex-type.2.4.b: The content of element 'person' is not comple te. One of '{staff}' is expected
Persons will the root tag. Persons will have the entry of each person with name, age, gender, address. A person can be either a student or staff. student will have rollno, standard and section. If staff, then staffid and subject. Every student must have an address with the following entry- doorno,street,city and state.
The admin has come up with an XML document.

Here is my XML:

```<code><?xml version="1.0" encoding="utf-8"?>
<persons>
    <person>
        <name>Tom</name>
        <age>11</age>
        <gender>M</gender>
        <address>
            <doorno>27</doorno>
            <street>Tony's road, koramangala</street>
            <city>Bangalore</city>
            <state>Karnataka</state>
        </address>
        <student>
            <rollno>10</rollno>
            <standard>6</standard>
            <section>A</section>
        </student>
    </person>
    <person>
        <name>Shiny</name>
        <age>12</age>
        <gender>F</gender>
        <address>
            <doorno>10</doorno>
            <street>Main Bazar, Madiwala</street>
            <city>Bangalore</city>
            <state>Karnataka</state>
        </address>
        <staff>
            <staffid>123</staffid>
            <subject>Maths</subject>
        </staff>
    </person>
</persons>
</code>```

and my XSD :

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

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">

    <xs:element name="persons">
        <xs:complexType>
        <xs:sequence>
            <xs:element name="person" maxOccurs="unbounded">
                <xs:complexType>
                <xs:sequence>
                    <xs:element name="name" type="xs:string"/>
                    <xs:element name="age" type="xs:integer"/>
                    <xs:element name="gender" type="xs:string"/>
                    <xs:element name="address">
                        <xs:complexType>
                        <xs:sequence>
                            <xs:element name="doorno" type="xs:integer"/>
                            <xs:element name="street" type="xs:string"/>
                            <xs:element name="city" type="xs:string"/>
                            <xs:element name="state" type="xs:string"/>
                        </xs:sequence>
                        </xs:complexType>
                    </xs:element>

                    <xs:element name="student">
                        <xs:complexType>
                        <xs:sequence>
                            <xs:element name="rollno" type="xs:integer"/>
                            <xs:element name="standard" type="xs:integer"/>
                            <xs:element name="section" type="xs:string"/>
                        </xs:sequence>
                        </xs:complexType>
                    </xs:element>

                    <xs:element name="staff">
                        <xs:complexType>
                        <xs:sequence>
                            <xs:element name="staffid" type="xs:integer"/>
                            <xs:element name="subject" type="xs:string"/>
                        </xs:sequence>
                        </xs:complexType>
                    </xs:element>

                </xs:sequence>
                </xs:complexType>
            </xs:element>

        </xs:sequence>
        </xs:complexType>
    </xs:element>

</xs:schema>
</code>```

Iam new to XML and a learner.

The error:

```<code>Exception: cvc-complex-type.2.4.b: The content of element 'person' is not comple te. One of '{staff}' is expected.
</code>```

答:
Your XSD says that there should be <xs:element name="student"> followed by <xs:element name="staff">, but instead you would like to have "either a student or staff". For this XSD has another element, <xs:choice>:

```<code><xs:choice>
    <xs:element name="student">
        <xs:complexType>
        <xs:sequence>
            <xs:element name="rollno" type="xs:integer"/>
            <xs:element name="standard" type="xs:integer"/>
            <xs:element name="section" type="xs:string"/>
        </xs:sequence>
        </xs:complexType>
    </xs:element>

    <xs:element name="staff">
        <xs:complexType>
        <xs:sequence>
            <xs:element name="staffid" type="xs:integer"/>
            <xs:element name="subject" type="xs:string"/>
        </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:choice>
</code>```

Please also check out another answer: How to specify in an XML schema that either one of two fields must be present?

Body:
Persons will the root tag. Persons will have the entry of each person with name, age, gender, address. A person can be either a student or staff. student will have rollno, standard and section. If staff, then staffid and subject. Every student must have an address with the following entry- doorno,street,city and state.
The admin has come up with an XML document.

Here is my XML:

<?xml version="1.0" encoding="utf-8"?>
<persons>
    <person>
        <name>Tom</name>
        <age>11</age>
        <gender>M</gender>
        <address>
            <doorno>27</doorno>
            <street>Tony's road, koramangala</street>
            <city>Bangalore</city>
            <state>Karnataka</state>
        </address>
        <student>
            <rollno>10</rollno>
            <standard>6</standard>

A

        </student>
    </person>
    <person>
        <name>Shiny</name>
        <age>12</age>
        <gender>F</gender>
        <address>
            <doorno>10</doorno>
            <street>Main Bazar, Madiwala</street>
            <city>Bangalore</city>
            <state>Karnataka</state>
        </address>
        <staff>
            <staffid>123</staffid>
            <subject>Maths</subject>
        </staff>
    </person>
</persons>

and my XSD :

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

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">

    <xs:element name="persons">
        <xs:complexType>
        <xs:sequence>
            <xs:element name="person" maxOccurs="unbounded">
                <xs:complexType>
                <xs:sequence>
                    <xs:element name="name" type="xs:string"/>
                    <xs:element name="age" type="xs:integer"/>
                    <xs:element name="gender" type="xs:string"/>
                    <xs:element name="address">
                        <xs:complexType>
                        <xs:sequence>
                            <xs:element name="doorno" type="xs:integer"/>
                            <xs:element name="street" type="xs:string"/>
                            <xs:element name="city" type="xs:string"/>
                            <xs:element name="state" type="xs:string"/>
                        </xs:sequence>
                        </xs:complexType>
                    </xs:element>

                    <xs:element name="student">
                        <xs:complexType>
                        <xs:sequence>
                            <xs:element name="rollno" type="xs:integer"/>
                            <xs:element name="standard" type="xs:integer"/>
                            <xs:element name="section" type="xs:string"/>
                        </xs:sequence>
                        </xs:complexType>
                    </xs:element>

                    <xs:element name="staff">
                        <xs:complexType>
                        <xs:sequence>
                            <xs:element name="staffid" type="xs:integer"/>
                            <xs:element name="subject" type="xs:string"/>
                        </xs:sequence>
                        </xs:complexType>
                    </xs:element>

                </xs:sequence>
                </xs:complexType>
            </xs:element>

        </xs:sequence>
        </xs:complexType>
    </xs:element>

</xs:schema>

Iam new to XML and a learner.

The error:

Exception: cvc-complex-type.2.4.b: The content of element 'person' is not comple te. One of '{staff}' is expected.

Body:
Your XSD says that there should be <xs:element name="student"> followed by <xs:element name="staff">, but instead you would like to have "either a student or staff". For this XSD has another element, <xs:choice>:

<xs:choice>
    <xs:element name="student">
        <xs:complexType>
        <xs:sequence>
            <xs:element name="rollno" type="xs:integer"/>
            <xs:element name="standard" type="xs:integer"/>
            <xs:element name="section" type="xs:string"/>
        </xs:sequence>
        </xs:complexType>
    </xs:element>

    <xs:element name="staff">
        <xs:complexType>
        <xs:sequence>
            <xs:element name="staffid" type="xs:integer"/>
            <xs:element name="subject" type="xs:string"/>
        </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:choice>

Please also check out another answer: How to specify in an XML schema that either one of two fields must be present?


来源: stackexchange

问:
Swift Image Download TableView
I'm trying to fix a problem with downloading an image asynchronously in a TableView in Swift. This is my Problem: I download the image from a url asynchronously, but if I scroll quickly the TableView my pictures begin to rotate.(The images alternate until the correct one appears).

This is my Download Async Code and imageCache

```<code>let imageCache = NSCache()

//DOWNLOAD Image ASINC
extension UIImageView {

    public func imageFromServerURL(url: String){

        if(imageCache.objectForKey(url) != nil){
            self.image = imageCache.objectForKey(url) as? UIImage
        }else{

            let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
            let session = NSURLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
            let task = session.dataTaskWithURL(NSURL(string: url)!, completionHandler: { (data, response, error) -> Void in
                if error == nil {

                    dispatch_async(dispatch_get_main_queue(), { () -> Void in
                        if let downloadedImage = UIImage(data: data!) {
                            imageCache.setObject(downloadedImage, forKey: url)
                            self.image = downloadedImage
                        }
                    })

                }
                else {
                    print(error)
                }
            })
            task.resume()
        }

    }
}
</code>```

and Which I recall in the TableView so:

```<code>func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier("record_charts", forIndexPath: indexPath) as! myTableViewCell

            let url_img = "https://image/download.jpg"
            cell.immagine.imageFromServerURL(url_img)

        return cell
    }
</code>```

This is the gif to show you the problem better

答:
This is because of cell reuse.  I will try to explain.  Suppose you have 10 cells each having a different image (Images 1 to 10) but only 5 cells fit on the screen.  The table starts to load and the first cell requests image 1 to be put in an image view and that starts happening in the background but the table is scrolled before the background loading of the image finishes and the first cell is scrolled of the screen.  Now that cell will be reused let's say by the sixth cell which requests image 6.  You background request for image 1 then finishes and as it is still holding a reference to the cell image 1 is put in the image view.  Then your background process for image 6 finishes and that replaces the image with the new version.  It will be even worse if image 6 finishes loading before image 1 as you then get image 6 put in the cell and it's then replaced by image 1.

What you need to do is implement some method so that when the image is available you can check that it is still the correct one to use.  I don't think you are going to be able to do that making the function an extension of ImageView so you probably need some kind of central image provider or something similar.

ContentLicense: CC BY-SA 3.0

Title: Swift Image Download TableView

Body:
I'm trying to fix a problem with downloading an image asynchronously in a TableView in Swift. This is my Problem: I download the image from a url asynchronously, but if I scroll quickly the TableView my pictures begin to rotate.(The images alternate until the correct one appears).

This is my Download Async Code and imageCache

let imageCache = NSCache()

//DOWNLOAD Image ASINC
extension UIImageView {

    public func imageFromServerURL(url: String){

        if(imageCache.objectForKey(url) != nil){
            self.image = imageCache.objectForKey(url) as? UIImage
        }else{

            let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
            let session = NSURLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
            let task = session.dataTaskWithURL(NSURL(string: url)!, completionHandler: { (data, response, error) -> Void in
                if error == nil {

                    dispatch_async(dispatch_get_main_queue(), { () -> Void in
                        if let downloadedImage = UIImage(data: data!) {
                            imageCache.setObject(downloadedImage, forKey: url)
                            self.image = downloadedImage
                        }
                    })

                }
                else {
                    print(error)
                }
            })
            task.resume()
        }

    }
}

and Which I recall in the TableView so:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier("record_charts", forIndexPath: indexPath) as! myTableViewCell

            let url_img = "https://image/download.jpg"
            cell.immagine.imageFromServerURL(url_img)

        return cell
    }

This is the gif to show you the problem better


问:
semicolon after the for loop block
```<code>#include <iostream>

int main() {
    for( int i = 0; i < 5; ++i) {
        std::cout << "Hello" << std::endl;
    };
}
</code>```

Is there any case that the semicolon after the for loop would affect the program ?

答:
No.

The semicolon is not even "attached" to the loop; it's just an empty statement sitting there, effectively on its own.

Title: semicolon after the for loop block

Body:
#include <iostream>

int main() {
    for( int i = 0; i < 5; ++i) {
        std::cout << "Hello" << std::endl;
    };
}

Is there any case that the semicolon after the for loop would affect the program ?


问:
Calling method after clicked outside of HTML input, Angular2
I have input in my template like this:

```<code><input type="text" class="form-control" [(ngModel)]="object.LanguageTableData" [formControl]="editControl" />
</code>```

"object" is something generated by *ngFor, so I have input with some value, which is "object.LanguageTableData". When I changed the input and click outside of this input (or press enter) I need to call my method (this method will insert - if input value is empty, or update the value in database). I know, that I can call on editControl (type of FormControl) some valueChanges with debounceTime, but I need to call the statement after edit of input is completed - it is when user click outside of the input or press enter.

答: Bind your code to ButtonPress and OnBlur input events.</p>

Body:
I have input in my template like this:

<input type="text" class="form-control" [(ngModel)]="object.LanguageTableData" [formControl]="editControl" />

"object" is something generated by *ngFor, so I have input with some value, which is "object.LanguageTableData". When I changed the input and click outside of this input (or press enter) I need to call my method (this method will insert - if input value is empty, or update the value in database). I know, that I can call on editControl (type of FormControl) some valueChanges with debounceTime, but I need to call the statement after edit of input is completed - it is when user click outside of the input or press enter.


问:
Unable to iterate a list and compare strings python
I am new to python programming and I really need help in comparing values in a list.

I have two lists(drink,food) .I'm not doing a comparison between two lists. What i am trying to do is comparing all the values within a list by itself.

So, I have to first compare all the values in drink list first using a for loop and an if-else statement. If there's a match in drink, I will do another for loop for food list and compare the values in food list using an if-else statement.

These are my code:

```<code>drinks = []
food = []

drinks.append("lemontea")
drinks.append("coke")
drinks.append("sprite")
drinks.append("orangejuice")
drinks.append("fantagrape")

food.append("nugget")
food.append("pizza")
food.append("chickenwing")
food.append("fries")
food.append("pizza")

for i in drinks:
    if i == drinks:
        for j in food:
            if j == food:
                print("fail")
    else:
         print("success")
</code>```

My issue is that I am supposed to be getting an 'failed' output as I have the same item in the food list that is pizza. Also, i'm not sure why am i getting 5 success output when im expected to get either only 1 'failed' or 'success' output.

This is my output i got:

```<code>success
success
success
success
success
</code>```

I would appreciate if any help was given. Thank you.

Update:
Thanks for the reply but however, it seem that people are confused with my question, hence im providing more information.

The reason why i have to compare each item in a list is because the items are generated randomly and are of string type which are then appended to the list. For example, the first item generated is '00100ABC'and so on. So in case, there are duplicate values/item in the list, i have to give an error message.

答:
you could use set to check for uniqueness and intersects

```<code>drinks = []
food = []

drinks.append("lemontea")
drinks.append("coke")
drinks.append("sprite")
drinks.append("orangejuice")
drinks.append("fantagrape")

food.append("nugget")
food.append("pizza")
food.append("chickenwing")
food.append("fries")
food.append("pizza")

success = True
</code>```

unique

```<code>if len(set(food)) != len(food):
    print('fail: duplicate entry in food')
    success = False
if len(set(drinks)) != len(drinks):
    print('fail: duplicate entry in drinks')
    success = False
</code>```

in both lists

```<code>if set(food) & set(drinks):  # if the intersection of both sets is not empty
    print('fail: entry in both food and drinks')
    success = False
</code>```

success!

```<code>if success:
    print('success')
</code>```

Body:
I am new to python programming and I really need help in comparing values in a list.

I have two lists(drink,food) .I'm not doing a comparison between two lists. What i am trying to do is comparing all the values within a list by itself.

So, I have to first compare all the values in drink list first using a for loop and an if-else statement. If there's a match in drink, I will do another for loop for food list and compare the values in food list using an if-else statement.

These are my code:

drinks = []
food = []

drinks.append("lemontea")
drinks.append("coke")
drinks.append("sprite")
drinks.append("orangejuice")
drinks.append("fantagrape")

food.append("nugget")
food.append("pizza")
food.append("chickenwing")
food.append("fries")
food.append("pizza")

for i in drinks:
    if i == drinks:
        for j in food:
            if j == food:
                print("fail")
    else:
         print("success")

My issue is that I am supposed to be getting an 'failed' output as I have the same item in the food list that is pizza. Also, i'm not sure why am i getting 5 success output when im expected to get either only 1 'failed' or 'success' output.

This is my output i got:

success
success
success
success
success

I would appreciate if any help was given. Thank you.

Update:
Thanks for the reply but however, it seem that people are confused with my question, hence im providing more information.

The reason why i have to compare each item in a list is because the items are generated randomly and are of string type which are then appended to the list. For example, the first item generated is '00100ABC'and so on. So in case, there are duplicate values/item in the list, i have to give an error message.

Body:
you could use set to check for uniqueness and intersects

drinks = []
food = []

drinks.append("lemontea")
drinks.append("coke")
drinks.append("sprite")
drinks.append("orangejuice")
drinks.append("fantagrape")

food.append("nugget")
food.append("pizza")
food.append("chickenwing")
food.append("fries")
food.append("pizza")

success = True

unique

if len(set(food)) != len(food):
    print('fail: duplicate entry in food')
    success = False
if len(set(drinks)) != len(drinks):
    print('fail: duplicate entry in drinks')
    success = False

in both lists

if set(food) & set(drinks):  # if the intersection of both sets is not empty
    print('fail: entry in both food and drinks')
    success = False

success!

if success:
    print('success')


问:
Grouping data in specific way
I am building report which shows the parts of one work order in different departments.
Consider the table below

```<code>work_order  part  dept_code  datein
aaaa        11    XXX        20/01/2017
aaaa        12    BBB        22/01/2017
bbbb        12    XXX        20/01/2017
bbbb        15    XXX        22/01/2017
cccc        13    XXX        20/01/2017
cccc        17    XYX        20/01/2017
</code>```

Now i want to group this data in such way that only the work order with different dept_code should show up.
RESULT

```<code>work_order  part  dept_code  datein
aaaa        11    XXX        20/01/2017
aaaa        12    BBB        22/01/2017
cccc        13    XXX        20/01/2017
cccc        17    XYX        20/01/2017
</code>```

答:
you can use count() over() as below:</p>

```<code>Select * from (
   Select *, cnt = Count(dept_code) over(partition by work_order, dept_code) from yourTable   ) a
   Where a.cnt = 1
</code>```

Title: Grouping data in specific way

Body:
I am building report which shows the parts of one work order in different departments.
Consider the table below

work_order  part  dept_code  datein
aaaa        11    XXX        20/01/2017
aaaa        12    BBB        22/01/2017
bbbb        12    XXX        20/01/2017
bbbb        15    XXX        22/01/2017
cccc        13    XXX        20/01/2017
cccc        17    XYX        20/01/2017

Now i want to group this data in such way that only the work order with different dept_code should show up.
RESULT

work_order  part  dept_code  datein
aaaa        11    XXX        20/01/2017
aaaa        12    BBB        22/01/2017
cccc        13    XXX        20/01/2017
cccc        17    XYX        20/01/2017

Body:
you can use count() over() as below:

Select * from (
   Select *, cnt = Count(dept_code) over(partition by work_order, dept_code) from yourTable   ) a
   Where a.cnt = 1


问:
How to create a list where each new element is obtained as the last element plus a constant?
Given these variables:

```<code>a_4th =  6.08
delta_a = 0.052
</code>```

I would like to create a list that contains:

```<code>a = [a_4th, a_5th, a_6th, a_7th ... ]
</code>```

where:

```<code>a_5th = a_4th + delta_a
a_6th = a_5th + delta_a
a_7th = a_6th + delta_a
</code>```

This code:

```<code>a = []  # create the empty list
a.insert(0, a_4th) # initialize the 1st item of the list

for i in xrange (1,19):   # I would like the list to be 18 items long.
                          # a[0] is defined in the previous line.
  a[i] = a[i-1] + delta_a
</code>```

is giving this error:

Traceback (most recent call last):
  File "so.py", line 8, in <module>
    a[i] = a[i-1] + delta_a
IndexError: list assignment index out of range
```

答:
The plain simple solution:

```<code>a = []
a.append(a_4th)
for i in xrange(1, 19):
    a.append(a[i-1] + delta_a)
</code>```

but given your definition:

a_5th = a_4th + delta_a

a_6th = a_5th + delta_a

a_7th = a_6th + delta_a

we can much more simply think of it as:

a_5th = a_4th + (delta_a * 1)

a_6th = a_4th + (delta_a * 2)

a_7th = a_4th + (delta_a * 3)

and write it as a simple (and faster) list comprehension, cf Ev Kounis answer.

Body:
Given these variables:

a_4th =  6.08
delta_a = 0.052

I would like to create a list that contains:

a = [a_4th, a_5th, a_6th, a_7th ... ]

where:

a_5th = a_4th + delta_a
a_6th = a_5th + delta_a
a_7th = a_6th + delta_a

This code:

a = []  # create the empty list
a.insert(0, a_4th) # initialize the 1st item of the list

for i in xrange (1,19):   # I would like the list to be 18 items long.
                          # a[0] is defined in the previous line.
  a[i] = a[i-1] + delta_a

is giving this error:

Traceback (most recent call last):
  File "so.py", line 8, in <module>
    a[i] = a[i-1] + delta_a
IndexError: list assignment index out of range

Body:
The plain simple solution:

a = []
a.append(a_4th)
for i in xrange(1, 19):
    a.append(a[i-1] + delta_a)

but given your definition:

a_5th = a_4th + delta_a

a_6th = a_5th + delta_a

a_7th = a_6th + delta_a

we can much more simply think of it as:

a_5th = a_4th + (delta_a * 1)

a_6th = a_4th + (delta_a * 2)

a_7th = a_4th + (delta_a * 3)

and write it as a simple (and faster) list comprehension, cf Ev Kounis answer.


问:
Hierarchical Dirichlet Process Gensim topic number independent of corpus size
I am using the Gensim HDP module on a set of documents.

```<code>>>> hdp = models.HdpModel(corpusB, id2word=dictionaryB)
>>> topics = hdp.print_topics(topics=-1, topn=20)
>>> len(topics)
150
>>> hdp = models.HdpModel(corpusA, id2word=dictionaryA)
>>> topics = hdp.print_topics(topics=-1, topn=20)
>>> len(topics)
150
>>> len(corpusA)
1113
>>> len(corpusB)
17
</code>```

Why is the number of topics independent of corpus length?

答:
@Aaron's code above is broken due to gensim API changes. I rewrote and simplified it as follows. Works as of June 2017 with gensim v2.1.0

```<code>import pandas as pd

def topic_prob_extractor(gensim_hdp):
    shown_topics = gensim_hdp.show_topics(num_topics=-1, formatted=False)
    topics_nos = [x[0] for x in shown_topics ]
    weights = [ sum([item[1] for item in shown_topics[topicN][1]]) for topicN in topics_nos ]

    return pd.DataFrame({'topic_id' : topics_nos, 'weight' : weights})
</code>```

Body:
I am using the Gensim HDP module on a set of documents.

>>> hdp = models.HdpModel(corpusB, id2word=dictionaryB)
>>> topics = hdp.print_topics(topics=-1, topn=20)
>>> len(topics)
150
>>> hdp = models.HdpModel(corpusA, id2word=dictionaryA)
>>> topics = hdp.print_topics(topics=-1, topn=20)
>>> len(topics)
150
>>> len(corpusA)
1113
>>> len(corpusB)
17

Why is the number of topics independent of corpus length?

Body:
@Aaron's code above is broken due to gensim API changes. I rewrote and simplified it as follows. Works as of June 2017 with gensim v2.1.0

import pandas as pd

def topic_prob_extractor(gensim_hdp):
    shown_topics = gensim_hdp.show_topics(num_topics=-1, formatted=False)
    topics_nos = [x[0] for x in shown_topics ]
    weights = [ sum([item[1] for item in shown_topics[topicN][1]]) for topicN in topics_nos ]

    return pd.DataFrame({'topic_id' : topics_nos, 'weight' : weights})


问:
Is it possible to work android 2.2 application on other android versions (1.5 to 2.1)?
I developed one application based on android 2.2 version.
Is it possible to work that application on other android versions (1.5 to 2.1)? </p>

答:
Depends on the functionality of the platform used in the application. If you have used any of the features of the 2.2, then you cannot. You can see which features are supported by checking the documentation (just an example). On the top right, you get a drop down list which you can filter for the API versions.

Easiest way to find out if it is working is to change minimum required version to LEVEL 3 of API (1.5) and then change the class path (sometimes it does it itself) and then compile. It will tell you if it works.

ContentLicense: CC BY-SA 2.5


问:
What is the equivalent pg SQL for this Mysql statement (inner join in UPDATE statement)?
Mysql:

UPDATE a INNER JOIN b on a.b_id = b.id SET n=1 WHERE b.n > 2

Postgresql (I know):

UPDATE a SET n=1 FROM b WHERE b.n > 2 AND a.b_id = b.id

But what are the equivalent pg statements for:

UPDATE a OUTER JOIN b on a.b_id = b.id SET n=1 WHERE b.n > 2

UPDATE a LEFT JOIN b on a.b_id = b.id SET n=1 WHERE b.n > 2

More generally, what's the equivalent pg statement if I have several inner join tables (e.g. 3 tables)in Mysql like:

```<code>UPDATE a
INNER JOIN b on a.b_id = b.id
INNER JOIN c on b.c_id = c.id
INNER JOIN d on c.d_id = d.id
SET n=1 WHERE d.n > 2
</code>```

答:
what's the use of the left join if you're filtering it anyway using n > 2 ?

```<code>Table a:
id | firstname | b_id
1  | elisabeth | 2
2  | sam       | 2
3  | john      | 3

table b:
id | surname
2  | smith
3  | doe

UPDATE a LEFT JOIN b on a.b_id = b.id SET firstname = null WHERE b.id > 2
</code>```

Only john doe will be updated.

As for this one:

```<code>UPDATE a
INNER JOIN b on a.b_id = b.id
INNER JOIN c on b.c_id = c.id
INNER JOIN d on c.d_id = d.id
SET n=1 WHERE d.n > 2
</code>```

In postgres :

```<code>UPDATE a
SET n=1
FROM b, c, d
WHERE a.b_id = b.id
AND b.c_id = c.id
AND c.d_id = d.id
AND d.n > 2
</code>```

Body:
Mysql:

UPDATE a INNER JOIN b on a.b_id = b.id SET n=1 WHERE b.n > 2

Postgresql (I know):

UPDATE a SET n=1 FROM b WHERE b.n > 2 AND a.b_id = b.id

But what are the equivalent pg statements for:

UPDATE a OUTER JOIN b on a.b_id = b.id SET n=1 WHERE b.n > 2

UPDATE a LEFT JOIN b on a.b_id = b.id SET n=1 WHERE b.n > 2

More generally, what's the equivalent pg statement if I have several inner join tables (e.g. 3 tables)in Mysql like:

UPDATE a
INNER JOIN b on a.b_id = b.id
INNER JOIN c on b.c_id = c.id
INNER JOIN d on c.d_id = d.id
SET n=1 WHERE d.n > 2

Body:
what's the use of the left join if you're filtering it anyway using n > 2 ?

Table a:
id | firstname | b_id
1  | elisabeth | 2
2  | sam       | 2
3  | john      | 3

table b:
id | surname
2  | smith
3  | doe

UPDATE a LEFT JOIN b on a.b_id = b.id SET firstname = null WHERE b.id > 2

Only john doe will be updated.

As for this one:

UPDATE a
INNER JOIN b on a.b_id = b.id
INNER JOIN c on b.c_id = c.id
INNER JOIN d on c.d_id = d.id
SET n=1 WHERE d.n > 2

In postgres :

UPDATE a
SET n=1
FROM b, c, d
WHERE a.b_id = b.id
AND b.c_id = c.id
AND c.d_id = d.id
AND d.n > 2


答:
Let's clean up your code:

```<code>a = []  # create the empty list
a.insert(0, a_4th) # initialize the 1st item of the list
</code>```

This wastes effort, both in reading and execution.  Just initialize the list:

```<code>a = [a_4th]
</code>```

As for the loop, you cannot assign to an element of the list that doesn't exist.  You create new list elements with append, insert, concatenation, or other defined operations.

```<code>for i in xrange (1,19):   # I would like the list to be 18 items long.
                          # a[0] is defined in the previous line.
  a.append( a[-1] + delta_a )
</code>```

Yes, I removed the i from i-1; that introduces another possibility of error.  Simply use the last (index minus-one) element of the list.

Title: How to create a list where each new element is obtained as the last element plus a constant?

Body:
Let's clean up your code:

a = []  # create the empty list
a.insert(0, a_4th) # initialize the 1st item of the list

This wastes effort, both in reading and execution.  Just initialize the list:

a = [a_4th]

As for the loop, you cannot assign to an element of the list that doesn't exist.  You create new list elements with append, insert, concatenation, or other defined operations.

for i in xrange (1,19):   # I would like the list to be 18 items long.
                          # a[0] is defined in the previous line.
  a.append( a[-1] + delta_a )

Yes, I removed the i from i-1; that introduces another possibility of error.  Simply use the last (index minus-one) element of the list.


问:
How to use Promise.all with an object as input
I've been working on a small 2D game library for my own use, and I've run into a bit of a problem. There is a particular function in the library called loadGame that takes dependency info as input (resource files, and a list of scripts ot be executed). Here's an example.

```<code>loadGame({
    "root" : "/source/folder/for/game/",

    "resources" : {
        "soundEffect" : "audio/sound.mp3",
        "someImage" : "images/something.png",
        "someJSON" : "json/map.json"
    },

    "scripts" : [
        "js/helperScript.js",
        "js/mainScript.js"
    ]
})
</code>```

Each item in resources has a key that is used by the game to access that particular resource. The loadGame function converts the resources into an object of promises.

The problem is that it tries to use Promises.all to check for when they're all ready, but Promise.all accepts only iterables as inputs - so an object like what I have is out of the question.

So I tried to convert the object into an array, this works great, except each resource is just an element in an array and doesn't have a key to identify them.

Here's the code for loadGame:

```<code>var loadGame = function (game) {
    return new Promise(function (fulfill, reject) {
        // the root folder for the game
        var root = game.root || '';

        // these are the types of files that can be loaded
        // getImage, getAudio, and getJSON are defined elsewhere in my code - they return promises
        var types = {
            jpg : getImage,
            png : getImage,
            bmp : getImage,

            mp3 : getAudio,
            ogg : getAudio,
            wav : getAudio,

            json : getJSON
        };

        // the object of promises is created using a mapObject function I made
        var resources = mapObject(game.resources, function (path) {
            // get file extension for the item
            var extension = path.match(/(?:\.([^.]+))?$/)[1];

            // find the correct 'getter' from types
            var get = types[extension];

            // get it if that particular getter exists, otherwise, fail
            return get ? get(root + path) :
                reject(Error('Unknown resource type "' + extension + '".'));
        });

        // load scripts when they're done
        // this is the problem here
        // my 'values' function converts the object into an array
        // but now they are nameless and can't be properly accessed anymore
        Promise.all(values(resources)).then(function (resources) {
            // sequentially load scripts
            // maybe someday I'll use a generator for this
            var load = function (i) {
                // load script
                getScript(root + game.scripts[i]).then(function () {
                    // load the next script if there is one
                    i++;

                    if (i < game.scripts.length) {
                        load(i);
                    } else {
                        // all done, fulfill the promise that loadGame returned
                        // this is giving an array back, but it should be returning an object full of resources
                        fulfill(resources);
                    }
                });
            };

            // load the first script
            load(0);
        });
    });
};
</code>```

Ideally I'd like for some way to properly manage a list of promises for resources while still mantaining an identifier for each item. Any help would be appreciated, thanks.

答:
Using async/await and lodash:</p>

```<code>// If resources are filenames
const loadedResources = _.zipObject(_.keys(resources), await Promise.all(_.map(resources, filename => {
    return promiseFs.readFile(BASE_DIR + '/' + filename);
})))

// If resources are promises
const loadedResources = _.zipObject(_.keys(resources), await Promise.all(_.values(resources)));
</code>```

Body:
I've been working on a small 2D game library for my own use, and I've run into a bit of a problem. There is a particular function in the library called loadGame that takes dependency info as input (resource files, and a list of scripts ot be executed). Here's an example.

loadGame({
    "root" : "/source/folder/for/game/",

    "resources" : {
        "soundEffect" : "audio/sound.mp3",
        "someImage" : "images/something.png",
        "someJSON" : "json/map.json"
    },

    "scripts" : [
        "js/helperScript.js",
        "js/mainScript.js"
    ]
})

Each item in resources has a key that is used by the game to access that particular resource. The loadGame function converts the resources into an object of promises.

The problem is that it tries to use Promises.all to check for when they're all ready, but Promise.all accepts only iterables as inputs - so an object like what I have is out of the question.

So I tried to convert the object into an array, this works great, except each resource is just an element in an array and doesn't have a key to identify them.

Here's the code for loadGame:

var loadGame = function (game) {
    return new Promise(function (fulfill, reject) {
        // the root folder for the game
        var root = game.root || '';

        // these are the types of files that can be loaded
        // getImage, getAudio, and getJSON are defined elsewhere in my code - they return promises
        var types = {
            jpg : getImage,
            png : getImage,
            bmp : getImage,

            mp3 : getAudio,
            ogg : getAudio,
            wav : getAudio,

            json : getJSON
        };

        // the object of promises is created using a mapObject function I made
        var resources = mapObject(game.resources, function (path) {
            // get file extension for the item
            var extension = path.match(/(?:\.([^.]+))?$/)[1];

            // find the correct 'getter' from types
            var get = types[extension];

            // get it if that particular getter exists, otherwise, fail
            return get ? get(root + path) :
                reject(Error('Unknown resource type "' + extension + '".'));
        });

        // load scripts when they're done
        // this is the problem here
        // my 'values' function converts the object into an array
        // but now they are nameless and can't be properly accessed anymore
        Promise.all(values(resources)).then(function (resources) {
            // sequentially load scripts
            // maybe someday I'll use a generator for this
            var load = function (i) {
                // load script
                getScript(root + game.scripts[i]).then(function () {
                    // load the next script if there is one
                    i++;

                    if (i < game.scripts.length) {
                        load(i);
                    } else {
                        // all done, fulfill the promise that loadGame returned
                        // this is giving an array back, but it should be returning an object full of resources
                        fulfill(resources);
                    }
                });
            };

            // load the first script
            load(0);
        });
    });
};

Ideally I'd like for some way to properly manage a list of promises for resources while still mantaining an identifier for each item. Any help would be appreciated, thanks.

Body:
Using async/await and lodash:

// If resources are filenames
const loadedResources = _.zipObject(_.keys(resources), await Promise.all(_.map(resources, filename => {
    return promiseFs.readFile(BASE_DIR + '/' + filename);
})))

// If resources are promises
const loadedResources = _.zipObject(_.keys(resources), await Promise.all(_.values(resources)));


问:
Changing color Axis in Highchart Choropleth
I'm fairly new to visualizing maps on R and I'm trying to change the legends in a motion choropleth.

My code is as under

```<code>ds <- a21 %>%
  group_by(fips) %>%
  do(item = list(
    fips = first(.$fips),
    sequence = .$freq,
    value = first(.$freq))) %>%
  .$item

hc <- highchart(type = "map") %>%
  hc_add_series(data = ds,
                name = "complaints",
                mapData = uscountygeojson,
                joinBy = "fips",
                borderWidth = 0.01) %>%
  hc_colorAxis(stops = color_stops()) %>%
  hc_title(text = "patient complaints") %>%
  hc_legend(layout = "vertical", reversed = TRUE,
            floating = TRUE, align = "right") %>%
  hc_add_theme(hc_theme_smpl()) %>%
  hc_motion(
    enabled = TRUE,
    axisLabel = "year",
    labels = sort(unique(a21$year)),
    series = 0,
    updateIterval = 50,
    magnet = list(
      round = "floor",
      step = 0.1
    )
  )
</code>```

Screenshot of the existing result:

As of now I see R automatically creates colorbins of frequencies

I wish to change this to a set of custom values in my dataframe.

A snippet of my dataframe is as under

```<code>a21:

      year  fips   freq            q
1     2004  1001      3 1st Quantile
2     2005  1001      0 1st Quantile
3     2006  1001      4 1st Quantile
4     2007  1001      0 1st Quantile
5     2008  1001      0 1st Quantile
6     2009  1001      0 1st Quantile
</code>```

I want the column q as color axis labels

答:
I think you need to associate column q with a color (perhaps as another column in the dataframe) and then use those colors in conjunction with the color_stops function.

For example:

```<code>library(dplyr)
library(highcharter)
mapdata <- get_data_from_map(download_map_data("countries/us/us-all"))

set.seed(1234)

data_fake <- mapdata %>%
  select(code = `hc-a2`) %>%
  mutate(value = 1e5 * abs(rt(nrow(.), df = 10)))

colors <- c("red", "blue", "green" , "yellow")

hcmap("countries/us/us-all", data = data_fake, value = "value",
      joinBy = c("hc-a2", "code"), name = "Fake data",
      dataLabels = list(enabled = TRUE, format = '{point.name}'),
      borderColor = "#FAFAFA", borderWidth = 0.1,
      tooltip = list(valueDecimals = 2, valuePrefix = "$", valueSuffix =
      "USD"))%>%
  hc_colorAxis(minColor = "blue", maxColor = "red",
  stops = color_stops(n=length(colors), colors = colors))
</code>```

Body:
I'm fairly new to visualizing maps on R and I'm trying to change the legends in a motion choropleth.

My code is as under

ds <- a21 %>%
  group_by(fips) %>%
  do(item = list(
    fips = first(.$fips),
    sequence = .$freq,
    value = first(.$freq))) %>%
  .$item

hc <- highchart(type = "map") %>%
  hc_add_series(data = ds,
                name = "complaints",
                mapData = uscountygeojson,
                joinBy = "fips",
                borderWidth = 0.01) %>%
  hc_colorAxis(stops = color_stops()) %>%
  hc_title(text = "patient complaints") %>%
  hc_legend(layout = "vertical", reversed = TRUE,
            floating = TRUE, align = "right") %>%
  hc_add_theme(hc_theme_smpl()) %>%
  hc_motion(
    enabled = TRUE,
    axisLabel = "year",
    labels = sort(unique(a21$year)),
    series = 0,
    updateIterval = 50,
    magnet = list(
      round = "floor",
      step = 0.1
    )
  )

Screenshot of the existing result:

As of now I see R automatically creates colorbins of frequencies

I wish to change this to a set of custom values in my dataframe.

A snippet of my dataframe is as under

a21:

      year  fips   freq            q
1     2004  1001      3 1st Quantile
2     2005  1001      0 1st Quantile
3     2006  1001      4 1st Quantile
4     2007  1001      0 1st Quantile
5     2008  1001      0 1st Quantile
6     2009  1001      0 1st Quantile

I want the column q as color axis labels

Body:
I think you need to associate column q with a color (perhaps as another column in the dataframe) and then use those colors in conjunction with the color_stops function.

For example:

library(dplyr)
library(highcharter)
mapdata <- get_data_from_map(download_map_data("countries/us/us-all"))

set.seed(1234)

data_fake <- mapdata %>%
  select(code = `hc-a2`) %>%
  mutate(value = 1e5 * abs(rt(nrow(.), df = 10)))

colors <- c("red", "blue", "green" , "yellow")

hcmap("countries/us/us-all", data = data_fake, value = "value",
      joinBy = c("hc-a2", "code"), name = "Fake data",
      dataLabels = list(enabled = TRUE, format = '{point.name}'),
      borderColor = "#FAFAFA", borderWidth = 0.1,
      tooltip = list(valueDecimals = 2, valuePrefix = "$", valueSuffix =
      "USD"))%>%
  hc_colorAxis(minColor = "blue", maxColor = "red",
  stops = color_stops(n=length(colors), colors = colors))


答:
The semicolon is an empty expression statement.

From section 6.2 of the C++ standard

The expression is a discarded-value expression (Clause 5). All side
  effects from an expression statement are completed before the next
  statement is executed. An expression statement with the expression
  missing is called a null statement. [ Note: Most statements are
  expression statements — usually assignments or function calls. A null
  statement is useful to carry a label just before the } of a compound
  statement and to supply a null body to an iteration statement such as
  a while statement (6.5.1). —end note ]

This will be more clear with some reformatting:

```<code>#include <iostream>

int main(){
    for(int i=0; i<5; ++i){
        std::cout <<"Hello"<<std::endl;
    }
    ;
}
</code>```

The presence of this null statement has no effect on the program.

Title: semicolon after the for loop block

Body:
#include <iostream>

int main() {
    for( int i = 0; i < 5; ++i) {
        std::cout << "Hello" << std::endl;
    };
}

Is there any case that the semicolon after the for loop would affect the program ?

Body:
The semicolon is an empty expression statement.

From section 6.2 of the C++ standard

The expression is a discarded-value expression (Clause 5). All side
  effects from an expression statement are completed before the next
  statement is executed. An expression statement with the expression
  missing is called a null statement. [ Note: Most statements are
  expression statements — usually assignments or function calls. A null
  statement is useful to carry a label just before the } of a compound
  statement and to supply a null body to an iteration statement such as
  a while statement (6.5.1). —end note ]

This will be more clear with some reformatting:

#include <iostream>

int main(){
    for(int i=0; i<5; ++i){
        std::cout <<"Hello"<<std::endl;
    }
    ;
}

The presence of this null statement has no effect on the program.


问:
EmberJS - testing input action on enter
I have an EmberJS (2.5.0) component similar to the following:

```<code>{{input type="text" value=searchValue enter='handleSearch'}}
</code>```

Basically, hitting enter on the input field should trigger the 'handleSearch' action. And in my component, so far I have this:

```<code>searchValue: null,
actions: {
  handleSearch() {
    var searchValue = this.get('searchValue');
    var submitSearch = this.get('submitSearch');
    console.log('Search term entered: ', searchValue);
    if (submitSearch) {
      submitSearch(searchValue);
    }
  }
}
</code>```

And the component is called via:

```<code>{{my-component submitSearch=(action 'externalAction')}}
</code>```

That all works fine and all, but I'm having trouble actually testing it.

Here's my integration test (pseudo-copied from the guide):

```<code>test('search input', function(assert) {
  this.set('externalAction', (actual) => {
    console.log('in external action');
    assert.equal(actual, 'hithere');
  });
  this.render(hbs`{{universal-header-search submitSearch=(action externalAction)}}`);
  this.$('input').val('hithere');
  this.$('input').change();
});
</code>```

The problem is, my handleSearch action handler never gets triggered. So how do I get my input field to trigger the handler in my integration test? I've also tried this.$('input').submit() and this.$('input').trigger('change'), but neither seems to do anything.

答:
I've faced with the same issue: I had to trigger "enter" event of Ember's (v.2.8) input component programmatically

```<code>{{input ... enter=(action "someAction")}}
</code>```

After some reverse engineering I've found a solution

```<code>const e = Ember.$.Event("keyup");
e.which = 13;
e.keyCode = 13;
Ember.$('input').trigger(e);
</code>```

Title: EmberJS - testing input action on enter

Body:
I have an EmberJS (2.5.0) component similar to the following:

{{input type="text" value=searchValue enter='handleSearch'}}

Basically, hitting enter on the input field should trigger the 'handleSearch' action. And in my component, so far I have this:

searchValue: null,
actions: {
  handleSearch() {
    var searchValue = this.get('searchValue');
    var submitSearch = this.get('submitSearch');
    console.log('Search term entered: ', searchValue);
    if (submitSearch) {
      submitSearch(searchValue);
    }
  }
}

And the component is called via:

{{my-component submitSearch=(action 'externalAction')}}

That all works fine and all, but I'm having trouble actually testing it.

Here's my integration test (pseudo-copied from the guide):

test('search input', function(assert) {
  this.set('externalAction', (actual) => {
    console.log('in external action');
    assert.equal(actual, 'hithere');
  });
  this.render(hbs`{{universal-header-search submitSearch=(action externalAction)}}`);
  this.$('input').val('hithere');
  this.$('input').change();
});

The problem is, my handleSearch action handler never gets triggered. So how do I get my input field to trigger the handler in my integration test? I've also tried this.$('input').submit() and this.$('input').trigger('change'), but neither seems to do anything.

Body:
I've faced with the same issue: I had to trigger "enter" event of Ember's (v.2.8) input component programmatically

{{input ... enter=(action "someAction")}}

After some reverse engineering I've found a solution

const e = Ember.$.Event("keyup");
e.which = 13;
e.keyCode = 13;
Ember.$('input').trigger(e);


问:
Is it possible to force fail a recaptcha v2 for testing purposes? (I.e. pretend to be a robot)
I'm implementing an invisible reCAPTCHA as per the instructions in the documentation: reCAPTCHA V2 documentation

I've managed to implement it without any problems. But, what I'd like to know is whether I can simulate being a robot for testing purposes?

Is there a way to force the reCAPTCHA to respond as if it thought I was a robot?

Thanks in advance for any assistance.

答: You can use a Chrome Plugin like Modify Headers and Add a user-agent like Googlebot/2.1 (+http://www.google.com/bot.html).</p>


问:
span tag text-align not working
I'm trying to make a line for price and I want the text-align like the first one on the left, second one on the center and the third one will be on right.

Normally the text-align works but I can't keep all three of them in them in the same line. Should I use something different? or there's a solution for this!?

First I tried like this:

.price span {
  display: inline;
  /* also tried with block and inline-block */
}

.previous-price {
  text-align: left;
}

.present-price {
  text-align: center;
}

.discount-price {
  text-align: right;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p class="price">
  <span class="previous-price"><s>Tk. 350000</s></span>
   <span class="present-price">Tk. 227500</span>
   <span class="discount-price">(35% OFF)</span>
  </p></code>```

答:
A simple solution is to make the .price element a flex-container with the following settings:

.price {
  display: flex;
  justify-content: space-between;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p class="price">
  <span class="previous-price"><s>Tk. 350000</s></span>
  <span class="present-price">Tk. 227500</span>
  <span class="discount-price">(35% OFF)</span>
</p></code>```

(BTW: You closed your  tags with closing
 tags - I changed that in my fiddle)

Title: span tag text-align not working

Body:
I'm trying to make a line for price and I want the text-align like the first one on the left, second one on the center and the third one will be on right.

Normally the text-align works but I can't keep all three of them in them in the same line. Should I use something different? or there's a solution for this!?

First I tried like this:

.price span {
  display: inline;
  /* also tried with block and inline-block */
}

.previous-price {
  text-align: left;
}

.present-price {
  text-align: center;
}

.discount-price {
  text-align: right;
}

  <s>Tk. 350000</s>
   Tk. 227500
   (35% OFF)

Body:
A simple solution is to make the .price element a flex-container with the following settings:

.price {
  display: flex;
  justify-content: space-between;
}

<p class="price">
  <span class="previous-price"><s>Tk. 350000</s></span>
  <span class="present-price">Tk. 227500</span>
  <span class="discount-price">(35% OFF)</span>
</p>

(BTW: You closed your <span> tags with closing </p> tags - I changed that in my fiddle)


问:
Mercurial moving commits in another branch
My coworker accidentally made two commits in the default branch instead of creating new his own development branch.

How can I change this situation and moves these two commits to a new branch?

答:
The two answers above are both correct but, assuming one has not yet pushed the commits, there's a third way.

I just successfully used the rebase command to move a string of commits to a topic branch I had forgotten to create in the first place.

I first updated to the revision from which I wanted to create the branch on which my commmits were supposed to be, then I rebased the earliest of my commits from the wrong branch on this new one and ta-da, done.

Takes more time to explain it than to do it with TortoiseHg or even the command line, really.

ContentLicense: CC BY-SA 4.0


问:
joomla BASE HREF uses HTTP instead of HTTPS
I wanted to change my site from http to https. Always.

So I configured my apache accordingly. Now when I enter the URL of my site (https://steamnet.de) it loads the index site fine but none of the referenced elements (CSS, images etc.)

It seems to me that it does so because the base href is set to http://steamnet.de/ and thous does not use https there. I have configured my firefox that it should not load mixed content.

So how can I tell Joomla to set the base href to https://steamnet.de (or otherwise make the site fully ssl?)

I tried to set the global ssl enforce element of joomla configuration ("SSL erzwingen" in german, $force_ssl in configuration.php) to "everything" but then the site breaks with infinite 303 error redirecting to itself.  (As an afterthought: I was surprised to find a 303 instead of 301 here. If someone could explain that I would be grateful)

(Laoneo suggested some solutions, that did not work out, for completeness here is the list)

configure $live_site to the https url.

probe if changing $sef and $sef_rewrite helps.

The apache logs:
access.log

```<code>91.42.221.000 - - [03/Nov/2013:12:41:25 +0100] "GET / HTTP/1.1" 303 4854 "-" "Mozilla/5.0 (Gecko) Firefox/64"
91.42.221.000 - - [03/Nov/2013:12:41:25 +0100] "GET / HTTP/1.1" 303 516 "-" "Mozilla/5.0 (Gecko) Firefox/64"
91.42.221.000 - - [03/Nov/2013:12:41:25 +0100] "GET / HTTP/1.1" 303 516 "-" "Mozilla/5.0 (Gecko) Firefox/64"
</code>```

error.log contains nothing on access, but the following lines on reload

```<code>[Sun Nov 03 12:41:16 2013] [notice] Graceful restart requested, doing restart
[Sun Nov 03 12:41:16 2013] [error] (9)Bad file descriptor: apr_socket_accept: (client socket)
[Sun Nov 03 12:41:17 2013] [warn] RSA server certificate CommonName (CN) `Angelo Neuschitzer' does NOT match server name!?
[Sun Nov 03 12:41:17 2013] [notice] Apache/2.2.16 (Debian) PHP/5.3.3-7+squeeze17 with Suhosin-Patch proxy_html/3.0.1 mod_ssl/2.2.16 OpenSSL/0.9.8o configured -- resuming normal operations
</code>```

答:
Removing the <base> tag altogether should solve your issues. You can do this in the index.php file of your template like this:

```<code>$doc = JFactory::getDocument();
unset($doc->base);
</code>```

Since this is not a core hack, it will be upgrade-proof. However, if you use a template from a theme store, and choose to upgrade the template in the future, you may have to add the code back.

References:

Protocol Relative URLs not working

How to remove the "base href" tag Joomla 3

Body:
I wanted to change my site from http to https. Always.

So I configured my apache accordingly. Now when I enter the URL of my site (https://steamnet.de) it loads the index site fine but none of the referenced elements (CSS, images etc.)

It seems to me that it does so because the base href is set to http://steamnet.de/ and thous does not use https there. I have configured my firefox that it should not load mixed content.

So how can I tell Joomla to set the base href to https://steamnet.de (or otherwise make the site fully ssl?)

I tried to set the global ssl enforce element of joomla configuration ("SSL erzwingen" in german, $force_ssl in configuration.php) to "everything" but then the site breaks with infinite 303 error redirecting to itself.  (As an afterthought: I was surprised to find a 303 instead of 301 here. If someone could explain that I would be grateful)

(Laoneo suggested some solutions, that did not work out, for completeness here is the list)

configure $live_site to the https url.

probe if changing $sef and $sef_rewrite helps.

The apache logs:
access.log

91.42.221.000 - - [03/Nov/2013:12:41:25 +0100] "GET / HTTP/1.1" 303 4854 "-" "Mozilla/5.0 (Gecko) Firefox/64"
91.42.221.000 - - [03/Nov/2013:12:41:25 +0100] "GET / HTTP/1.1" 303 516 "-" "Mozilla/5.0 (Gecko) Firefox/64"
91.42.221.000 - - [03/Nov/2013:12:41:25 +0100] "GET / HTTP/1.1" 303 516 "-" "Mozilla/5.0 (Gecko) Firefox/64"

error.log contains nothing on access, but the following lines on reload

[Sun Nov 03 12:41:16 2013] [notice] Graceful restart requested, doing restart
[Sun Nov 03 12:41:16 2013] [error] (9)Bad file descriptor: apr_socket_accept: (client socket)
[Sun Nov 03 12:41:17 2013] [warn] RSA server certificate CommonName (CN) `Angelo Neuschitzer' does NOT match server name!?
[Sun Nov 03 12:41:17 2013] [notice] Apache/2.2.16 (Debian) PHP/5.3.3-7+squeeze17 with Suhosin-Patch proxy_html/3.0.1 mod_ssl/2.2.16 OpenSSL/0.9.8o configured -- resuming normal operations

Body:
Removing the <base> tag altogether should solve your issues. You can do this in the index.php file of your template like this:

$doc = JFactory::getDocument();
unset($doc->base);

Since this is not a core hack, it will be upgrade-proof. However, if you use a template from a theme store, and choose to upgrade the template in the future, you may have to add the code back.

References:

Protocol Relative URLs not working

How to remove the "base href" tag Joomla 3


问:
Cordova's 3.1 navigator.device.capture.captureVideo always call error callback with error code 3
Part of my  www/js/index.html file :

```<code> receivedEvent: function(id) {
    var mkb = document.getElementById("make-video-button");

    mkb.addEventListener('click',function () {
        navigator.device.capture.captureVideo(app.captVidCall.success, app.captVidCall.error)
    } , false);

},
captVidCall : {
    success : function () {
        alert("success");
    },
    error   : function (error) {
        alert("Error code : " + error.code);
    }
}
</code>```

I added the media capture plugin by

```<code>cordova plugin add org.apache.cordova.media-capture

[ 'org.apache.cordova.camera',
'org.apache.cordova.file',
'org.apache.cordova.file-transfer',
'org.apache.cordova.media-capture' ]
</code>```

And cordova version is :

```<code> cordova --version
 3.1.0-0.1.0
</code>```

I read somewhere that this is the bug at the cordova's side... But I can't find this again. And I can't believe that stable version 3.1 could have such severe bug.

PS : Device I test on is Nexus 7 (2013) with Android 4.3

(Then it call an app.captVidCall.error with error.code == 3)

When running this one the Xperia Neo V With Android 4.0.4 the app crashes immediately after I capture video.

(To run the the app I use

```<code>cordova build
cordova run android
</code>```

)

Git repo with executable in videoAppCaptureFailure/platforms/android/bin
https://github.com/bluesm/videoAppCaptureFailure

答:
Its occur because if you click on start recording and do nothing, if you click on device back  button, so that  it will be generate the error.

During error code please compare error code and if it match with no-3 than make alert function for same.

Body:
Part of my  www/js/index.html file :

 receivedEvent: function(id) {
    var mkb = document.getElementById("make-video-button");

    mkb.addEventListener('click',function () {
        navigator.device.capture.captureVideo(app.captVidCall.success, app.captVidCall.error)
    } , false);

},
captVidCall : {
    success : function () {
        alert("success");
    },
    error   : function (error) {
        alert("Error code : " + error.code);
    }
}

I added the media capture plugin by

cordova plugin add org.apache.cordova.media-capture

[ 'org.apache.cordova.camera',
'org.apache.cordova.file',
'org.apache.cordova.file-transfer',
'org.apache.cordova.media-capture' ]

And cordova version is :

 cordova --version
 3.1.0-0.1.0

I read somewhere that this is the bug at the cordova's side... But I can't find this again. And I can't believe that stable version 3.1 could have such severe bug.

PS : Device I test on is Nexus 7 (2013) with Android 4.3

(Then it call an app.captVidCall.error with error.code == 3)

When running this one the Xperia Neo V With Android 4.0.4 the app crashes immediately after I capture video.

(To run the the app I use

cordova build
cordova run android

)

Git repo with executable in videoAppCaptureFailure/platforms/android/bin
https://github.com/bluesm/videoAppCaptureFailure


答:
It doesn't change anything. It just evaluates to an empty statement.

It's completely harmless. Just a bit of pointless clutter.

Title: semicolon after the for loop block


问:
Is it possible to define a function pointer to a constructor?
I'm using shared library with explicit linking (loading shared lib with dlopen) in order to implement plugin pattern in C++.

Is it possible to define a function pointer to a constructor of a class defined in the shared library or I would have to define factory method, within shared lib, that would instantiate (and initialize) object of a class from shared lib? Of course in my main app, then, I would define a function pointer to a factory method, and that method would return an instance of the class I need.

Cheers

答: You'd need to be aware of the name mangling problems when fetching pointers with dlsym(). It's not a good idea to rely on some specific mangling method, they're all too diverse. So the only reasonable thing to do is to expose your plugin interface as extern "C" { ... }, with factory function wrappers over constructors.</p>


问:
MS Access VBA Stored Procedure return value to text box
I'm having one of those moments and have forgot how to return a value from a SQL SP to a textbox?

I'm calling a SQL SP from MS Access 2013 using the below code and this returns the value to a listbox no problem - what property do I use to return the SP value to a text box?

Working Code:

```<code>With CurrentDb.QueryDefs("qMasterPass")
     .SQL = "exec SKULookup " & txtSKUSearch
     Set Me.List38.Recordset = .OpenRecordset
End With
</code>```

Non-working code - what should be where the ? are:

```<code>With CurrentDb.QueryDefs("qMasterPass")
     .SQL = "exec SKULookup " & txtSearch
     Set Me.Text7.?????? = .OpenRecordset
End With
</code>```

Thanks

答:
Assuming your recordset has 1 record with 1 column, you could do this:</p>

```<code>With CurrentDb.QueryDefs("qMasterPass")
     .SQL = "exec SKULookup " & txtSearch
     Me.Text7.Text = .OpenRecordset.Fields(0).Value
End With
</code>```

Body:
I'm having one of those moments and have forgot how to return a value from a SQL SP to a textbox?

I'm calling a SQL SP from MS Access 2013 using the below code and this returns the value to a listbox no problem - what property do I use to return the SP value to a text box?

Working Code:

With CurrentDb.QueryDefs("qMasterPass")
     .SQL = "exec SKULookup " & txtSKUSearch
     Set Me.List38.Recordset = .OpenRecordset
End With

Non-working code - what should be where the ? are:

With CurrentDb.QueryDefs("qMasterPass")
     .SQL = "exec SKULookup " & txtSearch
     Set Me.Text7.?????? = .OpenRecordset
End With

Thanks

Body:
Assuming your recordset has 1 record with 1 column, you could do this:

With CurrentDb.QueryDefs("qMasterPass")
     .SQL = "exec SKULookup " & txtSearch
     Me.Text7.Text = .OpenRecordset.Fields(0).Value
End With


问:
how to write case and group by in hive query
This is my hive table:

```<code>course   dept    subject   status

btech     cse     java     pass
btech     cse     hadoop   fail
btech     cse     cg       detained
btech     cse     cc       pass
btech      it     daa      pass
btech      it     wt       pass
btech      it     cnn      pass
mba        hr     hrlaw    pass
mba        hr     hrguid   absent
mtech      cs     java     pass
mtech      cs     cd       pass
mtech      cs     cp       detained
</code>```

I want to query this table to retrieve data in the following way:

```<code>course   dept    status

btech     cse     fail
btech      it     pass
mba        hr     absent
mtech      cs     fail
</code>```

First, it will check for "fail" or "detained" in the status of each dept and course grouped together. If it finds "fail" or "detained", it will output "fail" as the status. Else, if an "absent" is found in the same group, it will output "absent" as the status. Else, it will output "pass".

I got an error message when I ran the following query:

```<code>select course,dept,
case
when status in ( 'fail','detained') then 'fail'
when status in ( 'absent') then 'absent'
when status in ( 'pass') then 'pass'
else null
end as Final_Status
from college
group by course,dept;
</code>```

答:
If I understood correctly, you want something like:

```<code>select course,dept,
case
when status in ( 'fail','detained') then 'FAILED'
when status in ( 'absent') then 'absent'
when status in ( 'pass') then 'PASSED'
else null
end as Final_Status
from college
group by course,dept,
   CASE when status in ( 'fail','detained') then 'FAILED'
   when status in ( 'absent') then 'absent'
   when status in ( 'pass') then 'PASSED'
   else null END;
</code>```

I am using CASE in GROUP and it works fine with Hive.

Body:
This is my hive table:

course   dept    subject   status

btech     cse     java     pass
btech     cse     hadoop   fail
btech     cse     cg       detained
btech     cse     cc       pass
btech      it     daa      pass
btech      it     wt       pass
btech      it     cnn      pass
mba        hr     hrlaw    pass
mba        hr     hrguid   absent
mtech      cs     java     pass
mtech      cs     cd       pass
mtech      cs     cp       detained

I want to query this table to retrieve data in the following way:

course   dept    status

btech     cse     fail
btech      it     pass
mba        hr     absent
mtech      cs     fail

First, it will check for "fail" or "detained" in the status of each dept and course grouped together. If it finds "fail" or "detained", it will output "fail" as the status. Else, if an "absent" is found in the same group, it will output "absent" as the status. Else, it will output "pass".

I got an error message when I ran the following query:

select course,dept,
case
when status in ( 'fail','detained') then 'fail'
when status in ( 'absent') then 'absent'
when status in ( 'pass') then 'pass'
else null
end as Final_Status
from college
group by course,dept;

Body:
If I understood correctly, you want something like:

select course,dept,
case
when status in ( 'fail','detained') then 'FAILED'
when status in ( 'absent') then 'absent'
when status in ( 'pass') then 'PASSED'
else null
end as Final_Status
from college
group by course,dept,
   CASE when status in ( 'fail','detained') then 'FAILED'
   when status in ( 'absent') then 'absent'
   when status in ( 'pass') then 'PASSED'
   else null END;

I am using CASE in GROUP and it works fine with Hive.


问:
Enabling the microphone in a browser using node.js and capturing the information spoken
I have been struggling for a while and have been looking through many examples on how to enable the mic in a browser with Node.js. I have seen several Javascript examples but, I can't get the spoken content out of them and store it in variables. How can I enable the mic using Node.js? Will I need a specific npm package? I am currently working with the IBM Watson Speech to Text api. Any help is appreciated! Thanks in advance!</p>

答: Please be aware that streaming microphone will not work on any version of Safari. You will need to use FireFox, Chrome or IE to use streaming microphone into Watson Speech to Text. There's a YouTube tutorial on building a simple Bluemix App using Speech to Text here: (see Chapter 3) Youtube TutorialThe supporting code is in a public git repo here: Zero To Cognitive Repo</p>


问:
how to GET value into bootstrap modal
I have a table "on php page" that contain records from a database. At each row there is a button and when I click on the button, a modal bootstrap  should appear that contain details about members that you want to know.

This is the button code:

```<code>  <td> <?php echo '
         <a href="?id='.$tabel_id.'" class="btn btn-primary">details</a>'; ?> </td>
</code>```

and the modal bootstrap code:

```<code>    <?php
       $connect = mysqli_connect('127.0.0.1','root','','smart');
      $connect->set_charset("utf8");

      if(isset($_GET['id'])){
          $Mid = (int)$_GET['id'];
      $getid = "select * from members where id = '$Mid'";
      $runid = mysqli_query($connect, $getid);

      $row_id = mysqli_fetch_array($runid);

     $show_name = $row_id['name'];

     $show_number = $row_id['number'];

     ?>
    <div class="modal fade bd-example-modal-lg" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
       <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel"> اضافة فاتورة</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">×</span>
        </button>
      </div>
      <div class="modal-body">

              <div class="container">
                  <div class="row">
                  <form action="" method="post">

                      <label>الاسم</label>
                      <input type="textbox" name="" class="Mname" disabled value="<?php echo $show_name  ?>"></input>
                      <label>الرقم</label>
                      <input type="textbox" name="" class="Mname" disabled value="<?php echo $show_number;  ?>"></input>
                      <label>النوع</label>
                      <select name="dbType" id="dbType">
                      <option value="normal">عادي</option>
                      <option value="uargent">مستعجل</option>
                      </select>
                      <div id="otherType" style="display:none;">
                      <label for="specify">Specify</label>
                      <input type="text" name="specify" placeholder="Specify Databse Type"/>
                      </div>

                     </form>
                  </div>
                </div>

      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>
 <?php }else{echo'select an row please';} ?>
      <script>

$("#myModal").modal("show");</script>

    <script src="/our/js/jquery.min.js"></script>
    <script src="/our/js/bootstrap.min.js"></script>
    <script src="/our/js/run.js"></script>
</body>
</code>```

But when I click on the add button the modal doesn't appear but the url changes like this:

http://localhost/our/dashboard.php#myModal?id=2

Why doesn't the modal work?

答:
1. You have data-toggle='modal' but it doesn't know what modal it should open. Add this to your button.

```<code>data-target='#myModal'
</code>```

Source

2. This will also trigger the modal.

```<code>$("#myModal").modal("show");
</code>```

You can't use click function in a link that redirect you.

Make normal link with only href attr.

```<code><?php echo '<a href="?id=$tabel_id">Button</a>'; ?>
</code>```

url should be dashboard?id=1

html

```<code><?php if(isset($_GET["id"])) { ?>

    <div class="modal fade bd-example-modal-lg" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
        <!---Your same modal from your question--->
    </div>

<?php } ?>
</code>```

add this before your  closing body tag

```<code><script>$("#myModal").modal("show");</script>
</code>```

Title: how to GET value into bootstrap modal

Body:
I have a table "on php page" that contain records from a database. At each row there is a button and when I click on the button, a modal bootstrap  should appear that contain details about members that you want to know.

This is the button code:

   <?php echo '
         details'; ?>

and the modal bootstrap code:

    <?php
       $connect = mysqli_connect('127.0.0.1','root','','smart');
      $connect->set_charset("utf8");

      if(isset($_GET['id'])){
          $Mid = (int)$_GET['id'];
      $getid = "select * from members where id = '$Mid'";
      $runid = mysqli_query($connect, $getid);

      $row_id = mysqli_fetch_array($runid);

     $show_name = $row_id['name'];

     $show_number = $row_id['number'];

     ?>

 اضافة فاتورة

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

                  <form action="" method="post">

                      الاسم
                      <input type="textbox" name="" class="Mname" disabled value="<?php echo $show_name  ?>"></input>
                      الرقم
                      <input type="textbox" name="" class="Mname" disabled value="<?php echo $show_number;  ?>"></input>
                      النوع
                      <select name="dbType" id="dbType">
                      <option value="normal">عادي</option>
                      <option value="uargent">مستعجل</option>
                      </select>

                      Specify
                      <input type="text" name="specify" placeholder="Specify Databse Type"/>

                     </form>

        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>

 <?php }else{echo'select an row please';} ?>

But when I click on the add button the modal doesn't appear but the url changes like this:

http://localhost/our/dashboard.php#myModal?id=2

Why doesn't the modal work?

Body:
1. You have data-toggle='modal' but it doesn't know what modal it should open. Add this to your button.

data-target='#myModal'

Source

2. This will also trigger the modal.

$("#myModal").modal("show");

You can't use click function in a link that redirect you.

Make normal link with only href attr.

<?php echo '<a href="?id=$tabel_id">Button</a>'; ?>

url should be dashboard?id=1

html

<?php if(isset($_GET["id"])) { ?>

    <div class="modal fade bd-example-modal-lg" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
        <!---Your same modal from your question--->
    </div>

<?php } ?>

add this before your </body> closing body tag

<script>$("#myModal").modal("show");</script>


问:
Where is nodeValue for body.childNodes?
I runs this Javascript code and get nodeType and nodeName without problem for the body.childNode. However, nodeValue fail to display.</p>

```<code><!DOCTYPE html>
<html>
<body>

<p>Click the button to get the node types of the body element's child nodes.</p>
<button onclick="myFunction()">Try it</button>
<p><strong>Note:</strong> Whitespace inside elements is considered as text, and text is considered as nodes.</p>
<!-- My personal comment goes here..  -->
<div><strong>Note:</strong> Comments in the document are considered as comment nodes.</div>
<p id="demo"></p>

<script>
function myFunction() {
    var c = document.body.childNodes;
    var txt = "";
    var i;
    for (i = 0; i < c.length; i++) {
        txt = txt + "notdType: "+ c[i].nodeType + "    NodeName: "+c[i].nodeName+"    NodeValue: "+c[i].nodeValue +"<br>";
    }
    document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
</html>
</code>```

答: Element nodes don't have node values. Instead, they have child nodes of their own.</p>

Title: Where is nodeValue for body.childNodes?

Body:
I runs this Javascript code and get nodeType and nodeName without problem for the body.childNode. However, nodeValue fail to display.

<!DOCTYPE html>

Click the button to get the node types of the body element's child nodes.

<button onclick="myFunction()">Try it</button>

Note: Whitespace inside elements is considered as text, and text is considered as nodes.

Note: Comments in the document are considered as comment nodes.


问:
Checking values within a Base64 Encoded Image
Consider this Base64 encoded image string value:

```<code>data:application/pdf;base64,[encoded data, 12288 characters]
</code>```

This encoded string represents a 4 by 5 inch image with a string text in the middle "Image Title". Is there any way I can check this encoded Base64 string to validate that there is in fact a string with the value of "Image Title"?

The reason I need this is so I can unit test our Image Generation process to ensure that we are generating images properly.

答: You would need some form of OCR to process the detect "words" written within the image's pixels. There are a number of products and services which can accomplish this for you. With that said, I do not know if there are any free options available, outside of rolling your own OCR engine.</p>

Body:
Consider this Base64 encoded image string value:

data:application/pdf;base64,[encoded data, 12288 characters]

This encoded string represents a 4 by 5 inch image with a string text in the middle "Image Title". Is there any way I can check this encoded Base64 string to validate that there is in fact a string with the value of "Image Title"?

The reason I need this is so I can unit test our Image Generation process to ensure that we are generating images properly.


问:
Loop through a list, compare value to a threshold and copy and paste a corresponding value
I have a worksheet data with a list of companies and percentages corresponding to those companies. On worksheet Dashboard I have a threshold (say 20%)

I want to look through the percentages for each company and if the percentage is lower than the threshold (20%) then I want to copy that company into the next available row in column B on worksheet Dashboard.

The code I have so far is:

```<code>Sub companydraw()

Set wsDest = Sheets("Dashboard")
Set wsData = Sheets("Data")

wsDest.Columns("B").Rows(7 & ":" & wsDest.Rows.Count).ClearContents

lr = wsData.UsedRange.Rows.Count

Dim rRng As Range

Set rRng = wsData.Range("W5: W418")

For Each i In rRng

If i.Value > wsDest.Range("F2").Value Then

    wsData.Range("N5:N" & lr).Copy wsDest.Range("B" & Rows.Count).End(3)(2)

End If
Next i

End Sub
</code>```

My code posts all companies on one iteration, which is not correct as it is not taking into account all percentages of a all companies, it was then prompts me to save the spreadsheet which I don't understand.

if anyone can help it would be amazing

答:
Looking at your script you wish to check the value in column W from the data sheet against the value in F2 in the destination sheet and then copy the value from column N in the datasheet in the corresponding row to column B in the destination sheet in the next available row.

This should do it:

```<code>Sub companydraw()
Dim wsDest As Worksheet
Dim wsData As Worksheet
Dim i As Integer
Dim lastrow As Integer
Dim writerow As Integer

Set wsDest = Worksheets("Dashboard")
Set wsData = Worksheets("Data")

writerow = wsDest.Range("B65536").End(xlUp).Row + 1
lastrow = wsData.UsedRange.Rows.Count

For i = 2 To lastrow
    If wsData.Range("W" & i).value < wsDest.Range("F2").value Then 'F2 holds the threshold value
        wsDest.Range("B" & writerow).value = wsData.Range("N" & i).value
        writerow = writerow + 1
    End If
Next i

Set wsData = Nothing
Set wsDest = Nothing
End Sub
</code>```

Body:
I have a worksheet data with a list of companies and percentages corresponding to those companies. On worksheet Dashboard I have a threshold (say 20%)

I want to look through the percentages for each company and if the percentage is lower than the threshold (20%) then I want to copy that company into the next available row in column B on worksheet Dashboard.

The code I have so far is:

Sub companydraw()

Set wsDest = Sheets("Dashboard")
Set wsData = Sheets("Data")

wsDest.Columns("B").Rows(7 & ":" & wsDest.Rows.Count).ClearContents

lr = wsData.UsedRange.Rows.Count

Dim rRng As Range

Set rRng = wsData.Range("W5: W418")

For Each i In rRng

If i.Value > wsDest.Range("F2").Value Then

    wsData.Range("N5:N" & lr).Copy wsDest.Range("B" & Rows.Count).End(3)(2)

End If
Next i

End Sub

My code posts all companies on one iteration, which is not correct as it is not taking into account all percentages of a all companies, it was then prompts me to save the spreadsheet which I don't understand.

if anyone can help it would be amazing

Body:
Looking at your script you wish to check the value in column W from the data sheet against the value in F2 in the destination sheet and then copy the value from column N in the datasheet in the corresponding row to column B in the destination sheet in the next available row.

This should do it:

Sub companydraw()
Dim wsDest As Worksheet
Dim wsData As Worksheet
Dim i As Integer
Dim lastrow As Integer
Dim writerow As Integer

Set wsDest = Worksheets("Dashboard")
Set wsData = Worksheets("Data")

writerow = wsDest.Range("B65536").End(xlUp).Row + 1
lastrow = wsData.UsedRange.Rows.Count

For i = 2 To lastrow
    If wsData.Range("W" & i).value < wsDest.Range("F2").value Then 'F2 holds the threshold value
        wsDest.Range("B" & writerow).value = wsData.Range("N" & i).value
        writerow = writerow + 1
    End If
Next i

Set wsData = Nothing
Set wsDest = Nothing
End Sub


问:
Check which one of two buttons has been pressed and pass a value to sharedpreferences
I have an activity with two buttons. Both buttons bring you to the next activity and at the same time a value is being given to sharedpreferences. I want to access this value in my very last activity.

How do I check which of the two buttons has been pressed?

What is the problem in my code? I always get the same value in the end. So it seems like I always press the same button, which I don't.

Here the first activity where the two buttons are in:

public void imagebutton (){

        ImageButton btn = (ImageButton) findViewById(R.id.imageButton3);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(Akt1.this);
                SharedPreferences.Editor editor = preferences.edit();
                editor.putString("name2", "Geschlecht");

                editor.clear();
                editor.apply();
                startActivity(new Intent(Akt1.this, Akt2.class));
            }
        });
    }

               //buttonclick mit datapass gemixt

    private void imagebutton1 () {
        ImageButton btn = (ImageButton) findViewById(R.id.imageButton4);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                SharedPreferences preferences = getSharedPreferences("myprefs", MODE_PRIVATE);
                SharedPreferences.Editor editor = preferences.edit();
                editor.putString("name","Geschlecht");
                editor.commit();

                Intent intent = new Intent (Akt1.this,Akt2.class);
                startActivity(intent);```
</div>
</div>
</p>

<p>And here the code from the last activity where I want to access the value that has been passed to sharedpreferences from the buttonclick:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>public class Akt6 extends AppCompatActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //Hiermit Layout mit Activity verbinden
        setContentView(R.layout.activity_akt6);

        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        String name = preferences.getString("Name",null);
        name ="Männlich";

        SharedPreferences preferences2 = PreferenceManager.getDefaultSharedPreferences(this);
        String name2 = preferences.getString("Name", "default");
        name2 ="Weiblich";
        //zeige Wert on screen

        TextView textView19 = (TextView) findViewById(R.id.textView19);
        textView19.setText(name);</code>```

答:
I'm not sure what are you doing on your activity, but if you need to know wich button has been pressed you can do the follow:

To your button listeners add this:

```<code>public void imagebutton (){

    ...
    editor.putString("name2", "Geschlecht");
    editor.putString("ButtonPressed","Button1"); // This is the new line
    ...
}

...

public void imagebutton1 (){

    ...
    editor.putString("name2", "Geschlecht");
    editor.putString("ButtonPressed","Button2"); // This is the new line
    ...
}
</code>```

Then, to get the value of the button pressed in your activity do this:

```<code>...
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String button = preferences.getString("ButtonPressed","");
if(!button.isEmpty()){
    switch(button){
        case "Button":
            //You have pressed the first button
            break;
        case "Button2":
            //You have pressed the second button
            break;
    }
}
</code>```

You should use constants for every String passed as sharedpref name and value to avoid human mistakes on your code.
Good luck!

Body:
I have an activity with two buttons. Both buttons bring you to the next activity and at the same time a value is being given to sharedpreferences. I want to access this value in my very last activity.

How do I check which of the two buttons has been pressed?

What is the problem in my code? I always get the same value in the end. So it seems like I always press the same button, which I don't.

Here the first activity where the two buttons are in:

public void imagebutton (){

        ImageButton btn = (ImageButton) findViewById(R.id.imageButton3);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(Akt1.this);
                SharedPreferences.Editor editor = preferences.edit();
                editor.putString("name2", "Geschlecht");

                editor.clear();
                editor.apply();
                startActivity(new Intent(Akt1.this, Akt2.class));
            }
        });
    }

               //buttonclick mit datapass gemixt

    private void imagebutton1 () {
        ImageButton btn = (ImageButton) findViewById(R.id.imageButton4);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                SharedPreferences preferences = getSharedPreferences("myprefs", MODE_PRIVATE);
                SharedPreferences.Editor editor = preferences.edit();
                editor.putString("name","Geschlecht");
                editor.commit();

                Intent intent = new Intent (Akt1.this,Akt2.class);
                startActivity(intent);

And here the code from the last activity where I want to access the value that has been passed to sharedpreferences from the buttonclick:

public class Akt6 extends AppCompatActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //Hiermit Layout mit Activity verbinden
        setContentView(R.layout.activity_akt6);

        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        String name = preferences.getString("Name",null);
        name ="Männlich";

        SharedPreferences preferences2 = PreferenceManager.getDefaultSharedPreferences(this);
        String name2 = preferences.getString("Name", "default");
        name2 ="Weiblich";
        //zeige Wert on screen

        TextView textView19 = (TextView) findViewById(R.id.textView19);
        textView19.setText(name);

Body:
I'm not sure what are you doing on your activity, but if you need to know wich button has been pressed you can do the follow:

To your button listeners add this:

public void imagebutton (){

    ...
    editor.putString("name2", "Geschlecht");
    editor.putString("ButtonPressed","Button1"); // This is the new line
    ...
}

...

public void imagebutton1 (){

    ...
    editor.putString("name2", "Geschlecht");
    editor.putString("ButtonPressed","Button2"); // This is the new line
    ...
}

Then, to get the value of the button pressed in your activity do this:

...
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String button = preferences.getString("ButtonPressed","");
if(!button.isEmpty()){
    switch(button){
        case "Button":
            //You have pressed the first button
            break;
        case "Button2":
            //You have pressed the second button
            break;
    }
}

You should use constants for every String passed as sharedpref name and value to avoid human mistakes on your code.
Good luck!


问:
Excel formula to redistribute sets of items
Can something like this be done in Excel?

I have sets which each have a different number of items. For example:

Set A = A1, A2, A3, A4, A5

Set B = B1, B2

Set C = C1, C2, C3

I'd like to distribute the items between all the sets but I have two conditions on the resulting sets:

Each set must contain the same total items it started with.

Each set must contain none of the original items.

For example:

Set A = B1, B2, C1, C2, C3

Set B = A1, A2

Set C = A3, A4, A5

Each time I do this, I'd like the distribution to be different. The items don't have to be sequenced into each set. They could be distributed randomly as long as the two conditions above are met.

Edited to add an important factor I forgot initially:

Each time I do this, I have different numbers of items in each set which I cannot predict in advance. Each time, however, the number of sets remains the same.

Edited to add my working so far

I've attempted to have a list of all the items keyed to an index and use VLOOKUP to assign them to the equivalent key for the number of items each set can hold. I can't figure out how to tell Excel to skip any items that are from that set originally.

答:
For Set A the answer is easy, just list the contents of Sets B & C.

For Set B:
Place the candidate list in cells B1 through B8:

```<code>A1
A2
A3
A4
A5
C1
C2
C3
</code>```

In cells C1 through C8 enter:

```<code>=RAND()
</code>```

In cells A1 through A8 enter:

```<code>=INDEX(B$1:B$8,MATCH(LARGE(C$1:C$8,ROW()),C$1:C$8,0))
</code>```

As you see, column A is a randomization of the candidate list.  Since Set B must contain two items, just pick A1 and A2.

Use a similar technique for Set C.

Body:
For Set A the answer is easy, just list the contents of Sets B & C.

For Set B:
Place the candidate list in cells B1 through B8:

A1
A2
A3
A4
A5
C1
C2
C3

In cells C1 through C8 enter:

=RAND()

In cells A1 through A8 enter:

=INDEX(B$1:B$8,MATCH(LARGE(C$1:C$8,ROW()),C$1:C$8,0))

As you see, column A is a randomization of the candidate list.  Since Set B must contain two items, just pick A1 and A2.

Use a similar technique for Set C.


问:
ARM Template with DSC extension: Powershell file location from local destop
I would like to send the ARM template Project with related PS scripts for DSC to a third party. They would probably deploy option in VS to do the deployment. It is possible to attach the DSC script as part of the ARM project and on deploy picks up the dsc script from local disk? Under settings we have "ModulesUrl" it is possible to replace this with another parameter which points to local disk something like c:\myproject\IISInstall.ps1.zip</p>

```<code>{
  "apiVersion": "2015-06-15",
  "dependsOn": [
    "[concat('Microsoft.Compute/virtualMachines/', parameters('webSrvVmName'))]"
  ],
  "location": "[resourceGroup().location]",
  "name": "qawebsrv/iisinstall",
  "properties": {
    "publisher": "Microsoft.Powershell",
    "type": "DSC",
    "typeHandlerVersion": "2.19",
    "autoUpgradeMinorVersion": true,
    "settings": {
      "ModulesUrl": "https://dscscript.blob.core.windows.net/dscscripts/IISInstall.ps1.zip",
      "ConfigurationFunction": "[variables('configurationFunction')]",
      "Properties": {},
      "SasToken": "",
      "wmfVersion": "4.0"
    },
    "protectedSettings": {}
  },
  "tags": {
    "displayName": "VM Extensions"
  },
  "type": "Microsoft.Compute/virtualMachines/extensions"
}
</code>```

答:
If you're planning to use VS to do the deployment, then VS can stage the DSC package for you - the deployment script in VS does this... it can actually build the DSC package as well, but that has some limitations.

There's nothing magic about the VS script - this repo has a DSC sample that uses the same script used by VS - see: https://github.com/bmoore-msft/AzureRM-Samples/tree/master/VMDSCInstallFile

for a "Hello World" example...

Body:
I would like to send the ARM template Project with related PS scripts for DSC to a third party. They would probably deploy option in VS to do the deployment. It is possible to attach the DSC script as part of the ARM project and on deploy picks up the dsc script from local disk? Under settings we have "ModulesUrl" it is possible to replace this with another parameter which points to local disk something like c:\myproject\IISInstall.ps1.zip

{
  "apiVersion": "2015-06-15",
  "dependsOn": [
    "[concat('Microsoft.Compute/virtualMachines/', parameters('webSrvVmName'))]"
  ],
  "location": "[resourceGroup().location]",
  "name": "qawebsrv/iisinstall",
  "properties": {
    "publisher": "Microsoft.Powershell",
    "type": "DSC",
    "typeHandlerVersion": "2.19",
    "autoUpgradeMinorVersion": true,
    "settings": {
      "ModulesUrl": "https://dscscript.blob.core.windows.net/dscscripts/IISInstall.ps1.zip",
      "ConfigurationFunction": "[variables('configurationFunction')]",
      "Properties": {},
      "SasToken": "",
      "wmfVersion": "4.0"
    },
    "protectedSettings": {}
  },
  "tags": {
    "displayName": "VM Extensions"
  },
  "type": "Microsoft.Compute/virtualMachines/extensions"
}


问:
How do I import the linkedin sdk inside my app?
I downloaded and extracted the zip sdk from linkedin's site and copied linkedin-sdk into my project's lib folder.  Then in settings.gradle I added:

```<code>include ':libs:linkedin-sdk'
</code>```

Per How to add linkedin-sdk to a new android studio project? adding

```<code>compile fileTree(':libs:linkedin-sdk')
</code>```

should do the trick.  But when I expand the linkedin-sdk folder I just see linkedin-sdk.iml

答:
After downloading the linkedin sdk, you should import it into Android studio as a new module

You can do this by going to File -> New -> Import Module

Then select the linkedin-sdk directory. After importing, Android studio may ask you to install certain dependencies, just follow through.

Then add compile project(':linkedin-sdk') to your app/build.gradle file under dependencies

Hope this helps, tried the other ways too, it didnt work for me. This did.

Body:
I downloaded and extracted the zip sdk from linkedin's site and copied linkedin-sdk into my project's lib folder.  Then in settings.gradle I added:

include ':libs:linkedin-sdk'

Per How to add linkedin-sdk to a new android studio project? adding

compile fileTree(':libs:linkedin-sdk')

should do the trick.  But when I expand the linkedin-sdk folder I just see linkedin-sdk.iml