问:
Subset and filter not giving proper answer
I have following dataset and used subset and filter to segment the data:

```<code>KL <- read.table(text = "
ID  C1
A   597.69
B   239.64
C   601.3
D   4052.6
E   73.73
F   74.06
G   124
H   0
I   0
J   0
K   0
L   122.45
M   152.88
N   123.32
O   354.12",
stringsAsFactors = FALSE,
header = TRUE)

str(KL)
Classes ‘data.table’ and 'data.frame':  15 obs. of  2 variables:
 $ ID: chr  "A" "B" "C" "D" ...
 $ C1: num  597.7 239.6 601.3 4052.6 73.7 ...
</code>```

When I applied subset conditions

```<code>cl4  = subset(KL, C1 > "300.00")
</code>```

Output is:

```<code>ID C1
A  597.69
C  601.30
D  4052.60
E  73.73
F  74.06
O  354.12
</code>```

Why is it still showing number less than 300?

I have tried filter also but the output is same.

答:
Since your column C1 is numeric, you should not use quotes. Try this:

```<code> subset(KL, C1 > 300)

   ID      C1
1   A  597.69
3   C  601.30
4   D 4052.60
15  O  354.12
</code>```

But note that you should use caution with subset() - this will not always do what you think it does.

It's better to use [ for subsetting:

```<code>KL[KL$C1 > 300, ]
   ID      C1
1   A  597.69
3   C  601.30
4   D 4052.60
15  O  354.12
</code>```

Body:
I have following dataset and used subset and filter to segment the data:

KL <- read.table(text = "
ID  C1
A   597.69
B   239.64
C   601.3
D   4052.6
E   73.73
F   74.06
G   124
H   0
I   0
J   0
K   0
L   122.45
M   152.88
N   123.32
O   354.12",
stringsAsFactors = FALSE,
header = TRUE)

str(KL)
Classes ‘data.table’ and 'data.frame':  15 obs. of  2 variables:
 $ ID: chr  "A" "B" "C" "D" ...
 $ C1: num  597.7 239.6 601.3 4052.6 73.7 ...

When I applied subset conditions

cl4  = subset(KL, C1 > "300.00")

Output is:

ID C1
A  597.69
C  601.30
D  4052.60
E  73.73
F  74.06
O  354.12

Why is it still showing number less than 300?

I have tried filter also but the output is same.

Body:
Since your column C1 is numeric, you should not use quotes. Try this:

 subset(KL, C1 > 300)

   ID      C1
1   A  597.69
3   C  601.30
4   D 4052.60
15  O  354.12

But note that you should use caution with subset() - this will not always do what you think it does.

It's better to use [ for subsetting:

KL[KL$C1 > 300, ]
   ID      C1
1   A  597.69
3   C  601.30
4   D 4052.60
15  O  354.12


来源: stackexchange

问:
Custom css media queries not working with bootstrap3
I'm using bootstrap 3 with jquery UI to have search and select field for the user. The css code works fine on larger screen but absolutely not working with the smaller screen. I'm using following media query code but it is not taking effect. In fact I observed my custom css code does not work with any of the @media queries. I'm using bootstrap3 across the website. Any ideas please?</p>

```<code>@media only screen and (max-width: 500px) {
    .ui-autocomplete {
        position: absolute;
        top: 100%;
        left: 0;
        z-index: 1000;
        float: left;
        display: none;
        min-width: 160px;
        padding: 4px 0;
        margin: 0 0 10px 25px;
        list-style: none;
        background-color: #ffffff;
        border-color: #ccc;
        border-color: rgba(0, 0, 0, 0.2);
        border-style: solid;
        border-width: 1px;
        -webkit-border-radius: 5px;
        -moz-border-radius: 5px;
        border-radius: 5px;
        -webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
        -moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
        box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
        -webkit-background-clip: padding-box;
        -moz-background-clip: padding;
        background-clip: padding-box;
        *border-right-width: 2px;
        *border-bottom-width: 2px;
    }

.ui-menu-item > a.ui-corner-all {
        display: block;
        padding: 3px 15px;
        clear: both;
        font-weight: normal;
        line-height: 18px;
        color: #555555;
        white-space: nowrap;
        text-decoration: none;
    }

.ui-state-hover, .ui-state-active {
        color: #ffffff;
        text-decoration: none;
        background-color: #0088cc;
        border-radius: 0px;
        -webkit-border-radius: 0px;
        -moz-border-radius: 0px;
        background-image: none;
    }

    }
</code>```

答:
```<code><!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        body{
            background:red;
        }
        @media only screen and (max-width: 500px) {
            body{
                background:green;
            }
        }
    </style>
</head>
<body>

</body>
</html>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm using bootstrap 3 with jquery UI to have search and select field for the user. The css code works fine on larger screen but absolutely not working with the smaller screen. I'm using following media query code but it is not taking effect. In fact I observed my custom css code does not work with any of the @media queries. I'm using bootstrap3 across the website. Any ideas please?

@media only screen and (max-width: 500px) {
    .ui-autocomplete {
        position: absolute;
        top: 100%;
        left: 0;
        z-index: 1000;
        float: left;
        display: none;
        min-width: 160px;
        padding: 4px 0;
        margin: 0 0 10px 25px;
        list-style: none;
        background-color: #ffffff;
        border-color: #ccc;
        border-color: rgba(0, 0, 0, 0.2);
        border-style: solid;
        border-width: 1px;
        -webkit-border-radius: 5px;
        -moz-border-radius: 5px;
        border-radius: 5px;
        -webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
        -moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
        box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
        -webkit-background-clip: padding-box;
        -moz-background-clip: padding;
        background-clip: padding-box;
        *border-right-width: 2px;
        *border-bottom-width: 2px;
    }

.ui-menu-item > a.ui-corner-all {
        display: block;
        padding: 3px 15px;
        clear: both;
        font-weight: normal;
        line-height: 18px;
        color: #555555;
        white-space: nowrap;
        text-decoration: none;
    }

.ui-state-hover, .ui-state-active {
        color: #ffffff;
        text-decoration: none;
        background-color: #0088cc;
        border-radius: 0px;
        -webkit-border-radius: 0px;
        -moz-border-radius: 0px;
        background-image: none;
    }

    }


问:
Synchronization issue when running Protractor tests on an app with AngularFire
When writing tests in Protractor for an Angular2 app that's using AngularFire.

I am using browser.ignoreSynchronization as a workaround, otherwise my tests would timeout at each it. This forces me to write a lot of bloat code.

Is there a way to not be "forced" to use browser.ignoreSynchronization?

There are some discussions about this issue out there (like this one), but I don't see any definite solution. Does one exist at this point?

答:
I hope the issue is still not solved perfectly.

May be instead of using the browser.ignoreSynchronization=true; then and there, i would suggest you to use in the conf.js and  browser.ignoreSynchronization=false; at the teardown of each test suite.

That may reduce the so many bloat codes.
Thanks.


问:
what is a good way to pretty print a SQLAlchemy database as models and relations?
This one might be a challenge, but I am trying to find a nice way to get an overarching idea of how my entire database "looks". Here is a small example using Flask-SQLAlchemy, a few models with different relations and properties (admittedly, most just taken from SQLAlchemy Docs)

```<code>class IDModel(db.Model):
  __abstract__ = True
  id = db.Column(db.Integer, primary_key=True)

class User(db.Model, IDModel):
  __tablename__ = 'users'
  username = db.Column(db.String(64), unique=True)
  _roles = db.relationship(
    Role, lambda: user_role, collection_class=set,
    backref=db.backref('users', collection_class=set)
  )
  roles = association_proxy('_roles', 'name')

# One-to-many
class Post(db.Model, IDModel):
  __tablename__ = 'posts'
  html = db.Column(db.Text)
  author_id = db.Column(db.Integer, backref="users.id")
  author = db.relationship("User")

# Many-to-Many
class Role(db.Model, IDModel):
  __tablename__ = 'roles'
  name = db.Column(db.String)

user_role = db.Table(
  'user_role',
  db.Column('user_id', db.Integer, db.ForeignKey(User.id), primary_key=True),
  db.Column('role_id', db.Integer, db.ForeignKey(Role.id), primary_key=True)
)
</code>```

Ideally, what I want to do is change the __repr__ of my db to print something like the following for a given db:

```<code><Model 'User'>
id (primary key)
username
roles -> MANY-TO-MANY relationship with <Model 'Roles'>

<Model 'Post'>
id (primary_key)
html
author_id -> 'User.id'
author -> ONE-TO-MANY relationship with <Model 'User'>

<Model 'Role'>
id (primary key)
name
MANY TO MANY relationship with <Model 'User'>
</code>```

is such a thing possible?

to add my contribution, I was able to make it print ALL the tables and their columns, but am having trouble pretty printing the relationships and removing the relationship tables.

```<code>>>> from app import db
>>> inspector = db.inspect(db.engine)
>>> for table in inspector.get_table_names():
        print("<Model '{}'".format(table))
        for column in inspector.get_columns(table):
            print(column['name'])
</code>```

答:
For now, 2 solutions exist:

https://github.com/manicmaniac/sqlalchemy-repr - cool, but prints ALL attributes which can lead to huge repr's.

https://github.com/absent1706/sqlalchemy-mixins#beauty-repr - inspired by first one; allows you to specify attributes you want to see in repr.

Body:
This one might be a challenge, but I am trying to find a nice way to get an overarching idea of how my entire database "looks". Here is a small example using Flask-SQLAlchemy, a few models with different relations and properties (admittedly, most just taken from SQLAlchemy Docs)

class IDModel(db.Model):
  __abstract__ = True
  id = db.Column(db.Integer, primary_key=True)

class User(db.Model, IDModel):
  __tablename__ = 'users'
  username = db.Column(db.String(64), unique=True)
  _roles = db.relationship(
    Role, lambda: user_role, collection_class=set,
    backref=db.backref('users', collection_class=set)
  )
  roles = association_proxy('_roles', 'name')

# One-to-many
class Post(db.Model, IDModel):
  __tablename__ = 'posts'
  html = db.Column(db.Text)
  author_id = db.Column(db.Integer, backref="users.id")
  author = db.relationship("User")

# Many-to-Many
class Role(db.Model, IDModel):
  __tablename__ = 'roles'
  name = db.Column(db.String)

user_role = db.Table(
  'user_role',
  db.Column('user_id', db.Integer, db.ForeignKey(User.id), primary_key=True),
  db.Column('role_id', db.Integer, db.ForeignKey(Role.id), primary_key=True)
)

Ideally, what I want to do is change the __repr__ of my db to print something like the following for a given db:

<Model 'User'>
id (primary key)
username
roles -> MANY-TO-MANY relationship with <Model 'Roles'>

<Model 'Post'>
id (primary_key)
html
author_id -> 'User.id'
author -> ONE-TO-MANY relationship with <Model 'User'>

<Model 'Role'>
id (primary key)
name
MANY TO MANY relationship with <Model 'User'>

is such a thing possible?

to add my contribution, I was able to make it print ALL the tables and their columns, but am having trouble pretty printing the relationships and removing the relationship tables.

>>> from app import db
>>> inspector = db.inspect(db.engine)
>>> for table in inspector.get_table_names():
        print("<Model '{}'".format(table))
        for column in inspector.get_columns(table):
            print(column['name'])


问:
How do I plot a bar graph using Pandas?
I have pandas data frame like this

```<code>a  b  c  d  e  f  label
1  3  4  5  6  7    1
2  2  5  7  5  7    0
4  7  9  0  8  7    1
6  9  4  7  3  8    1
7  0  9  8  7  6    0
</code>```

I want a bar graph which looks something like this - :

I have tried using hist() function from pandas but I am not able to figure out how do I include label in the bar graph to get the following graph like the one in the image.

答:
Try

```<code>df.groupby('label').a.value_counts().unstack(0, fill_value=0).plot.bar()
</code>```

Consider the dataframe df

```<code>np.random.seed([3,1415])
df = pd.DataFrame(
    np.random.randint(10, size=(50, 6)),
    columns=list('abcdef')
).assign(label=np.random.randint(2, size=50))

