问:
try and catch executed at the same time
So i have this OOP Login & register system which gives a user the ability to change his/her name.

When a user is pressing "Update" button his/her name is changed in the DB the problem is that tho it changes the name in DB instead of redirecting the user where i want him/her to be redirected i get the error that should appear only when that name couldn't be changed.

User.php

```<code><?php

class User{
private $_db,
        $_data,
        $_sessionName,
        $_cookieName,
        $_isLoggedIn;

public function __construct($user = null){
    $this->_db = DB::getInstance();

    $this->_sessionName = Config::get('session/session_name');
    $this->_cookieName = Config::get('remember/cookie_name');

    if(!$user){
        if(Session::exists($this->_sessionName)){
            $user = Session::get($this->_sessionName);

            if($this->find($user)){
                $this->_isLoggedIn = true;
            } else{
                //process logout
            }
        }
    } else{
        $this->find($user);
    }
}

public function update($fields = array(), $id = null){

    if(!$id && $this->isLoggedIn()){
        $id = $this->data()->id;
    }

    if(!$this->_db->update('users', $id, $fields)){
        throw new Exception('There was a problem updating your profile.');
    }
}

public function create($fields = array()){
    if(!$this->_db->insert('users', $fields)){
        throw new Exception('There was a problem creating an account');
    }
}

public function find($user = null){
    if($user){
        $field = (is_numeric($user)) ? 'id' : 'username';
        $data = $this->_db->get('users', array($field, '=', $user));

        if($data->count()){
            $this->_data = $data->first();
            return true;
        }
    }
    return false;
}

public function login($username = null, $password = null, $remember = false){
    if(!$username && !$password && $this->exists()){
        Session::put($this->_sessionName, $this->data()->id);
    } else{
        $user = $this->find($username);
        if($user){
            if($this->data()->password === Hash::make($password, $this->data()->salt)){
                Session::put($this->_sessionName, $this->data()->id);

                if($remember){
                    $hash = Hash::unique();
                    $hashCheck = $this->_db->get('users_session', array('user_id', '=', $this->data()->id));

                    if(!$hashCheck->count()){
                        $this->_db->insert('users_session',array(
                            'user_id' => $this->data()->id,
                            'hash' => $hash
                        ));
                    } else{
                        $hash = $hashCheck->first()->hash;
                    }
                    Cookie::put($this->_cookieName, $hash, Config::get('remember/cookie_expiry'));
                }

                return true;
            }
        }
    }
    return false;
}

public function exists(){
    return(!empty($this->_data)) ? true : false;
}

public function logout(){
    $this->_db->delete('users_session', array('user_id', '=', $this->data()->id));

    Session::delete($this->_sessionName);
    Cookie::delete(Config::get('remember/cookie_name'));
}

public function data(){
    return $this->_data;
}

public function isLoggedIn(){
    return $this->_isLoggedIn;
}
}
</code>```

edit-profile.php

```<code><?php

    $user = new User();
    if(!$user->isLoggedIn()){
        Redirect::to('login');
    }

    if(Input::exists()){
        if(Token::check(Input::get('token'))){

            $validate = new Validate();
            $validation = $validate->check($_POST, array(
                'name' => array(
                    'required' => true,
                    'min' => 2,
                    'max' => 50
                )
            ));

            if($validation->passed()){

                try{
                    $user->update(array(
                        'name' => Input::get('name')
                    ));

                    Session::flash('flash', 'Your profile has been edited with success!');
                    Redirect::to('flash');

                } catch(Exception $e){
                    die($e->getMessage());
                }
            } else{
                foreach($validation->errors() as $error){
                    echo $error . '<br />';
                }
            }

        }
    }

    ?>

    <form action="" method="post">
        <div class="field">
            <input type="text" name="name" value="<?php echo escape($user->data()->name); ?>">
        </div>
        <input type="submit" value="Update">
        <input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
    </form>
</code>```

I have no clue why that is happening

This is the update() method in my DB.class

```<code>public function update($table, $id, $fields){
        $set = '';
        $x = 1;

        foreach ($fields as $name => $value) {
            $set .= "{$name} = ?";
            if($x < count($fields)){
                $set .= ', ';
            }
            $x++;
        }

        $sql = "UPDATE {$table} SET {$set} WHERE id = {$id}";

        if($this->query($sql, $fields)->error()){
            return true;
        }
        return false;
    }
</code>```

答:
For your update function

```<code>public function update($table, $id, $fields){
    $set = '';
    $x = 1;
    foreach ($fields as $name => $value) {
        $set .= "{$name} = ?";
        if($x < count($fields)){
            $set .= ', ';
        }
        $x++;
    }
    $sql = "UPDATE {$table} SET {$set} WHERE id = {$id}";
    if($this->query($sql, $fields)->error()){
        return true;
    }
    return false;
}
</code>```

Instead do

```<code>public function update($table, $id, $fields){

    $set = [];

    foreach ($fields as $name => $value) {
       $set[] = "{$name} = ?";
    }

    $set = implode(', ', $set);

    $sql = "UPDATE {$table} SET {$set} WHERE id = ?";
    $fields[] = $id; //id should always be the last ?
    if($this->query($sql, $fields)->error()){
        return true;
    }
    return false;
}
</code>```

Also there is the potential for the table and id and even the keys of $fields to be used as a vector for SQL injection.  You may be entering it where ever you use them. But it's possible because you are not checking the table against a white list and anytime you concatenate values into SQL there is the potential for them to be exploited.  All it takes is one mistake, you class should not allow coding errors in other places to compromise it's security.

You can get a list of tables from the database itself.

```<code>$statement = 'SELECT `TABLE_NAME` FROM `information_schema`.`TABLES` WHERE `TABLE_SCHEMA` LIKE "'.$database.'"';
</code>```

So when you connect to the DB you could set a list of acceptable tables then check when a table is put in ( with in_array or such ).  Just a thought.

It may also be possible to comprise the keys of the $fields array, for that you can do something similar to the table. but with this query

```<code>SHOW COLUMNS FROM {table}
</code>```

