问:
Matching attribute values using wildcards with JQuery
I have a selector like this:

```<code>$('link[href="../../../target/test/css/index.css"]')
</code>```

The portion after ../target/ can be anything.  How do I specify wildcards in jquery?  This is approximately what I'm looking for in terms of a globbing pattern:

```<code>$('link[href="../../../target/**/*.css"]')
</code>```

答:
There aren't wildcards per se, but you can combine the starts with (^=) and ends with ($=) selectors to achieve the effect you are looking for:

```<code>$('link[href^="../../../target/"][href$=".css"]');
</code>```

jQuery is equipped with a number of useful attribute selectors that can help for problems like this-- you can check them out at https://api.jquery.com/category/selectors/attribute-selectors/.

Body:
I have a selector like this:

$('link[href="../../../target/test/css/index.css"]')

The portion after ../target/ can be anything.  How do I specify wildcards in jquery?  This is approximately what I'm looking for in terms of a globbing pattern:

$('link[href="../../../target/**/*.css"]')

Body:
There aren't wildcards per se, but you can combine the starts with (^=) and ends with ($=) selectors to achieve the effect you are looking for:

$('link[href^="../../../target/"][href$=".css"]');

jQuery is equipped with a number of useful attribute selectors that can help for problems like this-- you can check them out at https://api.jquery.com/category/selectors/attribute-selectors/.


来源: stackexchange

问:
Array does not connect with the tableView(numberOfRowsInSection) method
I have an array which I will store all data that I get from http request and display them on tableView but it seems that tableView(numberOfRowsInSection) does not recognize the change in the array because the count remains as 0.

```<code>class OrdersViewController: UIViewController {
    @IBOutlet weak var tableView: UITableView!

    var arr = [[String: AnyObject]]()
    var selectedIndex = -1

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        let baseUrl = "my url"
        let consumer_key = "consumer_key"
        let consumer_secret = "consumer_key"
        let url = "\(baseUrl)?consumer_key=\(consumer_key)&consumer_secret=\(consumer_secret)&status=processing"

        let headers2 = ["Accept": "application/json"]
        Alamofire.request(url, headers: headers2)
            .responseJSON { response in
                    self.arr.append(data from request)
                }
        }

        let url2 = "\(baseUrl)?consumer_key=\(consumer_key)&consumer_secret=\(consumer_secret)&status=pending"
        Alamofire.request(url2, headers: headers2)
            .responseJSON { response in
                    self.arr.append(data from request)
                    print("arr", self.arr)
                }
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        print("after request", self.arr)
        return self.arr.count
    }
}
// and some other code...
</code>```

I do get data from the http request successfully and it gets updated in my Alamofire call but "after request" keeps printing empty array. What's going on here?

答:
use this code inside the Viewdidload

```<code>dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
 }
</code>```

instead of