print(df.head())

   a  b  c  d  e  f  label
0  0  2  7  3  8  7      0
1  0  6  8  6  0  2      0
2  0  4  9  7  3  2      0
3  4  3  3  6  7  7      0
4  4  5  3  7  5  9      1
</code>```

demo

```<code>df.groupby('label').a.value_counts().unstack(0, fill_value=0).plot.bar()
</code>```

Title: How do I plot a bar graph using Pandas?

Body:
I have pandas data frame like this

a  b  c  d  e  f  label
1  3  4  5  6  7    1
2  2  5  7  5  7    0
4  7  9  0  8  7    1
6  9  4  7  3  8    1
7  0  9  8  7  6    0

I want a bar graph which looks something like this - :

I have tried using hist() function from pandas but I am not able to figure out how do I include label in the bar graph to get the following graph like the one in the image.

Body:
Try

df.groupby('label').a.value_counts().unstack(0, fill_value=0).plot.bar()

Consider the dataframe df

np.random.seed([3,1415])
df = pd.DataFrame(
    np.random.randint(10, size=(50, 6)),
    columns=list('abcdef')
).assign(label=np.random.randint(2, size=50))

print(df.head())

   a  b  c  d  e  f  label
0  0  2  7  3  8  7      0
1  0  6  8  6  0  2      0
2  0  4  9  7  3  2      0
3  4  3  3  6  7  7      0
4  4  5  3  7  5  9      1

demo

df.groupby('label').a.value_counts().unstack(0, fill_value=0).plot.bar()


问:
Should I use real or sample data for unit tests?
I'm writing a parser for the output of a legacy application, and since there are no specs on the file syntax I've got as many samples of these files as I could.

Now I'm writing the unit tests before implementing the parser (because there is no other sane way to do this) but I'm not sure whether I should:

use the real files produced by the application, reading from them and comparing the output with the output that I would store in json format in another file.

or create a sample string with the tokens and possibilities I want to test and a dict (this is python) with the expected output.

I'm inclined to use the second alternative because I would test only what I need to, without all the "real-world" data included on the actual files, but I'm afraid I could forget to test for one possibility or another.

What do you think?

答:
You should be careful using production data in testing scenarios.  It could be a disaster if all your users got an email from a test environment, for example.  Its also probably unethical in certain scenarios for developers to have access to prod data, even if there is no way for the users to know this.  Think medical, bank, college grades types scenarios.

My answer is you should use data that is close to prod data.  If you want to use the actual prod data, you need to scrub it for the above scenarios.

ContentLicense: CC BY-SA 2.5


问:
issue while printing the variable to html page
I am trying to get the first name of the user in the ajax method and trying to print it on the html page but it is not getting printed

this is my html:

```<code><div ng-app="app" ng-controller="VolController">
<div class="account-action">

<h3 style="display:inline;"><img class="img"  align="left" src="images/u11.png">
    <p style="color:white">   Welcome {{first_name}}<p></h3>
</div>
</code>```

this is my controller:

```<code>    app.controller('VolController',['$scope','$sessionStorage','$state',function($scope,$sessionStorage,$state){

    var b=sessionStorage.getItem("userid");

    var a="http://localhost:8080/volunteers/"+b;

        $.ajax({
    type:'GET',
    url:a,

    success:function(data){
     console.log(JSON.stringify(data));
    $scope.volunteer=data;
    $scope.first_name=JSON.stringify($scope.volunteer.VolunteersDTO.first_name);

    console.log(data);

    },
    error:function(data){
        alert(data);
        },
    dataType:"json",
    contentType:"application/json",
})

}]);
</code>```

Question Updated!!!!

答:
Don't make ajax call using jquery $.ajax. Please make ajax call using $http service of angularjs.

$http.get(url);

Do not forget adding $http service as dependedency in angular.

Body:
I am trying to get the first name of the user in the ajax method and trying to print it on the html page but it is not getting printed

this is my html:

   Welcome {{first_name}}

this is my controller:

    app.controller('VolController',['$scope','$sessionStorage','$state',function($scope,$sessionStorage,$state){

    var b=sessionStorage.getItem("userid");

    var a="http://localhost:8080/volunteers/"+b;

        $.ajax({
    type:'GET',
    url:a,

    success:function(data){
     console.log(JSON.stringify(data));
    $scope.volunteer=data;
    $scope.first_name=JSON.stringify($scope.volunteer.VolunteersDTO.first_name);

    console.log(data);

    },
    error:function(data){
        alert(data);
        },
    dataType:"json",
    contentType:"application/json",
})

}]);

Question Updated!!!!


问:
Call json.Unmarshal inside UnmarshalJSON function without causing stack overflow
I wanted to perform some additional steps for initializing a data structure inside my implementation UnmarshalJSON. Calling json.Unmarshal(b, type) inside that implementation, naturally, causes a stack overflow.

The JSON decoder is continiously trying to look up, if there is a custom UnmarshalJSON implementation which then again, calls json.Unmarshal.

Is there another way to do this? Just call the underlying default implementation without causing this?

答:
An easy and common way to avoid this / protect from it is to create a new type with the type keyword, and use a type conversion to pass a value of this type (the value may be your original value, type conversion is possible because the new type has the original type as its underlying type).

This works because the type keyword creates a new type, and the new type will have zero methods (it does not "inherit" the methods of the underlying type).

Does this incur some run-time overhead? No. Quoting from Spec: Conversions:

Specific rules apply to (non-constant) conversions between numeric types or to and from a string type. These conversions may change the representation of x and incur a run-time cost. All other conversions only change the type but not the representation of x.

Let's see an example. We have a Person type with a numeric Age, and we want to make sure the Age cannot be negative (less than 0).

```<code>type Person struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

func (p *Person) UnmarshalJSON(data []byte) error {
    type person2 Person
    if err := json.Unmarshal(data, (*person2)(p)); err != nil {
        return err
    }

    // Post-processing after unmarshaling:
    if p.Age < 0 {
        p.Age = 0
    }
    return nil
}
</code>```

Testing it:

```<code>var p *Person
fmt.Println(json.Unmarshal([]byte(`{"name":"Bob","age":10}`), &p))
fmt.Println(p)