For example, imagine a post request that has inputs matching your array $fields. All someone would have to do is send your server a request with the SQL Attack part in the key instead of the value and you are unprotected. Something like this ( don't drop your DB without a backup, feel i should say that.)

```<code>  $_POST['1=1; DROP DATABASE --'] = true;
</code>```

When you construct your query you would have

```<code>INSERT INTO table SET 1=1; DROP DATABASE -- = ?, {field} = ? .. rest of query
</code>```

The -- starts a comment in SQL so nothing after the -- matter to the DB this prevents an error from happening..  So be careful of just dumping post keys into your SQL  I'm not sure 1=1 would work but they could use a field out of the input list just as easily.  this is just for example purposes.

To me this line

```<code>   if($this->query($sql, $fields)->error()){
        return true;
   }else{
        return false;
   }
</code>```

Says if there is an error return true not sure if that is the case as i don't know what $this->query or ->error() is but I imagine $this->query must return $this or some object that would contain the error.  It's just confusing worded that way.

Title: try and catch executed at the same time

Body:
So i have this OOP Login & register system which gives a user the ability to change his/her name.

When a user is pressing "Update" button his/her name is changed in the DB the problem is that tho it changes the name in DB instead of redirecting the user where i want him/her to be redirected i get the error that should appear only when that name couldn't be changed.

User.php

<?php

class User{
private $_db,
        $_data,
        $_sessionName,
        $_cookieName,
        $_isLoggedIn;

public function __construct($user = null){
    $this->_db = DB::getInstance();

    $this->_sessionName = Config::get('session/session_name');
    $this->_cookieName = Config::get('remember/cookie_name');

    if(!$user){
        if(Session::exists($this->_sessionName)){
            $user = Session::get($this->_sessionName);

            if($this->find($user)){
                $this->_isLoggedIn = true;
            } else{
                //process logout
            }
        }
    } else{
        $this->find($user);
    }
}

public function update($fields = array(), $id = null){

    if(!$id && $this->isLoggedIn()){
        $id = $this->data()->id;
    }

    if(!$this->_db->update('users', $id, $fields)){
        throw new Exception('There was a problem updating your profile.');
    }
}

public function create($fields = array()){
    if(!$this->_db->insert('users', $fields)){
        throw new Exception('There was a problem creating an account');
    }
}

public function find($user = null){
    if($user){
        $field = (is_numeric($user)) ? 'id' : 'username';
        $data = $this->_db->get('users', array($field, '=', $user));

        if($data->count()){
            $this->_data = $data->first();
            return true;
        }
    }
    return false;
}

public function login($username = null, $password = null, $remember = false){
    if(!$username && !$password && $this->exists()){
        Session::put($this->_sessionName, $this->data()->id);
    } else{
        $user = $this->find($username);
        if($user){
            if($this->data()->password === Hash::make($password, $this->data()->salt)){
                Session::put($this->_sessionName, $this->data()->id);

                if($remember){
                    $hash = Hash::unique();
                    $hashCheck = $this->_db->get('users_session', array('user_id', '=', $this->data()->id));

                    if(!$hashCheck->count()){
                        $this->_db->insert('users_session',array(
                            'user_id' => $this->data()->id,
                            'hash' => $hash
                        ));
                    } else{
                        $hash = $hashCheck->first()->hash;
                    }
                    Cookie::put($this->_cookieName, $hash, Config::get('remember/cookie_expiry'));
                }

                return true;
            }
        }
    }
    return false;
}

public function exists(){
    return(!empty($this->_data)) ? true : false;
}

public function logout(){
    $this->_db->delete('users_session', array('user_id', '=', $this->data()->id));

    Session::delete($this->_sessionName);
    Cookie::delete(Config::get('remember/cookie_name'));
}

public function data(){
    return $this->_data;
}

public function isLoggedIn(){
    return $this->_isLoggedIn;
}
}

edit-profile.php

<?php

    $user = new User();
    if(!$user->isLoggedIn()){
        Redirect::to('login');
    }

    if(Input::exists()){
        if(Token::check(Input::get('token'))){

            $validate = new Validate();
            $validation = $validate->check($_POST, array(
                'name' => array(
                    'required' => true,
                    'min' => 2,
                    'max' => 50
                )
            ));

            if($validation->passed()){

                try{
                    $user->update(array(
                        'name' => Input::get('name')
                    ));

                    Session::flash('flash', 'Your profile has been edited with success!');
                    Redirect::to('flash');

                } catch(Exception $e){
                    die($e->getMessage());
                }
            } else{
                foreach($validation->errors() as $error){
                    echo $error . '
';
                }
            }

        }
    }

    ?>

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

            <input type="text" name="name" value="<?php echo escape($user->data()->name); ?>">

        <input type="submit" value="Update">
        <input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
    </form>

I have no clue why that is happening

This is the update() method in my DB.class

public function update($table, $id, $fields){
        $set = '';
        $x = 1;

        foreach ($fields as $name => $value) {
            $set .= "{$name} = ?";
            if($x < count($fields)){
                $set .= ', ';
            }
            $x++;
        }

        $sql = "UPDATE {$table} SET {$set} WHERE id = {$id}";

        if($this->query($sql, $fields)->error()){
            return true;
        }
        return false;
    }

Body:
For your update function

public function update($table, $id, $fields){
    $set = '';
    $x = 1;
    foreach ($fields as $name => $value) {
        $set .= "{$name} = ?";
        if($x < count($fields)){
            $set .= ', ';
        }
        $x++;
    }
    $sql = "UPDATE {$table} SET {$set} WHERE id = {$id}";
    if($this->query($sql, $fields)->error()){
        return true;
    }
    return false;
}

Instead do

public function update($table, $id, $fields){

    $set = [];

    foreach ($fields as $name => $value) {
       $set[] = "{$name} = ?";
    }

    $set = implode(', ', $set);

    $sql = "UPDATE {$table} SET {$set} WHERE id = ?";
    $fields[] = $id; //id should always be the last ?
    if($this->query($sql, $fields)->error()){
        return true;
    }
    return false;
}

Also there is the potential for the table and id and even the keys of $fields to be used as a vector for SQL injection.  You may be entering it where ever you use them. But it's possible because you are not checking the table against a white list and anytime you concatenate values into SQL there is the potential for them to be exploited.  All it takes is one mistake, you class should not allow coding errors in other places to compromise it's security.

You can get a list of tables from the database itself.

$statement = 'SELECT `TABLE_NAME` FROM `information_schema`.`TABLES` WHERE `TABLE_SCHEMA` LIKE "'.$database.'"';

So when you connect to the DB you could set a list of acceptable tables then check when a table is put in ( with in_array or such ).  Just a thought.

It may also be possible to comprise the keys of the $fields array, for that you can do something similar to the table. but with this query

SHOW COLUMNS FROM {table}

For example, imagine a post request that has inputs matching your array $fields. All someone would have to do is send your server a request with the SQL Attack part in the key instead of the value and you are unprotected. Something like this ( don't drop your DB without a backup, feel i should say that.)

  $_POST['1=1; DROP DATABASE --'] = true;

When you construct your query you would have

INSERT INTO table SET 1=1; DROP DATABASE -- = ?, {field} = ? .. rest of query

The -- starts a comment in SQL so nothing after the -- matter to the DB this prevents an error from happening..  So be careful of just dumping post keys into your SQL  I'm not sure 1=1 would work but they could use a field out of the input list just as easily.  this is just for example purposes.

To me this line

   if($this->query($sql, $fields)->error()){
        return true;
   }else{
        return false;
   }

Says if there is an error return true not sure if that is the case as i don't know what $this->query or ->error() is but I imagine $this->query must return $this or some object that would contain the error.  It's just confusing worded that way.


来源: stackexchange

问:
Showing NaN for pandas column AD
How to get data to show NaN for pandas column AD

My data looks like:

df1

```<code>    EW   WE   DA   AA  DDA
0   CA   DA  DFA  DAW  DAQ
1   CA   DA  DFA  DAW  DAQ
2   CA   DA  DFA  DAW  DAQ
3    d  NaN  NaN  NaN  NaN
4  NaN  NaN  NaN  NaN  NaN
5  NaN  NaN  NaN  NaN  NaN
6  NaN  NaN  NaN  NaN  NaN
</code>```

df2

```<code>    AA   AB  AC   AD   AE
0  HAC   aw   d  1.0   xa
1  HAC   aw  aw  1.0   xa
2  HAC   aw  aw  1.0   xa
3  HAC   aw  aw  1.0   xa
4  HAC   aw  aw  1.0   xa
5  HAC   aw  aw  1.0   xa
6  NaN  NaN   d  NaN  NaN
</code>```

I want:

```<code>    AA   AB  AC   AD   AE
0  HAC   aw   d  1.0   xa
1  HAC   aw  aw  NaN   xa
2  HAC   aw  aw  NaN   xa
3  HAC   aw  aw  NaN   xa
4  HAC   aw  aw  NaN   xa
5  HAC   aw  aw  NaN   xa
6  NaN  NaN   d  1.0  NaN
</code>```

I am using:

```<code>df3 = df2[df2.AC.isin(df1.EW)]
df3 = df3[['AC','AD']]
print (df3)
</code>```

答:
```<code>mask = df2.AC.isin(df1.EW)
print (mask)
0     True
1    False
2    False
3    False
4    False
5    False
6     True
Name: AC, dtype: bool

df3 = df2.copy()
df3['AD'] = np.where(mask, df3['AD'], np.nan)
print (df3)
    AA   AB  AC   AD   AE
0  HAC   aw   d  1.0   xa
1  HAC   aw  aw  NaN   xa
2  HAC   aw  aw  NaN   xa
3  HAC   aw  aw  NaN   xa
4  HAC   aw  aw  NaN   xa
5  HAC   aw  aw  NaN   xa
6  NaN  NaN   d  NaN  NaN
</code>```

ContentLicense: CC BY-SA 3.0

Title: Showing NaN for pandas column AD

Body:
How to get data to show NaN for pandas column AD

My data looks like:

df1

    EW   WE   DA   AA  DDA
0   CA   DA  DFA  DAW  DAQ
1   CA   DA  DFA  DAW  DAQ
2   CA   DA  DFA  DAW  DAQ
3    d  NaN  NaN  NaN  NaN
4  NaN  NaN  NaN  NaN  NaN
5  NaN  NaN  NaN  NaN  NaN
6  NaN  NaN  NaN  NaN  NaN

df2

    AA   AB  AC   AD   AE
0  HAC   aw   d  1.0   xa
1  HAC   aw  aw  1.0   xa
2  HAC   aw  aw  1.0   xa
3  HAC   aw  aw  1.0   xa
4  HAC   aw  aw  1.0   xa
5  HAC   aw  aw  1.0   xa
6  NaN  NaN   d  NaN  NaN

I want:

    AA   AB  AC   AD   AE
0  HAC   aw   d  1.0   xa
1  HAC   aw  aw  NaN   xa
2  HAC   aw  aw  NaN   xa
3  HAC   aw  aw  NaN   xa
4  HAC   aw  aw  NaN   xa
5  HAC   aw  aw  NaN   xa
6  NaN  NaN   d  1.0  NaN

I am using:

df3 = df2[df2.AC.isin(df1.EW)]
df3 = df3[['AC','AD']]
print (df3)


问:
Set undeclared search parameter in $state.go ui-router angularjs
I'm trying to set a custom query string parameter during the $state.go() call. I would prefer if I did not have to set this parameter for each $stateProvider.state().

An example of this use case would be for setting a $stateChangeStart or $stateChangeSuccess function to look for a redirect parameter of some kind to redirect the transition.

When a user attempts to initially access to your website, but the request is unauthorized, you would redirect them to an authorization/login route. I am currently accomplishing this by a resolve in the $stateProvider.state() that verifies authorization. If authorization fails, in the resolve, I call $state.go(). In my attempts to preserve the current state, I get an empty state.

```<code>$state.current: {
    "name": "",
    "url": "^",
    "views": null,
    "abstract": true
}
</code>```

Also, when I transition to the login route:

```<code>$state.go('login', {
    redirect: window.location
});
</code>```

The redirect query string parameter gets lost. I would love if I did not have to define this for every single $stateProvider.state().

答:
On latest version of ui-router, all transition syntax was deprecated

legacy $stateChangeStart or $stateChangeSucces, was replaced

```<code>$rootScope.$on('$stateChangeSuccess', (evt, toState, toParams, fromState,
fromParams) => {
// do something
});
</code>```

on new version

```<code>app.run(($transitions) => {
 $transitions.onStart({ }, (trans) => {
// **trans** property has .to() & .from() values with all data about state
});
})
</code>```

read migration guide

Your state config could be:

```<code>.state({
        name: '**login**',
        url: '/',
        templateUrl: your template,
        controller: 'controller name',
        controllerAs: 'vm',
        params: {
            **redirect**: null,
        },
    });
</code>```

Body:
I'm trying to set a custom query string parameter during the $state.go() call. I would prefer if I did not have to set this parameter for each $stateProvider.state().

An example of this use case would be for setting a $stateChangeStart or $stateChangeSuccess function to look for a redirect parameter of some kind to redirect the transition.

When a user attempts to initially access to your website, but the request is unauthorized, you would redirect them to an authorization/login route. I am currently accomplishing this by a resolve in the $stateProvider.state() that verifies authorization. If authorization fails, in the resolve, I call $state.go(). In my attempts to preserve the current state, I get an empty state.

$state.current: {
    "name": "",
    "url": "^",
    "views": null,
    "abstract": true
}

Also, when I transition to the login route:

$state.go('login', {
    redirect: window.location
});

The redirect query string parameter gets lost. I would love if I did not have to define this for every single $stateProvider.state().

Body:
On latest version of ui-router, all transition syntax was deprecated

legacy $stateChangeStart or $stateChangeSucces, was replaced

$rootScope.$on('$stateChangeSuccess', (evt, toState, toParams, fromState,
fromParams) => {
// do something
});

on new version

app.run(($transitions) => {
 $transitions.onStart({ }, (trans) => {
// **trans** property has .to() & .from() values with all data about state
});
})

read migration guide

Your state config could be:

.state({
        name: '**login**',
        url: '/',
        templateUrl: your template,
        controller: 'controller name',
        controllerAs: 'vm',
        params: {
            **redirect**: null,
        },
    });


问:
Postgresql: How to group items based on their percentage to the grandtotal
```<code>    store_id   product_name   quantity
       1          apple          10
       1          orange         12
       1          grapes          9
       1          mango          17
       2          chicken        112
       2          beef           90
       2          pork           89
       2          lamb           115
</code>```

I want to group them from top and bottom 50% based on the percentage of their grandtotal grouped by their store_id, and label the bottom product as 'others'
something that looks like this:

```<code>     store_id    product_name    percent
        1           mango         35.42%
        1           orange        25.00%
        1           OTHER         20.83%
        1           OTHER         18.75%
        2           lamb          28.33%
        2           chicken       27.59%
        2           OTHER         22.17%
        2           OTHER         21.92%
</code>```

Is this possible? I really had a hard time google-ing this that's why I came here. Thanks!

答:
I would write this as:

```<code>select t.*,
       quantity / sum(quantity) over (partition by store_id) as ratio,
       (case when sum(quantity) over (partition by store_id order by quantity desc) - quantity <
                  0.5 * sum(quantity over (partition by store_id) as running_ratio
             then product_name
             else 'Other'
        end) as product_name
from t;
</code>```

Note that this produces a separate row for each Other, as in your example.  In practice, I would want to combine them.  If you want that (and can't figure out how to do it), then ask another question.

Body:
    store_id   product_name   quantity
       1          apple          10
       1          orange         12
       1          grapes          9
       1          mango          17
       2          chicken        112
       2          beef           90
       2          pork           89
       2          lamb           115

I want to group them from top and bottom 50% based on the percentage of their grandtotal grouped by their store_id, and label the bottom product as 'others'
something that looks like this:

     store_id    product_name    percent
        1           mango         35.42%
        1           orange        25.00%
        1           OTHER         20.83%
        1           OTHER         18.75%
        2           lamb          28.33%
        2           chicken       27.59%
        2           OTHER         22.17%
        2           OTHER         21.92%

Is this possible? I really had a hard time google-ing this that's why I came here. Thanks!

Body:
I would write this as:

select t.*,
       quantity / sum(quantity) over (partition by store_id) as ratio,
       (case when sum(quantity) over (partition by store_id order by quantity desc) - quantity <
                  0.5 * sum(quantity over (partition by store_id) as running_ratio
             then product_name
             else 'Other'
        end) as product_name
from t;

Note that this produces a separate row for each Other, as in your example.  In practice, I would want to combine them.  If you want that (and can't figure out how to do it), then ask another question.


问:
How do I initialise the size of my struct array, depending on the user input in C?
I've created a struct and now I want to initialise an array of those structs, which size would depend on the user's input;

```<code>struct StarsStruct
{
    int SerialNumber = 1;
    char StarName[6] = "Peter";
    double x = 0;
    double y = 0;
};
int NumberOfStars = 0;
if (strcmp(CurrentCommand, "bang") == 0)
    {
        Clear();

        printf("Enter the number of stars to be created: ");
        scanf("%d", &NumberOfStars);

        StarsStruct Stars[NumberOfStars];
    }
</code>```

However, on the last line of code, I'm greeted with an error; "Expression must have a constant value". So am I not able to just get a value from my scanf and use it to initialise the struct array?

答:
You will have to use malloc instead,

```<code>StarsStruct *Stars = malloc(sizeof(struct StarsStruct) * NumberOfStars));
</code>```

You can now index Stars as if it were an array.

Body:
I've created a struct and now I want to initialise an array of those structs, which size would depend on the user's input;

struct StarsStruct
{
    int SerialNumber = 1;
    char StarName[6] = "Peter";
    double x = 0;
    double y = 0;
};
int NumberOfStars = 0;
if (strcmp(CurrentCommand, "bang") == 0)
    {
        Clear();

        printf("Enter the number of stars to be created: ");
        scanf("%d", &NumberOfStars);

        StarsStruct Stars[NumberOfStars];
    }

However, on the last line of code, I'm greeted with an error; "Expression must have a constant value". So am I not able to just get a value from my scanf and use it to initialise the struct array?

Body:
You will have to use malloc instead,

StarsStruct *Stars = malloc(sizeof(struct StarsStruct) * NumberOfStars));

You can now index Stars as if it were an array.


问:
How to mirror and resize the part of image with fixed width and height

I'm building "Tagging from photo" functionality.

When the user move or pinch the square on the image,

PanResponder changes the state of x-coordinate(left), y-coordinate(top), the length of square(thumbSize)

With the data, I want to show the part of square real-time

So this image below should be placed into the left of A, All All from the image above.

Here is the part of render showing the "cropped" image.

```<code>console.log(left) // 80
console.log(top) // 200
console.log(thumbSize) // 150
<Image
      source={{uri: image}}
      style={{height:70, width: 70, bottom: (-top), right: (-left)
      }} <- style is not complete. I'm putting some example code
/>
</code>```

This is continuous problem from: How to show the only part of the image.

It works but the solution doesn't meet my expectation.

It's not changing width and height ( I want to fix resize the image from 'the width of square' to '70' for each width and height)

It breaks the whole style (A, All, All things disappear)

I've been trying to solve this idea for days but couldn't find the exact way.

Update: I almost solved it but resizing matters

I changed Image to CroppedImage (new component)

```<code><CroppedImage
      source={{uri: image}}
      cropTop={top}
      cropLeft={left}
      cropWidth={thumbSize}
      cropHeight={thumbSize}
      width={width(100)}
      height={width(100)}
      resizeMode="contain" />
</code>```

Here is CroppedImage

```<code>return (
  <View style={[{
    overflow: 'hidden',
    height: this.props.cropHeight,
    width: this.props.cropWidth,
    backgroundColor: 'transparent'
    }, this.props.style]}>
    <Image style={{
      position: 'absolute',
      top: this.props.cropTop * -1,
      left: this.props.cropLeft * -1,
      width: this.props.width,
      height: this.props.height
    }}
      source={this.props.source}
      resizeMode={this.props.resizeMode}>
      {this.props.children}
    </Image>
  </View>
);
</code>```

It seems working but it can't resize (from square width x height to 70x70).

答:
Well, I finally managed to create a working React Native code (never used it before, sorry if it is noobish code) doing the same as in my other answer.

Here is the code:

```<code>import React, { Component } from 'react';
import { TouchableWithoutFeedback, ImageBackground, Image, View, StyleSheet } from 'react-native';

const IMAGEURI = 'http://fakeimg.pl/300x300/';
const SIZERATIO = .6;
const IMAGEWIDTH = 300;
const IMAGEHEIGHT = 300;
const CROPIMAGEWIDTH = 100;
const CROPIMAGEHEIGHT = 100;

export default class App extends Component {
  state = {
    style: {
      marginLeft: 0,
      marginTop: 0,
    },
    uri: ''
  };

  repositionImage(event) {
    this.setState({
      style: {
        marginLeft: CROPIMAGEWIDTH/2 - event.nativeEvent.locationX*SIZERATIO,
        marginTop: CROPIMAGEHEIGHT/2 - event.nativeEvent.locationY*SIZERATIO
      },
      uri: IMAGEURI
    });
  }

  render() {
    return (
      <View>
        <TouchableWithoutFeedback onPress={(event) => this.repositionImage(event)}>
          <View>
            <Image
              style={styles.image}
              source={{ uri: IMAGEURI }}
            />
          </View>
        </TouchableWithoutFeedback>
        <View style={styles.tag}>
          <ImageBackground style={[styles.cropped,this.state.style]} source={{uri: this.state.uri }} />
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  image: {
    width: IMAGEWIDTH,
    height: IMAGEHEIGHT,
  },

  tag: {
    borderWidth: 1,
    borderColor: '#000',
    width: CROPIMAGEWIDTH,
    height: CROPIMAGEHEIGHT,
    overflow: 'hidden'
  },

  cropped: {
    width: IMAGEWIDTH*SIZERATIO,
    height: IMAGEHEIGHT*SIZERATIO
  }
});
</code>```

And here is the Snack

I really hope it helped!! Good luck!!

EDIT: Ok I will explain a bit what I'm doing here.

First, I set a State with the parameters that will change based on some event:

```<code> state = {
    style: {
      marginLeft: 0,
      marginTop: 0,
    },
    uri: ''
  };
</code>```

Then, I make the component to get its properties from that state:

< ImageBackground style={[styles.cropped,this.state.style]} source={{uri: this.state.uri }} />

Finally, I prepare the onPress event to call a function which will update the state:

< TouchableWithoutFeedback onPress={(event) => this.repositionImage(event)}>

Here I'm feeding my function with the event object so I will be available to get the coordinates where the user pressed.

That last function takes the data from the event and updates the state. The view will automatically refresh with the new state data.

```<code>repositionImage(event) {
  this.setState({
    style: {
      marginLeft: CROPIMAGEWIDTH/2 - event.nativeEvent.locationX*SIZERATIO,
      marginTop: CROPIMAGEHEIGHT/2 - event.nativeEvent.locationY*SIZERATIO
    },
    uri: IMAGEURI
  });
}
</code>```

To position the image, I simply do a math operation:

CROPIMAGEWIDTH is the width of my tag element so to get the center I divide it by 2. Then, I substract the locationX of the event to move the image to the left so the locationX will be at the center of the tag.

That is only for positioning. To scale it just multiply the size of the image and the locationX by the same value. Note I multiplied the width and height of the image with the SIZERATIO in the cropped style

```<code>cropped: {
  width: IMAGEWIDTH*SIZERATIO,
  height: IMAGEHEIGHT*SIZERATIO
}
</code>```

An example of this scaling stuff:

If your image has 200 width and you want to scale it to a half, you multiply it by 0.5. So if you click at the, say, pixel 180 starting for the left, the equivalent pixel for your scaled image will have to be multiplied by 0.5 too and it will be 90.

If there is something I didn't explaing clearly enough just ask me again a I will be glad to help you.

Body:
I'm building "Tagging from photo" functionality.

When the user move or pinch the square on the image,

PanResponder changes the state of x-coordinate(left), y-coordinate(top), the length of square(thumbSize)

With the data, I want to show the part of square real-time

So this image below should be placed into the left of A, All All from the image above.

Here is the part of render showing the "cropped" image.

console.log(left) // 80
console.log(top) // 200
console.log(thumbSize) // 150
<Image
      source={{uri: image}}
      style={{height:70, width: 70, bottom: (-top), right: (-left)
      }} <- style is not complete. I'm putting some example code
/>

This is continuous problem from: How to show the only part of the image.

It works but the solution doesn't meet my expectation.

It's not changing width and height ( I want to fix resize the image from 'the width of square' to '70' for each width and height)

It breaks the whole style (A, All, All things disappear)

I've been trying to solve this idea for days but couldn't find the exact way.

Update: I almost solved it but resizing matters

I changed Image to CroppedImage (new component)

<CroppedImage
      source={{uri: image}}
      cropTop={top}
      cropLeft={left}
      cropWidth={thumbSize}
      cropHeight={thumbSize}
      width={width(100)}
      height={width(100)}
      resizeMode="contain" />

Here is CroppedImage

return (
  <View style={[{
    overflow: 'hidden',
    height: this.props.cropHeight,
    width: this.props.cropWidth,
    backgroundColor: 'transparent'
    }, this.props.style]}>
    <Image style={{
      position: 'absolute',
      top: this.props.cropTop * -1,
      left: this.props.cropLeft * -1,
      width: this.props.width,
      height: this.props.height
    }}
      source={this.props.source}
      resizeMode={this.props.resizeMode}>
      {this.props.children}
    </Image>
  </View>
);

It seems working but it can't resize (from square width x height to 70x70).

Body:
Well, I finally managed to create a working React Native code (never used it before, sorry if it is noobish code) doing the same as in my other answer.

Here is the code:

import React, { Component } from 'react';
import { TouchableWithoutFeedback, ImageBackground, Image, View, StyleSheet } from 'react-native';

const IMAGEURI = 'http://fakeimg.pl/300x300/';
const SIZERATIO = .6;
const IMAGEWIDTH = 300;
const IMAGEHEIGHT = 300;
const CROPIMAGEWIDTH = 100;
const CROPIMAGEHEIGHT = 100;

export default class App extends Component {
  state = {
    style: {
      marginLeft: 0,
      marginTop: 0,
    },
    uri: ''
  };

  repositionImage(event) {
    this.setState({
      style: {
        marginLeft: CROPIMAGEWIDTH/2 - event.nativeEvent.locationX*SIZERATIO,
        marginTop: CROPIMAGEHEIGHT/2 - event.nativeEvent.locationY*SIZERATIO
      },
      uri: IMAGEURI
    });
  }

  render() {
    return (
      <View>
        <TouchableWithoutFeedback onPress={(event) => this.repositionImage(event)}>
          <View>
            <Image
              style={styles.image}
              source={{ uri: IMAGEURI }}
            />
          </View>
        </TouchableWithoutFeedback>
        <View style={styles.tag}>
          <ImageBackground style={[styles.cropped,this.state.style]} source={{uri: this.state.uri }} />
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  image: {
    width: IMAGEWIDTH,
    height: IMAGEHEIGHT,
  },

  tag: {
    borderWidth: 1,
    borderColor: '#000',
    width: CROPIMAGEWIDTH,
    height: CROPIMAGEHEIGHT,
    overflow: 'hidden'
  },

  cropped: {
    width: IMAGEWIDTH*SIZERATIO,
    height: IMAGEHEIGHT*SIZERATIO
  }
});

And here is the Snack

I really hope it helped!! Good luck!!

EDIT: Ok I will explain a bit what I'm doing here.

First, I set a State with the parameters that will change based on some event:

 state = {
    style: {
      marginLeft: 0,
      marginTop: 0,
    },
    uri: ''
  };

Then, I make the component to get its properties from that state:

< ImageBackground style={[styles.cropped,this.state.style]} source={{uri: this.state.uri }} />

Finally, I prepare the onPress event to call a function which will update the state:

< TouchableWithoutFeedback onPress={(event) => this.repositionImage(event)}>

Here I'm feeding my function with the event object so I will be available to get the coordinates where the user pressed.

That last function takes the data from the event and updates the state. The view will automatically refresh with the new state data.

repositionImage(event) {
  this.setState({
    style: {
      marginLeft: CROPIMAGEWIDTH/2 - event.nativeEvent.locationX*SIZERATIO,
      marginTop: CROPIMAGEHEIGHT/2 - event.nativeEvent.locationY*SIZERATIO
    },
    uri: IMAGEURI
  });
}

To position the image, I simply do a math operation:

CROPIMAGEWIDTH is the width of my tag element so to get the center I divide it by 2. Then, I substract the locationX of the event to move the image to the left so the locationX will be at the center of the tag.

That is only for positioning. To scale it just multiply the size of the image and the locationX by the same value. Note I multiplied the width and height of the image with the SIZERATIO in the cropped style

cropped: {
  width: IMAGEWIDTH*SIZERATIO,
  height: IMAGEHEIGHT*SIZERATIO
}

An example of this scaling stuff:

If your image has 200 width and you want to scale it to a half, you multiply it by 0.5. So if you click at the, say, pixel 180 starting for the left, the equivalent pixel for your scaled image will have to be multiplied by 0.5 too and it will be 90.

If there is something I didn't explaing clearly enough just ask me again a I will be glad to help you.


问:
show part of a text and then with a "read more" show the rest instantly angular2
I want to show only 50 characters of a text, and then "read more" than if I click I will show the full text, I'm doing it in angular2 and I'm trying to do it in typescript, I leave the code I have.

HTML:

```<code>    <table width="200px">
        <tr>
            <td>
                <div id="el_div">
                    uno dos tres cuatro cinco seis siete ocho nueve diez once doce trece catorce quince dieciseis diecisiete dieciocho diecinueve
                    veinte
                    uno dos tres cuatro cinco seis siete ocho nueve diez once doce trece catorce quince dieciseis diecisiete dieciocho diecinueve
                    veinte</div>
                <br />
                <div style="font-family:Courier New;font-size:8pt;color:Blue;cursor:hand" onclick="gestionarTexto(this);" id="mas">Leer más</div>
            </td>
        </tr>
    </table>

</body>
</code>```

TYPESCRIPT:

```<code>import { Component } from '@angular/core';

@Component({
   selector: 'produccion',
   styleUrls: ['./produccion.scss'],
   templateUrl: './produccion.html'
})
export class Produccion {

  constructor() {
  }

  texto_original: string;
  gestionarTexto(div) {
      if (div.innerHTML == 'Volver') { this.contraer(); div.innerHTML =
      'Leer más'; }
      else { this.expandir(); div.innerHTML = 'Volver' }
  }
  contraer() {
    this.texto_original = document.getElementById('el_div').innerHTML;
    document.getElementById('el_div').innerHTML =
    this.texto_original.substring(0, 50) + '...';
  }
  expandir() {
    document.getElementById('el_div').innerHTML = this.texto_original;
  }
}
</code>```

If you can lend me a hand, because it does not work for me, I do not know if the HTML or TYPESCRIPT part is wrong.

答:
I tried it using angular pipe.

HTML:

```<code><table width="200px">
        <tr>
            <td>
                <div id="el_div" >{{strText | showChar:togglePipe}}</div>
                    <button *ngIf="strText.length > 50" (click)="showMoreText()">{{togglePipe ? "Show More" : "Show Less"}}</button>
                <br />
                <!-- <div style="font-family:Courier New;font-size:8pt;color:Blue;cursor:hand" (click)="gestionarTexto(this);" id="mas">Leer más</div> -->
            </td>
        </tr>
    </table>
</code>```

Component.ts

```<code>strText:string = "uno dos tres cuatro cinco seis siete ocho nueve diez once doce trece catorce quince dieciseis diecisiete dieciocho diecinueve veinte uno dos tres cuatro cinco seis siete ocho nueve diez once doce trece catorce quince dieciseis diecisiete dieciocho diecinueve veinte";
  togglePipe: boolean = true;
  showMore: boolean = true;
  showMoreText() {
    this.togglePipe = !this.togglePipe;

  }
</code>```

pipe.ts

```<code>import { PipeTransform, Pipe } from "@angular/core";

@Pipe({
    name: 'showChar'
})
export class showCharPipe implements PipeTransform{

    transform(value:string,togglePipe:boolean): string {
        if(value.length > 50 && togglePipe){
            return value.substring(0, 50) + '...';
        }else{
            return value;
        }

    }

}
</code>```

All the best buddy

Body:
I want to show only 50 characters of a text, and then "read more" than if I click I will show the full text, I'm doing it in angular2 and I'm trying to do it in typescript, I leave the code I have.

HTML:

                    uno dos tres cuatro cinco seis siete ocho nueve diez once doce trece catorce quince dieciseis diecisiete dieciocho diecinueve
                    veinte
                    uno dos tres cuatro cinco seis siete ocho nueve diez once doce trece catorce quince dieciseis diecisiete dieciocho diecinueve
                    veinte

Leer más

TYPESCRIPT:

import { Component } from '@angular/core';

@Component({
   selector: 'produccion',
   styleUrls: ['./produccion.scss'],
   templateUrl: './produccion.html'
})
export class Produccion {

  constructor() {
  }

  texto_original: string;
  gestionarTexto(div) {
      if (div.innerHTML == 'Volver') { this.contraer(); div.innerHTML =
      'Leer más'; }
      else { this.expandir(); div.innerHTML = 'Volver' }
  }
  contraer() {
    this.texto_original = document.getElementById('el_div').innerHTML;
    document.getElementById('el_div').innerHTML =
    this.texto_original.substring(0, 50) + '...';
  }
  expandir() {
    document.getElementById('el_div').innerHTML = this.texto_original;
  }
}

If you can lend me a hand, because it does not work for me, I do not know if the HTML or TYPESCRIPT part is wrong.

Body:
I tried it using angular pipe.

HTML:

<table width="200px">
        <tr>
            <td>
                <div id="el_div" >{{strText | showChar:togglePipe}}</div>
                    <button *ngIf="strText.length > 50" (click)="showMoreText()">{{togglePipe ? "Show More" : "Show Less"}}</button>
                <br />
                <!-- <div style="font-family:Courier New;font-size:8pt;color:Blue;cursor:hand" (click)="gestionarTexto(this);" id="mas">Leer más</div> -->
            </td>
        </tr>
    </table>

Component.ts

strText:string = "uno dos tres cuatro cinco seis siete ocho nueve diez once doce trece catorce quince dieciseis diecisiete dieciocho diecinueve veinte uno dos tres cuatro cinco seis siete ocho nueve diez once doce trece catorce quince dieciseis diecisiete dieciocho diecinueve veinte";
  togglePipe: boolean = true;
  showMore: boolean = true;
  showMoreText() {
    this.togglePipe = !this.togglePipe;

  }

pipe.ts

import { PipeTransform, Pipe } from "@angular/core";

@Pipe({
    name: 'showChar'
})
export class showCharPipe implements PipeTransform{

    transform(value:string,togglePipe:boolean): string {
        if(value.length > 50 && togglePipe){
            return value.substring(0, 50) + '...';
        }else{
            return value;
        }

    }

}

All the best buddy


问:
Alter data in object of arrays
In a React app, I have this type of data:

```<code>const data = {
  open: [{
    id: 1,
    name: 'test 1'
  }, {
    id: 2,
    name: 'test 2'
  }],
  close: [{
    id: 3,
    name: 'test 3'
  }, {
    id: 4,
    name: 'test 4'
  }]
}
</code>```

I want to iterate over each object in the open and close arrays and return the existing data with additional type field. E.g.:

```<code>const data = {
  open: [{
    id: 1,
    name: 'test 1',
    type: 'alert'
  }, {...],
  close: [...]
}
</code>```

I'm trying something like this, but it returns undefined instead of the altered data:

```<code>const expandData = (data) => {
  return Object.keys(data).forEach((key) => {
    return data[key].map((item, idx) => ({
      ...item,
      type: 'alert'
    }))
  })
}

// call in another method
expandData(data) // the `data` above
</code>```

https://jsfiddle.net/x5aspec2/

答:
You can use reduce() instead of forEach() and return object.

const data = {"open":[{"id":1,"name":"test 1"},{"id":2,"name":"test 2"}],"close":[{"id":3,"name":"test 3"},{"id":4,"name":"test 4"}]}

function expandData (data) {
  return Object.keys(data)
    .reduce((r, k) => {
      r[k] = data[k].map(o => ({...o, type: 'alert'}))
       return r;
    }, {})
}

const result = expandData(data)
console.log(result)```

Title: Alter data in object of arrays

Body:
In a React app, I have this type of data:

const data = {
  open: [{
    id: 1,
    name: 'test 1'
  }, {
    id: 2,
    name: 'test 2'
  }],
  close: [{
    id: 3,
    name: 'test 3'
  }, {
    id: 4,
    name: 'test 4'
  }]
}

I want to iterate over each object in the open and close arrays and return the existing data with additional type field. E.g.:

const data = {
  open: [{
    id: 1,
    name: 'test 1',
    type: 'alert'
  }, {...],
  close: [...]
}

I'm trying something like this, but it returns undefined instead of the altered data:

const expandData = (data) => {
  return Object.keys(data).forEach((key) => {
    return data[key].map((item, idx) => ({
      ...item,
      type: 'alert'
    }))
  })
}

// call in another method
expandData(data) // the `data` above

https://jsfiddle.net/x5aspec2/


答:
Your code is returning the result of the forEach call, which will always be undefined. (forEach has side effects, but doesn't return anything).

use map instead of forEach:

const data = { open: [{ id: 1,
                        name: 'test 1'
                      }, {
                        id: 2,
                        name: 'test 2'
                      }],
               close: [{id: 3,
                        name: 'test 3'
                      }, {
                        id: 4,
                        name: 'test 4'
                      }]
             };

const expandData = (data) => {
  return Object.keys(data).map((key) => { //<-- use map here instead of forEach
    return data[key].map((item, idx) => ({
      ...item,
      type: 'alert'
    }))
  })
}

document.write('```'+JSON.stringify(expandData(data),null,2)+'```')```

Title: Alter data in object of arrays

Body:
Your code is returning the result of the forEach call, which will always be undefined. (forEach has side effects, but doesn't return anything).

use map instead of forEach:

const data = { open: [{ id: 1,
                        name: 'test 1'
                      }, {
                        id: 2,
                        name: 'test 2'
                      }],
               close: [{id: 3,
                        name: 'test 3'
                      }, {
                        id: 4,
                        name: 'test 4'
                      }]
             };

const expandData = (data) => {
  return Object.keys(data).map((key) => { //<-- use map here instead of forEach
    return data[key].map((item, idx) => ({
      ...item,
      type: 'alert'
    }))
  })
}

document.write('<pre>'+JSON.stringify(expandData(data),null,2)+'</pre>')


问:
jQuery Newbie, need a little help
Okay, so I am in the process of recreating this feature:

http://www.w3.org/html/logo/#the-technology

I current have it so when you click on a link, it will add a class to the image that relates to that link (href="#one" on the  and then id="#one" on the ), however it is currently not going through each  tag and only one. And also it is not removing the class I requested.

Code follows:

JS

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

var container = '#portfolio #text_container';

var img_container = '#portfolio #image_container';

$(container).children('a').bind('click', function() {

var this_attr = $(this).attr('href');

var this_img = $(img_container).find('img').attr('id');

if(this_attr == this_img) {

    //$(img_container).find('img').hasClass('current').removeClass('current');

        // ^^^ This line isn't working, any ideas? :/

    $(img_container + ' img[id*="' + this_attr + '"]').addClass('current');

}

else {

    alert(this_img + ' this img');

        alert(this_attr + ' this attr');

}

  });

});
</code>```

And the HTML is as follows

```<code><div id="portfolio">

    <div id="image_container">
        <img src="http://static.jquery.com/files/rocker/images/logo_jquery_215x53.gif" alt="" class="current" id="#one" />
        <img src="http://static.jquery.com/files/rocker/images/btn_downloadLarge.gif" alt="" id="#two" />
    </div>

    <div id="text_container">
        <a href="#one" class="link">Item 1</a>
        <a href="#two" class="link">Item 2</a>

        <p id="#one" class="current">A bunch of text!</p>
        <p id="#two">The second bunch of text!</p>
    </div>

</div>
</code>```

Please let me know if you need any more information :)

rcravens fixed this with the following code..

JS

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

    $('#text_container a').click(function(evt) {
        evt.preventDefault();

        $('.current').removeClass('current');

        var href = $(this).attr('href');

        $("." + href).addClass('current');

    });
</code>```

And the HTML..

```<code><div id="portfolio">

    <div id="image_container">
        <img src="http://static.jquery.com/files/rocker/images/logo_jquery_215x53.gif" alt="" class="one current" />
        <img src="http://static.jquery.com/files/rocker/images/btn_downloadLarge.gif" alt="" class="two" />
    </div>

    <div id="text_container">
        <a href="one" class="link">Item 1</a>
        <a href="two" class="link">Item 2</a>

        <p class="one current">A bunch of text!</p>
        <p class="two">The second bunch of text!</p>
    </div>

</div>
</code>```

答:
The reason this isn't working:

```<code>if(this_attr == this_img)
</code>```

is because this_attr is a URL and this_img is an ID attribute value.

ContentLicense: CC BY-SA 2.5

Title: jQuery Newbie, need a little help

Body:
Okay, so I am in the process of recreating this feature:

http://www.w3.org/html/logo/#the-technology

I current have it so when you click on a link, it will add a class to the image that relates to that link (href="#one" on the  and then id="#one" on the ), however it is currently not going through each  tag and only one. And also it is not removing the class I requested.

Code follows:

JS

$(document).ready(function() {

var container = '#portfolio #text_container';

var img_container = '#portfolio #image_container';

$(container).children('a').bind('click', function() {

var this_attr = $(this).attr('href');

var this_img = $(img_container).find('img').attr('id');

if(this_attr == this_img) {

    //$(img_container).find('img').hasClass('current').removeClass('current');

        // ^^^ This line isn't working, any ideas? :/

    $(img_container + ' img[id*="' + this_attr + '"]').addClass('current');

}

else {

    alert(this_img + ' this img');

        alert(this_attr + ' this attr');

}

  });

});

And the HTML is as follows

        Item 1
        Item 2

A bunch of text!

The second bunch of text!

Please let me know if you need any more information :)

rcravens fixed this with the following code..

JS

$(document).ready(function() {

    $('#text_container a').click(function(evt) {
        evt.preventDefault();

        $('.current').removeClass('current');

        var href = $(this).attr('href');

        $("." + href).addClass('current');

    });

And the HTML..

        Item 1
        Item 2

A bunch of text!

The second bunch of text!

Body:
The reason this isn't working:

if(this_attr == this_img)

is because this_attr is a URL and this_img is an ID attribute value.


问:
Push document into sub document in array of mongoose model
in my company schema i have a posted job which is type array and will hold subdocuments

companySchema.js

```<code>PostedJobs : [{
        JobName : { type: String, required : true},
        JobType : { type: String, required : true},
        JobLocation : { type: String, required : true},
        JobSalay: { type: String, required : true}
    }],
</code>```

in my /company route i get all company registered by specific user through Creatorentity in model

to get that user company i use

```<code>  router.get('/',  isLoggedIn ,  function(req, res, next) {
    Company.find({'Creator': req.user.id}).then(function(companies) {
        res.render('Company', { "Companies" : companies });
    });
});
</code>```

after getting company i want to visit a specific company page on clicking company name(unique)

```<code>router.get('/:name' , isLoggedIn , function(req , res , next) {
    var name = req.params.name;
    Company.findOne({Name : name}).then(function(Company) {
         res.render('dashboard',{
            "Company" : Company,
             errors : []
        });
    })
});
</code>```

now i want to post a job to this specific company from a POST route as
my req.body consist of JobName , JobType , JobLocation and JobSalary which i have assigned to a specific variable  now how should i push this doc to array

POST route

```<code>router.post('/:name' , isLoggedIn , function(req , res , next) {
    var JobName = req.body.JobName;
    var JobType = req.body.JobType;
    var JobLocation = req.body.JobLocation;
    var Salary = req.body.Salary;
    //push this job to that specific comapny
});
</code>```

答:
I don't know the schema of your company, but if you want to add PostedJobs to the companies, you should define an array field in it.</p>

```<code>router.post('/:name' , isLoggedIn , function(req , res , next) {
    var JobName = req.body.JobName;
    var JobType = req.body.JobType;
    var JobLocation = req.body.JobLocation;
    var Salary = req.body.Salary;
    //push this job to that specific comapny
    // create the postedJob object
    var postedJob = {JobName : JobName, JobType : JobType, JobLocation : JobLocation, JobSalay:Salary};
    // find the company in DB and add the postedJob to its array of postedJobs
    var name = req.params.name;
    Company.findOne({Name : name}).then(function(company) {
        //modify and save the object received via callback
        company.postedJobs.push(postedJob);
        company.save();
    });
});
</code>```

Body:
in my company schema i have a posted job which is type array and will hold subdocuments

companySchema.js

PostedJobs : [{
        JobName : { type: String, required : true},
        JobType : { type: String, required : true},
        JobLocation : { type: String, required : true},
        JobSalay: { type: String, required : true}
    }],

in my /company route i get all company registered by specific user through Creatorentity in model

to get that user company i use

  router.get('/',  isLoggedIn ,  function(req, res, next) {
    Company.find({'Creator': req.user.id}).then(function(companies) {
        res.render('Company', { "Companies" : companies });
    });
});

after getting company i want to visit a specific company page on clicking company name(unique)

router.get('/:name' , isLoggedIn , function(req , res , next) {
    var name = req.params.name;
    Company.findOne({Name : name}).then(function(Company) {
         res.render('dashboard',{
            "Company" : Company,
             errors : []
        });
    })
});

now i want to post a job to this specific company from a POST route as
my req.body consist of JobName , JobType , JobLocation and JobSalary which i have assigned to a specific variable  now how should i push this doc to array

POST route

router.post('/:name' , isLoggedIn , function(req , res , next) {
    var JobName = req.body.JobName;
    var JobType = req.body.JobType;
    var JobLocation = req.body.JobLocation;
    var Salary = req.body.Salary;
    //push this job to that specific comapny
});

Body:
I don't know the schema of your company, but if you want to add PostedJobs to the companies, you should define an array field in it.

router.post('/:name' , isLoggedIn , function(req , res , next) {
    var JobName = req.body.JobName;
    var JobType = req.body.JobType;
    var JobLocation = req.body.JobLocation;
    var Salary = req.body.Salary;
    //push this job to that specific comapny
    // create the postedJob object
    var postedJob = {JobName : JobName, JobType : JobType, JobLocation : JobLocation, JobSalay:Salary};
    // find the company in DB and add the postedJob to its array of postedJobs
    var name = req.params.name;
    Company.findOne({Name : name}).then(function(company) {
        //modify and save the object received via callback
        company.postedJobs.push(postedJob);
        company.save();
    });
});

ContentLicense: CC BY-SA 4.0


问:
Trying to update a mongodb document field via pug/node.js button click
This is a document from my todo mongodb:

```<code>"_id" : ObjectId("5a1e96f856f24c43b886eb54"),
"title" : "Drink coffee",
"note" : "Tomorrow morning",
"open" : true,
"duedate" : "2017-12-03"
</code>```

This is the pug code that populates a todo list page

```<code>each todo in todolist
   if todo.open
      div
         a(href="#") #{todo.title}
      div
         p(style='white-space:pre;')
          |   #{todo.note}
          |   Due: #{todo.duedate}
          button(id="doneButton") Done
</code>```

The above works fine. The todo page displays all todo items as expected.

What I want to do:
When user clicks on 'Done' button, I want to update that particular document to "open": false.
(I want to do this onclick, and not by loading the item on a new edit page with an edit button. When todo list page reloads, that todo item is removed from the list. I do not want to delete the document as I need to archive it later on.)

So my questions are:

How do I code the 'Done' button on the pug page so that it gets
associated with the particular document that needs to be updated?

How do I structure the POST code on my index.js so that it listens for
the button click and performs the relevant document update?

UPDATE

OK, so I don't know enough to understand kentor's reply (but thank you anyway!). I did a bit of research though and some copying and pasting, and I have moved the problem a couple of steps forward - I hope.

New pug code:

```<code>each todo in todolist
   if todo.open
      a(href="#") #{todo.title}
      p #{todo.note}
      p Due: #{todo.duedate}
      form#form_update_item(name="updateitem", method='post', action='/updateitem')
      input#input_name(type="hidden", placeholder="", name="_id", value="#{todo._id}")
      button(type="submit") Done
</code>```

index.js code

```<code>router.post('/updateitem', function(req, res) {
  var MongoClient = mongodb.MongoClient;

  var ObjectId = require('mongodb').ObjectId;

  var url = 'mongodb://localhost:27017/tododb';

  MongoClient.connect(url, function(err, db) {
    if (err) {
      console.log("can't connect", err);
    }
    else {
      console.log('Connected to server. Woohoo!');

      var collection = db.collection('todolist');

      collection.findOneAndUpdate(
        {"title": "Make smoothie"},
        {
        $set: {
          "open": false
          }
        },
        function(err, result) {
          if (err) {
              console.log(err);
          } else {
              res.redirect("todolist");
          }
          db.close();
      });
    }
  });
});
</code>```

What happens now:

On button click, doc with title "Make Smoothie" changes to "open": false. So button triggers the change I want. Bang! But this is only a partial solution to help me isolate the problem.

What I still need:

On button click, I want the doc's ID whose button was clicked to replace {"title": "Make smoothie"} so that the "open": false change can be made. Something like {_id: "doc ID coming from button blah blah"}.

UPDATE 2

Discovered that I was using Jade syntax not Pug, so instead of this

```<code>value="#{todo._id}
</code>```

I should be using

```<code>value=todo._id
</code>```

So now index.js can console.log the ID the Pug form is passing. Last challenge is to use that ID to change the corresponding mongodb document as described above.

答:
I finally solved it

Last step, I replaced

```<code>{"title": "Make smoothie"}
</code>```

with

```<code>{"_id": ObjectId(req.body._id)}
</code>```

and sure enough, every time I click on a button, the server updates the corresponding document's "open": false

Body:
This is a document from my todo mongodb:

"_id" : ObjectId("5a1e96f856f24c43b886eb54"),
"title" : "Drink coffee",
"note" : "Tomorrow morning",
"open" : true,
"duedate" : "2017-12-03"

This is the pug code that populates a todo list page

each todo in todolist
   if todo.open
      div
         a(href="#") #{todo.title}
      div
         p(style='white-space:pre;')
          |   #{todo.note}
          |   Due: #{todo.duedate}
          button(id="doneButton") Done

The above works fine. The todo page displays all todo items as expected.

What I want to do:
When user clicks on 'Done' button, I want to update that particular document to "open": false.
(I want to do this onclick, and not by loading the item on a new edit page with an edit button. When todo list page reloads, that todo item is removed from the list. I do not want to delete the document as I need to archive it later on.)

So my questions are:

How do I code the 'Done' button on the pug page so that it gets
associated with the particular document that needs to be updated?

How do I structure the POST code on my index.js so that it listens for
the button click and performs the relevant document update?

UPDATE

OK, so I don't know enough to understand kentor's reply (but thank you anyway!). I did a bit of research though and some copying and pasting, and I have moved the problem a couple of steps forward - I hope.

New pug code:

each todo in todolist
   if todo.open
      a(href="#") #{todo.title}
      p #{todo.note}
      p Due: #{todo.duedate}
      form#form_update_item(name="updateitem", method='post', action='/updateitem')
      input#input_name(type="hidden", placeholder="", name="_id", value="#{todo._id}")
      button(type="submit") Done

index.js code

router.post('/updateitem', function(req, res) {
  var MongoClient = mongodb.MongoClient;

  var ObjectId = require('mongodb').ObjectId;

  var url = 'mongodb://localhost:27017/tododb';

  MongoClient.connect(url, function(err, db) {
    if (err) {
      console.log("can't connect", err);
    }
    else {
      console.log('Connected to server. Woohoo!');

      var collection = db.collection('todolist');

      collection.findOneAndUpdate(
        {"title": "Make smoothie"},
        {
        $set: {
          "open": false
          }
        },
        function(err, result) {
          if (err) {
              console.log(err);
          } else {
              res.redirect("todolist");
          }
          db.close();
      });
    }
  });
});

What happens now:

On button click, doc with title "Make Smoothie" changes to "open": false. So button triggers the change I want. Bang! But this is only a partial solution to help me isolate the problem.

What I still need:

On button click, I want the doc's ID whose button was clicked to replace {"title": "Make smoothie"} so that the "open": false change can be made. Something like {_id: "doc ID coming from button blah blah"}.

UPDATE 2

Discovered that I was using Jade syntax not Pug, so instead of this

value="#{todo._id}

I should be using

value=todo._id

So now index.js can console.log the ID the Pug form is passing. Last challenge is to use that ID to change the corresponding mongodb document as described above.

Body:
I finally solved it

Last step, I replaced

{"title": "Make smoothie"}

with

{"_id": ObjectId(req.body._id)}

and sure enough, every time I click on a button, the server updates the corresponding document's "open": false


问:
Cordova iOS location message
I use the plugin cordova-plugin-geolocation. My only issue is that the message prompt to allow location looks like this:

/var/container/bundle/application/xxxxxx-xxxx-xxxx-xxxx-xxxxxxxx/my_project/www/index.html
  Would like to use your location.

Is there anyway to have something a little bit sexier, like

my_project would like to use your location

Cheers.

Added some code, for the non believers

```<code>document.addEventListener("deviceready", onDeviceReady, false);

function onDeviceReady(){

    navigator.geolocation.getCurrentPosition(onLocationSuccess, onLocationError, {maximumAge:3000, timeout:2000, enableHighAccuracy:true});

    function onLocationSuccess(){

    }

    function onLocationError(){

    }
 }
</code>```

答:
It seems like the version 3.0.0 of cordova-plugin-geolocation  ignores the install parameter

--variable GEOLOCATION_USAGE_DESCRIPTION=""

like Bruno Peres said above.

It works fine for me installing the  2.4.3  version.

Title: Cordova iOS location message

Body:
I use the plugin cordova-plugin-geolocation. My only issue is that the message prompt to allow location looks like this:

/var/container/bundle/application/xxxxxx-xxxx-xxxx-xxxx-xxxxxxxx/my_project/www/index.html
  Would like to use your location.

Is there anyway to have something a little bit sexier, like

my_project would like to use your location

Cheers.

Added some code, for the non believers

document.addEventListener("deviceready", onDeviceReady, false);

function onDeviceReady(){

    navigator.geolocation.getCurrentPosition(onLocationSuccess, onLocationError, {maximumAge:3000, timeout:2000, enableHighAccuracy:true});

    function onLocationSuccess(){

    }

    function onLocationError(){

    }
 }


问:
CSS - Unable to center vertically
I am trying to center vertically 4 divs present in a Bootstrap row.
Here is my basic code :

```<code><div class="row">
     <div class="col-md-3"><button type="button" style="float:right; height: 40px;">Contact</button></div>
     <div class="col-md-3">Activity 1</div>
     <div class="col-md-3">Activity 2</div>
     <div class="col-md-3">Activity 3</div>
</div>
</code>```

So, I can't use Flexbox because I need to keep the button on the right of the row in medium screen and justify-self:flex-end is not enough to keep the button on the right of the row. I can't also move the row with the button at the end of the code, because I need to keep it in first for mobile devices.
I have also tried to use display:table and display:table-cell and it still not working.

Anyone has an idea ?

答:
Try to display row as flex, remove the float right for your button.
The simplest way is to use justify-content: space-between; and set the button just before the </row>.
Then, use align-items: center.

Title: CSS - Unable to center vertically

Body:
I am trying to center vertically 4 divs present in a Bootstrap row.
Here is my basic code :

<button type="button" style="float:right; height: 40px;">Contact</button>

Activity 1

Activity 2

Activity 3

So, I can't use Flexbox because I need to keep the button on the right of the row in medium screen and justify-self:flex-end is not enough to keep the button on the right of the row. I can't also move the row with the button at the end of the code, because I need to keep it in first for mobile devices.
I have also tried to use display:table and display:table-cell and it still not working.

Anyone has an idea ?


问:
if else statement is not able to parsed by GroovyClassLoader with if enter between if and condition start bracket
i developing one simple application and using groovy script

i am not able to parse if else Satement if enter between if and else .

E.G:

below is not working script :

```<code>def execute(){
    if
      (condition 1)
         {

        }

    else if
      (condition 2)
      {

      }
}
</code>```

working script :

```<code>if(condition 1)
         {

        }

    else if  (condition 2)
      {

      }
}
</code>```

if i remove enter from if and condition start bracket then it is working fine.

can any one suggest me the workarround for this ?

Error :

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
script1512377268429238880887.groovy: 48: expecting '(', found "" @ line 48, column 8.
       if
          ^

1 error

答:
Well, the syntax simply is invalid, what workaround are you after?

Either do not use newline between the if and the condition, or escape the newline character by using

```<code>if \
  (condition 1)
     {

    }

else if \
  (condition 2)
  {

  }
</code>```

Body:
i developing one simple application and using groovy script

i am not able to parse if else Satement if enter between if and else .

E.G:

below is not working script :

def execute(){
    if
      (condition 1)
         {

        }

    else if
      (condition 2)
      {

      }
}

working script :

if(condition 1)
         {

        }

    else if  (condition 2)
      {

      }
}

if i remove enter from if and condition start bracket then it is working fine.

can any one suggest me the workarround for this ?

Error :

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
script1512377268429238880887.groovy: 48: expecting '(', found "" @ line 48, column 8.
       if
          ^

1 error

Body:
Well, the syntax simply is invalid, what workaround are you after?

Either do not use newline between the if and the condition, or escape the newline character by using

if \
  (condition 1)
     {

    }

else if \
  (condition 2)
  {

  }


问:
Handling the order of dropping constraints in Postgres
I am using a tool called apgdiff 'https://www.apgdiff.com/' for finding the DDL diff between 2 postgres database. It parses 2 postgres dumps and generate the diff between the 2 dumps in terms of alter queries .

       The tool actually doesn't mind the order of creating or dropping  foreign key constraints while generating the diff. i.e. foreign key constraints should be created after primary key , or to be dropped before dropping the primary key . But still, what  makes me curious is a line of code in their sourcecode, which says that all the primary keys should be dropped first and then all other non-primary keys should be dropped . Do we have any such constraint in Postgres that the primary keys should be dropped first and then the remaining constraints ..

答:
If anything, other constraints should be dropped first, because foreign key constraints depend on primary key (or unique) constraints. It doesn't matter, though, if you use the CASCADE keyword when dropping the constraints.

I can't see a reason why dropping primary key constraints first should make a difference.


问:
What is BUCKET_ID in MediaStore?
I was browsing through some code that queries the MediaStore.Images content provider and uses a column named BUCKET_ID:

```<code>Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String projection[] = {
    "DISTINCT " + MediaStore.Images.Media.BUCKET_DISPLAY_NAME,
    MediaStore.Images.Media.BUCKET_ID,
    MediaStore.Images.Media.DATE_TAKEN,
    MediaStore.Images.Media.DATA
};
String BUCKET_GROUP_BY = "1) GROUP BY 1,(2";
String BUCKET_ORDER_BY = "MAX(datetaken) DESC";
Cursor imagecursor = getContentResolver().query(uri, projection, BUCKET_GROUP_BY, null, BUCKET_ORDER_BY);
</code>```

In general, what do these columns represent? Can anyone explain with examples?(The docs have a one-liner about these columns that explains quite less)

答:
BUCKET_DISPLAY_NAME

added to API level 29
String BUCKET_DISPLAY_NAME
The bucket display name of the image. This is a read-only property that is automatically computed from the DATA column.

Type: TEXT

Constant Value: "bucket_display_name"

BUCKET_ID

added in API level 29
String BUCKET_ID
The bucket id of the image. This is a read-only property that is automatically computed from the DATA column.

Type: TEXT

Constant Value: "bucket_id"

DATE_TAKEN

added to API level 29
String DATE_TAKEN
The date & time that the image was taken in units of milliseconds since Jan 1, 1970.

Type: INTEGER

Constant Value: "datetaken"

Title: What is BUCKET_ID in MediaStore?

Body:
I was browsing through some code that queries the MediaStore.Images content provider and uses a column named BUCKET_ID:

Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String projection[] = {
    "DISTINCT " + MediaStore.Images.Media.BUCKET_DISPLAY_NAME,
    MediaStore.Images.Media.BUCKET_ID,
    MediaStore.Images.Media.DATE_TAKEN,
    MediaStore.Images.Media.DATA
};
String BUCKET_GROUP_BY = "1) GROUP BY 1,(2";
String BUCKET_ORDER_BY = "MAX(datetaken) DESC";
Cursor imagecursor = getContentResolver().query(uri, projection, BUCKET_GROUP_BY, null, BUCKET_ORDER_BY);

In general, what do these columns represent? Can anyone explain with examples?(The docs have a one-liner about these columns that explains quite less)


问:
Issue with jackson deserializing, sets all variables to null
I'm trying, and failing to deserialize in jackson 2.9.2, i am trying to make a game, for a uni project, where i am working on a save function, where i can save my Player class, and serialize it, but when i try to deserialize it, and make a new player from it, it sets all the variables to null, this is my method:

```<code>public void LoadSaveString() throws IOException{
    ObjectMapper mapper = new ObjectMapper();
    SimpleModule module = new SimpleModule();
    //module.addDeserializer(SaveFile.class, new SaveDeserializer());
    mapper.registerModule(module);

    String filePath = "files/SaveFile.json";
    BufferedReader reader = new BufferedReader(new FileReader(filePath));
    testfile = reader.readLine();

    System.out.println("Stringen testfilen bliver printet: " + testfile);
    Player player1 = (Player) mapper.readValue(testfile, Player.class);
    System.out.println("Test 2: " + player1.toString());

}
</code>```

and the output i get is:

Stringen testfilen bliver printet: {"player":{"hp":100,"air":97,"inventory":[],"hasCalledHelp":false,"wonGame":false,"playerName":"Mads","awesomePoints":0,"totalTimePlayed":3,"terminateThreads":false,"stopThreadOxygen":false,"stopThreadHP":false,"name":"Mads"}}

Test 2: Player{hp=0, air=0, inventory=null, hasCalledHelp=false, wonGame=false, awesomePoints=0, totalTimePlayed=0, terminateThreads=false, stopThreadOxygen=false, stopThreadHP=false}

And i have set my player class to ignore unknown properties, so i only, get and set, the things that are important for the playerclass

```<code>@JsonIgnoreProperties(ignoreUnknown = true)
</code>```

and the properties in my Player class:

```<code>public class Player {
private int hp;
private int air;
private ArrayList<Item> inventory;
private boolean hasCalledHelp = false;
private boolean wonGame = false;
public String playerName = "Mads"; // Non-negotiable
public int awesomePoints = 0;
public int totalTimePlayed = 0;
</code>```

Edit:

The content in the file SaveFile.json:

```<code>{
    "player": {
        "hp": 100,
        "air": 97,
        "inventory": [],
        "hasCalledHelp": false,
        "wonGame": false,
        "playerName": "Mads",
        "awesomePoints": 0,
        "totalTimePlayed": 3,
        "terminateThreads": false,
        "stopThreadOxygen": false,
        "stopThreadHP": false,
        "name": "Mads"
    }
}
</code>```

答:
First of all I suggest that you don't just read the first line but the whole file to a string. Just to make sure that JSON files with another format are supported.
Also, as Tobias already stated, the JSON file is not a "Player" it just contains a Player. Alternatively to Tobias' approach you can also pick the Player part in the JSON file.

```<code>public void LoadSaveString() throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    SimpleModule module = new SimpleModule();
    mapper.registerModule(module);

    String filePath = "files/SaveFile.json";

    //Read the whole file and not just one line
    byte[] encoded = Files.readAllBytes(Paths.get(filePath));
    String testfile = new String(encoded, "utf-8");

    JSONObject json = new JSONObject(testfile);
    //Pick only the player part
    String playerPart = json.getJSONObject("player").toString();

    System.out.println("Stringen testfilen bliver printet: " + testfile);
    Player player1 = (Player) mapper.readValue(playerPart, Player.class);
    System.out.println("Test 2: " + player1.toString());

}
</code>```

Also the Player class needs getters and setters for each attribute:

```<code>@JsonIgnoreProperties(ignoreUnknown = true)
public class Player {
    private int hp;
    private int air;
    private boolean hasCalledHelp = false;
    private boolean wonGame = false;
    public String playerName = "Mads"; // Non-negotiable
    public int awesomePoints = 0;
    public int totalTimePlayed = 0;

    public int getHp() {
        return hp;
    }
    public void setHp(int hp) {
        this.hp = hp;
    }
    public int getAir() {
        return air;
    }
    public void setAir(int air) {
        this.air = air;
    }
    public boolean isHasCalledHelp() {
        return hasCalledHelp;
    }
    public void setHasCalledHelp(boolean hasCalledHelp) {
        this.hasCalledHelp = hasCalledHelp;
    }
    public boolean isWonGame() {
        return wonGame;
    }
    public void setWonGame(boolean wonGame) {
        this.wonGame = wonGame;
    }
    public String getPlayerName() {
        return playerName;
    }
    public void setPlayerName(String playerName) {
        this.playerName = playerName;
    }
    public int getAwesomePoints() {
        return awesomePoints;
    }
    public void setAwesomePoints(int awesomePoints) {
        this.awesomePoints = awesomePoints;
    }
    public int getTotalTimePlayed() {
        return totalTimePlayed;
    }
    public void setTotalTimePlayed(int totalTimePlayed) {
        this.totalTimePlayed = totalTimePlayed;
    }
}
</code>```

Body:
I'm trying, and failing to deserialize in jackson 2.9.2, i am trying to make a game, for a uni project, where i am working on a save function, where i can save my Player class, and serialize it, but when i try to deserialize it, and make a new player from it, it sets all the variables to null, this is my method:

public void LoadSaveString() throws IOException{
    ObjectMapper mapper = new ObjectMapper();
    SimpleModule module = new SimpleModule();
    //module.addDeserializer(SaveFile.class, new SaveDeserializer());
    mapper.registerModule(module);

    String filePath = "files/SaveFile.json";
    BufferedReader reader = new BufferedReader(new FileReader(filePath));
    testfile = reader.readLine();

    System.out.println("Stringen testfilen bliver printet: " + testfile);
    Player player1 = (Player) mapper.readValue(testfile, Player.class);
    System.out.println("Test 2: " + player1.toString());

}

and the output i get is:

Stringen testfilen bliver printet: {"player":{"hp":100,"air":97,"inventory":[],"hasCalledHelp":false,"wonGame":false,"playerName":"Mads","awesomePoints":0,"totalTimePlayed":3,"terminateThreads":false,"stopThreadOxygen":false,"stopThreadHP":false,"name":"Mads"}}

Test 2: Player{hp=0, air=0, inventory=null, hasCalledHelp=false, wonGame=false, awesomePoints=0, totalTimePlayed=0, terminateThreads=false, stopThreadOxygen=false, stopThreadHP=false}

And i have set my player class to ignore unknown properties, so i only, get and set, the things that are important for the playerclass

@JsonIgnoreProperties(ignoreUnknown = true)

and the properties in my Player class:

public class Player {
private int hp;
private int air;
private ArrayList<Item> inventory;
private boolean hasCalledHelp = false;
private boolean wonGame = false;
public String playerName = "Mads"; // Non-negotiable
public int awesomePoints = 0;
public int totalTimePlayed = 0;

Edit:

The content in the file SaveFile.json:

{
    "player": {
        "hp": 100,
        "air": 97,
        "inventory": [],
        "hasCalledHelp": false,
        "wonGame": false,
        "playerName": "Mads",
        "awesomePoints": 0,
        "totalTimePlayed": 3,
        "terminateThreads": false,
        "stopThreadOxygen": false,
        "stopThreadHP": false,
        "name": "Mads"
    }
}

Body:
First of all I suggest that you don't just read the first line but the whole file to a string. Just to make sure that JSON files with another format are supported.
Also, as Tobias already stated, the JSON file is not a "Player" it just contains a Player. Alternatively to Tobias' approach you can also pick the Player part in the JSON file.

public void LoadSaveString() throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    SimpleModule module = new SimpleModule();
    mapper.registerModule(module);

    String filePath = "files/SaveFile.json";

    //Read the whole file and not just one line
    byte[] encoded = Files.readAllBytes(Paths.get(filePath));
    String testfile = new String(encoded, "utf-8");

    JSONObject json = new JSONObject(testfile);
    //Pick only the player part
    String playerPart = json.getJSONObject("player").toString();

    System.out.println("Stringen testfilen bliver printet: " + testfile);
    Player player1 = (Player) mapper.readValue(playerPart, Player.class);
    System.out.println("Test 2: " + player1.toString());

}

Also the Player class needs getters and setters for each attribute:

@JsonIgnoreProperties(ignoreUnknown = true)
public class Player {
    private int hp;
    private int air;
    private boolean hasCalledHelp = false;
    private boolean wonGame = false;
    public String playerName = "Mads"; // Non-negotiable
    public int awesomePoints = 0;
    public int totalTimePlayed = 0;

    public int getHp() {
        return hp;
    }
    public void setHp(int hp) {
        this.hp = hp;
    }
    public int getAir() {
        return air;
    }
    public void setAir(int air) {
        this.air = air;
    }
    public boolean isHasCalledHelp() {
        return hasCalledHelp;
    }
    public void setHasCalledHelp(boolean hasCalledHelp) {
        this.hasCalledHelp = hasCalledHelp;
    }
    public boolean isWonGame() {
        return wonGame;
    }
    public void setWonGame(boolean wonGame) {
        this.wonGame = wonGame;
    }
    public String getPlayerName() {
        return playerName;
    }
    public void setPlayerName(String playerName) {
        this.playerName = playerName;
    }
    public int getAwesomePoints() {
        return awesomePoints;
    }
    public void setAwesomePoints(int awesomePoints) {
        this.awesomePoints = awesomePoints;
    }
    public int getTotalTimePlayed() {
        return totalTimePlayed;
    }
    public void setTotalTimePlayed(int totalTimePlayed) {
        this.totalTimePlayed = totalTimePlayed;
    }
}


问:
How to delete a whole folder and content?
I want the users of my application to be able to delete the DCIM folder (which is located on the SD card and contains subfolders).

Is this possible, if so how?

答:
You can not delete the directory if it has subdirectories or files in Java. Try this two-line simple solution. This will delete the directory and contests inside the directory.

```<code>File dirName = new File("directory path");
FileUtils.deleteDirectory(dirName);
</code>```

Add this line in gradle file and sync the project

```<code>compile 'org.apache.commons:commons-io:1.3.2'
</code>```

Body:
You can not delete the directory if it has subdirectories or files in Java. Try this two-line simple solution. This will delete the directory and contests inside the directory.

File dirName = new File("directory path");
FileUtils.deleteDirectory(dirName);

Add this line in gradle file and sync the project

compile 'org.apache.commons:commons-io:1.3.2'


问:
Embedded audio wont play in UIWebView on iPad but plays well in iPhone, objective C
I am downloading webpage and storing it through may app; so that I can access it offline through my app. I am loading that webpage (.html) in UIWebView. I am playing audio or video on click. If that webpage contains video then it plays fine on all devices (iPhones, and iPads). But when I access a webpage which has audio in it; then that audio is played successfully on iPhone; but on iPad (on device and simulator as well) it does not play audio file in UIWebView. How can I do this ?</p>

答:
@Vicky_Vignesh your answer was partially right (Anyways thanks for providing foundation). You need to provide device type and OS version with UserAgent string. I have done this way:

    NSString *userAgentString = @"Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1";
    NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:userAgentString,@"UserAgent", nil];
    [[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
```


问:
How to activate JMX on my JROCKIT JVM for access with jconsole?
How to activate JMX on my JROCKIT JVM for access with jconsole?

(somewhat a follow up question to How to activate JMX on my JVM for access with jconsole?)

The main reason I ask is, because I get strange errors if I try to run jboss (6.0.0.Final) with activated JMX, and jboss doesn't start correctly. So maybe it is a jboss problem.

答:
The easiest way to do this, and at the same time support a variety of potential networking configuration challenges, as well as work with any JVM (most ?) is to install a JMXConnectorServer in the JBoss App Server. Now you're using standard J2SE connectivity.

Older builds of JBoss 6 had this support built in and I'm not sure why jboss removed it but here's how you can recreate it.

Find the jar jboss-as-jbossas-jmx-remoting.jar which has a maven signature of org.jboss.jbossas / jboss-as-jbossas-jmx-remoting. Copy it to the [jboss-home]/server/[your-server]/lib directory.

Create a file like jmx-connector-service.xml as outlined below and drop it into your [jboss-home]/server/[your-server]/deploy directory.

(Sorry, was having trouble formatting XML for stackoverflow).

When the server starts, you will see a log statement like this, pretty early on:

INFO  [JMXConnectorServerService] JMX Connector server: service:jmx:rmi://10.213.14.95/jndi/rmi://10.213.14.95:1090/jmxconnector

You can tweak the bindings, the use of a registry, the ports etc, but now you can open JConsole and connect to service:jmx:rmi://10.213.14.95/jndi/rmi://10.213.14.95:1090/jmxconnector.

You can find more information on the service here.


答:
Try using lodash with mapValues.

```<code>_.mapValues(data, element=>element.map(child=>{
    child.type = alert
    return child
}))
</code>```

https://jsfiddle.net/x5aspec2/2/

Title: Alter data in object of arrays

Body:
Try using lodash with mapValues.

_.mapValues(data, element=>element.map(child=>{
    child.type = alert
    return child
}))

https://jsfiddle.net/x5aspec2/2/


问:
Can a table be in 3NF with no primary keys?

1.
  A table is automatically in 3NF if one of the following holds:

  (i) If a relation consists of two attributes.

  (ii) If 2NF table consists of only one non key attribute.

2.
  If X → A is a dependency, then the table is in 3NF, if one of the following conditions exists:

  (i) If X is a superkey

  (ii) If A is a part of superkey

I got the above claims from this site.

I think that in both the claims, 2nd subpoint is wrong.

The first one says that a table in 2NF will be in 3NF if we have all non-key attributes and the table is in 2NF.

Consider the example R(A,B,C) with dependency A->B.

Here we have no candidate key, so all attributes are non-prime attributes and the relation is not in 3NF but in 2NF.

The second one says that for a dependency of the form X->A if A is part of a super key then it's in 3NF.

Consider the example R(A,B,C) with dependencies A->B, B->C . Here a CK is {A}. Now one of the super keys can be AC and the RHS of FD B->C contains part of AC but still the above relation R is not in 3NF.

I think it should be A should be part of a candidate key and not super key.

Am I correct?

Also can a particular relation be in 1NF, 3NF or 2NF if there are no functional dependencies present?

答:
A CK (candidate key) is a superkey that contains no smaller superkey. A superkey is a unique set of attributes. A relation is a set of tuples. So every relation has a superkey, the set of all attributes. So it has at least one CK.

A FD (functional dependency) holds by definition when each value of a determining set of attributes appears always with the same value for its determined set. Every relation value or variable satisfies "trivial" FDs, the ones where the determined set is a subset of the determining set. Every set of attributes determines {}. So every relation satisfies at least one FD. However, the correct forms of definitions typically specifically talk about non-trivial FDs. Don't use the web, use textbooks, of which dozens are free online, although not all are well-written. Many textbooks also forget about FDs where the determinant and/or determined set is {}.

Your first point is not a correct definition of 3NF. Since its phrased "if..." instead of "if and only if", maybe it's not trying to be a definition. However, it is still wrong. (i) is wrong because a relation with two attributes is not in 3NF if one is a CK and the other has the same value in every tuple, ie it is determined by {}.

Similarly the second point is not a proper definition and also even if you treat it as only a consequence of 3NF (if...) it's false. It would be a definition if it used if and only if and talked about an FD that holds and it said it was a non-trivial FD and some other things were fixed.

Since those are neither correct definitions nor correct implications, there's a unlimited number of ways to disprove them. Read a book (or my posts) and get correct definitions.

Some comments re your reasoning:

First one says that, a table in 2NF will be in 3NF if we have all non key attributes and table is in 2NF.

I have no idea why you think that.

Here we have no candidate key

There's always one or more CKs. You need to read a definition of CK. There are also non-brute-force algorithms for finding them all.

Second one says that, for the dependency of form X->A if A is part of super key then it's in 3NF.

I have no idea why you think that.

A should be part of candidate key and not super key.

A correct defintion like the second point does normally say "... or (ii) A-X is part of a CK". But I can't follow your reasoning.

Sound reasoning involves starting from assumptions and writing new statements that we know are true because we applied a definition, a previously proved statement (theorem) or a sound rule of reasoning, eg from 'A implies B' and 'A' we can derive 'B'. You seem to need to read about how to do that.


问:
Update deeply nested subdocument using mongoose
I tried to read most of the similar questions(and there are a lot) but couldn't find any solution I could understand.

The document structure as mentioned below-

```<code>[
  {RoomID:Room1,
  Boards:[
        {BoardID:Board1,
         Devices:[
         {DeviceID:Dev1}
         ....]
              }
              ....]
                   }
                   .....]
</code>```

How to add a new Device after querying both RoomID and BoardID?

答:
You can get the document with findOne() method.
When you have the room object, you can finde the board with this call:

```<code>var board = room.Boards.find(board => board.BoardId === BoardID);
</code>```

Once you have the board you can add it the device:

```<code>board.Devices.push(Device);
</code>```

And finally you have to save the room object in db:

```<code>room.save();
</code>```

Hope it helps

Body:
I tried to read most of the similar questions(and there are a lot) but couldn't find any solution I could understand.

The document structure as mentioned below-

[
  {RoomID:Room1,
  Boards:[
        {BoardID:Board1,
         Devices:[
         {DeviceID:Dev1}
         ....]
              }
              ....]
                   }
                   .....]

How to add a new Device after querying both RoomID and BoardID?

Body:
You can get the document with findOne() method.
When you have the room object, you can finde the board with this call:

var board = room.Boards.find(board => board.BoardId === BoardID);

Once you have the board you can add it the device:

board.Devices.push(Device);

And finally you have to save the room object in db:

room.save();

Hope it helps


问:
Reading values from json files into a node.js file
i was asked by my senior to establish connection into database, but rather than hardcoding the values to creating connection, he asked me to store the values which are required to establish connection in a .JSON file and asked me to get the values into node.js file

This is my json code

```<code>{
    "values" : {
        "host" : "localhost",
        "user" : "root",
        "password" : "root",
        "database" : "node"
    }
}
</code>```

This following code has HARDCODED the vlues to establish connection

```<code>var mysql = require('mysql');

var con  = mysql.createConnection({
    host : "localhost",
    user : "root",
    password : "root",
    database : "node"
});

con.connect(function(err) {
    if (err) throw err;
    console.log("Connected!");
    var sql = "INSERT INTO details (name, prof) VALUES ('grijan1', 'student')";
    con.query(sql, function (err, result) {
      if (err) throw err;
      console.log("1 record inserted");
    });
  });
</code>```

How can i do it?

答:
Create config.json file into your application containing above json.
Then use following</p>

```<code>var config = require('./config.json');
var con = mysql.createConnection(config.values);
</code>```

Body:
i was asked by my senior to establish connection into database, but rather than hardcoding the values to creating connection, he asked me to store the values which are required to establish connection in a .JSON file and asked me to get the values into node.js file

This is my json code

{
    "values" : {
        "host" : "localhost",
        "user" : "root",
        "password" : "root",
        "database" : "node"
    }
}

This following code has HARDCODED the vlues to establish connection

var mysql = require('mysql');

var con  = mysql.createConnection({
    host : "localhost",
    user : "root",
    password : "root",
    database : "node"
});

con.connect(function(err) {
    if (err) throw err;
    console.log("Connected!");
    var sql = "INSERT INTO details (name, prof) VALUES ('grijan1', 'student')";
    con.query(sql, function (err, result) {
      if (err) throw err;
      console.log("1 record inserted");
    });
  });

How can i do it?

Body:
Create config.json file into your application containing above json.
Then use following

var config = require('./config.json');
var con = mysql.createConnection(config.values);


问:
How to check java version at linux (RedHat6)
 I am trying to check what java version I have installed in my linux machine, I have tried:

```<code>which java
</code>```

and I get:

```<code>/usr/bin/java
</code>```

but when I type:

```<code>java -version
</code>```

the console is returning nothing and getting stuck in a "java mode" , feels like the command called java and its waiting for my inputs, any thing I type then returns nothing... until I type crt+C it exits the mode...

答:
To answer your question directly, you can use

rpm -qi java

OR

yum info "java"

For future Referenecs . You can try any of these commands.

rpm -qi "package_name_without_quotes"

It gives information of installed package. To display information about one or more packages (glob expressions are valid here as well), use the following command :

yum info "package_name_without quotes"

OR

yum list "package_name_without_quotes"

OR

yum --showduplicates list "package_name_without_quotes"

The yum info package_name command is similar to the rpm -q --info package_name command, but provides as additional information the ID of the Yum repository the RPM package is found in.

You can also query the Yum database for alternative and useful information about a package by using the following command :

yumdb info "package_name_without_quotes"

This command provides additional information about a package, including the check sum of the package (and algorithm used to produce it, such as SHA-256), the command given on the command line that was invoked to install the package (if any), and the reason that the package is installed on the system.

Body:
 I am trying to check what java version I have installed in my linux machine, I have tried:

which java

and I get:

/usr/bin/java

but when I type:

java -version

the console is returning nothing and getting stuck in a "java mode" , feels like the command called java and its waiting for my inputs, any thing I type then returns nothing... until I type crt+C it exits the mode...