问:
Display more information on an item php codeigniter
I have a database table in mysql that has 11 entities. When the user first searches for an item, my code displays 5 entities and then there is an link for the user to click to view more information on the item. When the user click the link it should lead them to a new page with information about the item that is clicked based on itemID. I don't know how to pass the itemID of the entity to the controller. Please help!
Here's my code:
Contoller:

```<code> <?php defined('BASEPATH') OR exit('No direct script access allowed');
class ItemView extends CI_Controller {
public function __construct(){
    parent::__construct();
    $this->load->helper('url');
    $this->load->helper('form');
    $this->load->model('itemModal');
}
public function index(){
    $this->load->view('base');
    $this->load->view('searchResult');
}
public function viewItems(){
    //trying to get the id of the clicked item
    $id = $this->input->post($rows['inventoryID']);
    $data['results'] = $this->itemModal->get_items($id);
    $this->load->view('base.php',$data);
    $this->load->view('itemview.php',$data);
}
}
?>
</code>```

Model:

```<code><?php
class ItemModal extends CI_Model {
function __construct(){
    parent::__construct();
}
function get_items($id){
    $this->db->select('*');
    $this->db->like('inventoryID',$id);

    // Execute the query.
    $query = $this->db->get('inventory');

    // Return the results.
    return $query->result_array();

}}?>
</code>```

View:

```<code><body>
    <h1><center>Item List</center></h1>
    <hr>
     <div class="container">
         <form method="post" action="<?php echo site_url('itemView/index'); ?>">
                <table>
                    <tr>
                        <th><input type="radio" name="chk"></th>
                        <th>Inventory ID</th>
                        <th>Master Code</th>
                        <th>Item Name</th>
                        <th>Color Name</th>
                        <th>Location</th>
                        <th>Link to more information</th>
                    </tr>
                    <?php foreach($results as $rows):?>
                    <tr>
                        <td><input type="radio" name="chk"></td>
                        <td><?php echo $rows['inventoryID'] ?></td>
                        <td><?php echo $rows['masterCode'] ?></td>
                        <td><?php echo $rows['itemName'] ?></td>
                        <td><?php echo $rows['colorName'] ?></td>
                        <td><?php echo $rows['location'] ?></td>
                        <td><a href="<?php echo site_url('itemView/viewItems'); ?>">click to view more information</a></td>
                    </tr>
                    <?php endforeach; ?>
                </table>
         </form>
 </div></body>
</code>```

View for itemView

```<code><html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>css/search.css">
    <title>Item Information Page</title>
</head>
<body>
    <h1><center>Item Information</center></h1>
    <hr>
    <div class="container">

    </div>
    <!-- End of Container -->
</body><br><br>
</html>
</code>```

答:
yo need to change like this
controller

```<code><?php defined('BASEPATH') OR exit('No direct script access allowed');
    class ItemView extends CI_Controller {
        public function __construct(){
            parent::__construct();
            $this->load->helper(array('url','form'));
            $this->load->model('itemModal', 'model_items');
        }

        public function index(){
            //get all items from db to display basic info in form
            $data['items']=$this->model_items->get_all();
            $this->load->view('base');
            $this->load->view('searchResult', $data);
        }

        //get the specific item to be updated
        public function updateItem( $id ){
            $data['results'] = $this->model_items->get_item_by_id($id);
            $this->load->view('base',$data);
            //viw with inpus form to change the info and send to controller to be updated
            $this->load->view('itemview',$data);
        }

        //get all items to be updated
        public function updateItems(){
            foreach($this->input->post() as $item => $value){
                ${$item} = $value;
            }

            //here you need to add logic to make wherever you want with all items selected in form
        }
    }
</code>```

model itemModal

```<code><?php
    class ItemModal extends CI_Model {
        function get_all(){
            return $this->db->get('inventory')->result();
        }

        function get_item_by_id($id){
            return $this->db->get_where('inventory', array('id' => $id))->row();
        }
    }
</code>```

view searchResult

```<code><form method="post" action="<?= site_url('itemView/updateItems'); ?>">
            <table>
                <tr>
                    <!-- select one or more items to be updated bach -->
                    <th><input type="checkbox" name="chk" value="<?= $rows->inventoryID ?>"></th>
                    <th>Inventory ID</th>
                    <th>Master Code</th>
                    <th>Item Name</th>
                    <th>Color Name</th>
                    <th>Location</th>
                    <th>Link to more information</th>
                </tr>
                <?php foreach($itemsas $rows):?>
                <tr>
                    <td><input type="radio" name="chk"></td>
                    <td><?= $rows->inventoryID ?></td>
                    <td><?= $rows['masterCode'] ?></td>
                    <td><?= $rows['itemName'] ?></td>
                    <td><?= $rows['colorName'] ?></td>
                    <td><?= $rows['location'] ?></td>
                    <!-- update specific item -->
                    <td><a href="<?= site_url('itemView/updateItem/'.$rows->inventoryID ); ?>">click to view more information</a></td>
                </tr>
                <?php endforeach; ?>
                <tr>
                    <td>Update all items selected</td>
                    <td><input type="submit" value="Update"></td>
                </tr>
            </table>
     </form>
</code>```

Body:
I have a database table in mysql that has 11 entities. When the user first searches for an item, my code displays 5 entities and then there is an link for the user to click to view more information on the item. When the user click the link it should lead them to a new page with information about the item that is clicked based on itemID. I don't know how to pass the itemID of the entity to the controller. Please help!
Here's my code:
Contoller:

 <?php defined('BASEPATH') OR exit('No direct script access allowed');
class ItemView extends CI_Controller {
public function __construct(){
    parent::__construct();
    $this->load->helper('url');
    $this->load->helper('form');
    $this->load->model('itemModal');
}
public function index(){
    $this->load->view('base');
    $this->load->view('searchResult');
}
public function viewItems(){
    //trying to get the id of the clicked item
    $id = $this->input->post($rows['inventoryID']);
    $data['results'] = $this->itemModal->get_items($id);
    $this->load->view('base.php',$data);
    $this->load->view('itemview.php',$data);
}
}
?>

Model:

<?php
class ItemModal extends CI_Model {
function __construct(){
    parent::__construct();
}
function get_items($id){
    $this->db->select('*');
    $this->db->like('inventoryID',$id);

    // Execute the query.
    $query = $this->db->get('inventory');

    // Return the results.
    return $query->result_array();

}}?>

View:

Item List

         <form method="post" action="<?php echo site_url('itemView/index'); ?>">

                        <input type="radio" name="chk">
                        Inventory ID
                        Master Code
                        Item Name
                        Color Name
                        Location
                        Link to more information

                    <?php foreach($results as $rows):?>

                        <input type="radio" name="chk">
                        <?php echo $rows['inventoryID'] ?>
                        <?php echo $rows['masterCode'] ?>
                        <?php echo $rows['itemName'] ?>
                        <?php echo $rows['colorName'] ?>
                        <?php echo $rows['location'] ?>
                        <a href="<?php echo site_url('itemView/viewItems'); ?>">click to view more information

                    <?php endforeach; ?>

         </form>

View for itemView

    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

    <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>css/search.css">
    <title>Item Information Page</title>

Item Information

Body:
yo need to change like this
controller

<?php defined('BASEPATH') OR exit('No direct script access allowed');
    class ItemView extends CI_Controller {
        public function __construct(){
            parent::__construct();
            $this->load->helper(array('url','form'));
            $this->load->model('itemModal', 'model_items');
        }

        public function index(){
            //get all items from db to display basic info in form
            $data['items']=$this->model_items->get_all();
            $this->load->view('base');
            $this->load->view('searchResult', $data);
        }

        //get the specific item to be updated
        public function updateItem( $id ){
            $data['results'] = $this->model_items->get_item_by_id($id);
            $this->load->view('base',$data);
            //viw with inpus form to change the info and send to controller to be updated
            $this->load->view('itemview',$data);
        }

        //get all items to be updated
        public function updateItems(){
            foreach($this->input->post() as $item => $value){
                ${$item} = $value;
            }

            //here you need to add logic to make wherever you want with all items selected in form
        }
    }

model itemModal

<?php
    class ItemModal extends CI_Model {
        function get_all(){
            return $this->db->get('inventory')->result();
        }

        function get_item_by_id($id){
            return $this->db->get_where('inventory', array('id' => $id))->row();
        }
    }

view searchResult

<form method="post" action="<?= site_url('itemView/updateItems'); ?>">
            <table>
                <tr>
                    <!-- select one or more items to be updated bach -->
                    <th><input type="checkbox" name="chk" value="<?= $rows->inventoryID ?>"></th>
                    <th>Inventory ID</th>
                    <th>Master Code</th>
                    <th>Item Name</th>
                    <th>Color Name</th>
                    <th>Location</th>
                    <th>Link to more information</th>
                </tr>
                <?php foreach($itemsas $rows):?>
                <tr>
                    <td><input type="radio" name="chk"></td>
                    <td><?= $rows->inventoryID ?></td>
                    <td><?= $rows['masterCode'] ?></td>
                    <td><?= $rows['itemName'] ?></td>
                    <td><?= $rows['colorName'] ?></td>
                    <td><?= $rows['location'] ?></td>
                    <!-- update specific item -->
                    <td><a href="<?= site_url('itemView/updateItem/'.$rows->inventoryID ); ?>">click to view more information</a></td>
                </tr>
                <?php endforeach; ?>
                <tr>
                    <td>Update all items selected</td>
                    <td><input type="submit" value="Update"></td>
                </tr>
            </table>
     </form>


来源: stackexchange

问:
Saving Password with Md5
I am using Postgresql,hibernate and Java and I need to store a password. Can someone suggest me how to encrypt the password with md5. Else is there a better way to store secure password in the database

Thanks