fmt.Println(json.Unmarshal([]byte(`{"name":"Bob","age":-1}`), &p))
fmt.Println(p)
</code>```

Output (try it on the Go Playground):

```<code><nil>
&{Bob 10}
<nil>
&{Bob 0}
</code>```

Of course the same technique works for custom marshaling (MarshalJSON()) too:

```<code>func (p *Person) MarshalJSON() ([]byte, error) {
    // Pre-processing before marshaling:
    if p.Age < 0 {
        p.Age = 0
    }

    type person2 Person
    return json.Marshal((*person2)(p))
}
</code>```

Testing it:

```<code>p = &Person{"Bob", 10}
fmt.Println(json.NewEncoder(os.Stdout).Encode(p))
p = &Person{"Bob", -1}
fmt.Println(json.NewEncoder(os.Stdout).Encode(p))
</code>```

Output (on the same Go Playground example):

```<code>{"name":"Bob","age":10}
<nil>
{"name":"Bob","age":0}
<nil>
</code>```

A very similar issue is when you define the String() string method for custom text representation for the fmt package, and you want to use the default string representation which you modify. Read more about it here: The difference between t and *t

Body:
An easy and common way to avoid this / protect from it is to create a new type with the type keyword, and use a type conversion to pass a value of this type (the value may be your original value, type conversion is possible because the new type has the original type as its underlying type).

This works because the type keyword creates a new type, and the new type will have zero methods (it does not "inherit" the methods of the underlying type).

Does this incur some run-time overhead? No. Quoting from Spec: Conversions:

Specific rules apply to (non-constant) conversions between numeric types or to and from a string type. These conversions may change the representation of x and incur a run-time cost. All other conversions only change the type but not the representation of x.

Let's see an example. We have a Person type with a numeric Age, and we want to make sure the Age cannot be negative (less than 0).

type Person struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

func (p *Person) UnmarshalJSON(data []byte) error {
    type person2 Person
    if err := json.Unmarshal(data, (*person2)(p)); err != nil {
        return err
    }

    // Post-processing after unmarshaling:
    if p.Age < 0 {
        p.Age = 0
    }
    return nil
}

Testing it:

var p *Person
fmt.Println(json.Unmarshal([]byte(`{"name":"Bob","age":10}`), &p))
fmt.Println(p)

fmt.Println(json.Unmarshal([]byte(`{"name":"Bob","age":-1}`), &p))
fmt.Println(p)

Output (try it on the Go Playground):

<nil>
&{Bob 10}
<nil>
&{Bob 0}

Of course the same technique works for custom marshaling (MarshalJSON()) too:

func (p *Person) MarshalJSON() ([]byte, error) {
    // Pre-processing before marshaling:
    if p.Age < 0 {
        p.Age = 0
    }

    type person2 Person
    return json.Marshal((*person2)(p))
}

Testing it:

p = &Person{"Bob", 10}
fmt.Println(json.NewEncoder(os.Stdout).Encode(p))
p = &Person{"Bob", -1}
fmt.Println(json.NewEncoder(os.Stdout).Encode(p))

Output (on the same Go Playground example):

{"name":"Bob","age":10}
<nil>
{"name":"Bob","age":0}
<nil>

A very similar issue is when you define the String() string method for custom text representation for the fmt package, and you want to use the default string representation which you modify. Read more about it here: The difference between t and *t

ContentLicense: CC BY-SA 4.0


问:
Issue reading in a char array using sscanf in octal using either C or C++
When trying to read in the octal value for "24" to an unsigned int, I get 0. Simply passing in the decimal value as a char array works.

I need the final value as a 32 bit unsigned int. The initial value is read in from a binary file.

MCVE

simple.cpp

```<code>#include <iostream>
#include <cstdlib>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
    char count[4] = "\030\000\000"; // Just "24" works
    __uint32_t value;
    sscanf(count, "%x", &value);
    fprintf(stderr, "%x", value);
    return 0;
}
</code>```

Compiled and executed using

```<code>$ g++ simple.cpp -g
$ ./a.out
0
$ g++ --version
g++ (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609
</code>```

答:
The octal value 030 is a single character representing the special "CAN" (Cancel) control character in ASCII encoding (which is the most common encoding for the English alphabet and digits and punctuation).

When you use scanf (or its sibling sscanf) it will try to read digits, which in the ASCII encoding are the values 060 to 071 (for the digits 0 to 9, inclusive).

To be able to use sscanf to read the number 24 you need to the two characters '2' and '4'. I.e. "24" (or "\062\064").

If you want to convert the single character '\030' to the integer value 24, then just do e.g.

```<code>value = count[0];
</code>```

Body:
When trying to read in the octal value for "24" to an unsigned int, I get 0. Simply passing in the decimal value as a char array works.

I need the final value as a 32 bit unsigned int. The initial value is read in from a binary file.

MCVE

simple.cpp

#include <iostream>
#include <cstdlib>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
    char count[4] = "\030\000\000"; // Just "24" works
    __uint32_t value;
    sscanf(count, "%x", &value);
    fprintf(stderr, "%x", value);
    return 0;
}

Compiled and executed using

$ g++ simple.cpp -g
$ ./a.out
0
$ g++ --version
g++ (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609

Body:
The octal value 030 is a single character representing the special "CAN" (Cancel) control character in ASCII encoding (which is the most common encoding for the English alphabet and digits and punctuation).

When you use scanf (or its sibling sscanf) it will try to read digits, which in the ASCII encoding are the values 060 to 071 (for the digits 0 to 9, inclusive).

To be able to use sscanf to read the number 24 you need to the two characters '2' and '4'. I.e. "24" (or "\062\064").

If you want to convert the single character '\030' to the integer value 24, then just do e.g.

value = count[0];


问:
Return mulitple string is not working
I want to return multiple string from the below function. How to do that</p>

```<code>public static string GETSTATE_SAP(string SAP)
    {
        string strState = "";
        string strSiteAdd = "";
        string strLatitude = "";
        string strLongtiude = "";
        try
        {
            OracleConnection Oraconn = new OracleConnection(ConfigurationManager.ConnectionStrings["ConnectionStringAPPSAPID"].ConnectionString);
            Oraconn.Open();
            OracleCommand cmd = new OracleCommand("Select STATE, SITE_NAME, SITE_ADDRESS, latitude, longitude from R4G_OSP.UBR where SAP_ID = '" + SAP + "'", Oraconn);
            OracleDataAdapter da = new OracleDataAdapter(cmd);
            DataTable dtSap = new DataTable();
            da.Fill(dtSap);
            strState = Convert.ToString(dtSap.Rows[0][0]);
            strSiteAdd = Convert.ToString(dtSap.Rows[0][0]);
            strLatitude = Convert.ToString(dtSap.Rows[0][0]);
            strLongtiude = Convert.ToString(dtSap.Rows[0][0]);
        }
        catch (Exception)
        {
        }
        return strState, strSiteAdd, strLatitude, strLongtiude;
    }
</code>```

答:
You can choose any one from  following

Create a new class say location with these members and populate this in your function and your function will return it.

public class location{
 public string strState = "";
 public string strSiteAdd = "";
 public string strLatitude = "";
 public string strLongtiude = "";
}

```<code>public static location GETSTATE_SAP(string SAP)
{
    _location = new location() ;
    try
    {

     _location.strState = Convert.ToString(dtSap.Rows[0][0]);
        _location.strSiteAdd = Convert.ToString(dtSap.Rows[0][0]);
        _location.strLatitude = Convert.ToString(dtSap.Rows[0][0]);
        _location.strLongtiude = Convert.ToString(dtSap.Rows[0][0]);
}

return _location;
</code>```

another option is dictionary

```<code>public static Dictionary<string,string> GETSTATE_SAP(string SAP) {

 Dictionary<string,string> _location = new dictionary<string,string>
_location.add("strState", Convert.ToString(dtSap.Rows[0][0]));`
</code>```

third one is datatable
  datatable _location = new datatable();
  _location.add("strState"); // add all columns
 _location.rows.add(Convert.ToString(dtSap.Rows[0][0]), , , ,..);

Return dynamic object

public object MyDynamicObject()
        {
            dynamic obj = new ExpandoObject();
            return obj;
        }

```<code>public static object GETSTATE_SAP(string SAP)
{
 object _location = MyDynamicObject();
try
        {

         _location.strState = Convert.ToString(dtSap.Rows[0][0]);
            _location.strSiteAdd = Convert.ToString(dtSap.Rows[0][0]);
            _location.strLatitude = Convert.ToString(dtSap.Rows[0][0]);
            _location.strLongtiude = Convert.ToString(dtSap.Rows[0][0]);
    }

    return _location;`
</code>```

Title: Return mulitple string is not working

Body:
I want to return multiple string from the below function. How to do that

public static string GETSTATE_SAP(string SAP)
    {
        string strState = "";
        string strSiteAdd = "";
        string strLatitude = "";
        string strLongtiude = "";
        try
        {
            OracleConnection Oraconn = new OracleConnection(ConfigurationManager.ConnectionStrings["ConnectionStringAPPSAPID"].ConnectionString);
            Oraconn.Open();
            OracleCommand cmd = new OracleCommand("Select STATE, SITE_NAME, SITE_ADDRESS, latitude, longitude from R4G_OSP.UBR where SAP_ID = '" + SAP + "'", Oraconn);
            OracleDataAdapter da = new OracleDataAdapter(cmd);
            DataTable dtSap = new DataTable();
            da.Fill(dtSap);
            strState = Convert.ToString(dtSap.Rows[0][0]);
            strSiteAdd = Convert.ToString(dtSap.Rows[0][0]);
            strLatitude = Convert.ToString(dtSap.Rows[0][0]);
            strLongtiude = Convert.ToString(dtSap.Rows[0][0]);
        }
        catch (Exception)
        {
        }
        return strState, strSiteAdd, strLatitude, strLongtiude;
    }

Body:
You can choose any one from  following

Create a new class say location with these members and populate this in your function and your function will return it.

public class location{
 public string strState = "";
 public string strSiteAdd = "";
 public string strLatitude = "";
 public string strLongtiude = "";
}

public static location GETSTATE_SAP(string SAP)
{
    _location = new location() ;
    try
    {

     _location.strState = Convert.ToString(dtSap.Rows[0][0]);
        _location.strSiteAdd = Convert.ToString(dtSap.Rows[0][0]);
        _location.strLatitude = Convert.ToString(dtSap.Rows[0][0]);
        _location.strLongtiude = Convert.ToString(dtSap.Rows[0][0]);
}

return _location;

another option is dictionary

public static Dictionary<string,string> GETSTATE_SAP(string SAP) {

 Dictionary<string,string> _location = new dictionary<string,string>
_location.add("strState", Convert.ToString(dtSap.Rows[0][0]));`

third one is datatable
  datatable _location = new datatable();
  _location.add("strState"); // add all columns
 _location.rows.add(Convert.ToString(dtSap.Rows[0][0]), , , ,..);

Return dynamic object

public object MyDynamicObject()
        {
            dynamic obj = new ExpandoObject();
            return obj;
        }

public static object GETSTATE_SAP(string SAP)
{
 object _location = MyDynamicObject();
try
        {

         _location.strState = Convert.ToString(dtSap.Rows[0][0]);
            _location.strSiteAdd = Convert.ToString(dtSap.Rows[0][0]);
            _location.strLatitude = Convert.ToString(dtSap.Rows[0][0]);
            _location.strLongtiude = Convert.ToString(dtSap.Rows[0][0]);
    }

    return _location;`


问:
Changing value of a variable on OnClick Android
I have 2 buttons in my layout when user presses button 1 the value of 'number' should change to '2' and when the user presses button 2 the value of 'number' should change to '1'.But the value does not change.
Here is my code :

```<code>public class test extends AppCompatActivity{

public  int number ;

private Button btn1;
private Button btn2;
@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.testing);

    btn1=(Button)findViewById(R.id.btn1);
    btn2=(Button)findViewById(R.id.btn2);

    test();
}

void test()
{

  if(number<1) {
    number = 1;
    }

        Log.e("number value : ",String.valueOf(number));

    if(number==1)
    {

         btn1.setOnClickListener(new View.OnClickListener() {

         @Override
         public void onClick(View arg0) {
          number=2;

             Log.e("number value : ",String.valueOf(number));

         }

    });

    }

     if(number==2)
    {
     btn2.setOnClickListener(new View.OnClickListener() {

         @Override
        public void onClick(View arg0) {
             number=1;
             Log.e("number value : ",String.valueOf(number));

    }

    });

    }

    }
</code>```

Log.e outputs ``` E/number value :: 2``` when I press btn1 but when i press btn2 nothing happens and only btn1 works

答:
try this</p>

```<code> public class test extends AppCompatActivity{

    public  int number ;

    private Button btn1;
    private Button btn2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.testing);

        btn1=(Button)findViewById(R.id.btn1);
        btn2=(Button)findViewById(R.id.btn2);

        test();

         btn1.setOnClickListener(new View.OnClickListener() {

         @Override
         public void onClick(View arg0) {
          if(number==1){
          number=2;
            }
             Log.e("number value : ",String.valueOf(number));

         }
    });

     btn2.setOnClickListener(new View.OnClickListener() {

         @Override
        public void onClick(View arg0) {
        if(number==2){
             number=1;
          }
             Log.e("number value : ",String.valueOf(number));

    }

    });

}

    void test()
    {

      if(number<1) {
        number = 1;
        }

            Log.e("number value : ",String.valueOf(number));

        }

 }
</code>```

Body:
I have 2 buttons in my layout when user presses button 1 the value of 'number' should change to '2' and when the user presses button 2 the value of 'number' should change to '1'.But the value does not change.
Here is my code :

public class test extends AppCompatActivity{

public  int number ;

private Button btn1;
private Button btn2;
@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.testing);

    btn1=(Button)findViewById(R.id.btn1);
    btn2=(Button)findViewById(R.id.btn2);

    test();
}

void test()
{

  if(number<1) {
    number = 1;
    }

        Log.e("number value : ",String.valueOf(number));

    if(number==1)
    {

         btn1.setOnClickListener(new View.OnClickListener() {

         @Override
         public void onClick(View arg0) {
          number=2;

             Log.e("number value : ",String.valueOf(number));

         }

    });

    }

     if(number==2)
    {
     btn2.setOnClickListener(new View.OnClickListener() {

         @Override
        public void onClick(View arg0) {
             number=1;
             Log.e("number value : ",String.valueOf(number));

    }

    });

    }

    }

Log.e outputs
 E/number value :: 2
 when I press btn1 but when i press btn2 nothing happens and only btn1 works

Body:
try this

 public class test extends AppCompatActivity{

    public  int number ;

    private Button btn1;
    private Button btn2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.testing);

        btn1=(Button)findViewById(R.id.btn1);
        btn2=(Button)findViewById(R.id.btn2);

        test();

         btn1.setOnClickListener(new View.OnClickListener() {

         @Override
         public void onClick(View arg0) {
          if(number==1){
          number=2;
            }
             Log.e("number value : ",String.valueOf(number));

         }
    });

     btn2.setOnClickListener(new View.OnClickListener() {

         @Override
        public void onClick(View arg0) {
        if(number==2){
             number=1;
          }
             Log.e("number value : ",String.valueOf(number));

    }

    });

}

    void test()
    {

      if(number<1) {
        number = 1;
        }

            Log.e("number value : ",String.valueOf(number));

        }

 }


问:
Django POST data in request.body but can not store in variable
I am posting some raw JSON to my backend

```<code>{
    "access_token": "hU5C7so4reJOYTzPyhKPs8PWq07tb",
    "id": 3,
    "order_details": [{"meal_id": 1, "quantity": 3}, {"meal_id": 2, "quantity": 2}]
}
</code>```

However when I try to

```<code>print (request.POST.get("access_token"))
</code>```

I receive None

But, when I do

```<code>print (request.body)
</code>```

The values seem to there:

b'{\n\t"access_token": "hU5C7so4reJOYTzPyhKPs8PWq07tb",\n\t"id": 3,\n\t",\n\t"order_details": [{"meal_id": 1, "quantity": 3}, {"meal_id": 2, "quantity": 2}]\n}'

I am using Postman to post the data.

I want to store the access token into some variable like so:

```<code>access_token = request.POST.get("access_token")
</code>```

with the post data

I am still fairly new to Django, any help would be great.

答:
you need to decode the json first:

```<code>import json
variable = urlopen(request).read().decode('utf-8')
json_obj = json.loads(variable)
</code>```

then you can retrive your informations

```<code>for i in json_obj:
   token = i['access_token']
   order_details = i['order_details']
</code>```

Hope this help

Body:
I am posting some raw JSON to my backend

{
    "access_token": "hU5C7so4reJOYTzPyhKPs8PWq07tb",
    "id": 3,
    "order_details": [{"meal_id": 1, "quantity": 3}, {"meal_id": 2, "quantity": 2}]
}

However when I try to

print (request.POST.get("access_token"))

I receive None

But, when I do

print (request.body)

The values seem to there:

b'{\n\t"access_token": "hU5C7so4reJOYTzPyhKPs8PWq07tb",\n\t"id": 3,\n\t",\n\t"order_details": [{"meal_id": 1, "quantity": 3}, {"meal_id": 2, "quantity": 2}]\n}'

I am using Postman to post the data.

I want to store the access token into some variable like so:

access_token = request.POST.get("access_token")

with the post data

I am still fairly new to Django, any help would be great.

Body:
you need to decode the json first:

import json
variable = urlopen(request).read().decode('utf-8')
json_obj = json.loads(variable)

then you can retrive your informations

for i in json_obj:
   token = i['access_token']
   order_details = i['order_details']

Hope this help


问:
Exception in registering FFEngine
I am using FFEngine for playing video via rtmp. I am getting the following exception:

__NSCFString objectFromJSONString]: unrecognized selector sent to instance 0xa039d80 on the line
  RegisterFFEngine(@"yQ2oiBQRbXoo35veDico9ggF4ARFxRdjq3yiIvBltwIPe/SgphrthjEVCzt6mtAfejcyM1fkbDdY+wE8j7oeJLK+u1KEO7IgfEDQ+KrnsNc=")

I don't know whether the registration key is incorrect or there is some other issue. Need some help.

答:
when you use FFEngine framework , you have to add “-ObjC” in your project. below is the simple step add to “-ObjC” in your project :

1) Select the project file from the project navigator on the far left side of the window.

2) Select the target for where you want to add the linker flag.

3) Select the “Build Settings” tab

4) Choose “All” to show all Build Settings.

5) Scroll down to the “Linking” section, and double-click to the right of where it says “Other Linking Flags”.

6) A box will appear, Click on the “+” button to add a new linker flag.

7) Type “-ObjC” (no quotes) and press enter.

when you add -ObjC then after error will solved.

Title: Exception in registering FFEngine


问:
GNUplot: string value in ternary operator
Coming back to an old project and have obviously forgotten something here.
Datafile:

```<code>2017-03-31 14:38   6.42 feet  High Tide
2017-03-31 20:40   -0.30 feet  Low Tide
2017-04-01 02:56   6.92 feet  High Tide
2017-04-01 06:34   Full Moon
2017-04-01 09:19  -0.58 feet  Low Tide
2017-04-01 15:33   6.17 feet  High Tide
</code>```

When I plot as follows, all works fine except the ternary operator to test for the string(s) in strcol(3):

```<code>set terminal aqua size 950,594
set timefmt "%Y-%m-%d %H:%M"
unset key
set samples 1000
set xtics 86400
set x2tics 86400
set xtics nomirror font "Gill Sans Light,14" tc rgb "blue"
set grid ytics back
set grid x2tics
set format x "%a"
set format x2 "%d"
set xdata time
set x2data time
set yrange [-1:7.5]
set xzeroaxis lt 1 lw 1 lc rgb "red"
myDate(col1,col2)=sprintf("%s %s",strcol(1),strcol(2))
myLabel(col3,col2) = sprintf("%s ft.\n%s",strcol(col3),strcol(col2))
plot "tidefiles-test2.txt" \
u (myDate(1,2)):3:((strcol(5) eq "High") ? (myLabel(3,2)) :1/0) with labels font "Gill Sans Light,12" offset 0,-2  tc rgb "blue",\
"" u (myDate(1,2)):3:((strcol(5) eq "Low") ? (myLabel(3,2)) :1/0) with labels font "Gill Sans Light,12" offset 0,+2  tc rgb "red",\
"" u (myDate(1,2)):3:(strcol(3) eq "Full") ?  ("●"):1/0 w labels left font "Symbola,48" offset -4,0,\
"" u (myDate(1,2)):3 lc rgb "green" lw 1  sm cspl notitle
</code>```

答:
The line with the string Full doesn't have a y-value. So, when the condition strcol(3) eq "Full" is fulfilled, at the same time the actual y-value is not a valid number and so that point is also skipped.

Using e.g.

```<code>plot "tidefiles-test2.txt" \
    "" u (myDate(1,2)):(strcol(3) eq "Full" ? 0 : $3):((strcol(3) eq "Full") ? ("●"):1/0) w labels left font "Symbola,24" offset -4,0
</code>```

works fine, but requires you to use a hard-coded y-value. Otherwise you must add an appropriate y-value in your data file for the "Full"-case.

Body:
Coming back to an old project and have obviously forgotten something here.
Datafile:

2017-03-31 14:38   6.42 feet  High Tide
2017-03-31 20:40   -0.30 feet  Low Tide
2017-04-01 02:56   6.92 feet  High Tide
2017-04-01 06:34   Full Moon
2017-04-01 09:19  -0.58 feet  Low Tide
2017-04-01 15:33   6.17 feet  High Tide

When I plot as follows, all works fine except the ternary operator to test for the string(s) in strcol(3):

set terminal aqua size 950,594
set timefmt "%Y-%m-%d %H:%M"
unset key
set samples 1000
set xtics 86400
set x2tics 86400
set xtics nomirror font "Gill Sans Light,14" tc rgb "blue"
set grid ytics back
set grid x2tics
set format x "%a"
set format x2 "%d"
set xdata time
set x2data time
set yrange [-1:7.5]
set xzeroaxis lt 1 lw 1 lc rgb "red"
myDate(col1,col2)=sprintf("%s %s",strcol(1),strcol(2))
myLabel(col3,col2) = sprintf("%s ft.\n%s",strcol(col3),strcol(col2))
plot "tidefiles-test2.txt" \
u (myDate(1,2)):3:((strcol(5) eq "High") ? (myLabel(3,2)) :1/0) with labels font "Gill Sans Light,12" offset 0,-2  tc rgb "blue",\
"" u (myDate(1,2)):3:((strcol(5) eq "Low") ? (myLabel(3,2)) :1/0) with labels font "Gill Sans Light,12" offset 0,+2  tc rgb "red",\
"" u (myDate(1,2)):3:(strcol(3) eq "Full") ?  ("●"):1/0 w labels left font "Symbola,48" offset -4,0,\
"" u (myDate(1,2)):3 lc rgb "green" lw 1  sm cspl notitle

Body:
The line with the string Full doesn't have a y-value. So, when the condition strcol(3) eq "Full" is fulfilled, at the same time the actual y-value is not a valid number and so that point is also skipped.

Using e.g.

plot "tidefiles-test2.txt" \
    "" u (myDate(1,2)):(strcol(3) eq "Full" ? 0 : $3):((strcol(3) eq "Full") ? ("●"):1/0) w labels left font "Symbola,24" offset -4,0

works fine, but requires you to use a hard-coded y-value. Otherwise you must add an appropriate y-value in your data file for the "Full"-case.


问:
how to open excel on foreground in VBA using powerpoint
i am trying to open an excel file in a powerpoint presentation.
this is my code:

```<code>Sub diversestickersKoole()

Dim xlApp As Object
Dim xlWorkBook As Object

Set xlApp = CreateObject("Excel.Application")

xlApp.Visible = True
Set xlWorkBook = xlApp.Workbooks.Open("V:\Oliedocs\Koole\Stickers Scheepstanks Koole.xltm", True, False)

Set xlApp = Nothing
Set xlWorkBook = Nothing
End Sub
</code>```

the excel file is opening in the background. this must be in the foreground.

can someone help me?

答:
since you seem not interested in keeping Excel object and its derived ones , you may want to code like follows</p>

```<code>Sub diversestickersKoole()
    With CreateObject("Excel.Application") '<--| create a new Excel instance and reference it (all its derived objects will be reached by a 'dot')
        .Visible = True
        .WindowState = -4137 '<--| maximize Excel window
        .Workbooks.Open("V:\Oliedocs\Koole\Stickers Scheepstanks Koole.xltm", True, False).Activate
    End With
End Sub
</code>```

Body:
i am trying to open an excel file in a powerpoint presentation.
this is my code:

Sub diversestickersKoole()

Dim xlApp As Object
Dim xlWorkBook As Object

Set xlApp = CreateObject("Excel.Application")

xlApp.Visible = True
Set xlWorkBook = xlApp.Workbooks.Open("V:\Oliedocs\Koole\Stickers Scheepstanks Koole.xltm", True, False)

Set xlApp = Nothing
Set xlWorkBook = Nothing
End Sub

the excel file is opening in the background. this must be in the foreground.

can someone help me?

Body:
since you seem not interested in keeping Excel object and its derived ones , you may want to code like follows

Sub diversestickersKoole()
    With CreateObject("Excel.Application") '<--| create a new Excel instance and reference it (all its derived objects will be reached by a 'dot')
        .Visible = True
        .WindowState = -4137 '<--| maximize Excel window
        .Workbooks.Open("V:\Oliedocs\Koole\Stickers Scheepstanks Koole.xltm", True, False).Activate
    End With
End Sub


问:
I have to automate PDF document in IE
I never tried performing PDF. When I click on the view link the PDF open I have to save the document and verify,But not sure how to download the file because we don't have download option.

once i click on view PDF document open

this how it open

答: Check if you can edit the headers in DMViewDocument.do and change the Content-Disposition from inline to attachment</p>

Title: I have to automate PDF document in IE


问:
How to identify an anonymous function
I have a class that creates a List<Action<int>> and holds on to them until a later time. This class can add and remove delegates from this list. This works well as long as people don't get too fancy. To combat anonymous function (which can't be removed) I check against the target of the delegate being null. If its null I throw an exception. The problem comes in when there is an anonymous delegate that contains a function. This has a target, but is just as unremovable. The simplified code below illustrates my issues

```<code> public class MyDelegateContainer
 {
    List<Action<int>> m_Container = new List<Action<int>>();

    public void Add(Action<int> del)
    {
        if (del.Target == null)
        {
            throw new Exception("No static handlers");
        }
        m_Container.Add(del);
    }

    public bool Remove(Action<int> del)
    {
        if (m_Container.Contains(del))
        {
            m_Container.Remove(del);
            return true;
        }

        return false;
    }
}

public class MyFakeActionClass
{
    public void Test(int temp) { }
}

class Program
{
    static void Main(string[] args)
    {
        bool removed = false;
        int counter = 0;
        MyDelegateContainer container = new MyDelegateContainer();
        MyFakeActionClass fake = new MyFakeActionClass();
        //container.Add(p => { }); //Throws, this is what I want to happen
        container.Add(fake.Test); //Works, this is the use case
        removed = container.Remove(fake.Test); //Works, this is the use case
        Debug.Assert(removed);
        container.Add(p => { fake.Test(p); counter++; }); //Works but I would like it not to
        removed = container.Remove(p => { fake.Test(p); counter++; }); //doesn't work
        Debug.Assert(removed);
    }
}
</code>```

I need some way to identify

```<code>   p => { fake.Test(p); counter++; }
</code>```

is an anonymous function so I can throw if someone tries it. Thanks for any help

EDIT: I should note that I could use an Action<int> variable for the anonymous function and everything would work, but the Add and Remove are never in the same scope in practice.

答:
I would use introspection to check the names of the methods.

Anonymous methods typically have very predictable names. (I don't remember the exact format, but run some tests, and it should be obvious).

The drawback would be that if anyone created a non-anonymous method, but decided to name it anonMethod123 (or whatever the format is...) It would be falsely rejected.

Title: How to identify an anonymous function

Body:
I have a class that creates a List<Action<int>> and holds on to them until a later time. This class can add and remove delegates from this list. This works well as long as people don't get too fancy. To combat anonymous function (which can't be removed) I check against the target of the delegate being null. If its null I throw an exception. The problem comes in when there is an anonymous delegate that contains a function. This has a target, but is just as unremovable. The simplified code below illustrates my issues

 public class MyDelegateContainer
 {
    List<Action<int>> m_Container = new List<Action<int>>();

    public void Add(Action<int> del)
    {
        if (del.Target == null)
        {
            throw new Exception("No static handlers");
        }
        m_Container.Add(del);
    }

    public bool Remove(Action<int> del)
    {
        if (m_Container.Contains(del))
        {
            m_Container.Remove(del);
            return true;
        }

        return false;
    }
}

public class MyFakeActionClass
{
    public void Test(int temp) { }
}

class Program
{
    static void Main(string[] args)
    {
        bool removed = false;
        int counter = 0;
        MyDelegateContainer container = new MyDelegateContainer();
        MyFakeActionClass fake = new MyFakeActionClass();
        //container.Add(p => { }); //Throws, this is what I want to happen
        container.Add(fake.Test); //Works, this is the use case
        removed = container.Remove(fake.Test); //Works, this is the use case
        Debug.Assert(removed);
        container.Add(p => { fake.Test(p); counter++; }); //Works but I would like it not to
        removed = container.Remove(p => { fake.Test(p); counter++; }); //doesn't work
        Debug.Assert(removed);
    }
}

I need some way to identify

   p => { fake.Test(p); counter++; }

is an anonymous function so I can throw if someone tries it. Thanks for any help

EDIT: I should note that I could use an Action<int> variable for the anonymous function and everything would work, but the Add and Remove are never in the same scope in practice.


问:
Unable to import 'Rx' to my Angular 2 application
I am pretty new at Angular2. I am trying to learn it using a dummy app.

I have recently gone through a tutorial on RxJS and got a basic hold on Observables (or atleast I assume so). Based on that, I have an idea of returning a list of users from my array in service as a stream. I intent to use interval for it and display a kind  of lazy loading effect on screen.

My intention is something like:

```<code>getUsers() {
        return Rx.Observable.from(this.users); //want to add interval too on this
    }
</code>```

However, I am stuck at importing 'Rx' in to my service. Using 'Rx' without import obviously gives me error. The rest imports for Observables and operator works fine.

I went to node_modules and found there is a rx and a rxjs module too. But somehow using any of these below commands, I can't get rid of my error on Rx.

```<code>import 'rxjs/Rx';
import  Rx from 'rxjs/Rx';
import { Rx} from 'rx/Rx';
import { Rx} from 'rx';
</code>```

I went through few links on SO those say Rx is no longer bundled with Angular. However, I am working with the latest angular official seed and I do see rx and rxjs packages. I have a 5.0.1 version mentioned in package.json. Am I assuming something wrong here ??

Please let me know How does one work with creating custom observables using Rx in Angular 2.

Note: I have no issues working Observable return by Http service, just want to create a Observable from scratch using Array

答:
You import rxjs like this.

```<code>import Rx from 'rxjs';
</code>```

And in systemjs.config.js file place like this.

```<code> rxjs: {
    defaultExtension: 'js',
      main: 'Rx.js'
  }
</code>```

Body:
I am pretty new at Angular2. I am trying to learn it using a dummy app.

I have recently gone through a tutorial on RxJS and got a basic hold on Observables (or atleast I assume so). Based on that, I have an idea of returning a list of users from my array in service as a stream. I intent to use interval for it and display a kind  of lazy loading effect on screen.

My intention is something like:

getUsers() {
        return Rx.Observable.from(this.users); //want to add interval too on this
    }

However, I am stuck at importing 'Rx' in to my service. Using 'Rx' without import obviously gives me error. The rest imports for Observables and operator works fine.

I went to node_modules and found there is a rx and a rxjs module too. But somehow using any of these below commands, I can't get rid of my error on Rx.

import 'rxjs/Rx';
import  Rx from 'rxjs/Rx';
import { Rx} from 'rx/Rx';
import { Rx} from 'rx';

I went through few links on SO those say Rx is no longer bundled with Angular. However, I am working with the latest angular official seed and I do see rx and rxjs packages. I have a 5.0.1 version mentioned in package.json. Am I assuming something wrong here ??

Please let me know How does one work with creating custom observables using Rx in Angular 2.

Note: I have no issues working Observable return by Http service, just want to create a Observable from scratch using Array

Body:
You import rxjs like this.

import Rx from 'rxjs';

And in systemjs.config.js file place like this.

 rxjs: {
    defaultExtension: 'js',
      main: 'Rx.js'
  }


问:
How to Export & Import Existing User (with its Privileges!)
I have an existing MySQL instance (test), containing 2 databases and a few users each having different access privileges to each database.

I now need to duplicate one of the databases (into production) and the users associated with it.

Duplicating the database was easy:

Export:

```<code>mysqldump --no-data --tables -u root -p secondb >> secondb_schema.sql
</code>```

Import:

```<code>mysql -u root -p -h localhost secondb < secondb_schema.sql
</code>```

I didn't find, however, a straightforward way to export and import users, from the command line (either inside or outside mysql).

How do I export and import a user, from the command line?

Update: So far, I have found manual (and thus error prone) steps for accomplishing this:

```<code>-- lists all users
select user,host from mysql.user;
</code>```

Then find its grants:

```<code>-- find privilege granted to a particular user
show grants for 'root'@'localhost';
</code>```

Then manually create user with the grants listed in the result of the 'show grants' command above.

I prefer a safer, more automated way. Is there one?

答:
A PHP script to loop over your users to get the grant commands would be as such:

```<code>// Set up database root credentials
$host = 'localhost';
$user = 'root';
$pass = 'YOUR PASSWORD';
// ---- Do not edit below this ----
// Misc settings
header('Content-type: text/plain; Charset=UTF-8');
// Final import queries goes here
$export = array();
// Connect to database
try {
    $link = new PDO("mysql:host=$host;dbname=mysql", $user, $pass);
} catch (PDOException $e) {
    printf('Connect failed: %s', $e->getMessage());
    die();
}

// Get users from database
$statement = $link->prepare("select `user`, `host`, `password` FROM `user`");
$statement->execute();
while ($row = $statement->fetch())
{
    $user   = $row[0];
    $host   = $row[1];
    $pass   = $row[2];
    $export[] = "CREATE USER '{$user}'@'{$host}' IDENTIFIED BY '{$pass}'";
    // Fetch any permissions found in database
    $statement2 = $link->prepare("SHOW GRANTS FOR '{$user}'@'{$host}'");
    $statement2->execute();
    while ($row2 = $statement2->fetch())
    {
        $export[] = $row2[0];
    }
}

$link = null;
echo implode(";\n", $export);
</code>```

Gist: https://gist.github.com/zaiddabaeen/e88a2d10528e31cd6692

Body:
I have an existing MySQL instance (test), containing 2 databases and a few users each having different access privileges to each database.

I now need to duplicate one of the databases (into production) and the users associated with it.

Duplicating the database was easy:

Export:

mysqldump --no-data --tables -u root -p secondb >> secondb_schema.sql

Import:

mysql -u root -p -h localhost secondb < secondb_schema.sql

I didn't find, however, a straightforward way to export and import users, from the command line (either inside or outside mysql).

How do I export and import a user, from the command line?

Update: So far, I have found manual (and thus error prone) steps for accomplishing this:

-- lists all users
select user,host from mysql.user;

Then find its grants:

-- find privilege granted to a particular user
show grants for 'root'@'localhost';

Then manually create user with the grants listed in the result of the 'show grants' command above.

I prefer a safer, more automated way. Is there one?

Body:
A PHP script to loop over your users to get the grant commands would be as such:

// Set up database root credentials
$host = 'localhost';
$user = 'root';
$pass = 'YOUR PASSWORD';
// ---- Do not edit below this ----
// Misc settings
header('Content-type: text/plain; Charset=UTF-8');
// Final import queries goes here
$export = array();
// Connect to database
try {
    $link = new PDO("mysql:host=$host;dbname=mysql", $user, $pass);
} catch (PDOException $e) {
    printf('Connect failed: %s', $e->getMessage());
    die();
}

// Get users from database
$statement = $link->prepare("select `user`, `host`, `password` FROM `user`");
$statement->execute();
while ($row = $statement->fetch())
{
    $user   = $row[0];
    $host   = $row[1];
    $pass   = $row[2];
    $export[] = "CREATE USER '{$user}'@'{$host}' IDENTIFIED BY '{$pass}'";
    // Fetch any permissions found in database
    $statement2 = $link->prepare("SHOW GRANTS FOR '{$user}'@'{$host}'");
    $statement2->execute();
    while ($row2 = $statement2->fetch())
    {
        $export[] = $row2[0];
    }
}

$link = null;
echo implode(";\n", $export);

Gist: https://gist.github.com/zaiddabaeen/e88a2d10528e31cd6692


问:
Wave diagram in QT (functionality issues in logic)
Wave diagram in QT.. There was some functionality issues in logic. I tried a wave diagram logically using QPainter. Wave diagram is drawn perfectly but there was one line has drawn.. Any one help me to solve this problem.

//dialog.cpp

```<code>#include "dialog.h"
#include "ui_dialog.h"
#include <QtMath>
#include <QDebug>
#include <QDialog>
#include <QTGui>
#include <QtCore>

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);
}