```<code>tableView.reloadData()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have an array which I will store all data that I get from http request and display them on tableView but it seems that tableView(numberOfRowsInSection) does not recognize the change in the array because the count remains as 0.

class OrdersViewController: UIViewController {
    @IBOutlet weak var tableView: UITableView!

    var arr = [[String: AnyObject]]()
    var selectedIndex = -1

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        let baseUrl = "my url"
        let consumer_key = "consumer_key"
        let consumer_secret = "consumer_key"
        let url = "\(baseUrl)?consumer_key=\(consumer_key)&consumer_secret=\(consumer_secret)&status=processing"

        let headers2 = ["Accept": "application/json"]
        Alamofire.request(url, headers: headers2)
            .responseJSON { response in
                    self.arr.append(data from request)
                }
        }

        let url2 = "\(baseUrl)?consumer_key=\(consumer_key)&consumer_secret=\(consumer_secret)&status=pending"
        Alamofire.request(url2, headers: headers2)
            .responseJSON { response in
                    self.arr.append(data from request)
                    print("arr", self.arr)
                }
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        print("after request", self.arr)
        return self.arr.count
    }
}
// and some other code...

I do get data from the http request successfully and it gets updated in my Alamofire call but "after request" keeps printing empty array. What's going on here?

Body:
use this code inside the Viewdidload

dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
 }

instead of

tableView.reloadData()

ContentLicense: CC BY-SA 3.0


问:
Choose random data from an Array in Swift
I would like to create a new Array of 3 random values pulled from this list to be used in two other view controllers.  Not sure how to assign the Array so those values are accessible.

```<code>class WorkoutDataSource {
var allWorkouts:[Workout]

init() {
    allWorkouts = []
    let bh1 = Workout(title: "Figure 8s - Clockwise", workoutText: "Clockwise around each leg.", color:  UIColor.flatNavyBlueColorDark())
    allWorkouts.append(bh1)
    let bh2 = Workout(title: "Figure 8s - Counter Clockwise", workoutText: "Counter Clockwise around each leg.", color:  UIColor.flatNavyBlue())
    allWorkouts.append(bh2)
    let bh3 = Workout(title: "Dribble Left Handed", workoutText: "Low and Powerfull.", color:  UIColor.flatTealColorDark())
    allWorkouts.append(bh3)
    let bh4 = Workout(title: "Dribble Right Handed", workoutText: "Low and powerfull", color:  UIColor.flatTeal())
    allWorkouts.append(bh4)
    let bh5 = Workout(title: "Around Both Feet", workoutText: "With feet together, circles around ankles-waist-head, work up & down, the full length of body.", color:  UIColor.flatSkyBlueColorDark())
    allWorkouts.append(bh5)
    let bh6 = Workout(title: "Spider Dribble", workoutText: "feet apart, 1 dribble with each hand in front, then 1 dribble with each hand in back. ", color:  UIColor.flatSkyBlue())
    allWorkouts.append(bh6)
    let bh7 = Workout(title: "Helicopter", workoutText: "1 hand in front, 1 hand in back – move your hands from front to back while catching the ball between your legs.", color:  UIColor.flatGreenColorDark())
    allWorkouts.append(bh7)
    let bh8 = Workout(title: "Scissors - Legs Not Moving", workoutText: "One leg forward and one leg back. Dribble between your legs low and fast.", color:  UIColor.flatGreen())
    allWorkouts.append(bh8)
    let bh9 = Workout(title: "Behind the Back", workoutText: ".",color:  UIColor.flatGray())
    allWorkouts.append(bh9)
    let bh10 = Workout(title: "Fingertip Squeeze", workoutText: ".",color:  UIColor.flatPink())
    allWorkouts.append(bh10)
}

func getWorkOuts() -> [Workout]{

return allWorkouts
}

}
</code>```

Thank you

答:
If you simply want to get a random value from the allWorkouts array, then you can do something like this:

```<code>let ndx = Int(arc4random_uniform(UInt32(allWorkouts.count)))
let workout = allWorkouts[ndx]
</code>```

If you want to get three workouts at random, and you don't care if they are unique or not, then you can do something like this:

```<code>var workouts = [Workout]()
for i in 0 ..< 3 {
    let ndx = Int(arc4random_uniform(UInt32(allWorkouts.count)))
    let workout = allWorkouts[ndx]
    workouts.append(workout)
}
</code>```

The workouts array will have the three workouts at that point.

If you want the random items to be unique, then you should use a Set instead of an array and ensure that you run till you get three items, like this:

```<code>var workouts = Set<Workout>()
while workouts.count < 3 {
    let ndx = Int(arc4random_uniform(UInt32(allWorkouts.count)))
    let workout = allWorkouts[ndx]
    workouts.insert(workout)
}
</code>```

Body:
I would like to create a new Array of 3 random values pulled from this list to be used in two other view controllers.  Not sure how to assign the Array so those values are accessible.

class WorkoutDataSource {
var allWorkouts:[Workout]

init() {
    allWorkouts = []
    let bh1 = Workout(title: "Figure 8s - Clockwise", workoutText: "Clockwise around each leg.", color:  UIColor.flatNavyBlueColorDark())
    allWorkouts.append(bh1)
    let bh2 = Workout(title: "Figure 8s - Counter Clockwise", workoutText: "Counter Clockwise around each leg.", color:  UIColor.flatNavyBlue())
    allWorkouts.append(bh2)
    let bh3 = Workout(title: "Dribble Left Handed", workoutText: "Low and Powerfull.", color:  UIColor.flatTealColorDark())
    allWorkouts.append(bh3)
    let bh4 = Workout(title: "Dribble Right Handed", workoutText: "Low and powerfull", color:  UIColor.flatTeal())
    allWorkouts.append(bh4)
    let bh5 = Workout(title: "Around Both Feet", workoutText: "With feet together, circles around ankles-waist-head, work up & down, the full length of body.", color:  UIColor.flatSkyBlueColorDark())
    allWorkouts.append(bh5)
    let bh6 = Workout(title: "Spider Dribble", workoutText: "feet apart, 1 dribble with each hand in front, then 1 dribble with each hand in back. ", color:  UIColor.flatSkyBlue())
    allWorkouts.append(bh6)
    let bh7 = Workout(title: "Helicopter", workoutText: "1 hand in front, 1 hand in back – move your hands from front to back while catching the ball between your legs.", color:  UIColor.flatGreenColorDark())
    allWorkouts.append(bh7)
    let bh8 = Workout(title: "Scissors - Legs Not Moving", workoutText: "One leg forward and one leg back. Dribble between your legs low and fast.", color:  UIColor.flatGreen())
    allWorkouts.append(bh8)
    let bh9 = Workout(title: "Behind the Back", workoutText: ".",color:  UIColor.flatGray())
    allWorkouts.append(bh9)
    let bh10 = Workout(title: "Fingertip Squeeze", workoutText: ".",color:  UIColor.flatPink())
    allWorkouts.append(bh10)
}

func getWorkOuts() -> [Workout]{

return allWorkouts
}

}

Thank you

Body:
If you simply want to get a random value from the allWorkouts array, then you can do something like this:

let ndx = Int(arc4random_uniform(UInt32(allWorkouts.count)))
let workout = allWorkouts[ndx]

If you want to get three workouts at random, and you don't care if they are unique or not, then you can do something like this:

var workouts = [Workout]()
for i in 0 ..< 3 {
    let ndx = Int(arc4random_uniform(UInt32(allWorkouts.count)))
    let workout = allWorkouts[ndx]
    workouts.append(workout)
}

The workouts array will have the three workouts at that point.

If you want the random items to be unique, then you should use a Set instead of an array and ensure that you run till you get three items, like this:

var workouts = Set<Workout>()
while workouts.count < 3 {
    let ndx = Int(arc4random_uniform(UInt32(allWorkouts.count)))
    let workout = allWorkouts[ndx]
    workouts.insert(workout)
}


问:
How to use proxies to download files
I'm downloading a website with heaps of GPL-licensed free content, however my computer exceeds the daily download limit of 20 files (out of some 10,000!)

Is there a proxy service I can use (via PHP) to continue accessing such content?

答:
You shouldn't be trying to bypass that limit. It's there to stop people like you from overloading their connection by trying to download everything.

If you really need to download the entire site, and the content is really free, maybe it's mirrored on another site where you can get at it more easily.

Edit: Or you could email the site administrator and ask nicely. Maybe he can give it to you in a convenient format or disable the limit for you.

ContentLicense: CC BY-SA 2.5

Title: How to use proxies to download files


问:
Cant find CSS & JS files with excluded templates JAVA + Spring
i am using spring for my project and i excluded all template-files to another "html-Project". I did it because i can do changes without any redeployment and for me its ways clearer. it works fine and the spring application find all templates. But now, the template cant find any css or js files. The template try to search the files in my spring-project but they are included in the html project. How i can fix it? I need something like a relative path i think.

Projects

SpringApp

---- lib

---- src

-------- main

------------ java

---------------- com.example.test

-------------------- controller

------------------------ ShowIndex.java

------------ resources

------------ webapp

-------- test

HTML-Templates

---- lib

---- src

-------- main

------------ java

------------ resources

------------ templates

---------------- css

-------------------- bootstrap.min.css

---------------- js

-------------------- bootstrap.min.js

---------------- images

---------------- index.ftl

---------------- test.ftl

-------- test

Content of ShowIndex.java

```<code>@RequestMapping(value = "/index", method = RequestMethod.GET)
public String index(ModelMap model) {
    model.put("prename", "Hans-Peter");

    return "index";
}
</code>```

HeaderContent of index.ftl

```<code><!-- Bootstrap core CSS -->
<link rel="stylesheet" href="./css/bootstrap.min.css">
<link rel="stylesheet" href="./css/zeus.css">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</code>```

Any ideas?

I use:

JAVA

Spring WebMVC

Freemarker as TemplateEngine

答:
Put your css, js, images to the src/main/webapps folder, separate from the templates ftl files.

EDIT

With Servlet 3.0 you have another choice, but maybe not work in all containers...

create a META-INF/resources folder

put all you resources js, css, images and etc to this folder

and 'jar' it.

for example I created a assembly.xml file for automate this work

```<code><assembly>
    <id>bin</id>
    <formats>
        <format>jar</format>
    </formats>
    <includeBaseDirectory>false</includeBaseDirectory>
    <dependencySets>
        <dependencySet>
            <useProjectArtifact>false</useProjectArtifact>
            <outputDirectory>/</outputDirectory>
            <excludes>
                <exclude>**</exclude>
            </excludes>
        </dependencySet>
    </dependencySets>
    <fileSets>
        <fileSet>
            <directory>target/classes</directory>
            <outputDirectory>/</outputDirectory>
            <includes>
                <include>**/*.class</include>
            </includes>
            <excludes>
                <exclude>**/DefaultController.class</exclude>
            </excludes>
        </fileSet>
        <fileSet>
            <directory>WebContent</directory>
            <outputDirectory>META-INF/resources</outputDirectory>
            <includes>
                <include>/WEB-INF/jsp/**</include>
            </includes>
        </fileSet>

        <fileSet>
            <directory>WebContent</directory>
            <outputDirectory>META-INF/resources</outputDirectory>
            <includes>
                <include>js/**</include>
                <include>plugins/**</include>
            </includes>
        </fileSet>
    </fileSets>
</assembly>
</code>```

This file works when use maven building mvn package.

PS:

In maven pom.xml:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    ...

    <build>
        ...

        <plugins>
            ...

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <descriptors>
                        <descriptor>assembly.xml</descriptor>
                    </descriptors>
                </configuration>
                <executions>
                    <execution>
                        <id>make-assembly</id>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

        </plugins>
    </build>
    ...

</project>
</code>```

Body:
i am using spring for my project and i excluded all template-files to another "html-Project". I did it because i can do changes without any redeployment and for me its ways clearer. it works fine and the spring application find all templates. But now, the template cant find any css or js files. The template try to search the files in my spring-project but they are included in the html project. How i can fix it? I need something like a relative path i think.

Projects

SpringApp

---- lib

---- src

-------- main

------------ java

---------------- com.example.test

-------------------- controller

------------------------ ShowIndex.java

------------ resources

------------ webapp

-------- test

HTML-Templates

---- lib

---- src

-------- main

------------ java

------------ resources

------------ templates

---------------- css

-------------------- bootstrap.min.css

---------------- js

-------------------- bootstrap.min.js

---------------- images

---------------- index.ftl

---------------- test.ftl

-------- test

Content of ShowIndex.java

@RequestMapping(value = "/index", method = RequestMethod.GET)
public String index(ModelMap model) {
    model.put("prename", "Hans-Peter");

    return "index";
}

HeaderContent of index.ftl

<link rel="stylesheet" href="./css/bootstrap.min.css">
<link rel="stylesheet" href="./css/zeus.css">

Any ideas?

I use:

JAVA

Spring WebMVC

Freemarker as TemplateEngine

Body:
Put your css, js, images to the src/main/webapps folder, separate from the templates ftl files.

EDIT

With Servlet 3.0 you have another choice, but maybe not work in all containers...

create a META-INF/resources folder

put all you resources js, css, images and etc to this folder

and 'jar' it.

for example I created a assembly.xml file for automate this work

<assembly>
    <id>bin</id>
    <formats>
        <format>jar</format>
    </formats>
    <includeBaseDirectory>false</includeBaseDirectory>
    <dependencySets>
        <dependencySet>
            <useProjectArtifact>false</useProjectArtifact>
            <outputDirectory>/</outputDirectory>
            <excludes>
                <exclude>**</exclude>
            </excludes>
        </dependencySet>
    </dependencySets>
    <fileSets>
        <fileSet>
            <directory>target/classes</directory>
            <outputDirectory>/</outputDirectory>
            <includes>
                <include>**/*.class</include>
            </includes>
            <excludes>
                <exclude>**/DefaultController.class</exclude>
            </excludes>
        </fileSet>
        <fileSet>
            <directory>WebContent</directory>
            <outputDirectory>META-INF/resources</outputDirectory>
            <includes>
                <include>/WEB-INF/jsp/**</include>
            </includes>
        </fileSet>

        <fileSet>
            <directory>WebContent</directory>
            <outputDirectory>META-INF/resources</outputDirectory>
            <includes>
                <include>js/**</include>
                <include>plugins/**</include>
            </includes>
        </fileSet>
    </fileSets>
</assembly>

This file works when use maven building mvn package.

PS:

In maven pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    ...

    <build>
        ...

        <plugins>
            ...

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <descriptors>
                        <descriptor>assembly.xml</descriptor>
                    </descriptors>
                </configuration>
                <executions>
                    <execution>
                        <id>make-assembly</id>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

        </plugins>
    </build>
    ...

</project>


问:
Retrieving a element with multiple xpaths
This isn't much of a coding question but one about what options should I take next. I've just started using selenium about a week ago and started to get the hang of most of its function.

I was working on a work project to login into various websites until I ran into a issue where I was getting this error when I tried to find the password field

Exception in thread "main" org.openqa.selenium.ElementNotVisibleException: element not visible

I went ahead and double checked the name & id  but I couldn't find the field using locators like .id, name, and xpath. I inspected the xpath with Firebug and noticed that it returned two results instead of one.

Current Xpath looks like this

```<code>.//*[@id='password']
</code>```

I was wondering if anyone could point me to the right direct when  dealing with something like this.

答:
Normally, id attribute suppose to be unique value, but there are some cases when front-end developer just hide part of DOM, create similar and forget to remove hidden one.

In such case you can (if it possible) ask developer to get rid of redundant code or use index as

```<code>"(.//*[@id='password'])[2]"
</code>```

Body:
This isn't much of a coding question but one about what options should I take next. I've just started using selenium about a week ago and started to get the hang of most of its function.

I was working on a work project to login into various websites until I ran into a issue where I was getting this error when I tried to find the password field

Exception in thread "main" org.openqa.selenium.ElementNotVisibleException: element not visible

I went ahead and double checked the name & id  but I couldn't find the field using locators like .id, name, and xpath. I inspected the xpath with Firebug and noticed that it returned two results instead of one.

Current Xpath looks like this

.//*[@id='password']

I was wondering if anyone could point me to the right direct when  dealing with something like this.

Body:
Normally, id attribute suppose to be unique value, but there are some cases when front-end developer just hide part of DOM, create similar and forget to remove hidden one.

In such case you can (if it possible) ask developer to get rid of redundant code or use index as

"(.//*[@id='password'])[2]"


问:
after crypt password,validation not function well
now i using this code to crypt my password on database,it function when login or validation.
But it only valid the first 7 character.
let say my password is miow12345, but i can just type in miow123 or miow12312q... to login

```<code>$pas = crypt($_POST["pas"], "MiO1!");
</code>```

validation.php

```<code>    if(isset($_POST['username']))
{
$username = $_POST['username'];
}
if (isset($_POST['password']))
{
$password=crypt($_POST["password"], "MiO1!");
}

$q = 'SELECT * FROM users WHERE username=:username AND password=:password';

$query = $dbh->prepare($q);

$query->execute(array(':username' => $username, ':password' => $password));

if($query->rowCount() == 0)
{
header('Location: login.php?err=1');
}
</code>```

another method(same problem)

```<code>if( crypt($_POST["pas"], "TmP2!") != $row["password"])
</code>```

答:
The thing is your code here is wrong $password=crypt($_POST["password"], "MiO1!"); it will return a different set of string. the proper thing to use is the has_equals function. here is a sample provided by php documentation.

```<code>if (hash_equals($hashed_password, crypt($user_input, $hashed_password))) {
//your query here;}
</code>```

Body:
now i using this code to crypt my password on database,it function when login or validation.
But it only valid the first 7 character.
let say my password is miow12345, but i can just type in miow123 or miow12312q... to login

$pas = crypt($_POST["pas"], "MiO1!");

validation.php

    if(isset($_POST['username']))
{
$username = $_POST['username'];
}
if (isset($_POST['password']))
{
$password=crypt($_POST["password"], "MiO1!");
}

$q = 'SELECT * FROM users WHERE username=:username AND password=:password';

$query = $dbh->prepare($q);

$query->execute(array(':username' => $username, ':password' => $password));

if($query->rowCount() == 0)
{
header('Location: login.php?err=1');
}

another method(same problem)

if( crypt($_POST["pas"], "TmP2!") != $row["password"])

Body:
The thing is your code here is wrong $password=crypt($_POST["password"], "MiO1!"); it will return a different set of string. the proper thing to use is the has_equals function. here is a sample provided by php documentation.

if (hash_equals($hashed_password, crypt($user_input, $hashed_password))) {
//your query here;}


问:
How to convert a dict inside a list to a DataFrame in python?
Python beginner here. I am struggling to dump my list of dicts into a pandas.DataFrame the right away. My data has the following structure.

```<code>a = {'Scores': {'s1': [{'Math': '95',
'Science': '74.5',
'English': '60.5'},
{'Math': '87.9',
'Science': '97.3',
'English': '78.3'}],
's2': [{'Math': '67.2',
'Science': '74.2',
'English': '89'}]}}
</code>```

My pandas.Dataframe columns should be the subjects 'Math', 'Science' and 'English' and the rows should be the scores. The columns are dynamically created so I can not explicitly mention the column names to call it. All I need are the values of keys S1.... Sn.

This what I have tried so far:

```<code>b = a.pop('Scores')
c = list(b.values())
df = pd.DataFrame(c)
</code>```

This displays my dataframe as:

```<code>                                               0  \
0  {'Math': '95', 'Science': '74.5', 'English': '...
1  {'Math': '67.2', 'Science': '74.2', 'English':...

                                               1
0  {'Math': '87.9', 'Science': '97.3', 'English':...
1                                               None
</code>```

Instead, I am looking for:

```<code>Math  Science  English
95    74.5     60.5
87.9  97.3     78.3
67.2  74.2     89
</code>```

I would appreciate any help I can get.

答:
You've got to apply yourself

```<code>pd.Series(a['Scores']).apply(pd.Series).stack().apply(pd.Series)

     English  Math Science
s1 0    60.5    95    74.5
   1    78.3  87.9    97.3
s2 0      89  67.2    74.2
</code>```

Body:
Python beginner here. I am struggling to dump my list of dicts into a pandas.DataFrame the right away. My data has the following structure.

a = {'Scores': {'s1': [{'Math': '95',
'Science': '74.5',
'English': '60.5'},
{'Math': '87.9',
'Science': '97.3',
'English': '78.3'}],
's2': [{'Math': '67.2',
'Science': '74.2',
'English': '89'}]}}

My pandas.Dataframe columns should be the subjects 'Math', 'Science' and 'English' and the rows should be the scores. The columns are dynamically created so I can not explicitly mention the column names to call it. All I need are the values of keys S1.... Sn.

This what I have tried so far:

b = a.pop('Scores')
c = list(b.values())
df = pd.DataFrame(c)

This displays my dataframe as:

                                               0  \
0  {'Math': '95', 'Science': '74.5', 'English': '...
1  {'Math': '67.2', 'Science': '74.2', 'English':...

                                               1
0  {'Math': '87.9', 'Science': '97.3', 'English':...
1                                               None

Instead, I am looking for:

Math  Science  English
95    74.5     60.5
87.9  97.3     78.3
67.2  74.2     89

I would appreciate any help I can get.

Body:
You've got to apply yourself

pd.Series(a['Scores']).apply(pd.Series).stack().apply(pd.Series)

     English  Math Science
s1 0    60.5    95    74.5
   1    78.3  87.9    97.3
s2 0      89  67.2    74.2


问:
How to remove character from last array element
I need to remove the last element comma in Javascript array

```<code>var arr =  ["AAA,","BBB,"];
</code>```

I need the result below

```<code>var arr =  ["AAA,","BBB"];
</code>```

Any help is appreciated...

答:
This answer explains how you can do it using regex:</p>

```<code>>> var str = "BBB,"
>> str = str.replace(/,[^,]*$/ , "")
>> str
>> "BBB"
</code>```

Body:
I need to remove the last element comma in Javascript array

var arr =  ["AAA,","BBB,"];

I need the result below

var arr =  ["AAA,","BBB"];

Any help is appreciated...

Body:
This answer explains how you can do it using regex:

>> var str = "BBB,"
>> str = str.replace(/,[^,]*$/ , "")
>> str
>> "BBB"


问:
React JS Rest Api Call
We have made a simple application that supports CRUD operations on a student model(Get Student by ID, Delete Student by ID etc). Can someone help with how to make a simple restful api call to the endpoint(http://ip:port/allstudents) and render the obtained json format in React UI?
My code is as follows:

```<code>import React, { Component } from 'react';
import './App.css';
class App extends Component {
Getfunction() {
<a href="http://www.stackoverflow.com/">
<button>b1</button>
</a>
}
render() {
return (
<div>
  <button id='b1'
    style={{fontSize: 20, color: 'green'}}
    onClick={() => this.Getfunction()}>
    Get!
  </button>
);
}
}

export default App;
</code>```

Where can I put my restful api call to query and how exactly?

答:
I would suggest you to make api call in life cycle method componentDidMount and when api call returns some data set it to your state and let your user interface update accordingly.

E.g your api call method may be like this -

```<code>ApiCall() {
    return $.ajax({
       url: 'http://ip:port/allstudents',
       type: 'GET',
    }).fail((responseData) => {
        if (responseData.responseCode) {
            console.error(responseData.responseCode);
        }
    });
}
</code>```

After new data is fetched from server set the state with new data

```<code>this.setState({data:newDataFromServer});
</code>```

Basically above call will return you a jquery promise which you can use later.

Now in what ever method you want to make ApiCall just use like this -

```<code>class App extends Component {

 constructor() {
   this.state = {
      data : []
   }
 }
 componentDidMount()
 {
   this.getFunction();
 }

 getFunction = () => {
     this.ApiCall()
        .then(
            function(data){
              console.log(data);
              // set the state here
              this.setState({data:data});
            },
            function(error){
              console.log(error);
           }
    );
 }

 render() {
   return (
      <div>
        <button id='b1'
           style={{fontSize: 20, color: 'green'}}
           onClick={() => this.Getfunction()}>
        Get!
     </button>
     {/* Now render your data here using jsx if it is array iterate over it */}
    </div>
   );
 }
}
</code>```

Title: React JS Rest Api Call

Body:
We have made a simple application that supports CRUD operations on a student model(Get Student by ID, Delete Student by ID etc). Can someone help with how to make a simple restful api call to the endpoint(http://ip:port/allstudents) and render the obtained json format in React UI?
My code is as follows:

import React, { Component } from 'react';
import './App.css';
class App extends Component {
Getfunction() {

<button>b1</button>

}
render() {
return (

  <button id='b1'
    style={{fontSize: 20, color: 'green'}}
    onClick={() => this.Getfunction()}>
    Get!
  </button>
);
}
}

export default App;

Where can I put my restful api call to query and how exactly?

Body:
I would suggest you to make api call in life cycle method componentDidMount and when api call returns some data set it to your state and let your user interface update accordingly.

E.g your api call method may be like this -

ApiCall() {
    return $.ajax({
       url: 'http://ip:port/allstudents',
       type: 'GET',
    }).fail((responseData) => {
        if (responseData.responseCode) {
            console.error(responseData.responseCode);
        }
    });
}

After new data is fetched from server set the state with new data

this.setState({data:newDataFromServer});

Basically above call will return you a jquery promise which you can use later.

Now in what ever method you want to make ApiCall just use like this -

class App extends Component {

 constructor() {
   this.state = {
      data : []
   }
 }
 componentDidMount()
 {
   this.getFunction();
 }

 getFunction = () => {
     this.ApiCall()
        .then(
            function(data){
              console.log(data);
              // set the state here
              this.setState({data:data});
            },
            function(error){
              console.log(error);
           }
    );
 }

 render() {
   return (
      <div>
        <button id='b1'
           style={{fontSize: 20, color: 'green'}}
           onClick={() => this.Getfunction()}>
        Get!
     </button>
     {/* Now render your data here using jsx if it is array iterate over it */}
    </div>
   );
 }
}


问:
Whitelisting inline script with csp sha-256 in firefox
I can not get whitelisting by checksum to work in firefox (52.0.2, windows). Firefox supports content security policy version 2 according to caniuse, so checksumming should be supported.

When chrome blocks an inline script, it prints the needed sha-256 to console.
Adding it to the csp rules successfully whitelists the script.
The checksum is also identical to the one calculated at
https://report-uri.io/home/hash

But firefox refuse to accept it.

I noted that the example in the MDN docs is using base-16 as opposed to base-64 encoding for the checksum.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src

But even with the MDN example I get the same results. (Also chrome rejects with the base-16 encoding). I tried a bunch of variations on the following:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="Content-Security-Policy"
          content="script-src 'sha256-076c8f1ca6979ef156b510a121b69b6265011597557ca2971db5ad5a2743545f'">
    <title>Hello CSP</title>

```