答:
If you're going to use a hashing algorithm, you don't (can't) decrypt the password.  You hash the password and store the hash.  When the user provides their password in the future, you hash it with the same algorithm and compare the new hash with what you stored before.

You can use the MessageDigest class in Java to hash a value.  Ref: Get MD5 hash in a few lines of Java.

Edit: Also, I agree with the others who are saying not to use MD5 for this anymore.  It's an old algorithm that used to be common, but it's been attacked to the point of worthlessness (for passwords).  There are all sorts of resources online for MD5 reverse lookup.

ContentLicense: CC BY-SA 2.5

Title: Saving Password with Md5


问:
Send JSON with PHP
I want to follow with Instagram API in PHP, but it shows an error:

Fatal error: Uncaught Error: Call to undefined function sendPostData() in /storage/h11/133/1908133/public_html/index.php:13 Stack trace: #0 {main} thrown in /storage/h11/133/1908133/public_html/index.php on line 13
```

<p>My code: </p>

```

<title>indexer</title>

<?php
$access = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$user_id = 'xxxxxxxx';
$url= 'https://api.instagram.com/v1/users/'.$user_id.'/relationship?access_token='.$access;
$data = 'action=follow';
$resultObj = json_decode(sendPostData($url,$data));
print_r($resultObj);
?>
```

答:
What you want to get or to modify first be clear about it.
if you want to retrieve it needs a GET request
- Get information about a relationship to another user.

```<code>  $request_uri =  https://api.instagram.com/v1/users/{user-id}/relationship?access_token=ACCESS-TOKEN
</code>```

and if you want to modify something
- Modify the relationship between the current user and the target user.

```<code>   $request_uri = https://api.instagram.com/v1/users/{user-id}/relationship?access_token=ACCESS-TOKEN
</code>```

about curl request

```<code>$request_uri = 'https://api.instagram.com/v1/users/{user-id}/relationship';

$ch = curl_init();
$curlConfig = array(
    CURLOPT_URL            => $request_uri,
    CURLOPT_POST           => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POSTFIELDS     => array(
        'access_token' => ACCESS-TOKEN,
    )
);
curl_setopt_array($ch, $curlConfig);
$result = curl_exec($ch);
var_dump($result);
curl_close($ch);
</code>```

Hope this will be helpful to you.

ContentLicense: CC BY-SA 3.0

Title: Send JSON with PHP

Body:
I want to follow with Instagram API in PHP, but it shows an error:

Fatal error: Uncaught Error: Call to undefined function sendPostData() in /storage/h11/133/1908133/public_html/index.php:13 Stack trace: #0 {main} thrown in /storage/h11/133/1908133/public_html/index.php on line 13

My code:

<title>indexer</title>

<?php
$access = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$user_id = 'xxxxxxxx';
$url= 'https://api.instagram.com/v1/users/'.$user_id.'/relationship?access_token='.$access;
$data = 'action=follow';
$resultObj = json_decode(sendPostData($url,$data));
print_r($resultObj);
?>

Body:
What you want to get or to modify first be clear about it.
if you want to retrieve it needs a GET request
- Get information about a relationship to another user.

  $request_uri =  https://api.instagram.com/v1/users/{user-id}/relationship?access_token=ACCESS-TOKEN

and if you want to modify something
- Modify the relationship between the current user and the target user.

   $request_uri = https://api.instagram.com/v1/users/{user-id}/relationship?access_token=ACCESS-TOKEN

about curl request

$request_uri = 'https://api.instagram.com/v1/users/{user-id}/relationship';

$ch = curl_init();
$curlConfig = array(
    CURLOPT_URL            => $request_uri,
    CURLOPT_POST           => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POSTFIELDS     => array(
        'access_token' => ACCESS-TOKEN,
    )
);
curl_setopt_array($ch, $curlConfig);
$result = curl_exec($ch);
var_dump($result);
curl_close($ch);

Hope this will be helpful to you.


问:
Mnesia doesn't recognize data after sys restart (no_exists error)
I'm building an erlang app in a docker container.
My data directory is connected as a docker volume.
I'm using:
application:set_env(mnesia, schema_location, disc),
and {disc_copies, Nodes}.

When I restart the app with:

```<code>docker-composer stop myapp && docker-composer up myapp
</code>```

all works fine but when I turn it off completely with:

```<code>sudo systemctl restart docker
docker-composer up -d
</code>```

Mnesia stops recognizing my data. The same is true when I restart my computer.

Basically (after this "hard" restart) Mnesia starts normally but when I try to read anything from it, I get an error:

```<code>{running_method,getTasksByProjectId}
terminate reason: {aborted,{no_exists,mtm_tasks}}
terminate reason: {{aborted,{no_exists,mtm_tasks}},
                   {gen_server,call,
                       [{global,tasks_da_serv},
                        {get_tasks_by_project_id,
                            "j1xvqric-2oj2q784xieccowg8880"}]}}

=ERROR REPORT==== 8-Jun-2017::10:29:04 ===
** Generic server tasks_da_serv terminating
** Last message in was {get_tasks_by_project_id,
                           "j1xvqric-2oj2q784xieccowg8880"}
** When Server state == {tasks_da_state}
** Reason for termination ==
** {{aborted,{no_exists,mtm_tasks}},
    [{mnesia,wrap_trans,6,[{file,"mnesia.erl"},{line,404}]},
     {tasks_logic,get_tasks_by_project_id,1,
                  [{file,"/release/_build/default/lib/tasks/src/tasks_logic.erl"},
                   {line,70}]},
     {tasks_da_serv,handle_call,3,
                    [{file,"/release/_build/default/lib/tasks/src/tasks_da_serv.erl"},
                     {line,52}]},
     {gen_server,try_handle_call,4,[{file,"gen_server.erl"},{line,615}]},
     {gen_server,handle_msg,5,[{file,"gen_server.erl"},{line,647}]},
     {proc_lib,init_p_do_apply,3,[{file,"proc_lib.erl"},{line,247}]}]}
Starting {global,tasks_da_serv} (<0.492.0>)
Starting {global,tasks_manager_serv} (<0.497.0>)

=ERROR REPORT==== 8-Jun-2017::10:29:04 ===
** Generic server tasks_manager_serv terminating
** Last message in was {{'basic.deliver',
                            <<"amq.ctag-pt-OySikx5BShVLRASvIPw">>,1,false,
                            <<>>,<<"tasks">>},
                        {amqp_msg,
                            {'P_basic',undefined,undefined,[],undefined,
                                undefined,undefined,undefined,undefined,
                                undefined,undefined,undefined,undefined,
                                undefined,undefined},
                            <<"{\"correlationId\":\"j3oa5b84-pcxn9ld6mswsck8kw48\",\"replyTo\":\"amq.gen-8h_kLqz4sHB-qjJ2cj8Y6w\",\"method\":\"getTasksByProjectId\",\"params\":{\"projectId\":\"j1xvqric-2oj2q784xieccowg8880\"}}">>}}
** When Server state == {tasks_manager_state,<0.481.0>,<0.490.0>}
** Reason for termination ==
** {{{aborted,{no_exists,mtm_tasks}},
     {gen_server,call,
                 [{global,tasks_da_serv},
                  {get_tasks_by_project_id,"j1xvqric-2oj2q784xieccowg8880"}]}},
    [{gen_server,call,2,[{file,"gen_server.erl"},{line,204}]},
     {tasks_manager_logic,handle_message,2,
                          [{file,"/release/_build/default/lib/tasks/src/tasks_manager_logic.erl"},
                           {line,7}]},
     {tasks_manager_serv,handle_info,2,
                         [{file,"/release/_build/default/lib/tasks/src/tasks_manager_serv.erl"},
                          {line,45}]},
     {gen_server,try_dispatch,4,[{file,"gen_server.erl"},{line,601}]},
     {gen_server,handle_msg,5,[{file,"gen_server.erl"},{line,667}]},
     {proc_lib,init_p_do_apply,3,[{file,"proc_lib.erl"},{line,247}]}]}
</code>```

At this point the only way to make it work again is to remove the data from the docker volume.

答:
I have figured it out. The problem is that docker is assigning a custom hostnames to containers and Mnesia disc copy apparently is bound to hostname.
Now I have fixed hostname in docker-compose.yaml file:

```<code>version: '2'
services:
  myapp:
    build: './myapp'
    hostname: 'myapp'
    volumes:
      ...
</code>```

And now can restart it without loosing data.

Body:
I'm building an erlang app in a docker container.
My data directory is connected as a docker volume.
I'm using:
application:set_env(mnesia, schema_location, disc),
and {disc_copies, Nodes}.

When I restart the app with:

docker-composer stop myapp && docker-composer up myapp

all works fine but when I turn it off completely with:

sudo systemctl restart docker
docker-composer up -d

Mnesia stops recognizing my data. The same is true when I restart my computer.

Basically (after this "hard" restart) Mnesia starts normally but when I try to read anything from it, I get an error:

{running_method,getTasksByProjectId}
terminate reason: {aborted,{no_exists,mtm_tasks}}
terminate reason: {{aborted,{no_exists,mtm_tasks}},
                   {gen_server,call,
                       [{global,tasks_da_serv},
                        {get_tasks_by_project_id,
                            "j1xvqric-2oj2q784xieccowg8880"}]}}

=ERROR REPORT==== 8-Jun-2017::10:29:04 ===
** Generic server tasks_da_serv terminating
** Last message in was {get_tasks_by_project_id,
                           "j1xvqric-2oj2q784xieccowg8880"}
** When Server state == {tasks_da_state}
** Reason for termination ==
** {{aborted,{no_exists,mtm_tasks}},
    [{mnesia,wrap_trans,6,[{file,"mnesia.erl"},{line,404}]},
     {tasks_logic,get_tasks_by_project_id,1,
                  [{file,"/release/_build/default/lib/tasks/src/tasks_logic.erl"},
                   {line,70}]},
     {tasks_da_serv,handle_call,3,
                    [{file,"/release/_build/default/lib/tasks/src/tasks_da_serv.erl"},
                     {line,52}]},
     {gen_server,try_handle_call,4,[{file,"gen_server.erl"},{line,615}]},
     {gen_server,handle_msg,5,[{file,"gen_server.erl"},{line,647}]},
     {proc_lib,init_p_do_apply,3,[{file,"proc_lib.erl"},{line,247}]}]}
Starting {global,tasks_da_serv} (<0.492.0>)
Starting {global,tasks_manager_serv} (<0.497.0>)

=ERROR REPORT==== 8-Jun-2017::10:29:04 ===
** Generic server tasks_manager_serv terminating
** Last message in was {{'basic.deliver',
                            <<"amq.ctag-pt-OySikx5BShVLRASvIPw">>,1,false,
                            <<>>,<<"tasks">>},
                        {amqp_msg,
                            {'P_basic',undefined,undefined,[],undefined,
                                undefined,undefined,undefined,undefined,
                                undefined,undefined,undefined,undefined,
                                undefined,undefined},
                            <<"{\"correlationId\":\"j3oa5b84-pcxn9ld6mswsck8kw48\",\"replyTo\":\"amq.gen-8h_kLqz4sHB-qjJ2cj8Y6w\",\"method\":\"getTasksByProjectId\",\"params\":{\"projectId\":\"j1xvqric-2oj2q784xieccowg8880\"}}">>}}
** When Server state == {tasks_manager_state,<0.481.0>,<0.490.0>}
** Reason for termination ==
** {{{aborted,{no_exists,mtm_tasks}},
     {gen_server,call,
                 [{global,tasks_da_serv},
                  {get_tasks_by_project_id,"j1xvqric-2oj2q784xieccowg8880"}]}},
    [{gen_server,call,2,[{file,"gen_server.erl"},{line,204}]},
     {tasks_manager_logic,handle_message,2,
                          [{file,"/release/_build/default/lib/tasks/src/tasks_manager_logic.erl"},
                           {line,7}]},
     {tasks_manager_serv,handle_info,2,
                         [{file,"/release/_build/default/lib/tasks/src/tasks_manager_serv.erl"},
                          {line,45}]},
     {gen_server,try_dispatch,4,[{file,"gen_server.erl"},{line,601}]},
     {gen_server,handle_msg,5,[{file,"gen_server.erl"},{line,667}]},
     {proc_lib,init_p_do_apply,3,[{file,"proc_lib.erl"},{line,247}]}]}

At this point the only way to make it work again is to remove the data from the docker volume.

Body:
I have figured it out. The problem is that docker is assigning a custom hostnames to containers and Mnesia disc copy apparently is bound to hostname.
Now I have fixed hostname in docker-compose.yaml file:

version: '2'
services:
  myapp:
    build: './myapp'
    hostname: 'myapp'
    volumes:
      ...

And now can restart it without loosing data.


问:
How to make GoJS link not to take shortest path between blocks
Layout :

```<code> diagrams.toolManager.linkingTool.temporaryLink.routing = go.Link.Orthogonal;
 diagrams.toolManager.relinkingTool.temporaryLink.routing = go.Link.Orthogonal;
</code>```

Link code:

```<code>this.go.Link,  // the whole link panel
            {
                routing: this.go.Link.AvoidsNodes,
                curve: this.go.Link.JumpOver,
                corner: 5, toShortLength: 4,
                relinkableFrom: true,
                relinkableTo: true,
                reshapable: true,
                resegmentable: true,
                toPortChanged:  (a, b, c) =>{ console.log(a,"test");},
                mouseEnter: (e, link) => { link.findObject("HIGHLIGHT").stroke = "rgba(30,144,255,0.2)"; },
                mouseLeave: (e, link) => { link.findObject("HIGHLIGHT").stroke = "transparent"; }
            },
</code>```

Link line always reconnected to shortest path between blocks (from block left side  to block  right side )

答:
I imagine your nodes are acting as ports. You'll want to define multiple ports if you'd like to be able to connect to different sides of the node.

Intro to Ports

Or maybe you want to set fromSpot and toSpots.

Intro to Connection Points

ContentLicense: CC BY-SA 4.0

Body:
Layout :

 diagrams.toolManager.linkingTool.temporaryLink.routing = go.Link.Orthogonal;
 diagrams.toolManager.relinkingTool.temporaryLink.routing = go.Link.Orthogonal;

Link code:

this.go.Link,  // the whole link panel
            {
                routing: this.go.Link.AvoidsNodes,
                curve: this.go.Link.JumpOver,
                corner: 5, toShortLength: 4,
                relinkableFrom: true,
                relinkableTo: true,
                reshapable: true,
                resegmentable: true,
                toPortChanged:  (a, b, c) =>{ console.log(a,"test");},
                mouseEnter: (e, link) => { link.findObject("HIGHLIGHT").stroke = "rgba(30,144,255,0.2)"; },
                mouseLeave: (e, link) => { link.findObject("HIGHLIGHT").stroke = "transparent"; }
            },

Link line always reconnected to shortest path between blocks (from block left side  to block  right side )


问:
Prometheus feed one data
I feed one data, the value is 121695000128 byte, it is not a point, it is a line, keep for 9 min more.

This is the query:

```<code>spark_history_apps_total_input_bytes{app_id="application_1477490087146_186839"}
</code>```

Start: Thu, 08 Jun 2017 09:55:51 GMT

End:

If i change the value from byte to MB:

```<code>spark_history_apps_total_input_bytes{app_id="application_1477490087146_186839"}/1024/1024
</code>```

The result’s time is changed.

Start: Thu, 08 Jun 2017 09:55:31 GMT
End:

Questions:

Why the result's time is changed? i don't understand.

How can i get a point, not a line?

Please help me. thx.

答:
Prometheus is a time based monitoring application, collecting and processing metrics.

Q1: Why the result's time is changed?

The x-axis of you graph is time, and Prometheus is showing you the evolution of the metric spark_history_apps_total_input_bytes for application application_1477490087146_186839 in time.

If you point the mouse on the last dot available in the graph, you'll have the last metric pulled by Prometheus.

Q2: How can i get a point, not a line?

You can't have a point in a time based graph, if you use the Console tab, then you can have latest result pulled by Prometheus.

Title: Prometheus feed one data

Body:
I feed one data, the value is 121695000128 byte, it is not a point, it is a line, keep for 9 min more.

This is the query:

spark_history_apps_total_input_bytes{app_id="application_1477490087146_186839"}

Start: Thu, 08 Jun 2017 09:55:51 GMT

End:

If i change the value from byte to MB:

spark_history_apps_total_input_bytes{app_id="application_1477490087146_186839"}/1024/1024

The result’s time is changed.

Start: Thu, 08 Jun 2017 09:55:31 GMT
End:

Questions:

Why the result's time is changed? i don't understand.

How can i get a point, not a line?

Please help me. thx.


问:
how to upload excel file using Java Restful web services and AngularJS
I want to take Excel file from html input type="file" and pass that Excel file to my rest method java by http post method. I have a angular controller for that. I want to know how the controller should look like and what should be there in my rest method. I am using Apache POI to process the excel file. </p>

答:
@POST

@Path("/post")

@Consumes(MediaType.APPLICATION_JSON)

public Response getExcelData(ExcelView excelObj)

{ //this will be the service

}

if you need to know hot to write excel using poi check out this link

http://www.avajava.com/tutorials/lessons/how-do-i-write-to-an-excel-file-using-poi.html


问:
Project Tango Raw Data (IMU and RGBD)
I'm a beginner in android and with the Tango (I just wanted to say it to prevent possible mistakes) and I'm using the Project Tango Tablet (Yellowstone). I want to do slam with it, that's why I want to get the raw data.

Currently I know how to get poseData and cloud of point. I read that it was not possible to get IMU and RGBD. But instead of RGBD the RGB picture wich is display by some sample could be enought, but I don't know get it. I think that it will probably works with "onFrameAvailable(int i)" but I don't really know how to get the RGB picture.

For the IMU data I saw that there is an EVENT_IMU with "onTangoEvent(TangoEvent tangoEvent)". But it never happens/is never handled when it's supposed to be a high frequency event right ? However I handle the EVENT_FEATURE_TRACKING (= 5) and EVENT_FISHEYE_CAMERA (= 2) so "onTangoEvent(TangoEvent tangoEvent)" works.
So my questions are the following :

How can I get the RGB picture ? (in matrix, buffer or anything else)

Why the EVENT_IMU is never handled ?

Is there a way to get the IMU data or something equivalent ?

Thanks for your answers

答:
maybe it's too late to ask you. But is there any chance that you can give me your code to get IMU measurements and RGB-video from Project-Tango. I'm dealing with this problem now.
Tks a lot!</p>

Title: Project Tango Raw Data (IMU and RGBD)


问:
Why is a trait not implemented for a type that clearly has it implemented?
I'm trying to use Diesel to query a MySQL database and display the results with a Handlebars template with Rocket.

I have this in models.rs

```<code>#[derive(Queryable, Serialize)]
pub struct Post {
    pub id: i32,
    pub title: String,
    pub text: String,
    pub published: bool,
}
</code>```

cargo run outputs this:

  --> src/main.rs:69:5
   |
69 |     Template::render("index", &results)
   |     ^^^^^^^^^^^^^^^^ the trait `serde::ser::Serialize` is not implemented for `tasty::models::Post`
   |
   = note: required because of the requirements on the impl of `serde::ser::Serialize` for `std::vec::Vec<tasty::models::Post>`
   = note: required by `rocket_contrib::Template::render`
```

<p>In my Cargo.toml, I have this:</p>

```[dependencies]
chrono = "0.3.0"
rocket = "0.2.8"
rocket_codegen = "0.2.8"
serde = "1.0.8"
serde_derive = "1.0.8"
serde_json = "1.0.2"
mysql = "11.1.2"
diesel = { version = "0.13.0", features = ["mysql","chrono"] }
diesel_codegen = { version = "0.13.0", features = ["mysql"] }
dotenv = "0.10.0"

[dependencies.rocket_contrib]
version = "*"
default-features = false
features = ["handlebars_templates"]
```

I have read that Diesel does not support Serialize at the moment, but I am not sure.

答:
The general problem is that the code has multiple versions of the crate, each providing a different version of the traits. The fact that Rust allows this is a good thing, but the error messages around it are confusing.

Your crate implements Serialize from version A but the library is using version B in a public interface. These traits are not compatible, so when you pass your type implementing Serialize@A to the function requiring Serialize@B, the compiler stops you.

While your example is about different traits, it's also possible for this to occur for types which have been re-exported from a crate.

cargo tree, available starting in Rust 1.44 is highly useful to verify this is your problem. It shows all of your dependencies and their versions. It even has a -d flag to show duplicate dependencies! That mode isn't shown here, but is highly useful.

The general solution is to manually restrict your version of Serde in your Cargo.toml to match the rest of the dependencies:

```<code>serde = "0.9"
serde_derive = "0.9"
serde_json = "0.9"
</code>```

This may not always be possible, in which case you may need to hound the crate owners to upgrade their dependencies.

Worked examples

Rocket

```<code>[dependencies]
chrono = "0.3.0"
rocket = "0.2.8"
rocket_codegen = "0.2.8"
serde = "1.0.8"
serde_derive = "1.0.8"
serde_json = "1.0.2"
mysql = "11.1.2"
diesel = { version = "0.13.0", features = ["mysql","chrono"] }
diesel_codegen = { version = "0.13.0", features = ["mysql"] }
dotenv = "0.10.0"

[dependencies.rocket_contrib]
version = "*"
default-features = false
features = ["handlebars_templates"]
</code>```

rocket_contrib 0.2.8 depends on Serde 0.9, but you have pulled in Serde 1.0. This abridged snippet from cargo tree shows the problem:

reproduction v0.1.0 (file:///private/tmp/reproduction)
├── rocket_contrib v0.2.8
│   ├── handlebars v0.25.3
│   │   └── serde_json v0.9.10
│   │       └── serde v0.9.15
│   ├── serde v0.9.15 (*)
│   └── serde_json v0.9.10 (*)
├── serde v1.0.8 (*)
├── serde_derive v1.0.8
│   ├── serde_derive_internals v0.15.1
└── serde_json v1.0.2 (*)
```
<p>The upcoming version 0.3 of Rocket should allow using Serde 1.0.</p>
<h3>Iron / Bson / MongoDB</h3>
```[dependencies]
bodyparser = "0.5"
bson = "0.8"
iron = "0.5"
jwt = "0.4"
mongodb = "0.3"
router = "0.5"
rust-crypto = "0.2"
serde = "1.0"
serde_derive = "1.0"
serde_json = "1.0"
time = "0.1"
```
<p>bodyparser 0.5 depends on Serde 0.8, MongoDB has pulled in 0.9, but the crate and BSON have pulled in Serde 1.0. This abridged snippet from <code>cargo tree</code> shows the problem:</p>
<pre class="lang-none prettyprint-override"><code>reproduction v0.1.0 (file:///private/tmp/reproduction)
├── bodyparser v0.5.0
│   ├── serde v0.8.23
│   └── serde_json v0.8.6
│       └── serde v0.8.23 (*)
├── bson v0.8.0
│   ├── serde v1.0.8
│   ├── serde_json v1.0.2
│   │   └── serde v1.0.8 (*)
├── mongodb v0.3.0
│   ├── textnonce v0.6.0
│   │   ├── serde v0.9.15
│   │   └── serde_derive v0.9.15
├── serde v1.0.8 (*)
├── serde_derive v1.0.8
├── serde_json v1.0.2 (*)
</code>```

Bodyparser 0.7.0 should support Serde 1.0. The state of textnonce is less clear, but that dependency might be a private one, so it might not matter in this case.

Diesel / Chrono

```<code>chrono = "0.4.0"
diesel = { version = "0.13.0", features = [ "chrono", "sqlite" ] }
diesel_codegen = { version = "0.13.0", features = [ "sqlite" ] }
dotenv = "0.9.0"
</code>```

The current version of Chrono is 0.4.0, but Diesel only knows how to serialize Chrono 0.3.0.

reproduction v0.1.0 (file:///private/tmp/reproduction)
├── chrono v0.4.0
├── diesel v0.13.0
│   ├── chrono v0.3.0
```
<h3>blowfish / block-cipher-trait</h3>
```[dependencies]
blowfish = "0.2.1"
block-cipher-trait = "0.3.0"
```
<pre class="lang-none prettyprint-override"><code>reproduction v0.1.0 (file:///private/tmp/reproduction)
├── block-cipher-trait v0.3.0
│── blowfish v0.2.1
    ├── block-cipher-trait v0.2.0
</code>```

conrod / piston2d-graphics

```<code>[dependencies]
piston_window = "0.74.0"
conrod = { version = "0.56.0", features = ["piston"] }
</code>```

repro v0.1.0 (file:///private/tmp/repro)
├── conrod v0.56.0
│   ├── piston2d-graphics v0.23.0
└── piston_window v0.74.0
    ├── piston2d-graphics v0.24.0 (*)
```
<h3>actix / futures</h3>
```[dependencies]
actix-web = "0.6.10"
futures = "0.2.1"
```
<pre class="lang-none prettyprint-override"><code>repro v0.1.0 (file:///private/tmp/repro)
├── actix-web v0.6.12
│   ├── actix v0.5.8
│   │   ├── futures v0.1.21
└── futures v0.2.1
</code>```

A bright future?

RFC 1977 proposes to introduce the notion of public and private dependencies to Cargo. If you use a crate that in turn publicly exposes another crate's types, Cargo would ensure that you use a single unified version for the crate with the common types.

Body:
I'm trying to use Diesel to query a MySQL database and display the results with a Handlebars template with Rocket.

I have this in models.rs

#[derive(Queryable, Serialize)]
pub struct Post {
    pub id: i32,
    pub title: String,
    pub text: String,
    pub published: bool,
}

cargo run outputs this:

  --> src/main.rs:69:5
   |
69 |     Template::render("index", &results)
   |     ^^^^^^^^^^^^^^^^ the trait `serde::ser::Serialize` is not implemented for `tasty::models::Post`
   |
   = note: required because of the requirements on the impl of `serde::ser::Serialize` for `std::vec::Vec<tasty::models::Post>`
   = note: required by `rocket_contrib::Template::render`

In my Cargo.toml, I have this:

[dependencies]
chrono = "0.3.0"
rocket = "0.2.8"
rocket_codegen = "0.2.8"
serde = "1.0.8"
serde_derive = "1.0.8"
serde_json = "1.0.2"
mysql = "11.1.2"
diesel = { version = "0.13.0", features = ["mysql","chrono"] }
diesel_codegen = { version = "0.13.0", features = ["mysql"] }
dotenv = "0.10.0"

[dependencies.rocket_contrib]
version = "*"
default-features = false
features = ["handlebars_templates"]

I have read that Diesel does not support Serialize at the moment, but I am not sure.

Body:
The general problem is that the code has multiple versions of the crate, each providing a different version of the traits. The fact that Rust allows this is a good thing, but the error messages around it are confusing.

Your crate implements Serialize from version A but the library is using version B in a public interface. These traits are not compatible, so when you pass your type implementing Serialize@A to the function requiring Serialize@B, the compiler stops you.

While your example is about different traits, it's also possible for this to occur for types which have been re-exported from a crate.

cargo tree, available starting in Rust 1.44 is highly useful to verify this is your problem. It shows all of your dependencies and their versions. It even has a -d flag to show duplicate dependencies! That mode isn't shown here, but is highly useful.

The general solution is to manually restrict your version of Serde in your Cargo.toml to match the rest of the dependencies:

serde = "0.9"
serde_derive = "0.9"
serde_json = "0.9"

This may not always be possible, in which case you may need to hound the crate owners to upgrade their dependencies.

Worked examples

Rocket

[dependencies]
chrono = "0.3.0"
rocket = "0.2.8"
rocket_codegen = "0.2.8"
serde = "1.0.8"
serde_derive = "1.0.8"
serde_json = "1.0.2"
mysql = "11.1.2"
diesel = { version = "0.13.0", features = ["mysql","chrono"] }
diesel_codegen = { version = "0.13.0", features = ["mysql"] }
dotenv = "0.10.0"

[dependencies.rocket_contrib]
version = "*"
default-features = false
features = ["handlebars_templates"]

rocket_contrib 0.2.8 depends on Serde 0.9, but you have pulled in Serde 1.0. This abridged snippet from cargo tree shows the problem:

reproduction v0.1.0 (file:///private/tmp/reproduction)
├── rocket_contrib v0.2.8
│   ├── handlebars v0.25.3
│   │   └── serde_json v0.9.10
│   │       └── serde v0.9.15
│   ├── serde v0.9.15 (*)
│   └── serde_json v0.9.10 (*)
├── serde v1.0.8 (*)
├── serde_derive v1.0.8
│   ├── serde_derive_internals v0.15.1
└── serde_json v1.0.2 (*)

The upcoming version 0.3 of Rocket should allow using Serde 1.0.

Iron / Bson / MongoDB

[dependencies]
bodyparser = "0.5"
bson = "0.8"
iron = "0.5"
jwt = "0.4"
mongodb = "0.3"
router = "0.5"
rust-crypto = "0.2"
serde = "1.0"
serde_derive = "1.0"
serde_json = "1.0"
time = "0.1"

bodyparser 0.5 depends on Serde 0.8, MongoDB has pulled in 0.9, but the crate and BSON have pulled in Serde 1.0. This abridged snippet from cargo tree shows the problem:

reproduction v0.1.0 (file:///private/tmp/reproduction)
├── bodyparser v0.5.0
│   ├── serde v0.8.23
│   └── serde_json v0.8.6
│       └── serde v0.8.23 (*)
├── bson v0.8.0
│   ├── serde v1.0.8
│   ├── serde_json v1.0.2
│   │   └── serde v1.0.8 (*)
├── mongodb v0.3.0
│   ├── textnonce v0.6.0
│   │   ├── serde v0.9.15
│   │   └── serde_derive v0.9.15
├── serde v1.0.8 (*)
├── serde_derive v1.0.8
├── serde_json v1.0.2 (*)

Bodyparser 0.7.0 should support Serde 1.0. The state of textnonce is less clear, but that dependency might be a private one, so it might not matter in this case.

Diesel / Chrono

chrono = "0.4.0"
diesel = { version = "0.13.0", features = [ "chrono", "sqlite" ] }
diesel_codegen = { version = "0.13.0", features = [ "sqlite" ] }
dotenv = "0.9.0"

The current version of Chrono is 0.4.0, but Diesel only knows how to serialize Chrono 0.3.0.

reproduction v0.1.0 (file:///private/tmp/reproduction)
├── chrono v0.4.0
├── diesel v0.13.0
│   ├── chrono v0.3.0

blowfish / block-cipher-trait

[dependencies]
blowfish = "0.2.1"
block-cipher-trait = "0.3.0"

reproduction v0.1.0 (file:///private/tmp/reproduction)
├── block-cipher-trait v0.3.0
│── blowfish v0.2.1
    ├── block-cipher-trait v0.2.0

conrod / piston2d-graphics

[dependencies]
piston_window = "0.74.0"
conrod = { version = "0.56.0", features = ["piston"] }

repro v0.1.0 (file:///private/tmp/repro)
├── conrod v0.56.0
│   ├── piston2d-graphics v0.23.0
└── piston_window v0.74.0
    ├── piston2d-graphics v0.24.0 (*)

actix / futures

[dependencies]
actix-web = "0.6.10"
futures = "0.2.1"

repro v0.1.0 (file:///private/tmp/repro)
├── actix-web v0.6.12
│   ├── actix v0.5.8
│   │   ├── futures v0.1.21
└── futures v0.2.1

A bright future?

RFC 1977 proposes to introduce the notion of public and private dependencies to Cargo. If you use a crate that in turn publicly exposes another crate's types, Cargo would ensure that you use a single unified version for the crate with the common types.


问:
Extracting selected feature names from scikit pipeline
```<code># Load dataset
iris = datasets.load_iris()
X, y = iris.data, iris.target

rf_feature_imp = RandomForestClassifier(100)
feat_selection = SelectFromModel(rf_feature_imp, threshold=0.5)

clf = RandomForestClassifier(5000)

model = Pipeline([
          ('fs', feat_selection),
          ('clf', clf),
        ])

 params = {
    'fs__threshold': [0.5, 0.3, 0.7],
    'fs__estimator__max_features': ['auto', 'sqrt', 'log2'],
    'clf__max_features': ['auto', 'sqrt', 'log2'],
 }

 gs = GridSearchCV(model, params, ...)
 gs.fit(X,y)
</code>```

The above code is based on Ensuring right order of operations in random forest classification in scikit learn

Since I am using SelectFromModel, I would like to print the names of the features that were selected (in the SelectFromModel pipeline), but not sure how to extract them.

答:
SelectFromModel has a get_support() method that returns a boolean mask for the features that were selected. So you could do (in addition to the preliminary step described by @David Maust):

```<code>feature_names = np.array(iris.feature_names)
selected_features = feature_names[fs.get_support()]
</code>```

Body:
# Load dataset
iris = datasets.load_iris()
X, y = iris.data, iris.target

rf_feature_imp = RandomForestClassifier(100)
feat_selection = SelectFromModel(rf_feature_imp, threshold=0.5)

clf = RandomForestClassifier(5000)

model = Pipeline([
          ('fs', feat_selection),
          ('clf', clf),
        ])

 params = {
    'fs__threshold': [0.5, 0.3, 0.7],
    'fs__estimator__max_features': ['auto', 'sqrt', 'log2'],
    'clf__max_features': ['auto', 'sqrt', 'log2'],
 }

 gs = GridSearchCV(model, params, ...)
 gs.fit(X,y)

The above code is based on Ensuring right order of operations in random forest classification in scikit learn

Since I am using SelectFromModel, I would like to print the names of the features that were selected (in the SelectFromModel pipeline), but not sure how to extract them.

Body:
SelectFromModel has a get_support() method that returns a boolean mask for the features that were selected. So you could do (in addition to the preliminary step described by @David Maust):

feature_names = np.array(iris.feature_names)
selected_features = feature_names[fs.get_support()]


问:
Delete all child data based on parent node id in tree
I am using kentico application where i have to delete all child items which contains either node id of parent or parentnodeid of parent based on the child inside there.
Below is the screen shot:

In this picture we can see we have a parent node called membership and inside one child called Blog. Under of Blog which node id is 583 having 29 child. Now I am running a code and getting all the child data under of that parent as a list.
Below is the screen shot:

Now i have to remove all the child data from list whose parentnodeid or parent-parent node id is 583 (Blog).

Below is the code used to get the list of all parent and child items:

 TreeProvider tree = new TreeProvider();
    var childNodeDataSet = tree.SelectNodes(childNodeId, null, SiteContext.CurrentSiteName);
    var getAllChildItems = childNodeDataSet.Items[0].AllChildren;
    var getItems = getAllChildItems.ToList().OrderBy(a=>a.NodeAliasPath);```
</div>
</div>

As we can see above code childNodeId is nothing but the Membership page node id. Using this i am getting all the child items.
Now in this getItems i have all the values where i have to remove Blog page parent and child completely.</p>

<p>I tried this code to remove the matching parent item from list:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code> string excludeFileName = "583, 683, 686, 687";
                    string[] arrStringList = excludeFileName.Split(',');
                    foreach (var excName in arrStringList)
                    {
                        getItems.RemoveAll(a => (a.NodeID == Convert.ToInt32(excName.Trim()) || a.NodeParentID == Convert.ToInt32(excName.Trim()))
                        || (a.Parent.NodeID == Convert.ToInt32(excName.Trim()) || a.Parent.NodeParentID == Convert.ToInt32(excName.Trim()))
                        || (a.Parent.Parent.NodeID == Convert.ToInt32(excName.Trim()) || a.Parent.Parent.NodeParentID == Convert.ToInt32(excName.Trim()))
                        || (a.Parent.Parent.Parent.NodeID == Convert.ToInt32(excName.Trim()) || a.Parent.Parent.Parent.NodeParentID == Convert.ToInt32(excName.Trim())));
                    }</code>```

This code is working fine if i know particular node has how many level.

But if some of the node don't have that much level then in that case this code is giving exception.

If found any issues please let me know.

答:
I am a little confused at the path you're taking.  If you want to get all children of a particular node, why not just get all nodes where the NodeAliasPath is like "The/Parent/Node/Path"+"/%"?

This will select all the children nodes all the way down.

If you only want to grab a certain number of levels, you can get the Parent's NodeLevel, and then in the query add a NodeLevel <= "+(ParentNodeLevel+2)  to grab all the children and grandchildren only.

To exclude certain nodes, you can also put a "NodeID not in (123,234)".

Perhaps if you can clearly say what you are trying to accomplish we can help out easier!

PS: I Put the SQL, but the DocumentQuery object has most of these in methods, like .WhereNotIn("NodeID", ListOfNodeIDsToExclude)

Body:
I am using kentico application where i have to delete all child items which contains either node id of parent or parentnodeid of parent based on the child inside there.
Below is the screen shot:

In this picture we can see we have a parent node called membership and inside one child called Blog. Under of Blog which node id is 583 having 29 child. Now I am running a code and getting all the child data under of that parent as a list.
Below is the screen shot:

Now i have to remove all the child data from list whose parentnodeid or parent-parent node id is 583 (Blog).

Below is the code used to get the list of all parent and child items:

 TreeProvider tree = new TreeProvider();
    var childNodeDataSet = tree.SelectNodes(childNodeId, null, SiteContext.CurrentSiteName);
    var getAllChildItems = childNodeDataSet.Items[0].AllChildren;
    var getItems = getAllChildItems.ToList().OrderBy(a=>a.NodeAliasPath);

As we can see above code childNodeId is nothing but the Membership page node id. Using this i am getting all the child items.
Now in this getItems i have all the values where i have to remove Blog page parent and child completely.

I tried this code to remove the matching parent item from list:

 string excludeFileName = "583, 683, 686, 687";
                    string[] arrStringList = excludeFileName.Split(',');
                    foreach (var excName in arrStringList)
                    {
                        getItems.RemoveAll(a => (a.NodeID == Convert.ToInt32(excName.Trim()) || a.NodeParentID == Convert.ToInt32(excName.Trim()))
                        || (a.Parent.NodeID == Convert.ToInt32(excName.Trim()) || a.Parent.NodeParentID == Convert.ToInt32(excName.Trim()))
                        || (a.Parent.Parent.NodeID == Convert.ToInt32(excName.Trim()) || a.Parent.Parent.NodeParentID == Convert.ToInt32(excName.Trim()))
                        || (a.Parent.Parent.Parent.NodeID == Convert.ToInt32(excName.Trim()) || a.Parent.Parent.Parent.NodeParentID == Convert.ToInt32(excName.Trim())));
                    }

This code is working fine if i know particular node has how many level.

But if some of the node don't have that much level then in that case this code is giving exception.

If found any issues please let me know.


问:
List of available **kwargs
In the python help documents I often see a Signature line with function name and named parameters, then you will see **kwarg (keyword arguments).

```<code>list?
</code>```

Which prints to the help docstring:

```<code>Init signature: list(self, /, *args, **kwargs)
Docstring:
list() -> new empty list
list(iterable) -> new list initialized from iterable's items
Type:           type
</code>```

Is there a way to list the available keywords and/or args that can be passed?

答:
There is inspect module, which can help you:

```<code>>>> inspect.getargspec(aMethod)
(['arg1', 'arg2'], None, None, None)
</code>```

For builtin methods you can use __doc__ argument:

```<code>>>> list.__doc__
"list() -> new empty list\nlist(iterable) -> new list initialized from iterable's items"
</code>```

Title: List of available **kwargs

Body:
In the python help documents I often see a Signature line with function name and named parameters, then you will see **kwarg (keyword arguments).

list?

Which prints to the help docstring:

Init signature: list(self, /, *args, **kwargs)
Docstring:
list() -> new empty list
list(iterable) -> new list initialized from iterable's items
Type:           type

Is there a way to list the available keywords and/or args that can be passed?

Body:
There is inspect module, which can help you:

>>> inspect.getargspec(aMethod)
(['arg1', 'arg2'], None, None, None)

For builtin methods you can use __doc__ argument:

>>> list.__doc__
"list() -> new empty list\nlist(iterable) -> new list initialized from iterable's items"


问:
how to use inflections on a rails engine
i have created an engine with

```<code>rails plugin new myengine --mountable
</code>```

when searching for 'inflections' in the project folder, i find the
/test/dummy/config/initializers/inflections.rb file

in this file i put

```<code>ActiveSupport::Inflector.inflections(:en) do |inflect|
  inflect.irregular 'singular_model', 'plural_model'
end
</code>```

when i try to use the model generator (from project root)

```<code>bin/rails generate model singular_model
</code>```

then i get the a migration with singular_models as the table name and migration name

when i run the same command from myengine/test/dummy

```<code>bin/rails generate model singular_model
</code>```

i get the spected result: plural_model as table name and migration name

so, how can i load the inflector into the rails generator?

答:
In Rails 4.2, rails engines do not load the initializers when running generators, which is discussed in this issue: https://github.com/rails/rails/issues/14472

Workaround

Define inflections in my_engine/config/initializers/inflections.rb:

```<code># my_engine/config/initializers/inflections.rb

ActiveSupport::Inflector.inflections do |inflect|
  inflect.irregular 'regatta', 'regattas'
end
</code>```

Require the inflections initializer in the engine.rb:

```<code># my_engine/lib/my_engine/engine.rb

require_relative '../../config/initializers/inflections'

module MyEngine
  class Engine < ::Rails::Engine
    # ...
  end
end
</code>```

Use the generator as expected: bin/rails g model Regatta

Body:
i have created an engine with

rails plugin new myengine --mountable

when searching for 'inflections' in the project folder, i find the
/test/dummy/config/initializers/inflections.rb file

in this file i put

ActiveSupport::Inflector.inflections(:en) do |inflect|
  inflect.irregular 'singular_model', 'plural_model'
end

when i try to use the model generator (from project root)

bin/rails generate model singular_model

then i get the a migration with singular_models as the table name and migration name

when i run the same command from myengine/test/dummy

bin/rails generate model singular_model

i get the spected result: plural_model as table name and migration name

so, how can i load the inflector into the rails generator?

Body:
In Rails 4.2, rails engines do not load the initializers when running generators, which is discussed in this issue: https://github.com/rails/rails/issues/14472

Workaround

Define inflections in my_engine/config/initializers/inflections.rb:

# my_engine/config/initializers/inflections.rb

ActiveSupport::Inflector.inflections do |inflect|
  inflect.irregular 'regatta', 'regattas'
end

Require the inflections initializer in the engine.rb:

# my_engine/lib/my_engine/engine.rb

require_relative '../../config/initializers/inflections'

module MyEngine
  class Engine < ::Rails::Engine
    # ...
  end
end

Use the generator as expected: bin/rails g model Regatta


问:
Git log author name from htpasswd
we want to use git and one very important thing would be that if someone is committing something we need to know who exactly was it. Since we are accessing git via https we need to put the htpasswd login information in the git commit logs. Is this possible?

Regards

Phillip

答: Gitolite will work just fine (certainly for centralised repo push/pull; the custom commands might be a little trickier) using Git http-backend. See https://github.com/sitaramc/gitolite/blob/pu/doc/http-backend.mkd for the documentation on how to do it.</p>

Title: Git log author name from htpasswd


问:
How to extract image names from SQL column
We have Wordpress installation based on SQL Server and would like to extract the image names from the field post_content in wp_post. I have tried a lot with patindex, like clause and so on but I cant figure out how to do.

Here's an example of the content on row in the post_content column :

```<code><a href="http://www.example.com/wp-content/uploads/2017/06/1-1.jpg"><img class="aligncenter size-large wp-image-133975" src="http://www.example.com/wp-content/uploads/2017/06/1-1-1024x682.jpg" alt="" width="604" height="402" /></a>
</code>```

I have about 10 000 records in the table and the content in post_content can contain one or more images.
I would like to extract the image names like this :

/wp-content/uploads/2017/06/1-1.jpg

/wp-content/uploads/2017/06/1-1-1024x682.jpg

Thankful for help.

答:
If you are open to a TVF.

Tired of extracting strings, I modified a parse function to accept two, non-like parameters.

Example

```<code>Declare @YourTable table (ID int,post_content varchar(max))
Insert Into @YourTable values
(1,'<a href="http://www.example.com/wp-content/uploads/2017/06/1-1.jpg"><img class="aligncenter size-large wp-image-133975" src="http://www.example.com/wp-content/uploads/2017/06/1-1-1024x682.jpg" alt="" width="604" height="402" /></a>')

Select A.ID
      ,ImageSrc = B.RetVal
 From  @YourTable A
 Cross Apply [dbo].[udf-Str-Extract](A.post_content,'.com','"') B
 Where right(B.RetVal,4) in ('.jpg','.png','.gif')
</code>```

Returns

```<code>ID  ImageSrc
1   /wp-content/uploads/2017/06/1-1.jpg
1   /wp-content/uploads/2017/06/1-1-1024x682.jpg
</code>```

The UDF if Interested

```<code>CREATE FUNCTION [dbo].[udf-Str-Extract] (@String varchar(max),@Delimiter1 varchar(100),@Delimiter2 varchar(100))
Returns Table
As
Return (

with   cte1(N)   As (Select 1 From (Values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) N(N)),
       cte2(N)   As (Select Top (IsNull(DataLength(@String),0)) Row_Number() over (Order By (Select NULL)) From (Select N=1 From cte1 N1,cte1 N2,cte1 N3,cte1 N4,cte1 N5,cte1 N6) A ),
       cte3(N)   As (Select 1 Union All Select t.N+DataLength(@Delimiter1) From cte2 t Where Substring(@String,t.N,DataLength(@Delimiter1)) = @Delimiter1),
       cte4(N,L) As (Select S.N,IsNull(NullIf(CharIndex(@Delimiter1,@String,s.N),0)-S.N,8000) From cte3 S)

Select RetSeq = Row_Number() over (Order By N)
      ,RetPos = N
      ,RetVal = left(RetVal,charindex(@Delimiter2,RetVal)-1)
 From  (
        Select *,RetVal = Substring(@String, N, L)
         From  cte4
       ) A
 Where charindex(@Delimiter2,RetVal)>1

)
/*
Max Length of String 1MM characters

Declare @String varchar(max) = 'Dear [[FirstName]] [[LastName]], ...'
Select * From [dbo].[udf-Str-Extract] (@String,'[[',']]')
*/
</code>```

Body:
We have Wordpress installation based on SQL Server and would like to extract the image names from the field post_content in wp_post. I have tried a lot with patindex, like clause and so on but I cant figure out how to do.

Here's an example of the content on row in the post_content column :

I have about 10 000 records in the table and the content in post_content can contain one or more images.
I would like to extract the image names like this :

/wp-content/uploads/2017/06/1-1.jpg

/wp-content/uploads/2017/06/1-1-1024x682.jpg

Thankful for help.

Body:
If you are open to a TVF.

Tired of extracting strings, I modified a parse function to accept two, non-like parameters.

Example

Declare @YourTable table (ID int,post_content varchar(max))
Insert Into @YourTable values
(1,'<a href="http://www.example.com/wp-content/uploads/2017/06/1-1.jpg"><img class="aligncenter size-large wp-image-133975" src="http://www.example.com/wp-content/uploads/2017/06/1-1-1024x682.jpg" alt="" width="604" height="402" /></a>')

Select A.ID
      ,ImageSrc = B.RetVal
 From  @YourTable A
 Cross Apply [dbo].[udf-Str-Extract](A.post_content,'.com','"') B
 Where right(B.RetVal,4) in ('.jpg','.png','.gif')

Returns

ID  ImageSrc
1   /wp-content/uploads/2017/06/1-1.jpg
1   /wp-content/uploads/2017/06/1-1-1024x682.jpg

The UDF if Interested

CREATE FUNCTION [dbo].[udf-Str-Extract] (@String varchar(max),@Delimiter1 varchar(100),@Delimiter2 varchar(100))
Returns Table
As
Return (

with   cte1(N)   As (Select 1 From (Values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) N(N)),
       cte2(N)   As (Select Top (IsNull(DataLength(@String),0)) Row_Number() over (Order By (Select NULL)) From (Select N=1 From cte1 N1,cte1 N2,cte1 N3,cte1 N4,cte1 N5,cte1 N6) A ),
       cte3(N)   As (Select 1 Union All Select t.N+DataLength(@Delimiter1) From cte2 t Where Substring(@String,t.N,DataLength(@Delimiter1)) = @Delimiter1),
       cte4(N,L) As (Select S.N,IsNull(NullIf(CharIndex(@Delimiter1,@String,s.N),0)-S.N,8000) From cte3 S)

Select RetSeq = Row_Number() over (Order By N)
      ,RetPos = N
      ,RetVal = left(RetVal,charindex(@Delimiter2,RetVal)-1)
 From  (
        Select *,RetVal = Substring(@String, N, L)
         From  cte4
       ) A
 Where charindex(@Delimiter2,RetVal)>1

)
/*
Max Length of String 1MM characters

Declare @String varchar(max) = 'Dear [[FirstName]] [[LastName]], ...'
Select * From [dbo].[udf-Str-Extract] (@String,'[[',']]')
*/


问:
Recursive way to find number of items in a object of array
What is the recursive way to get the number of titi in the following object :

```<code>{
    titi: "h0",
    history: [{
        titi: "h1",
        history: [{
            titi: "h11"
        }, {
            titi: "h12"
        }]
    }, {
        titi: "h12",
        history: [{
            titi: "h121"
        }, {
            titi: "h122"
        }]
    }]
}
</code>```

Expected result is the total. In this example : 7.

答:
var json = {  titi:"h0", history : [{ titi :"h1", history : [{ titi :"h11"}, { titi : "h12"}] }, { titi : "h12", history : [{ titi :"h121"}, { titi : "h122"}]}]}

var count = 0;

function getCount(haystack, needle) {
    for (var k in haystack) {
        if (haystack.hasOwnProperty(k)) {
          if ( k == needle ) {count = count + 1};
          if (typeof haystack[k] === 'object') getCount(haystack[k], needle);
        }
    }
}

getCount(json, 'titi');
console.log('count: ',count)```

Body:
What is the recursive way to get the number of titi in the following object :

{
    titi: "h0",
    history: [{
        titi: "h1",
        history: [{
            titi: "h11"
        }, {
            titi: "h12"
        }]
    }, {
        titi: "h12",
        history: [{
            titi: "h121"
        }, {
            titi: "h122"
        }]
    }]
}

Expected result is the total. In this example : 7.


答:
Nope - *args and **kwargs are catch-all arguments where the former one will capture every extra unnamed argument in a list, and the latter will capture every named argument in a dict.

People who write functions/methods utilizing one or both of these special capture arguments decide what to do with them so, unless you look through their code, if they haven't provided documentation for their functions/methods you cannot know what is their intention or what they expect to get.

Title: List of available **kwargs


问:
How to embed H2 database into jar file delivered to the client?
I use H2 database for a desktop application in embedded mode. When I compress the application into jar file the database file is omitted. So, when I run MyApplication.jar nothing works. What is the correct way to embed/include/connect h2.jar file with MyApplication.jar? Or maybe there is another way to deliver database and application in the bundle?</p>

答:
One common scheme is to put h2.jar in a lib directory relative to your application and include a Class-Path entry in your JAR's manifest with an entry for it:

```<code>Class-Path: lib/h2.jar lib/…
</code>```

Addendum: This small project includes a link to the JAR specification and a handy utility for examining the manifest in situ.

Body:
One common scheme is to put h2.jar in a lib directory relative to your application and include a Class-Path entry in your JAR's manifest with an entry for it:

Class-Path: lib/h2.jar lib/…

Addendum: This small project includes a link to the JAR specification and a handy utility for examining the manifest in situ.


问:
super and base class should have different instances of same attribute name
I'm new to python, I'm trying to learn basic inheritance and I want the super and base class to have attributes with same name, but they should have different instances. Below is the code I've written to experiment with this Idea.

```<code>class master(object):

    def __init__(self, name):
        self.name = name

    def print_name(self):
        print (self.name)

class slave(master):

    def __init__(self, master_name, slave_name):

        self.name = slave_name
        super(slave, self).__init__(master_name)

    def print_name(self):

        super(slave, self).print_name()
        print (self.name)

def main():
    obj = slave('hello', 'world')
    obj.print_name()

if __name__ == '__main__':
    main()
</code>```

The out put I'm getting is :
hello
hello

But I want want the output to be
world
hello

答: The __init__ from master is overriding the value of self.name that you set in slave. You need to use different variable names.

Body:
I'm new to python, I'm trying to learn basic inheritance and I want the super and base class to have attributes with same name, but they should have different instances. Below is the code I've written to experiment with this Idea.

class master(object):

    def __init__(self, name):
        self.name = name

    def print_name(self):
        print (self.name)

class slave(master):

    def __init__(self, master_name, slave_name):

        self.name = slave_name
        super(slave, self).__init__(master_name)

    def print_name(self):

        super(slave, self).print_name()
        print (self.name)

def main():
    obj = slave('hello', 'world')
    obj.print_name()

if __name__ == '__main__':
    main()

The out put I'm getting is :
hello
hello

But I want want the output to be
world
hello


问:
Ext JS exclude null values in summary Ext.grid.feature.Summary in grid
I have some null values in my datastore. I am using ftype summary to show the summary row, when it is calculating the summary(min/max) it is considering the null as min/max . Is there any way to exclude the null values and calculate the summary. I have created the grid as below</p>

```<code>var grid = Ext.create('Ext.grid.Panel', {
    width: width,
    height: height,
    //frame: true,
    cls: 'gridPadding, x-panel gridPadding x-grid-with-row-lines x-panel-default-framed x-grid',
    id: 'dashboardSearchGrid_' + DivId,
    renderTo: DivId,
    buffered: true,
    store: store,
    plugins: [
        Ext.create('Ext.ux.grid.plugin.GroupingPanel')
    ],
    features: [{
        ftype: 'summary',
        dock: 'bottom'
    }]
});
</code>```

答:
I had the same issue, i did not found a solution to configure that.

That should work:

You can use a renderer inside your column definiton

```<code>renderer: function (value, meta, record) {
   if (value === null || value === "") {
     value = 0;
   }
return value;
}
</code>```

Or you can manipulate the data using convert or calculate inside your model definition.

http://docs.sencha.com/extjs/6.0.1/classic/Ext.data.field.Field.html#cfg-convert

Body:
I have some null values in my datastore. I am using ftype summary to show the summary row, when it is calculating the summary(min/max) it is considering the null as min/max . Is there any way to exclude the null values and calculate the summary. I have created the grid as below

var grid = Ext.create('Ext.grid.Panel', {
    width: width,
    height: height,
    //frame: true,
    cls: 'gridPadding, x-panel gridPadding x-grid-with-row-lines x-panel-default-framed x-grid',
    id: 'dashboardSearchGrid_' + DivId,
    renderTo: DivId,
    buffered: true,
    store: store,
    plugins: [
        Ext.create('Ext.ux.grid.plugin.GroupingPanel')
    ],
    features: [{
        ftype: 'summary',
        dock: 'bottom'
    }]
});

Body:
I had the same issue, i did not found a solution to configure that.

That should work:

You can use a renderer inside your column definiton

renderer: function (value, meta, record) {
   if (value === null || value === "") {
     value = 0;
   }
return value;
}

Or you can manipulate the data using convert or calculate inside your model definition.

http://docs.sencha.com/extjs/6.0.1/classic/Ext.data.field.Field.html#cfg-convert


问:
Function call from aspx design time error "name does not exist in the current context"
I want to change the styles of certain elements on my page depending on the role of the logged in user.

To achieve this, I'm calling a function to execute some server code that does the evaluation and returns a string being the name of the style rule:

```<code><li class="<%=CheckAllowed("admin"); %>">
</code>```

In my code file I have the following:

```<code>public string CheckAllowed(string role)
{
    if (HttpContext.Current.User.IsRole(role))
    {
        return "visible-menu-item";
    }
    else
    {
        return "hidden-menu-item";
    }
}
</code>```

The function name in the markup is underlined red with the following error:

The name 'CheckAllowed' does not exist in the current context.

Am I calling the function correctly? If not, how would this be done correctly?

答:
In your sample code, your function is named CheckAddlowed, not CheckAllowed...

Try this syntax:

```<code><% Response.Write(CheckAllowed("admin")); %>
</code>```

Body:
I want to change the styles of certain elements on my page depending on the role of the logged in user.

To achieve this, I'm calling a function to execute some server code that does the evaluation and returns a string being the name of the style rule:

<li class="<%=CheckAllowed("admin"); %>">

In my code file I have the following:

public string CheckAllowed(string role)
{
    if (HttpContext.Current.User.IsRole(role))
    {
        return "visible-menu-item";
    }
    else
    {
        return "hidden-menu-item";
    }
}

The function name in the markup is underlined red with the following error:

The name 'CheckAllowed' does not exist in the current context.

Am I calling the function correctly? If not, how would this be done correctly?

Body:
In your sample code, your function is named CheckAddlowed, not CheckAllowed...

Try this syntax:

<% Response.Write(CheckAllowed("admin")); %>


问:
How to update html element in ng-repeat collection every second automatically
In my controller I have a function that receives data from API every 2 seconds($interval). This data is rendered and displayed to user. When I get positive numbers from my API I want to set background color in HTML to green for 1 second and return it  to original color. If it is negative, set background color to red for 1 second, and so on...

controller.js

```<code>function checkForUpdatedIndices(){
  dataService.getIndices().then(function(res){
    $scope.recentIndeces = res.data;
 });}

 var indicesTimer = setInterval(checkForUpdatedIndices,2000);
 checkForUpdatedIndices();
</code>```

My HTML:

```<code><ul id="ctr_indices">
        <li class="cl_indeces" ng-repeat="i in recentIndeces track by $index">
            <span class="itemname">{{i.itemName}}</span>
            <span class="itemlastvalue">{{i.itemLastValue}}</span>
            <span class="itemchange">{{i.itemChange}}</span>
            <span class="itempercentage">{{i.itemPercentageChange}}</span>
        </li>
 </ul>
</code>```

When i.itemLastValue contains "+" I want to see it green for 1 second and after that change it back to original color.
Thanks in advance

答:
you can do this using ng-style directive. set this style like this

```<code>ng-style="{'background-color' : i.color}"
</code>```

and call a function inside ng-init and pass the item as a parameter

```<code><span class="itemlastvalue" ng-style="{'background-color' : i.color}" ng-init="setColor(i)">{{i.itemLastValue}}</span>
</code>```

In the function assign the color according to the condition and use timeout function to reverse it to the original value

```<code>$scope.setColor = function(i){
    if( i.itemLastValue == "+"){
      i.color = 'green'
    }
    else if( i.itemLastValue == "-"){
      i.color = 'red'
    }

    $timeout(function(){
       i.color = "white" // what ever the original value
    },1000)
}
</code>```

UPDATED

the second scenario is removing the ng-init function and call the function inside checkForUpdatedIndices

```<code>function checkForUpdatedIndices(){
  dataService.getIndices().then(function(res){
    $scope.recentIndeces = res.data;
    setColor()
 });
}

function setColor(){
   var backUp = angular.copy($scope.recentIndeces);
   for(var i=0; i<= $scope.recentIndeces.length-1; i++){
      if( $scope.recentIndeces[i].itemLastValue == "+"){
        $scope.recentIndeces[i].color = 'green'
      }
      else if( $scope.recentIndeces[i].itemLastValue == "-"){
        $scope.recentIndeces[i].color = 'red'
      }
   }
   $timeout(function(){
      $scope.recentIndeces =  angular.copy(backUp);
   },1000)
}
</code>```

Body:
In my controller I have a function that receives data from API every 2 seconds($interval). This data is rendered and displayed to user. When I get positive numbers from my API I want to set background color in HTML to green for 1 second and return it  to original color. If it is negative, set background color to red for 1 second, and so on...

controller.js

function checkForUpdatedIndices(){
  dataService.getIndices().then(function(res){
    $scope.recentIndeces = res.data;
 });}

 var indicesTimer = setInterval(checkForUpdatedIndices,2000);
 checkForUpdatedIndices();

My HTML:

            {{i.itemName}}
            {{i.itemLastValue}}
            {{i.itemChange}}
            {{i.itemPercentageChange}}

When i.itemLastValue contains "+" I want to see it green for 1 second and after that change it back to original color.
Thanks in advance

Body:
you can do this using ng-style directive. set this style like this

ng-style="{'background-color' : i.color}"

and call a function inside ng-init and pass the item as a parameter

<span class="itemlastvalue" ng-style="{'background-color' : i.color}" ng-init="setColor(i)">{{i.itemLastValue}}</span>

In the function assign the color according to the condition and use timeout function to reverse it to the original value

$scope.setColor = function(i){
    if( i.itemLastValue == "+"){
      i.color = 'green'
    }
    else if( i.itemLastValue == "-"){
      i.color = 'red'
    }

    $timeout(function(){
       i.color = "white" // what ever the original value
    },1000)
}

UPDATED

the second scenario is removing the ng-init function and call the function inside checkForUpdatedIndices

function checkForUpdatedIndices(){
  dataService.getIndices().then(function(res){
    $scope.recentIndeces = res.data;
    setColor()
 });
}

function setColor(){
   var backUp = angular.copy($scope.recentIndeces);
   for(var i=0; i<= $scope.recentIndeces.length-1; i++){
      if( $scope.recentIndeces[i].itemLastValue == "+"){
        $scope.recentIndeces[i].color = 'green'
      }
      else if( $scope.recentIndeces[i].itemLastValue == "-"){
        $scope.recentIndeces[i].color = 'red'
      }
   }
   $timeout(function(){
      $scope.recentIndeces =  angular.copy(backUp);
   },1000)
}


问:
Django admin: Restrict many-to-many relationship items to newly created ones
My problem is that I don't really know how to put my design in terms of a relational db.

I have a class 'Feat', which should contain several other classes, namely lists of 'Stat's, 'Skill's and 'Attribute's. The exact number of those depends on the instance of 'Feat', so I can't just define a static number of fields.

In normal Python, I'd simply use lists:

```<code>class Feat():
    name
    desc
    att_effects = []
    skill_effects = []
    stat_effects = []
</code>```

I tried to replicate this in Django using the Many-to-Many relationship, but that didn't quite work out.

```<code>class Attribute_Name(models.Model):
    name =  models.CharField(max_length=100)
    desc = models.TextField()
    def __unicode__(self):
        return str(self.name)

...

class Attribute(models.Model):
    name = models.ForeignKey(Attribute_Name)
    value = models.IntegerField()
    def __unicode__(self):
        return "%s: %s" % (self.name, self.value)

...

class Feat(models.Model):
    name = models.CharField(max_length=100)
    desc = models.TextField()
    att_effects = models.ManyToManyField(Attribute)
    skill_effects = models.ManyToManyField(Skill)
    stat_effects = models.ManyToManyField(Stat)
</code>```

With these models, I could create new 'Attribute's when creating a new 'Feat' in the admin interface. However, I would always see all existing 'Attribute's, not just those pertaining to my new 'Feat'. Is there a way to restrict the view to only those created along with the new 'Feat'? Something like a back-link to the 'Feat' which created the 'Attribute'?

Basically, when I create or edit a 'Feat', I should only be able to use 'Attribute's created from the page of this instance or add a new 'Attribute' instance. I don't want 'Attribute's belonging to another 'Feat' (or another unrelated class) to show up.

Note that I don't want to add a field to the 'Attribute' class, since it should also be used along with other classes (eg 'Character')

I'd also like to do this within the admin interface, since it saves me quite a bit of work.

On a related note: Is there a way to leave a Many-to-Many field empty? Or should I just create a magic 'empty' value and set it as the default?

答:
"there a way to restrict the view to only those created along with the new 'Feat'? Something like a back-link to the 'Feat' which created the 'Attribute'?"

Yes: use the queryset feature of ModelAdmin as described in this question

Body:
My problem is that I don't really know how to put my design in terms of a relational db.

I have a class 'Feat', which should contain several other classes, namely lists of 'Stat's, 'Skill's and 'Attribute's. The exact number of those depends on the instance of 'Feat', so I can't just define a static number of fields.

In normal Python, I'd simply use lists:

class Feat():
    name
    desc
    att_effects = []
    skill_effects = []
    stat_effects = []

I tried to replicate this in Django using the Many-to-Many relationship, but that didn't quite work out.

class Attribute_Name(models.Model):
    name =  models.CharField(max_length=100)
    desc = models.TextField()
    def __unicode__(self):
        return str(self.name)

...

class Attribute(models.Model):
    name = models.ForeignKey(Attribute_Name)
    value = models.IntegerField()
    def __unicode__(self):
        return "%s: %s" % (self.name, self.value)

...

class Feat(models.Model):
    name = models.CharField(max_length=100)
    desc = models.TextField()
    att_effects = models.ManyToManyField(Attribute)
    skill_effects = models.ManyToManyField(Skill)
    stat_effects = models.ManyToManyField(Stat)

With these models, I could create new 'Attribute's when creating a new 'Feat' in the admin interface. However, I would always see all existing 'Attribute's, not just those pertaining to my new 'Feat'. Is there a way to restrict the view to only those created along with the new 'Feat'? Something like a back-link to the 'Feat' which created the 'Attribute'?

Basically, when I create or edit a 'Feat', I should only be able to use 'Attribute's created from the page of this instance or add a new 'Attribute' instance. I don't want 'Attribute's belonging to another 'Feat' (or another unrelated class) to show up.

Note that I don't want to add a field to the 'Attribute' class, since it should also be used along with other classes (eg 'Character')

I'd also like to do this within the admin interface, since it saves me quite a bit of work.

On a related note: Is there a way to leave a Many-to-Many field empty? Or should I just create a magic 'empty' value and set it as the default?


问:
Will my files be deleted if the Azure webapp is upgraded or updated by Microsoft?
If I have an Azure web app which has to download a file from Azure storage, save it to a folder then process it.

If the Azure web app is upgraded/ updated by Microsoft, will my saved file be lost?

答:
As long as you write the files under the %HOME% folder, they will be persisted regardless of upgrades performed by Microsoft. Only you can ever modify those files.

See this page for more details.


问:
Linked list: Should the type of pointer "next" and the name of struct be same?
```<code>#include<stdio.h>
#include<stdlib.h>
typedef struct {
    int val;
    struct node* next;
} Node, *NodePtr;
void makeInitialLinkedList(int a[], int n)
{
    int i;
    NodePtr rec=NULL;
    NodePtr head=NULL;
    for (i=0; i<n; i++) {
        NodePtr cur=(NodePtr)malloc(sizeof(Node));
        if (i==0) head=cur;
        if (rec!=NULL) rec->next=(node*)cur;
        cur->val=a[i];
        cur->next=NULL;
        rec=cur;
    }

    // test
    while(n--) {
        printf("%d ", head->val);
        head=(NodePtr)head->next;
    }
}
NodePtr copy(NodePtr head)
{
    return NULL;
}
int main()
{
    //Mission #2
    int initialDataArray[10]={5,3,2,8,9,7,0,6,4,1};
    makeInitialLinkedList(initialDataArray, 10);

}
</code>```

I do not understand why this works. I did not make a name initially for the struct and only made a surname "Node" by typedef. Then how does "struct node* next" work correctly? is node* a kind of data types like int* or char*? I thought like this:

```<code>typedef struct strName {
    int val;
    struct strName* next;
} strSurName, *strPtr;
</code>```

Does the type of pointer "next" and the initial name of struct have to same?

答:
With struct node* next as a member of your (unnamed) struct, you actually do two things - forward declare a structure struct node and define a member named next as a pointer to the (forward declared) struct node. Note that struct node, as it has been just forward declared, is incomplete and is an additinal, new structure that is different from the enclosing struct you actually wanted to refer to. Confer also struct forward declaration at cppreference:

A declaration of the following form struct name; hides any
  previously declared meaning for the name name in the tag name space
  and declares name as a new struct name in current scope, which will be
  defined later. Until the definition appears, this struct name has
  incomplete type. This allows structs that refer to each other:

```<code>struct y;
struct x { struct y *p; /* ... */ };
struct y { struct x *q; /* ... */ };
</code>```

So It just seems as if you had a pointer to the same struct you are defining, but actually you are (forward declaring) and using a new structure. See the following example, which actually compiles.

```<code>struct known_struct {
    int a[20];
};

struct own_struct {
    int val;
    struct known_struct* known;
    struct own_struct *own;
    struct unknown_struct* unknown;
} test;

int main(){

    size_t sizeOfKnownMember = sizeof(*(test.known));  // gives 80
    size_t sizeOfMemberOwn = sizeof(*(test.own));  // gives 32
    // size_t sizeOfunknownMember = sizeof(*(test.unknown));  // invalid application of sizeof to incomplete type `struct unknown_struct`

    return 0;
}
</code>```

Body:
#include<stdio.h>
#include<stdlib.h>
typedef struct {
    int val;
    struct node* next;
} Node, *NodePtr;
void makeInitialLinkedList(int a[], int n)
{
    int i;
    NodePtr rec=NULL;
    NodePtr head=NULL;
    for (i=0; i<n; i++) {
        NodePtr cur=(NodePtr)malloc(sizeof(Node));
        if (i==0) head=cur;
        if (rec!=NULL) rec->next=(node*)cur;
        cur->val=a[i];
        cur->next=NULL;
        rec=cur;
    }

    // test
    while(n--) {
        printf("%d ", head->val);
        head=(NodePtr)head->next;
    }
}
NodePtr copy(NodePtr head)
{
    return NULL;
}
int main()
{
    //Mission #2
    int initialDataArray[10]={5,3,2,8,9,7,0,6,4,1};
    makeInitialLinkedList(initialDataArray, 10);

}

I do not understand why this works. I did not make a name initially for the struct and only made a surname "Node" by typedef. Then how does "struct node* next" work correctly? is node* a kind of data types like int* or char*? I thought like this:

typedef struct strName {
    int val;
    struct strName* next;
} strSurName, *strPtr;

Does the type of pointer "next" and the initial name of struct have to same?

Body:
With struct node* next as a member of your (unnamed) struct, you actually do two things - forward declare a structure struct node and define a member named next as a pointer to the (forward declared) struct node. Note that struct node, as it has been just forward declared, is incomplete and is an additinal, new structure that is different from the enclosing struct you actually wanted to refer to. Confer also struct forward declaration at cppreference:

A declaration of the following form struct name; hides any
  previously declared meaning for the name name in the tag name space
  and declares name as a new struct name in current scope, which will be
  defined later. Until the definition appears, this struct name has
  incomplete type. This allows structs that refer to each other:

struct y;
struct x { struct y *p; /* ... */ };
struct y { struct x *q; /* ... */ };

So It just seems as if you had a pointer to the same struct you are defining, but actually you are (forward declaring) and using a new structure. See the following example, which actually compiles.

struct known_struct {
    int a[20];
};

struct own_struct {
    int val;
    struct known_struct* known;
    struct own_struct *own;
    struct unknown_struct* unknown;
} test;

int main(){

    size_t sizeOfKnownMember = sizeof(*(test.known));  // gives 80
    size_t sizeOfMemberOwn = sizeof(*(test.own));  // gives 32
    // size_t sizeOfunknownMember = sizeof(*(test.unknown));  // invalid application of sizeof to incomplete type `struct unknown_struct`

    return 0;
}


问:
I want to create an alert for the first time an app is opened
I want to create an alert for the first time an app is opened on the device but I am having some trouble with the code. this is what I have so far, any help would be appreciated </p>

```<code>    // alert first time app is opened
    // making of alert

    let alert = UIAlertController(title: "Navigation", message: "Tap Right Hand Side of Screen For Next Quote, Left Hand Side To Go Back", preferredStyle: UIAlertControllerStyle.alert)

    //add ok button
    alert.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default, handler: nil))

    // detect if first launch
    let launchedBefore = UserDefaults.standard.bool(forKey: "launcedBefore")
    if launchedBefore {
    }
    else {
        self.present(alert, animated: true, completion: nil)
        UserDefaults.standard.set(true, forKey: "launchedBefore")
    }
</code>```

<p>this is where I am trying to place the code </p>

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
</code>```

答:
There is a typo in the launcedBefore key
Change it to:

```<code>let launchedBefore = UserDefaults.standard.bool(forKey: "launchedBefore")
</code>```

Body:
I want to create an alert for the first time an app is opened on the device but I am having some trouble with the code. this is what I have so far, any help would be appreciated

    // alert first time app is opened
    // making of alert

    let alert = UIAlertController(title: "Navigation", message: "Tap Right Hand Side of Screen For Next Quote, Left Hand Side To Go Back", preferredStyle: UIAlertControllerStyle.alert)

    //add ok button
    alert.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default, handler: nil))

    // detect if first launch
    let launchedBefore = UserDefaults.standard.bool(forKey: "launcedBefore")
    if launchedBefore {
    }
    else {
        self.present(alert, animated: true, completion: nil)
        UserDefaults.standard.set(true, forKey: "launchedBefore")
    }

this is where I am trying to place the code

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

Body:
There is a typo in the launcedBefore key
Change it to:

let launchedBefore = UserDefaults.standard.bool(forKey: "launchedBefore")


问:
Sum up vector values till threshold, then start again
I have a vector a = [1 3 4 2 1 5 6 3 2]. Now I want to create a new vector 'b' with the cumsum of a, but after reaching a threshold, let's say 5, cumsum should reset and start again till it reaches the threshold again, so the new vector should look like this:

```<code>b = [1 4 4 2 3 5 6 3 5]
</code>```

Any ideas?

答:
One way is to use a loop. You create the first cumulative sum cs, and then as long as elements in cs are larger than your threshold th, you replace them with elements from the cumulative sum on the rest of the elements in a.

Because some elements in a might be larger than th, this loop will be infinite unless we also eliminate these elements too.

Here is a simple solution with a while loop:

```<code>a = [1 3 4 2 1 5 6 3 2];
th = 5;
cs = cumsum(a);
while any(cs>th & cs~=a) % if 'cs' has values larger that 'th',
                       % and there are any values smaller than th left in 'a'
    % sum all the values in 'a' that are after 'cs' reached 'th',
    % excluding values that are larger then 'th'
    cs(cs>th & cs~=a) = cumsum(a(cs>th & cs~=a));
end
</code>```

Body:
I have a vector a = [1 3 4 2 1 5 6 3 2]. Now I want to create a new vector 'b' with the cumsum of a, but after reaching a threshold, let's say 5, cumsum should reset and start again till it reaches the threshold again, so the new vector should look like this:

b = [1 4 4 2 3 5 6 3 5]

Any ideas?

Body:
One way is to use a loop. You create the first cumulative sum cs, and then as long as elements in cs are larger than your threshold th, you replace them with elements from the cumulative sum on the rest of the elements in a.

Because some elements in a might be larger than th, this loop will be infinite unless we also eliminate these elements too.

Here is a simple solution with a while loop:

a = [1 3 4 2 1 5 6 3 2];
th = 5;
cs = cumsum(a);
while any(cs>th & cs~=a) % if 'cs' has values larger that 'th',
                       % and there are any values smaller than th left in 'a'
    % sum all the values in 'a' that are after 'cs' reached 'th',
    % excluding values that are larger then 'th'
    cs(cs>th & cs~=a) = cumsum(a(cs>th & cs~=a));
end


问:
.gitignore two or more extensions file
I have the next files in my local repository:

app.component.js
core.component.js
core.service.local.js
core.service.power.ts

My question is very simple, How can I do to ignore the files with the extension .component.js and .service.local.js and other, I mean any file to end with .Any_String.ext

答:
The easiest way is to add these to your .gitignore file.

use this command to stop tracking the specific file

```<code>git rm --cached .
</code>```

or

In this case you can stop tracking the below file.

```<code>git rm --cached public/app/core.service.local.js
</code>```

or

Add these in your gitignore file. I'm not sure you want to skip all files with *.component.js or just only these 4 files.

```<code>app.component.js
core.component.js
core.service.local.js
core.service.power.ts
</code>```

Or use wildcard representation and make sure you ignore unwanted files only.

Title: .gitignore two or more extensions file

Body:
The easiest way is to add these to your .gitignore file.

use this command to stop tracking the specific file

git rm --cached .

or

In this case you can stop tracking the below file.

git rm --cached public/app/core.service.local.js

or

Add these in your gitignore file. I'm not sure you want to skip all files with *.component.js or just only these 4 files.

app.component.js
core.component.js
core.service.local.js
core.service.power.ts

Or use wildcard representation and make sure you ignore unwanted files only.


问:
set language within a django view
background:
The view is called when a payment service pings back a payment outcome behind the scenes - afterwhich I need to send an email in the right language to confirm payment and so on. I can get the language code back in the request from the payment server and would like to use that along with Django's i18n systems to determine which language to send my email out in.

So I need to set the language of my django app from within a view. And then do my template rendering and emailing all in one go.

setting request.session['django_language'] = lang only effects the next view when I'm testing.

Is there any other way to do it?

Cheers,

Guy

答:
If you are using django 1.10 or higher, there's a new syntax for custom middleware:</p>

```<code>from django.utils import translation

class LocaleMiddleware(object):

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):

        language_code = 'en' #TODO, your logic

        translation.activate(language_code)

        response = self.get_response(request)

        translation.deactivate()

        return response
</code>```

Title: set language within a django view

Body:
If you are using django 1.10 or higher, there's a new syntax for custom middleware:

from django.utils import translation

class LocaleMiddleware(object):

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):

        language_code = 'en' #TODO, your logic

        translation.activate(language_code)

        response = self.get_response(request)

        translation.deactivate()

        return response