Dialog::~Dialog()
{
    delete ui;
}

void Dialog::paintEvent(QPaintEvent *e)
{
    e->accept();

    float scale = 40;
    //boolean negativeX = true;
    float width = 500;
    float height = 108;

    QPainter painter(this);

    QPen linepen(Qt::red);
    linepen.setWidth(2);
    QPoint p1;
    QPoint p2;

    painter.setPen(linepen);

    float xx, yy, dx=4, x0=width / 2, y0=height / 2;

    //float iMax = (width - x0) / dx;
    float iMax = 63;

    //float iMin = negativeX ? -x0 / dx : 0;
    float iMin = -63;

    for (int i=iMin;i<=iMax;i++) {
           float x = x0+xx;
           float y = y0-yy;
         p1.setX(x);
         p1.setY(y);

         xx = dx*i;
         float xscl = xx/scale;
         yy = scale * qCos( 3* xscl );

           x = x0+xx;
           y = y0-yy;

         p2.setX(x);
         p2.setY(y);

         painter.drawLine(p1, p2);

     }

   }
</code>```

// dialog.h

```<code>protected:
    void paintEvent(QPaintEvent *e);
</code>```

// main.cpp

```<code>QApplication a(argc, argv);
Dialog w;
w.show();
</code>```

答:
Not sure (a) if this is what's causing your problem since you have undefined behaviour (meaning anything could happen) but, the first time through the loop, you use xx and yy before they've been given a value:

```<code>float xx, yy, ...                 // will be arbitrary value.
float iMax = 63;
float iMin = -63;
for (int i=iMin;i<=iMax;i++) {
   float x = x0+xx;               // shouldn't be using them here.
   float y = y0-yy;

   p1.setX(x);
   p1.setY(y);

   xx = dx*i;                     // not set until here.
   float xscl = xx/scale;
   yy = scale * qCos( 3* xscl );
</code>```

This may be a simple case of initialising them to zero before use, since that's likely to be the best offset for the initial point.

(a) It's certainly feasible that this is the case since the initial value of xx and yy may be such that it sets the initial point to the rightmost end of that straight line.

That means the initial line draw, far from being a small line forming part of the cosine wave, will be from that point to the leftmost point of that wave. You can check this by simply putting a break as the final statement within the for loop and seeing that the straight line is the only thing that appears.

You could also check it by actually debugging the code, either putting a breakpoint at the calculation of x and y and seeing what the xx and yy values are, or printing them out before each time you use them. Debugging skills are an invaluable tool in your arsenal.

If that is the case, setting xx and yy to zero before the loop starts should definitely fix your problem.

Body:
Wave diagram in QT.. There was some functionality issues in logic. I tried a wave diagram logically using QPainter. Wave diagram is drawn perfectly but there was one line has drawn.. Any one help me to solve this problem.

//dialog.cpp

#include "dialog.h"
#include "ui_dialog.h"
#include <QtMath>
#include <QDebug>
#include <QDialog>
#include <QTGui>
#include <QtCore>

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);
}

Dialog::~Dialog()
{
    delete ui;
}

void Dialog::paintEvent(QPaintEvent *e)
{
    e->accept();

    float scale = 40;
    //boolean negativeX = true;
    float width = 500;
    float height = 108;

    QPainter painter(this);

    QPen linepen(Qt::red);
    linepen.setWidth(2);
    QPoint p1;
    QPoint p2;

    painter.setPen(linepen);

    float xx, yy, dx=4, x0=width / 2, y0=height / 2;

    //float iMax = (width - x0) / dx;
    float iMax = 63;

    //float iMin = negativeX ? -x0 / dx : 0;
    float iMin = -63;

    for (int i=iMin;i<=iMax;i++) {
           float x = x0+xx;
           float y = y0-yy;
         p1.setX(x);
         p1.setY(y);

         xx = dx*i;
         float xscl = xx/scale;
         yy = scale * qCos( 3* xscl );

           x = x0+xx;
           y = y0-yy;

         p2.setX(x);
         p2.setY(y);

         painter.drawLine(p1, p2);

     }

   }

// dialog.h

protected:
    void paintEvent(QPaintEvent *e);

// main.cpp

QApplication a(argc, argv);
Dialog w;
w.show();

Body:
Not sure (a) if this is what's causing your problem since you have undefined behaviour (meaning anything could happen) but, the first time through the loop, you use xx and yy before they've been given a value:

float xx, yy, ...                 // will be arbitrary value.
float iMax = 63;
float iMin = -63;
for (int i=iMin;i<=iMax;i++) {
   float x = x0+xx;               // shouldn't be using them here.
   float y = y0-yy;

   p1.setX(x);
   p1.setY(y);

   xx = dx*i;                     // not set until here.
   float xscl = xx/scale;
   yy = scale * qCos( 3* xscl );

This may be a simple case of initialising them to zero before use, since that's likely to be the best offset for the initial point.

(a) It's certainly feasible that this is the case since the initial value of xx and yy may be such that it sets the initial point to the rightmost end of that straight line.

That means the initial line draw, far from being a small line forming part of the cosine wave, will be from that point to the leftmost point of that wave. You can check this by simply putting a break as the final statement within the for loop and seeing that the straight line is the only thing that appears.

You could also check it by actually debugging the code, either putting a breakpoint at the calculation of x and y and seeing what the xx and yy values are, or printing them out before each time you use them. Debugging skills are an invaluable tool in your arsenal.

If that is the case, setting xx and yy to zero before the loop starts should definitely fix your problem.


问: When using KaTeX, why put one

Title: When using KaTeX, why put one <script> in the head and one after the body?

Body:
See this example of the use of KaTeX on a Jekyll website.

Why is the KaTeX script in the head but the inline script that does the KaTeX rendering after the body?

If I am using KaTeX on my Github pages website, would it be better to put both scripts in the head with async or defer attributes as described in this StackOverflow question?

Body:
As you've already referred to: placing script

1) Placing one script tag in header means the stop everything before this script is loaded So, in your KaTeX example The author wants to emphasize in order for the example to work, katex.min file should be loaded and parsed first, until then, he doesn't want to load/parse any of the html content because, the the second <script> in body will fail if the katex.min isn't loaded properly.

This is just one way of doing it. Bu there are many more like:

Remove the <script> tag from head and place before the <script> in body

Remove the <script> tag after the body and place it after the <script> tag in head with defer attribute in both the scripts (so, we need not wait for them to be downloaded and go to body part to print things, and once they are loaded execute them) defer will make sure that everything in the dom is loaded asynchronously except that the scripts will be loaded in the order which they are declared.


问:
Pinging Multiple IPs using in PHP in Windows
I want to Ping 2 or More IPs getting from HTML Form using Exec Command in PHP on Windows Based Apache Server.

```<code><?php
if(isset($_REQUEST['go'])){
    $ips=implode(" ",$_REQUEST['ips']);
    $total=count($ips);

        for ($i=1; $i<=$total; $i++){
        exec ("ping -n 2".$ips, $ping_output, $value);
        echo $ping_output;
        }
}
?>

<form method="post" enctype="multipart/form-data">
<label>Enter First IP</label><br/>
<input type="text" name="ips[]" placeholder="192.168.0.1" required="true" /><br/>
<label>Enter Second IP</label><br/>
<input type="text" name="ips[]" placeholder="127.0.0.1" required="true" /><br/>
<button type="submit" name="go">Get Results</button>
</form>
</code>```

When I run this script it goes to infinite loop and doesn't show anything but Processing.
All I want to show IP ping Result against its IP either successful or Not.

答:
First Create function to Ping Single IP Address

```<code>function pingIp($ip) {
    exec ("ping -n 2 ".$ip, $ping_output, $value);
    return $ping_output;
}
if(isset($_REQUEST['go'])){
//$arr = array('127.0.0.1','127.0.0.9','46.101.113.87','159.203.96.186');
  $arr =$_REQUEST['ip'];
for($i=0; $i<count($arr); $i++){
    ?>
    ```
    <?php
    print_r(pingIp($arr[$i]));
    echo('

');
}
}
```

Then get IPs from Form and Call that function as in given example.

Body:
I want to Ping 2 or More IPs getting from HTML Form using Exec Command in PHP on Windows Based Apache Server.

<?php
if(isset($_REQUEST['go'])){
    $ips=implode(" ",$_REQUEST['ips']);
    $total=count($ips);

        for ($i=1; $i<=$total; $i++){
        exec ("ping -n 2".$ips, $ping_output, $value);
        echo $ping_output;
        }
}
?>

<form method="post" enctype="multipart/form-data">
Enter First IP

<input type="text" name="ips[]" placeholder="192.168.0.1" required="true" />

Enter Second IP

<input type="text" name="ips[]" placeholder="127.0.0.1" required="true" />

<button type="submit" name="go">Get Results</button>
</form>

When I run this script it goes to infinite loop and doesn't show anything but Processing.
All I want to show IP ping Result against its IP either successful or Not.

Body:
First Create function to Ping Single IP Address

function pingIp($ip) {
    exec ("ping -n 2 ".$ip, $ping_output, $value);
    return $ping_output;
}
if(isset($_REQUEST['go'])){
//$arr = array('127.0.0.1','127.0.0.9','46.101.113.87','159.203.96.186');
  $arr =$_REQUEST['ip'];
for($i=0; $i<count($arr); $i++){
    ?>
    <pre>
    <?php
    print_r(pingIp($arr[$i]));
    echo('<br/><br/>');
}
}

Then get IPs from Form and Call that function as in given example.


问:
SQL Count on multiple joins with dynamic WHERE
My issue is that I have a Select statement that has a where clause that is generated on the fly.  It is joined across 5 tables.

I basically need a Count of each DISTINCT instance of a USER ID in table 1 that falls into the scope of the WHERE.  This has to be able to be executed in one statement as well. So, Esentially, I can't do a global GROUP BY because of the other 4 tables data I need returned.

If I could get a column that had the count that was duplicated where the primary key column is that would be perfect.  Right now this is what I'm looking at as my query:

```<code>SELECT  *
FROM    TBL1 1
        INNER JOIN TBL2 2 On 2.FK = 1.FK
        INNER JOIN TBL3 3 On 3.PK = 2.PK INNER JOIN TBL4 4 On 4.PK = 3.PK
        LEFT OUTER JOIN TBL5 5 ON 4.PK = 5.PK
WHERE   1.Date_Time_In BETWEEN '2010-11-15 12:00:00' AND '2010-11-30 12:00:00'
ORDER BY
        4.Column
        , 3.Column
        , 3.Column2
        , 1.Date_Time_In DESC
</code>```

So instead of selecting all columns, I will be filtering it down to about 5 or 6 but with that I need something like a Total column that is the Distinct count of TBL1's Primary Key that applies the WHERE clause that has a possibility of growing and shrinking in size.

I almost wish there was a way to apply the same WHERE clause to a subselect because I realize that would work but don't know of a way other than creating a variable and just placing it in both places which I can't do either.

答:
If you are using SQL Server 2005 or higher, you could use one of the AGGREGATE OVER functions.</p>

```<code>SELECT  *
        , COUNT(UserID) OVER(PARTITION BY UserID) AS 'Total'
FROM    TBL1 1
        INNER JOIN TBL2 2 On 2.FK = 1.FK
        INNER JOIN TBL3 3 On 3.PK = 2.PK INNER JOIN TBL4 4 On 4.PK = 3.PK
        LEFT OUTER JOIN TBL5 5 ON 4.PK = 5.PK
WHERE   1.Date_Time_In BETWEEN '2010-11-15 12:00:00' AND '2010-11-30 12:00:00'
ORDER BY
        4.Column, 3.Column, 3.Column2, 1.Date_Time_In DESC
</code>```

Body:
My issue is that I have a Select statement that has a where clause that is generated on the fly.  It is joined across 5 tables.

I basically need a Count of each DISTINCT instance of a USER ID in table 1 that falls into the scope of the WHERE.  This has to be able to be executed in one statement as well. So, Esentially, I can't do a global GROUP BY because of the other 4 tables data I need returned.

If I could get a column that had the count that was duplicated where the primary key column is that would be perfect.  Right now this is what I'm looking at as my query:

SELECT  *
FROM    TBL1 1
        INNER JOIN TBL2 2 On 2.FK = 1.FK
        INNER JOIN TBL3 3 On 3.PK = 2.PK INNER JOIN TBL4 4 On 4.PK = 3.PK
        LEFT OUTER JOIN TBL5 5 ON 4.PK = 5.PK
WHERE   1.Date_Time_In BETWEEN '2010-11-15 12:00:00' AND '2010-11-30 12:00:00'
ORDER BY
        4.Column
        , 3.Column
        , 3.Column2
        , 1.Date_Time_In DESC

So instead of selecting all columns, I will be filtering it down to about 5 or 6 but with that I need something like a Total column that is the Distinct count of TBL1's Primary Key that applies the WHERE clause that has a possibility of growing and shrinking in size.

I almost wish there was a way to apply the same WHERE clause to a subselect because I realize that would work but don't know of a way other than creating a variable and just placing it in both places which I can't do either.

Body:
If you are using SQL Server 2005 or higher, you could use one of the AGGREGATE OVER functions.

SELECT  *
        , COUNT(UserID) OVER(PARTITION BY UserID) AS 'Total'
FROM    TBL1 1
        INNER JOIN TBL2 2 On 2.FK = 1.FK
        INNER JOIN TBL3 3 On 3.PK = 2.PK INNER JOIN TBL4 4 On 4.PK = 3.PK
        LEFT OUTER JOIN TBL5 5 ON 4.PK = 5.PK
WHERE   1.Date_Time_In BETWEEN '2010-11-15 12:00:00' AND '2010-11-30 12:00:00'
ORDER BY
        4.Column, 3.Column, 3.Column2, 1.Date_Time_In DESC


问:
Handle multiple camera capture UWP
I'm working with a Universal application that let we capture an image for each camera (two or more). So do we have any ways to manage all camera capture stream sand process it? I just found the tutorial about individual camera handling in MSDN.

I found some article about manage multiple IP cameras in Winforms but nothing for UWP.

答:
As we know, for UWP app, the simplest way to capture photos and video is using the MediaCapture class. See Basic photo, video, and audio capture with MediaCapture.

In this official sample Camera frames sample, it shows how to list all capture source and access camera with different profile.

So do we have any ways to manage all camera capture stream sand
  process it?

We can initialize multiple MediaCapture instances and read frame by using MediaFrameReader Class. Check out this wrapper to see how to process frame as you need.

Share a multiple camera sample based on the above official sample: Github LINK

The screenshot(Running on my laptop which connected a Microsoft Life Camera HD-3000):

Title: Handle multiple camera capture UWP


问:
How to crawl and parse only precise data using Nutch?
I'm new to Nutch and crawling. I have installed Nutch 2.0, crawled and indexed the data using Solr 4.5 by following some basic tutorials. Now I don't want to parse all the text content of a page, I want to customize it like Nutch should crawl the page and scrape/fetch only the data related to address because my use case is to crawl URLs and parse only address info as text.

For example, I need to crawl and parse only the text content which has address information, email id, phone number and fax number.

How should I do this? Is there any plugin already available for this?

If I want to write a customized parser for this can anyone help me in this regards?

答: Check [NUTCH-978] which introduces a plugin called XPath which allows the user of nutch to process various web page and get only certain information that user wants therefore making the index more accurate and its content more flexible.</p>


问:
Delete view is returning null object to controller
I'm new in ASP.NET MVC and I'm trying to develop a simple application for realizing CRUD operations, but the Delete operation is having a strange problem when get back to the controller, because it returns a null object, not allowing the operation to complete. I'll show below the code for the model, controller and its respective view.

Model:

```<code>public class Biblioteca
{
    public int IdBiblioteca { get; set; }
    public string Nome { get; set; }
    public string Endereco { get; set; }
}
</code>```

Controller

```<code>public class BibliotecaController : Controller
{
    ADAO dao = DAOFactory.GetInstance(DAOFactory.DAOType.Biblioteca);

    [HttpGet]
    public ActionResult DeleteLibrary(int id)
    {
        return View(dao.Select(id));
    }

    [HttpPost]
    public ActionResult DeleteLibrary(Biblioteca b)
    {
        dao.Delete(b);
        return RedirectToAction("Index");
    }
}
</code>```

View DeleteLibrary

```<code>@model BibliotecaWebApp.Models.Biblioteca

<h2>DeleteLibrary</h2>
<h3>Are you sure you want to delete this?</h3>
<div>
    <h4>Biblioteca</h4>
    <hr />
    <dl class="dl-horizontal">
        <dt>@Html.DisplayNameFor(model => model.IdBiblioteca)</dt>
        <dd>@Html.DisplayFor(model => model.IdBiblioteca)</dd>
        <dt>@Html.DisplayNameFor(model => model.Nome)</dt>
        <dd>@Html.DisplayFor(model => model.Nome)</dd>
        <dt>@Html.DisplayNameFor(model => model.Endereco)</dt>
        <dd>@Html.DisplayFor(model => model.Endereco)</dd>
    </dl>

    @using (Html.BeginForm()) {
        @Html.AntiForgeryToken()
        <div class="form-actions no-color">
            <input type="submit" value="Delete" class="btn btn-default" /> |
            @Html.ActionLink("Back to List", "Index")
        </div>
    }
</div>
</code>```

As we can see in the controller snippet, there are two controllers for each operation: a [HttpGet] which retrieve the data to be shown in a confirmation view, before the same can be deleted [HttpPost]. The problem arises in the [HttpPost]DeleteLibrary, once it gets a null Biblioteca object from the view to perform the exclusion. Below there are two screenshots that better presents this:

[HttpGet] DeleteLibrary works properly:

But when the user clicks in the Delete button, on the [HttpPost]DeleteLibrary method is received a null object, as shown below:

My question is: Why the returning object is getting null when it's passed to the view? What can be the problem?

答:
Use this

**@using (Html.BeginForm()) {
        @Html.AntiForgeryToken()
        @Html.HiddenFor(m => m.IdBiblioteca)

            <input type="submit" value="Delete" class="btn btn-default" /> |
            @Html.ActionLink("Back to List", "Index")

    }**```
</div>
</div>
</p>

<p>instead of this</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-html lang-html prettyprint-override"><code>**@using (Html.BeginForm()) {
        @Html.AntiForgeryToken()
        <div class="form-actions no-color">
            <input type="submit" value="Delete" class="btn btn-default" /> |
            @Html.ActionLink("Back to List", "Index")
        </div>
    }**</code>```

Body:
I'm new in ASP.NET MVC and I'm trying to develop a simple application for realizing CRUD operations, but the Delete operation is having a strange problem when get back to the controller, because it returns a null object, not allowing the operation to complete. I'll show below the code for the model, controller and its respective view.

Model:

public class Biblioteca
{
    public int IdBiblioteca { get; set; }
    public string Nome { get; set; }
    public string Endereco { get; set; }
}

Controller

public class BibliotecaController : Controller
{
    ADAO dao = DAOFactory.GetInstance(DAOFactory.DAOType.Biblioteca);

    [HttpGet]
    public ActionResult DeleteLibrary(int id)
    {
        return View(dao.Select(id));
    }

    [HttpPost]
    public ActionResult DeleteLibrary(Biblioteca b)
    {
        dao.Delete(b);
        return RedirectToAction("Index");
    }
}

View DeleteLibrary

@model BibliotecaWebApp.Models.Biblioteca

DeleteLibrary

Are you sure you want to delete this?

Biblioteca

@Html.DisplayNameFor(model => model.IdBiblioteca)

@Html.DisplayFor(model => model.IdBiblioteca)

@Html.DisplayNameFor(model => model.Nome)

@Html.DisplayFor(model => model.Nome)

@Html.DisplayNameFor(model => model.Endereco)

@Html.DisplayFor(model => model.Endereco)

    @using (Html.BeginForm()) {
        @Html.AntiForgeryToken()

            <input type="submit" value="Delete" class="btn btn-default" /> |
            @Html.ActionLink("Back to List", "Index")

    }

As we can see in the controller snippet, there are two controllers for each operation: a [HttpGet] which retrieve the data to be shown in a confirmation view, before the same can be deleted [HttpPost]. The problem arises in the [HttpPost]DeleteLibrary, once it gets a null Biblioteca object from the view to perform the exclusion. Below there are two screenshots that better presents this:

[HttpGet] DeleteLibrary works properly:

But when the user clicks in the Delete button, on the [HttpPost]DeleteLibrary method is received a null object, as shown below:

My question is: Why the returning object is getting null when it's passed to the view? What can be the problem?

Body:
Use this

**@using (Html.BeginForm()) {
        @Html.AntiForgeryToken()
        @Html.HiddenFor(m => m.IdBiblioteca)
        <div class="form-actions no-color">
            <input type="submit" value="Delete" class="btn btn-default" /> |
            @Html.ActionLink("Back to List", "Index")
        </div>
    }**

instead of this

**@using (Html.BeginForm()) {
        @Html.AntiForgeryToken()
        <div class="form-actions no-color">
            <input type="submit" value="Delete" class="btn btn-default" /> |
            @Html.ActionLink("Back to List", "Index")
        </div>
    }**


问:
Using swipe gesture to edit table view cells in swift3
How can I use Swip gesture to do "edit" and "delete" action on Each table view cell? Something like the email app! Any suggestion?</p>

答:
```<code>func tableView(_ tableView: UITableView, canEditRowAt indexPath:
IndexPath) -> Bool {
  // Return NO if you do not want the specified item to be editable.
  return true
}
// Override to support editing the table view.

   func tableView(_ tableView: UITableView, commitEditingStyle
   editingStyle: UITableViewCellEditingStyle, forRowAt indexPath:
  IndexPath) {
   if editingStyle == .delete {
        // Delete the row from the data source
        tableView.deleteRows(at: [indexPath], with: .fade)
   }
  else if editingStyle == .insert {
      // Create a new instance of the appropriate class, insert it
         into the array, and add a new row to the table view
   }

}
</code>```


问:
ArrayIndexOutOfBoundsException iterating over 2D arrays in Java
Sorry this question can't really be applied to others. I've been looking at it for a couple hours and I still can't see it. It must  be super simple yet I can't find where I'm trying to access something that isnt there. I am getting a

ArrayIndexOutOfBoundsException while iterating over a 9x9 grid.

```<code>public ArrayList<Grid> next9Grids()
{
    ArrayList<Grid> next9 = new ArrayList<Grid>();//list of new Grids

    for(int i = 0; i < values.length; i++){
        for(int j = 0; i < values[i].length; j++){
            if (values[i][j] == 0){//if empty
                for(int next = 1; next <= 9; next++){
                    Grid temp9 = new Grid(this);//need to make another grid for each #
                    temp9.values[i][j] = next; // changes value of empty space to 1->9
                    next9.add(temp9); //add grid to arrayList
                }
                return next9;
            }
        }

    }
    return null;

}
</code>```

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9
    at sudoku.Grid.next9Grids(Grid.java:112)    at
  sudoku.Solver.solveRecurse(Solver.java:54)    at
  sudoku.Solver.solveRecurse(Solver.java:56)    at
  sudoku.Solver.solveRecurse(Solver.java:56)

This is the source of the error.(Grid.java:112) is ----> if(values[i][j] ==0){

Another question is Why is an error thrown on line 112 when it's accessing something that the second for loop is first iterating over and not the second for loop?

Anything is greatly appreciated. Thanks for the feedback.

答:
in the sixth line of you code, replace i with j

```<code>public ArrayList<Grid> next9Grids(){

ArrayList<Grid> next9 = new ArrayList<Grid>(); //list of new Grids

for(int i = 0; i < values.length; i++){
    for(int j = 0; j < values[i].length; j++){  // The change is here
        if (values[i][j] == 0){ //if empty
            for(int next = 1; next <= 9; next++){
                Grid temp9 = new Grid(this);//need to make another grid for each #
                temp9.values[i][j] = next; // changes value of empty space to 1->9
                next9.add(temp9); //add grid to arrayList
            }
            return next9;
        }
    }
}
return null;
</code>```

}

Body:
Sorry this question can't really be applied to others. I've been looking at it for a couple hours and I still can't see it. It must  be super simple yet I can't find where I'm trying to access something that isnt there. I am getting a

ArrayIndexOutOfBoundsException while iterating over a 9x9 grid.

public ArrayList<Grid> next9Grids()
{
    ArrayList<Grid> next9 = new ArrayList<Grid>();//list of new Grids

    for(int i = 0; i < values.length; i++){
        for(int j = 0; i < values[i].length; j++){
            if (values[i][j] == 0){//if empty
                for(int next = 1; next <= 9; next++){
                    Grid temp9 = new Grid(this);//need to make another grid for each #
                    temp9.values[i][j] = next; // changes value of empty space to 1->9
                    next9.add(temp9); //add grid to arrayList
                }
                return next9;
            }
        }

    }
    return null;

}

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9
    at sudoku.Grid.next9Grids(Grid.java:112)    at
  sudoku.Solver.solveRecurse(Solver.java:54)    at
  sudoku.Solver.solveRecurse(Solver.java:56)    at
  sudoku.Solver.solveRecurse(Solver.java:56)

This is the source of the error.(Grid.java:112) is ----> if(values[i][j] ==0){

Another question is Why is an error thrown on line 112 when it's accessing something that the second for loop is first iterating over and not the second for loop?

Anything is greatly appreciated. Thanks for the feedback.

Body:
in the sixth line of you code, replace i with j

public ArrayList<Grid> next9Grids(){

ArrayList<Grid> next9 = new ArrayList<Grid>(); //list of new Grids

for(int i = 0; i < values.length; i++){
    for(int j = 0; j < values[i].length; j++){  // The change is here
        if (values[i][j] == 0){ //if empty
            for(int next = 1; next <= 9; next++){
                Grid temp9 = new Grid(this);//need to make another grid for each #
                temp9.values[i][j] = next; // changes value of empty space to 1->9
                next9.add(temp9); //add grid to arrayList
            }
            return next9;
        }
    }
}
return null;

}


问:
Difference between acceptance test and functional test?
What is the real difference between acceptance tests and functional tests?

What are the highlights or aims of each? Everywhere I read they are ambiguously similar.

答:
Audience.  Functional testing is to assure members of the team producing the software that it does what they expect.  Acceptance testing is to assure the consumer that it meets their needs.

Scope.  Functional testing only tests the functionality of one component at a time.  Acceptance testing covers any aspect of the product that matters to the consumer enough to test before accepting the software (i.e., anything worth the time or money it will take to test it to determine its acceptability).

Software can pass functional testing, integration testing, and system testing; only to fail acceptance tests when the customer discovers that the features just don't meet their needs.  This would usually imply that someone screwed up on the spec.  Software could also fail some functional tests, but pass acceptance testing because the customer is willing to deal with some functional bugs as long as the software does the core things they need acceptably well (beta software will often be accepted by a subset of users before it is completely functional).


问:
How to use threads in qt
I am new to QT. I need to use threads for some purpose. I searched a lot about threading in QT but all the articles and videos are using same example. They are using dialog and putting a label with 2 buttons to print some data on label. I want to use threads with MainWindow. My application include reading a serial data and then displaying the related information on a label. That information contains a string and an audio file. String and audio file needs to be played at the same time. I have a connected a signal for serial read like below:

```<code>connect(&Serial, SIGNAL(readyRead()), this, SLOT(SerialRead()));

QString MainWindow::SerialRead()
{
  word Words; //
  QString serialData = Serial.readAll();              //Reading Serial Data
  //Now here I want to start the two threads
  //Thread 1 to display string
  //Thread 2 to play audio
  return 0;

}
</code>```

How can I achieve above task. Can anyone please refer me to some usefull links or articles. Thanks

答: you may not need to use 2 threads to do such things. just emit a signal connected to setText(const QString&) and the other signal connected to the slot for playing audio. what is the size of serial data?</p>

Title: How to use threads in qt

Body:
I am new to QT. I need to use threads for some purpose. I searched a lot about threading in QT but all the articles and videos are using same example. They are using dialog and putting a label with 2 buttons to print some data on label. I want to use threads with MainWindow. My application include reading a serial data and then displaying the related information on a label. That information contains a string and an audio file. String and audio file needs to be played at the same time. I have a connected a signal for serial read like below:

connect(&Serial, SIGNAL(readyRead()), this, SLOT(SerialRead()));

QString MainWindow::SerialRead()
{
  word Words; //
  QString serialData = Serial.readAll();              //Reading Serial Data
  //Now here I want to start the two threads
  //Thread 1 to display string
  //Thread 2 to play audio
  return 0;

}

How can I achieve above task. Can anyone please refer me to some usefull links or articles. Thanks


问:
how to create website using Django
I have one Django App. I want to get this app on World Wide Web.
Can anyone please help me with steps.
Like Some server addition(e.g. Apache or Nginx),Configuration of server,Integrating with Django,Web Hosting,etc.

Thanks

答:
In regards to hosting, you will have to get a domain name (unless you want to connect to your web page via IP address).

If you want to host your own web page from your server you will also have to set up your router to forward traffic to your server's IP. Having a static IP from your internet provider is preferable and also set your machine to have a static IP so you don't have problems with routing.

Title: how to create website using Django


答:
Of course you can remove an anonymous method, you just need to have a reference to the same anonymous method.</p>

```<code>var myAnonymousMethod = p => { fake.Test(p); counter++; };
container.Add(myAnonymousMethod);
removed = container.Remove(myAnonymousMethod);
</code>```

Title: How to identify an anonymous function

Body:
I have a class that creates a List<Action<int>> and holds on to them until a later time. This class can add and remove delegates from this list. This works well as long as people don't get too fancy. To combat anonymous function (which can't be removed) I check against the target of the delegate being null. If its null I throw an exception. The problem comes in when there is an anonymous delegate that contains a function. This has a target, but is just as unremovable. The simplified code below illustrates my issues

 public class MyDelegateContainer
 {
    List<Action<int>> m_Container = new List<Action<int>>();

    public void Add(Action<int> del)
    {
        if (del.Target == null)
        {
            throw new Exception("No static handlers");
        }
        m_Container.Add(del);
    }

    public bool Remove(Action<int> del)
    {
        if (m_Container.Contains(del))
        {
            m_Container.Remove(del);
            return true;
        }

        return false;
    }
}

public class MyFakeActionClass
{
    public void Test(int temp) { }
}

class Program
{
    static void Main(string[] args)
    {
        bool removed = false;
        int counter = 0;
        MyDelegateContainer container = new MyDelegateContainer();
        MyFakeActionClass fake = new MyFakeActionClass();
        //container.Add(p => { }); //Throws, this is what I want to happen
        container.Add(fake.Test); //Works, this is the use case
        removed = container.Remove(fake.Test); //Works, this is the use case
        Debug.Assert(removed);
        container.Add(p => { fake.Test(p); counter++; }); //Works but I would like it not to
        removed = container.Remove(p => { fake.Test(p); counter++; }); //doesn't work
        Debug.Assert(removed);
    }
}

I need some way to identify

   p => { fake.Test(p); counter++; }

is an anonymous function so I can throw if someone tries it. Thanks for any help

EDIT: I should note that I could use an Action<int> variable for the anonymous function and everything would work, but the Add and Remove are never in the same scope in practice.

Body:
Of course you can remove an anonymous method, you just need to have a reference to the same anonymous method.

var myAnonymousMethod = p => { fake.Test(p); counter++; };
container.Add(myAnonymousMethod);
removed = container.Remove(myAnonymousMethod);


问:
How to start a program using cmd in windows
What i need is to accept a path (via args) to a mongod.cfg file and use it to start mongod from java. This is whar i am using

```<code>Runtime.getRuntime().exec("cmd /k start mongod --config C:\\Users\\Ivan\\git\\StudentsDBMS_Server\\StudentsDBMS_Server\\mongod.bat");
</code>```

And this is what i get

On removing start command it does not runs the command.
Also can you explain why does it prints the command infinitely but does not execute anyone of them.

Please

答:
Maybe the cmd syntax is off. Try like this maybe:</p>

```<code>'cmd /k "start mongod --config C:\\Users\\Ivan\\git\\StudentsDBMS_Server\\StudentsDBMS_Server\\mongod.bat"'
</code>```

Body:
What i need is to accept a path (via args) to a mongod.cfg file and use it to start mongod from java. This is whar i am using

Runtime.getRuntime().exec("cmd /k start mongod --config C:\\Users\\Ivan\\git\\StudentsDBMS_Server\\StudentsDBMS_Server\\mongod.bat");

And this is what i get

On removing start command it does not runs the command.
Also can you explain why does it prints the command infinitely but does not execute anyone of them.

Please

Body:
Maybe the cmd syntax is off. Try like this maybe:

'cmd /k "start mongod --config C:\\Users\\Ivan\\git\\StudentsDBMS_Server\\StudentsDBMS_Server\\mongod.bat"'


问:
C# Avoiding Duplicated Logic
Suppose I had a base class A, with subclasses B, C and D. I have a class, MyClass which contains an overload for each of them. I want a counter to increment any time one of these methods is invoked from anywhere other than inside MyClass. This can be accomplished with a few simple helper methods:

```<code>public class MyClass
{
   int counter;

   public doSomethingExternal(B b) {counter++; doSomething(b);}
   public doSomethingExternal(C c) {counter++; doSomething(c);}
   public doSomethingExternal(D d) {counter++; doSomething(d);}

   private doSomething(B b) {...}
   private doSomething(C c) {...}
   private doSomething(D d) {...}
}
</code>```

This really bothers the dev in me. Is there no way better way we can write those helper methods so that we don't have duplicated logic for every subclass? The solution I envision is something like:

```<code>// Magically, we know which type we are and call the correct doSomething
public doSomethingExternal(A a) {counter++; doSomething(a);}
</code>```

I think this kind of generalization could be accomplished with Reflection, but I have heard that reflection is generally slow and can be complicated to understand. I am curious if there is a more conventional pattern I am overlooking that solves this logic-duplication issue.

答:
This really bothers the dev in me. Is there no way better way we can write those helper methods so that we don't have duplicated logic for every subclass?

Why? I actually find your code pretty easy to read. I wouldn't really consider "duplicate code", incrementing a simple counter and delegating to a private method. Consider all the alternatives posted? Does any of them make your life any easier?

Of course you could leverage c# 7's pattern matching, but is it really worth it?

```<code>public void doSomethingExternal(A a)
{
    counter++;

    switch (a)
    {
        case B b:
            doSomething(b);
            break;
        case C c:
            doSomething(c);
            break;
        case D d:
            doSomething(d);
            break;
        case null:
            throw new ArgumentNullException(nameof(a));
        default:
            throw new InvalidOperationException();
    }
}
</code>```

All that to simply avoid duplicating counter++?

Its your call, we are probably only seeing a very simplified scenario of what your code really looks like and the extent of your "duplicated" logic.

Title: C# Avoiding Duplicated Logic

Body:
Suppose I had a base class A, with subclasses B, C and D. I have a class, MyClass which contains an overload for each of them. I want a counter to increment any time one of these methods is invoked from anywhere other than inside MyClass. This can be accomplished with a few simple helper methods:

public class MyClass
{
   int counter;

   public doSomethingExternal(B b) {counter++; doSomething(b);}
   public doSomethingExternal(C c) {counter++; doSomething(c);}
   public doSomethingExternal(D d) {counter++; doSomething(d);}

   private doSomething(B b) {...}
   private doSomething(C c) {...}
   private doSomething(D d) {...}
}

This really bothers the dev in me. Is there no way better way we can write those helper methods so that we don't have duplicated logic for every subclass? The solution I envision is something like:

// Magically, we know which type we are and call the correct doSomething
public doSomethingExternal(A a) {counter++; doSomething(a);}

I think this kind of generalization could be accomplished with Reflection, but I have heard that reflection is generally slow and can be complicated to understand. I am curious if there is a more conventional pattern I am overlooking that solves this logic-duplication issue.

Body:
This really bothers the dev in me. Is there no way better way we can write those helper methods so that we don't have duplicated logic for every subclass?

Why? I actually find your code pretty easy to read. I wouldn't really consider "duplicate code", incrementing a simple counter and delegating to a private method. Consider all the alternatives posted? Does any of them make your life any easier?

Of course you could leverage c# 7's pattern matching, but is it really worth it?

public void doSomethingExternal(A a)
{
    counter++;

    switch (a)
    {
        case B b:
            doSomething(b);
            break;
        case C c:
            doSomething(c);
            break;
        case D d:
            doSomething(d);
            break;
        case null:
            throw new ArgumentNullException(nameof(a));
        default:
            throw new InvalidOperationException();
    }
}

All that to simply avoid duplicating counter++?

Its your call, we are probably only seeing a very simplified scenario of what your code really looks like and the extent of your "duplicated" logic.