Content Security Policy: The page’s settings blocked the loading of a resource at self (“script-src 'sha256-076c8f1ca6979ef156b510a121b69b6265011597557ca2971db5ad5a2743545f'”). Source: var inline = 1;.

答:
It will work if you change the hash value as in the following:

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta http-equiv="Content-Security-Policy"
        content="script-src 'sha256-B2yPHKaXnvFWtRChIbabYmUBFZdVfKKXHbWtWidDVF8='">
  <title>Hello CSP</title>

```

Not sure why you were seeing the behavior in Chrome you describe; when I test the example in the question in Chrome, it blocks the script and emits an error message saying to use the hash value sha256-B2yPHKaXnvFWtRChIbabYmUBFZdVfKKXHbWtWidDVF8=.

And https://report-uri.io/home/hash also outputs that value when given var inline = 1;.

Body:
I can not get whitelisting by checksum to work in firefox (52.0.2, windows). Firefox supports content security policy version 2 according to caniuse, so checksumming should be supported.

When chrome blocks an inline script, it prints the needed sha-256 to console.
Adding it to the csp rules successfully whitelists the script.
The checksum is also identical to the one calculated at
https://report-uri.io/home/hash

But firefox refuse to accept it.

I noted that the example in the MDN docs is using base-16 as opposed to base-64 encoding for the checksum.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src

But even with the MDN example I get the same results. (Also chrome rejects with the base-16 encoding). I tried a bunch of variations on the following:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="Content-Security-Policy"
          content="script-src 'sha256-076c8f1ca6979ef156b510a121b69b6265011597557ca2971db5ad5a2743545f'">
    <title>Hello CSP</title>

Content Security Policy: The page’s settings blocked the loading of a resource at self (“script-src 'sha256-076c8f1ca6979ef156b510a121b69b6265011597557ca2971db5ad5a2743545f'”). Source: var inline = 1;.

Body:
It will work if you change the hash value as in the following:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta http-equiv="Content-Security-Policy"
        content="script-src 'sha256-B2yPHKaXnvFWtRChIbabYmUBFZdVfKKXHbWtWidDVF8='">
  <title>Hello CSP</title>
</head>
<body>
  <script type="text/javascript">var inline = 1;</script>
</body>
</html>

Not sure why you were seeing the behavior in Chrome you describe; when I test the example in the question in Chrome, it blocks the script and emits an error message saying to use the hash value sha256-B2yPHKaXnvFWtRChIbabYmUBFZdVfKKXHbWtWidDVF8=.

And https://report-uri.io/home/hash also outputs that value when given var inline = 1;.


问:
What pattern is this using?
In order to add some behavior into onScroll event of ListView，I added some code by subclass ListView like this:

```<code>class MyListView extends ListView{
      public void setOnScrollListener(OnScrollListener listener){
            final OnScrollListener lis = new OnScrollListener(){
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                listener.onScrollStateChanged(view, scrollState);
                //below is added behavior of my Listview
                }
            }

        super.setOnScrollListener(lis);
      }
}
</code>```

and the usage of it is simple:

```<code>MyListView myList = new MyListView(...);
myList.setOnScrollListener(new OnScrollListener(){...});//here is the old logic
</code>```

this sounds like Decorator pattern but it is not, because there is no composite but only inheritance(in facto I do not need composite here).

So the problem is what should I call it?

答: This is not a Gang of Four Design Pattern. You are simply using inheritance to extend functionality.</p>

Title: What pattern is this using?

Body:
In order to add some behavior into onScroll event of ListView，I added some code by subclass ListView like this:

class MyListView extends ListView{
      public void setOnScrollListener(OnScrollListener listener){
            final OnScrollListener lis = new OnScrollListener(){
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                listener.onScrollStateChanged(view, scrollState);
                //below is added behavior of my Listview
                }
            }

        super.setOnScrollListener(lis);
      }
}

and the usage of it is simple:

MyListView myList = new MyListView(...);
myList.setOnScrollListener(new OnScrollListener(){...});//here is the old logic

this sounds like Decorator pattern but it is not, because there is no composite but only inheritance(in facto I do not need composite here).

So the problem is what should I call it?


问:
Using Django Rest Framework, is it possible to get results internally on server within Django?
I have a complex DRF ViewSet that supports paging, filtering, sorting, etc. that backends a grid view.  To build an "export" capability, I need to be able to take the same querystring that my endpoint uses, such as:

?obj_id=129&ordering=latitude&city__icontains=nap

And be able to, in Django, send that string into DRF somehow and get the fully-modified queryset after all the view's filters, sorts, etc are applied (the same way as the GET did).  I could use the fully-rendered json response or some interim filter-applied queryset.  Is it possible to use DRF in this way?

答:
Yes you could, if you already have a request object i.e. If you want to use this DRF viewset into another view which has the request object:

```<code>def another_view(request):

    # make a copy of the `GET` attribute of request object
    request.GET = request.GET.copy()

    # now you can set the query params on this GET object
    # ?obj_id=129&ordering=latitude&city__icontains=nap
    request.GET['obj_id'] = 129
    request.GET['ordering'] = 'latitude'
    request.GET['city__icontains'] = 'nap'

    # you can also set paging options in similar way

    # now instantiate the viewset
    vs = DRFViewset.as_view()

    # call the view for response
    # set kwargs as you need
    response = vs(request, *args, **kwargs)

    # response.data will have what you want here
</code>```

Body:
Yes you could, if you already have a request object i.e. If you want to use this DRF viewset into another view which has the request object:

def another_view(request):

    # make a copy of the `GET` attribute of request object
    request.GET = request.GET.copy()

    # now you can set the query params on this GET object
    # ?obj_id=129&ordering=latitude&city__icontains=nap
    request.GET['obj_id'] = 129
    request.GET['ordering'] = 'latitude'
    request.GET['city__icontains'] = 'nap'

    # you can also set paging options in similar way

    # now instantiate the viewset
    vs = DRFViewset.as_view()

    # call the view for response
    # set kwargs as you need
    response = vs(request, *args, **kwargs)

    # response.data will have what you want here


问:
Managing LINQ to SQL .dbml model complexity
This question is addressed to a degree in this question on LINQ to SQL .dbml best practices, but I am not sure how to add to a question.

One of our applications uses LINQ to SQL and we have currently have one .dbml file for the entire database which is becoming difficult to manage.  We are looking at refactoring it a bit into separate files that are more module/functionality specific, but one problem is that many of the high level classes would have to be duplicated in several .dbml files as the associations can't be used across .dbml files (as far as I know), with the additional partial class code as well.

Has anyone grappled with this problem and what recommendations would you make?

答: Past a certain size it probably becomes easier to work with the xml instead of the dbml designer.</p>

OwnerDisplayName: Scott Nichols

OwnerDisplayName: liammclennan


问:
Linear time majority algorithm?
Can anyone think of a linear time algorithm for determining a majority element in a list of elements? The algorithm should use O(1) space.

If n is the size of the list, a majority element is an element that occurs at least ceil(n / 2) times.

```<code>[Input] 1, 2, 1, 1, 3, 2

[Output] 1
</code>```

[Editor Note] This question has a technical mistake. I preferred to leave it so as not to spoil the wording of the accepted answer, which corrects the mistake and discusses why. Please check the accepted answer.

答:
This is a popular challenge question, and the answer is that it's impossible. The language of strings with majority elements is not regular (this is easily proven by the pumping lemma) so there is no way it can be recognized in constant space.

Of course the trick is that you need a counter variable which takes O(log n) space, but since n is boundd by 2^32 or 2^64 and your computer is really a finite state machine with ~8^(ramsize+hddsize) states, everything is O(1).

Title: Linear time majority algorithm?

Body:
Can anyone think of a linear time algorithm for determining a majority element in a list of elements? The algorithm should use O(1) space.

If n is the size of the list, a majority element is an element that occurs at least ceil(n / 2) times.

[Input] 1, 2, 1, 1, 3, 2

[Output] 1

[Editor Note] This question has a technical mistake. I preferred to leave it so as not to spoil the wording of the accepted answer, which corrects the mistake and discusses why. Please check the accepted answer.


问:
Angular2: ng2-img-cropper does not crop url image
I am using ng2-img-cropper to crop a photo (not avatar).
https://github.com/cstefanache/angular2-img-cropper

I followed the example:
https://embed.plnkr.co/V91mKCNkBQZB5QO2MUP4/

I saw that it seems not to support url image, only local image. Is there anyway to make it work with url image?

If not, is there any alternative which can work with url image?

Thanks for any suggestion.

答:
please check the discussion in the following thread: https://github.com/cstefanache/angular2-img-cropper/issues/110

The idea is to work with something like:
var image:HTMLImageElement = new Image();
    this.image.crossOrigin = 'Anonymous';
    image.src ='https://www.google.ro/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png';
    image.addEventListener('load', (data) => {
        this.cropper.setImage(image);
    });


问:
CSS and JQuery: spaces inside image name break code of url()
I have a page that is supposed to display a larger version of an image when hovered over a thumbnail.

I have a 'div' with an ID and the JQuery code is as following:

```<code>$(document).ready(function(){

  $('img').hover(function() {

    var src = $("#im" + this.id).attr("src");
    $('#viewlarge').css('backgroundImage','url(' + src +')');
    return false;
  });

});
</code>```

The images I use, are generated by a Ruby script that "generate" an image with a similar, yet different id. However, sometimes, photo's are uploaded that have "spaces" inside. My developer tools tell me that the background-image is not set correctly, yet the image path is correct and the browser don't have problems finding the image.

My question is, can I somehow sanitize the url 'src', so spaces won't be a problem? I am aware of doing this server side, yet I would like to know how to do this with JQuery/JS too.

Thanks!

答:
I know you've already selected your answer, but I want to improve Pekka's solution and provide the most feasible solution because I ran into another problem while it's handling a file name with brackets.

```<code>$("#viewlarge").css("background",'url(' + "'" + url+ "'" + ')');
</code>```

I hope it helps !

Body:
I have a page that is supposed to display a larger version of an image when hovered over a thumbnail.

I have a 'div' with an ID and the JQuery code is as following:

$(document).ready(function(){

  $('img').hover(function() {

    var src = $("#im" + this.id).attr("src");
    $('#viewlarge').css('backgroundImage','url(' + src +')');
    return false;
  });

});

The images I use, are generated by a Ruby script that "generate" an image with a similar, yet different id. However, sometimes, photo's are uploaded that have "spaces" inside. My developer tools tell me that the background-image is not set correctly, yet the image path is correct and the browser don't have problems finding the image.

My question is, can I somehow sanitize the url 'src', so spaces won't be a problem? I am aware of doing this server side, yet I would like to know how to do this with JQuery/JS too.

Thanks!

Body:
I know you've already selected your answer, but I want to improve Pekka's solution and provide the most feasible solution because I ran into another problem while it's handling a file name with brackets.

$("#viewlarge").css("background",'url(' + "'" + url+ "'" + ')');

I hope it helps !


问:
Progressive encryption/decryption using the WebCrypto API?
So, I started looking into the WebCrypto API as it seems very fast, the api seems fairly simple to use and I managed to implement encryption/decryption quite easily.

Now I'm trying to see if it's possible to do progressive encryption/decryption using it. I currently use CryptoJs and there are many situations where I deal with chunked download and upload of files, meaning that files are broken into smaller pieces and the processing of those pieces are done separately.

On CryptoJs it's possible to keep an instance of the "Encryptor" open so you can keep passing the chunks to it as you get them from the source and you can call a finalize() function when you're done.

I've been searching on Google and StackOverflow for hours for a way to achieve the same thing using WebCrypto but I can't find an answer.

Does anyone know how to do it or if it's even possible to be done using the current apis?

答:
Unfortunately WebCrypto API was not defined with streams support, there are a few reasons but I suspect the main two are that not all algorithms support this and it is the sort of thing that can be added later.

Here is the bug tracking streams support - https://github.com/w3c/webcrypto/issues/73


问:
Tableview Cell Is override from bottom
I am Creating One tableview with tableview cell fro XIB.
When I integrate tableview cell with Tableview and run it it is not showing perfectly ,It shows me override.

Image is

Code is

```<code>static NSString *cellIdentifier =@"DiscussionTableViewCell";

            DiscussionTableViewCell *cell = (DiscussionTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
            if (cell == nil) {

                NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"DiscussionTableViewCell" owner:self options:nil];
                cell = [topLevelObjects objectAtIndex:0];
                cell.selectionStyle=UITableViewCellSelectionStyleNone;
                // [cell.btnConnect addTarget:self action:@selector(btnUserConnectClick:) forControlEvents:UIControlEventTouchUpInside];
                // [cell.btnNotnow addTarget:self action:@selector(btnNotNowClick:) forControlEvents:UIControlEventTouchUpInside];
                 self.cellHeight  += cell.frame.size.height;
                NSLog(@"Cell height is %f",self.cellHeight);
</code>```

答:
Your problem is your cell height and tableview row height are different you can solve this in 2 ways

Implementing AutoLayout to your custom cell,
by this way your cell will grow/shrink according to your row height.

The second method is you can make your row height as same as cell height
by using -(CGFloat)tableView:(UITableView *)tableView
heightForRowAtIndexPath:(NSIndexPath *)indexPath delegate method

Just return your cell height in the above delegate method it will solve your problem.

Title: Tableview Cell Is override from bottom

Body:
I am Creating One tableview with tableview cell fro XIB.
When I integrate tableview cell with Tableview and run it it is not showing perfectly ,It shows me override.

Image is

Code is

static NSString *cellIdentifier =@"DiscussionTableViewCell";

            DiscussionTableViewCell *cell = (DiscussionTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
            if (cell == nil) {

                NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"DiscussionTableViewCell" owner:self options:nil];
                cell = [topLevelObjects objectAtIndex:0];
                cell.selectionStyle=UITableViewCellSelectionStyleNone;
                // [cell.btnConnect addTarget:self action:@selector(btnUserConnectClick:) forControlEvents:UIControlEventTouchUpInside];
                // [cell.btnNotnow addTarget:self action:@selector(btnNotNowClick:) forControlEvents:UIControlEventTouchUpInside];
                 self.cellHeight  += cell.frame.size.height;
                NSLog(@"Cell height is %f",self.cellHeight);


问:
DirectX 9 - Getting camera resolutions? (C++)
noob question:
Any examples of how to get parameters from the connected camera, such as supported resolutions?

I'm using DirectX June 2010.
Code to create a device:

```<code>HWND                    m_hwnd;
HDC                     *phdc;
IDirect3D9              *m_pD3D;
IDirect3DDevice9        *m_pDevice;
IDirect3DSwapChain9     *m_pSwapChain;

HRESULT DrawDevice::CreateDevice(HWND hwnd)
{
    if (m_pDevice)
    {
        return S_OK;
    }

    // Create the Direct3D object.
    if (m_pD3D == NULL)
    {
        m_pD3D = Direct3DCreate9(D3D_SDK_VERSION);

        if (m_pD3D == NULL)
        {
            return E_FAIL;
        }
    }

    HRESULT hr = S_OK;
    D3DPRESENT_PARAMETERS pp = { 0 };
    D3DDISPLAYMODE mode = { 0 };

    hr = m_pD3D->GetAdapterDisplayMode(
        D3DADAPTER_DEFAULT,
        &mode
    );

    if (FAILED(hr)) { return hr; }

    hr = m_pD3D->CheckDeviceType(
        D3DADAPTER_DEFAULT,
        D3DDEVTYPE_HAL,
        mode.Format,
        D3DFMT_X8R8G8B8,
        TRUE    // windowed
    );

    if (FAILED(hr)) { return hr; }

    pp.BackBufferFormat = D3DFMT_X8R8G8B8;
    pp.SwapEffect = D3DSWAPEFFECT_COPY;
    pp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
    pp.Windowed = TRUE;
    pp.hDeviceWindow = hwnd;

    hr = m_pD3D->CreateDevice(
        D3DADAPTER_DEFAULT,
        D3DDEVTYPE_HAL,
        hwnd,
        D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_FPU_PRESERVE,
        &pp,
        &m_pDevice
    );

    if (FAILED(hr)) { return hr; }

    m_hwnd = hwnd;
    m_d3dpp = pp;

    return hr;
}
</code>```

My purpose is to give the user a list of options to choose...

Thanks !!

答:
Direct3D is used to render to a monitor, not to capture images from a camera. Depending on what version of the OS you are using, you should take a look at Media Foundation or legacy DirectShow.

Direct3D 9 itself is also deprecated, as is the legacy DirectX SDK. See MSDN and this post. New projects should use DirectX 11 (or very experienced Direct3D graphics developers looking for high performance on Windows 10 / Xbox One should consider DirectX 12).

For a Win32 desktop application, you should look at this sample on GitHub.

For a Universal Windows Platform (UWP) app, you should look at this sample on GitHub.

Body:
noob question:
Any examples of how to get parameters from the connected camera, such as supported resolutions?

I'm using DirectX June 2010.
Code to create a device:

HWND                    m_hwnd;
HDC                     *phdc;
IDirect3D9              *m_pD3D;
IDirect3DDevice9        *m_pDevice;
IDirect3DSwapChain9     *m_pSwapChain;

HRESULT DrawDevice::CreateDevice(HWND hwnd)
{
    if (m_pDevice)
    {
        return S_OK;
    }

    // Create the Direct3D object.
    if (m_pD3D == NULL)
    {
        m_pD3D = Direct3DCreate9(D3D_SDK_VERSION);

        if (m_pD3D == NULL)
        {
            return E_FAIL;
        }
    }

    HRESULT hr = S_OK;
    D3DPRESENT_PARAMETERS pp = { 0 };
    D3DDISPLAYMODE mode = { 0 };

    hr = m_pD3D->GetAdapterDisplayMode(
        D3DADAPTER_DEFAULT,
        &mode
    );

    if (FAILED(hr)) { return hr; }

    hr = m_pD3D->CheckDeviceType(
        D3DADAPTER_DEFAULT,
        D3DDEVTYPE_HAL,
        mode.Format,
        D3DFMT_X8R8G8B8,
        TRUE    // windowed
    );

    if (FAILED(hr)) { return hr; }

    pp.BackBufferFormat = D3DFMT_X8R8G8B8;
    pp.SwapEffect = D3DSWAPEFFECT_COPY;
    pp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
    pp.Windowed = TRUE;
    pp.hDeviceWindow = hwnd;

    hr = m_pD3D->CreateDevice(
        D3DADAPTER_DEFAULT,
        D3DDEVTYPE_HAL,
        hwnd,
        D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_FPU_PRESERVE,
        &pp,
        &m_pDevice
    );

    if (FAILED(hr)) { return hr; }

    m_hwnd = hwnd;
    m_d3dpp = pp;

    return hr;
}

My purpose is to give the user a list of options to choose...

Thanks !!


问:
Print shell environment functions on a single line
In bash, running set will display all environment settings. I want to display my functions as a single line for each function. So instead of running set and getting this (for example):

```<code>gcm ()
{
    git commit -m "$@";
    git --no-pager log -1 | grep --color ^commit
}
gcma ()
{
    git commit -a -m "$@";
    git --no-pager log -1 | grep --color ^commit
}
</code>```

I want to see this:

```<code>gcm () { git commit -m "$@"; git --no-pager log -1 | grep --color ^commit }
gcma () { git commit -a -m "$@"; git --no-pager log -1 | grep --color ^commit }
</code>```

So I think I want a sed/awk command that will look for regex ' ()$' and concatenate every line following (with a space separation char) until the regex '^}$' is matched, and anything else should just print as is.

UPDATE: All of the examples submitted so far take all the input and render it on a single line, and that's not exactly right. I want each function (the set of ' ()$' to '^}$', inclusive) as a single line.

答:
In awk:

```<code>$ awk 'sub(/}/,"}\n")||$1=$1' ORS='' file
</code>```

or remove file and pipe to it (in which case you need to awk -v ORS=''...). Result:

```<code>gcm (){git commit -m "$@";git --no-pager log -1 | grep --color ^commit}
gcma (){git commit -a -m "$@";git --no-pager log -1 | grep --color ^commit}
</code>```

replace } with }\n

and use ORS='' to remove the (other than above) newlines

and $1=$1 to rebuild the records to trim space

Body:
In bash, running set will display all environment settings. I want to display my functions as a single line for each function. So instead of running set and getting this (for example):

gcm ()
{
    git commit -m "$@";
    git --no-pager log -1 | grep --color ^commit
}
gcma ()
{
    git commit -a -m "$@";
    git --no-pager log -1 | grep --color ^commit
}

I want to see this:

gcm () { git commit -m "$@"; git --no-pager log -1 | grep --color ^commit }
gcma () { git commit -a -m "$@"; git --no-pager log -1 | grep --color ^commit }

So I think I want a sed/awk command that will look for regex ' ()$' and concatenate every line following (with a space separation char) until the regex '^}$' is matched, and anything else should just print as is.

UPDATE: All of the examples submitted so far take all the input and render it on a single line, and that's not exactly right. I want each function (the set of ' ()$' to '^}$', inclusive) as a single line.

Body:
In awk:

$ awk 'sub(/}/,"}\n")||$1=$1' ORS='' file

or remove file and pipe to it (in which case you need to awk -v ORS=''...). Result:

gcm (){git commit -m "$@";git --no-pager log -1 | grep --color ^commit}
gcma (){git commit -a -m "$@";git --no-pager log -1 | grep --color ^commit}

replace } with }\n

and use ORS='' to remove the (other than above) newlines

and $1=$1 to rebuild the records to trim space


问:
Get EOFException while reading serialized object in Java
I have two methods, one that serialize the Object, and it works ok:

```<code>public void record()throws RecordingException
    {
        ObjectOutputStream outputStream = null;
        try
        {
            outputStream = new ObjectOutputStream(new FileOutputStream("src/data/employee.dat"));
            outputStream.writeObject(this);
        } catch (FileNotFoundException ex)
        {
            ex.printStackTrace();
            throw new RecordingException(ex);
        } catch (IOException ex)
        {
            ex.printStackTrace();
            throw new RecordingException(ex);
        }finally
        {
            try
            {
                if (outputStream != null) outputStream.close();
            } catch (IOException ex){}
        }
    }
</code>```

The problem here when deserializing the object, I get EOFException!:

```<code>public final User loadObject(UserType usertype) throws InvalidLoadObjectException
    {
        ObjectInputStream istream = null;
        String path = null;
        if (usertype == UserType.EMPLOYEE)
        {
            path = "data/employee.dat";
        }else if (usertype == UserType.CUSTOMER)
        {
            path = "data/customer.dat";
        }else
            throw new InvalidLoadObjectException("Object is not a sub class of User");

        try
        {
            istream = new ObjectInputStream(ObjectLoader.class.getClassLoader().getResourceAsStream(path));

            User u = loadObject(istream);
            istream.close();
            return u;
        }catch (EOFException ex)
        {
            System.out.println(ex.getMessage());
            return null;
        }catch(Exception ex)
        {
            ex.printStackTrace();
            throw new InvalidLoadObjectException(ex);
        }
    }

private User loadObject(ObjectInputStream stream) throws InvalidLoadObjectException
    {
        try
        {
            return (User) stream.readObject();
        } catch (IOException ex)
        {
            ex.printStackTrace();
            throw new InvalidLoadObjectException(ex);
        } catch (ClassNotFoundException ex)
        {
            ex.printStackTrace();
            throw new InvalidLoadObjectException(ex);
        }
    }
</code>```

答: The file was empty, or didn't contain the full serialization of the object.</p>

Body:
I have two methods, one that serialize the Object, and it works ok:

public void record()throws RecordingException
    {
        ObjectOutputStream outputStream = null;
        try
        {
            outputStream = new ObjectOutputStream(new FileOutputStream("src/data/employee.dat"));
            outputStream.writeObject(this);
        } catch (FileNotFoundException ex)
        {
            ex.printStackTrace();
            throw new RecordingException(ex);
        } catch (IOException ex)
        {
            ex.printStackTrace();
            throw new RecordingException(ex);
        }finally
        {
            try
            {
                if (outputStream != null) outputStream.close();
            } catch (IOException ex){}
        }
    }

The problem here when deserializing the object, I get EOFException!:

public final User loadObject(UserType usertype) throws InvalidLoadObjectException
    {
        ObjectInputStream istream = null;
        String path = null;
        if (usertype == UserType.EMPLOYEE)
        {
            path = "data/employee.dat";
        }else if (usertype == UserType.CUSTOMER)
        {
            path = "data/customer.dat";
        }else
            throw new InvalidLoadObjectException("Object is not a sub class of User");

        try
        {
            istream = new ObjectInputStream(ObjectLoader.class.getClassLoader().getResourceAsStream(path));

            User u = loadObject(istream);
            istream.close();
            return u;
        }catch (EOFException ex)
        {
            System.out.println(ex.getMessage());
            return null;
        }catch(Exception ex)
        {
            ex.printStackTrace();
            throw new InvalidLoadObjectException(ex);
        }
    }

private User loadObject(ObjectInputStream stream) throws InvalidLoadObjectException
    {
        try
        {
            return (User) stream.readObject();
        } catch (IOException ex)
        {
            ex.printStackTrace();
            throw new InvalidLoadObjectException(ex);
        } catch (ClassNotFoundException ex)
        {
            ex.printStackTrace();
            throw new InvalidLoadObjectException(ex);
        }
    }


问:
How to delay the sending of the data of the widget to the server side (to wait for a potential change in the input of the widget)
I have some widgets that receives a lot of user inputs in a very short period of time.
eg. a selectInput with multiple selection on which the user are clicking a lot very quickly

This causes unnecessary calls to the server side of the Shiny application.

Is there a way to set a delay before the widget sends its new data to the server? either application wise or on a per-widget basis.

I guess that would ask for some 'setTimeout' and 'clearTimeout' in the javascript.

If that's not available natively what are my options?

I have written a few custom widgets using http://www.htmlwidgets.org/ but I don't want to reinvent the wheel and I don't want to make a clone of the native widget because that would force me to track new versions of the  the widget and update the clone correspondingly.

Is there a way to extend an existing widget and override only some part of it (the part sending the new input to the server side), and keep getting the updates of this existing widget?

Another option would be to let the widget send its updated input every time there is a change on the widget BUT to tell the server to wait before handling it, in case a new input comes in. That would work for me as well.

NOTE: I don't want to use observeEvent/eventReactive

答: If you are able to use JavaScript then I would recommend using a setInterval loops stored in variables. I find them really handy for running functions in intervals and you can run multiple loops at the same time and tweak the timing for best performance as you can also close off and start up new ones. Hope this helps. </p>


问:
Copy/clone SQL Server database schema and some data programmatically
I am developing a point-of-sale Windows Forms application which handling multiple companies. When user creating a new company, I want programmatically clone an existing database with some of the data (some master tables). I am using SQL Server Express and C#.</p>

答: Instead of copying a database, could you not prepare a backup of an empty database with the data required, then restore that to a new database?</p>


问:
How do I disable Git Credential Manager for Windows?
I notice that in the latest version of Git, the default is now to popup a "Git Credential Manager for Windows" dialog instead of prompting me for me password at the Bash prompt every time.

I really hate this behaviour. How can I just disable it and go back to entering the password at the Bash shell every time?

By the way, I don't want Git caching my credentials in any way, whether through Windows credentials or some internal daemon. I want to disable all credential caching.

答:
I was able to uninstall the Git Credential Manager for Windows using the uninstall option:

```<code>git-credential-manager.exe uninstall
</code>```

Run this command in C:\Program Files\Git\mingw64\libexec\git-core

Body:
I was able to uninstall the Git Credential Manager for Windows using the uninstall option:

git-credential-manager.exe uninstall

Run this command in C:\Program Files\Git\mingw64\libexec\git-core


问:
Apply a function to every column of a dataframe in pandas
I have this:

```<code>df = DataFrame(dict(person= ['andy', 'rubin', 'ciara', 'jack'],
     item = ['a', 'b', 'a', 'c'],
     group= ['c1', 'c2', 'c3', 'c1'],
     age= [23, 24, 19, 49]))
df:

    age group item person
0   23  c1    a    andy
1   24  c2    b    rubin
2   19  c3    a    ciara
3   49  c1    c    jack
</code>```

what I want to do, is to get the length of unique items in each column.
Now I know I can do something like:

```<code>len(df.person.unique())
</code>```

for every column.

Is there a way to do this in one go for all columns?

I tried to do:

```<code>for column in df.columns:
    print(len(df.column.unique()))
</code>```

but I know this is not right.

How can I accomplish this?

答:
You can use:

```<code>for column in df:
    print(len(df[column].unique()))

4
3
3
4
</code>```

Or:

```<code>for column in df:
    print(df[column].nunique())

4
3
3
4
</code>```

Body:
I have this:

df = DataFrame(dict(person= ['andy', 'rubin', 'ciara', 'jack'],
     item = ['a', 'b', 'a', 'c'],
     group= ['c1', 'c2', 'c3', 'c1'],
     age= [23, 24, 19, 49]))
df:

    age group item person
0   23  c1    a    andy
1   24  c2    b    rubin
2   19  c3    a    ciara
3   49  c1    c    jack

what I want to do, is to get the length of unique items in each column.
Now I know I can do something like:

len(df.person.unique())

for every column.

Is there a way to do this in one go for all columns?

I tried to do:

for column in df.columns:
    print(len(df.column.unique()))

but I know this is not right.

How can I accomplish this?

Body:
You can use:

for column in df:
    print(len(df[column].unique()))

4
3
3
4

Or:

for column in df:
    print(df[column].nunique())

4
3
3
4


答:
You can the number of unique items in each column as:</p>

```<code>for column in df.columns:
    print(len(df[column].unique()))
</code>```

Title: Apply a function to every column of a dataframe in pandas

Body:
You can the number of unique items in each column as:

for column in df.columns:
    print(len(df[column].unique()))


问:
How to source file in bash with Robot framework?
Anyone know how to source a file using Robot framework?

I try to use "Run" or "Run Process" to execute source, but seems the environment variables set in the sourced file are not retained.

e.g.

```<code>${out} | Run Process | source | set_config.sh | shell=True
${out} | Run Process | check_env_vars.pl
</code>```

The check_env_vars.pl returns the error message saying the environment vars are not set yet, although they have been set in the previous line.
Any suggestion on how to accomplish this?

Thanks in advance!

答:
Set environmental variables using "Set Environment Variable" instead and I see it accessible throughout the robot test run.

```<code>*** Settings ***
Library  Process
Library  OperatingSystem

*** Test Cases ***
sample
    Set Environment Variable  VAR  2
    Run Process   sh  Sample2.sh
</code>```

Sample.sh looks like:

```<code>echo $VAR > console.txt
</code>```

The env variable which is set in robotframework, is accessible in Sample2.sh also. In the same way you can set variables are run "check_env_vars.pl" which will have access to all those variables.

Hope it helps!

Body:
Anyone know how to source a file using Robot framework?

I try to use "Run" or "Run Process" to execute source, but seems the environment variables set in the sourced file are not retained.

e.g.

${out} | Run Process | source | set_config.sh | shell=True
${out} | Run Process | check_env_vars.pl

The check_env_vars.pl returns the error message saying the environment vars are not set yet, although they have been set in the previous line.
Any suggestion on how to accomplish this?

Thanks in advance!

Body:
Set environmental variables using "Set Environment Variable" instead and I see it accessible throughout the robot test run.

*** Settings ***
Library  Process
Library  OperatingSystem

*** Test Cases ***
sample
    Set Environment Variable  VAR  2
    Run Process   sh  Sample2.sh

Sample.sh looks like:

echo $VAR > console.txt

The env variable which is set in robotframework, is accessible in Sample2.sh also. In the same way you can set variables are run "check_env_vars.pl" which will have access to all those variables.

Hope it helps!


问:
ErrorException in 2b026073a4c3afa6c3599efffe5361a356c89d88.php line 63: Trying to get property of non-object (View: \index.blade.php)
model user

```<code>protected $table = "users";
protected $fillable = ['name', 'email', 'password' ];

protected $hidden = [
    'password', 'remember_token',
];

public function solicitud(){
    return $this->hasMany('App\solicitud');
}
</code>```

Model tiposolicitud

```<code>      protected $table = "tiposolicitud";
protected $fillable = ['nombre'];

public function solicitud(){
    return $this->hasMany('App\solicitud');
}
</code>```

Model solicitud ( principal )

```<code>  protected $table = "solicitud";
  protected $fillable = [..extract...   'tiposolicitud_id','users_id'....];

  public function tiposolicitud(){
    return $this->belongsTo('App\tiposolicitud');
}

      public function User(){
    return $this->belongsTo('App\User');
}
</code>```

Controller ( extract)

```<code> use App\solicitud as VarModel;
 use App\User;
 use App\tiposolicitud ;
 ...
 public function index()
{

    $var1 = VarModel::all();
    return view('private.solicitud.index',compact('var1'));
}
</code>```

index.php

```<code>  @foreach ($var1 as $var)
   <tr>
       <td>{{$var->id}}</td>               // OK
       <td>{{$var->user->name}}</td>       //NOT OK
       <td>{{$var->tiposolicitud}}</td>    // OK
</code>```

Trying to get property of non-object (View: C:\wamp64\www\issdgr\resources\views\private\solicitud\index.blade.php)

I have problem with app / user

I have persisted the id of the user but I can not find the name ..

HELP!!!!!

答:
The error is on your blade view with the following statement:

```<code>$var->id
</code>```

I think its a multi-dimension Std Class Object. So before iterating, put a print_r() to check the content of it.

And one more thing, laravel maintain cache of all views inside

```<code>your_project/storage/framework/views
</code>```

with name like 2b026073a4c3afa6c3599efffe5361a356c89d88.php that's why it is showing error here.

Body:
model user

protected $table = "users";
protected $fillable = ['name', 'email', 'password' ];

protected $hidden = [
    'password', 'remember_token',
];

public function solicitud(){
    return $this->hasMany('App\solicitud');
}

Model tiposolicitud

      protected $table = "tiposolicitud";
protected $fillable = ['nombre'];

public function solicitud(){
    return $this->hasMany('App\solicitud');
}

Model solicitud ( principal )

  protected $table = "solicitud";
  protected $fillable = [..extract...   'tiposolicitud_id','users_id'....];

  public function tiposolicitud(){
    return $this->belongsTo('App\tiposolicitud');
}

      public function User(){
    return $this->belongsTo('App\User');
}

Controller ( extract)

 use App\solicitud as VarModel;
 use App\User;
 use App\tiposolicitud ;
 ...
 public function index()
{

    $var1 = VarModel::all();
    return view('private.solicitud.index',compact('var1'));
}

index.php

  @foreach ($var1 as $var)

       {{$var->id}}	               // OK
       {{$var->user->name}}	       //NOT OK
       {{$var->tiposolicitud}}	    // OK

Trying to get property of non-object (View: C:\wamp64\www\issdgr\resources\views\private\solicitud\index.blade.php)

I have problem with app / user

I have persisted the id of the user but I can not find the name ..

HELP!!!!!

Body:
The error is on your blade view with the following statement:

$var->id

I think its a multi-dimension Std Class Object. So before iterating, put a print_r() to check the content of it.

And one more thing, laravel maintain cache of all views inside

your_project/storage/framework/views

with name like 2b026073a4c3afa6c3599efffe5361a356c89d88.php that's why it is showing error here.


问:
How to remove character from last array element
I need to remove the last element comma in Javascript array

```<code>var arr =  ["AAA,","BBB,"];
</code>```

I need the result below

```<code>var arr =  ["AAA,","BBB"];
</code>```

Any help is appreciated...

答:
```<code>var arr =  ["AAA,","BBB,"];
var lastelmnt = arr[(arr.length)-1].replace(',', '');
arr.splice(((arr.length)-1),1,lastelmnt);
</code>```

Output :

```<code>["AAA,", "BBB"]
</code>```

Body:
I need to remove the last element comma in Javascript array

var arr =  ["AAA,","BBB,"];

I need the result below

var arr =  ["AAA,","BBB"];

Any help is appreciated...

Body:
var arr =  ["AAA,","BBB,"];
var lastelmnt = arr[(arr.length)-1].replace(',', '');
arr.splice(((arr.length)-1),1,lastelmnt);

Output :

["AAA,", "BBB"]


问:
What is this syntax in ES6 or ES7?
I came across this syntax which I believe is ES6 or ES7. What do these lines of code do?</p>

```<code>module.exports = async (taskData) => {
  // do stuff
}
</code>```

答:
Async await syntax is set to be supported when ES2017 is released. Your code is essentially a function that returns a promise. Additionally, the async keyword allows for syntactic sugar when working with promises by use of the await keyword.

The => part is called an arrow function which again is a syntactic sugar for the most part. It is part of ES6.

Your function

```<code>module.exports = async (taskData) => {
  // do stuff
}
</code>```

... is almost the same as:

```<code>module.exports = function(taskData) {
  return new Promise(function() {

    // do stuff
    if (err) reject(err)
    resolve(your return value)
  }
}
</code>```

Note: the main difference is just the binding of the this keyword via the arrow function.

Title: What is this syntax in ES6 or ES7?

Body:
I came across this syntax which I believe is ES6 or ES7. What do these lines of code do?

module.exports = async (taskData) => {
  // do stuff
}

Body:
Async await syntax is set to be supported when ES2017 is released. Your code is essentially a function that returns a promise. Additionally, the async keyword allows for syntactic sugar when working with promises by use of the await keyword.

The => part is called an arrow function which again is a syntactic sugar for the most part. It is part of ES6.

Your function

module.exports = async (taskData) => {
  // do stuff
}

... is almost the same as:

module.exports = function(taskData) {
  return new Promise(function() {

    // do stuff
    if (err) reject(err)
    resolve(your return value)
  }
}

Note: the main difference is just the binding of the this keyword via the arrow function.


问:
Concatenate several child items into one child item using XSLT
I have an xml with several parent-child structures. One structure is like this:

```<code><parent>
  <child>Sam</child>
  <child>Tom</child>
  <child>Joe</child>
</parent>
</code>```

I want the result to look like this:

```<code><parent>
  <child>Sam;Tom;Joe</child>
</parent>
</code>```

How do I achieve the result in XSLT?

答:
In XSLT 2.0 you can write:</p>

```<code><xsl:template match="parent">
  <xsl:copy>
    <child>
      <xsl:value-of select="child" separator=";"/>
    </child>
  </xsl:copy>
</xsl:template>
</code>```

Body:
I have an xml with several parent-child structures. One structure is like this:

<parent>
  <child>Sam</child>
  <child>Tom</child>
  <child>Joe</child>
</parent>

I want the result to look like this:

<parent>
  <child>Sam;Tom;Joe</child>
</parent>

How do I achieve the result in XSLT?

Body:
In XSLT 2.0 you can write:

<xsl:template match="parent">
  <xsl:copy>
    <child>
      <xsl:value-of select="child" separator=";"/>
    </child>
  </xsl:copy>
</xsl:template>


问:
Input type button not working within table tds
I do refers to this fiddle and this post but this doesn't solve my problems. I'm well informed since I used CSP, onclick attribute is not working, thus I use jQuery .on('click') to get this done but still no satisfied results.
Here is the structure of my code(will include only codes related to this issues):-

html

```<code><td><input value="Resend" class="btn btn-primary btn-xs" id="resend_sms" name="resend_sms" type="button"></td>
</code>```

script

```<code>$(function(){
            $('#resend_sms').on('click', function(e){
                console.log('clicked');
            });
        });
</code>```

Above is the codes related. For your notice, this part of html is generated by server-side script. Again, I re-test the this guy but still no results upon clicked.

答:
If your part of html is dynamic generated or it is generating from server side script:

Then use it like:

```<code>       $(function(){
            $(document).on('click','#resend_sms', function(e){
                console.log('clicked');
            });
        });
</code>```

This will work.

Body:
I do refers to this fiddle and this post but this doesn't solve my problems. I'm well informed since I used CSP, onclick attribute is not working, thus I use jQuery .on('click') to get this done but still no satisfied results.
Here is the structure of my code(will include only codes related to this issues):-

html

<input value="Resend" class="btn btn-primary btn-xs" id="resend_sms" name="resend_sms" type="button">

script

$(function(){
            $('#resend_sms').on('click', function(e){
                console.log('clicked');
            });
        });

Above is the codes related. For your notice, this part of html is generated by server-side script. Again, I re-test the this guy but still no results upon clicked.

Body:
If your part of html is dynamic generated or it is generating from server side script:

Then use it like:

       $(function(){
            $(document).on('click','#resend_sms', function(e){
                console.log('clicked');
            });
        });

This will work.


答:
you want pd.Series.nunique

```<code>df.apply(pd.Series.nunique)

age       4
group     3
item      3
person    4
dtype: int64
</code>```

Body:
you want pd.Series.nunique

df.apply(pd.Series.nunique)

age       4
group     3
item      3
person    4
dtype: int64