答:
you don't need to add set to $(this).val(), just update value to set using $(this).val(set);. something like this:

$(".ok").on('click', function() {
var set = $(this).closest('tr').find('.done').val();
if ( set ){
    $(this).closest('tr').find('.text').each(function(){
        $(this).val(set);
    })
}
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr>

    <td>
      <input type="button"  value="ok" class="ok"></td>
    <td>done<input type="text" value="100" class="done" \> </td>
    <td>text1<textarea class="text">hi</textarea> </td>
    <td>text2<textarea class="text">hello</textarea> </td>
    <td>text3<textarea class="text">sup</textarea> </td>

  </tr>
  <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script></code>```

Title: Jquery Updating input field value [Replace the old value with the new value]

Body:
you don't need to add set to $(this).val(), just update value to set using $(this).val(set);. something like this:

$(".ok").on('click', function() {
var set = $(this).closest('tr').find('.done').val();
if ( set ){
    $(this).closest('tr').find('.text').each(function(){
        $(this).val(set);
    })
}
});

<table>
  <tr>

    <td>
      <input type="button"  value="ok" class="ok"></td>
    <td>done<input type="text" value="100" class="done" \> </td>
    <td>text1<textarea class="text">hi</textarea> </td>
    <td>text2<textarea class="text">hello</textarea> </td>
    <td>text3<textarea class="text">sup</textarea> </td>

  </tr>
  <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>


来源: stackexchange

问:
How to search same fiile and compare in pandas
I have some directory and files

```<code>Directory1

file1
file2
file3

Directory2

file1
file2
file3
</code>```

I would like to compare each file in each directory.

I tried

```<code>'glob.glob'
</code>```

and

'read csv'

I guess I should have applied

'diff'
method.

But I couldnt figure out next step.
How can I compare same name files in each directory?

答: if you could read csv files and convert to data frames then this link might be useful</p>

ContentLicense: CC BY-SA 3.0

Body:
I have some directory and files

Directory1

file1
file2
file3

Directory2

file1
file2
file3

I would like to compare each file in each directory.

I tried

'glob.glob'

and

'read csv'

I guess I should have applied

'diff'
method.

But I couldnt figure out next step.
How can I compare same name files in each directory?


问:
How to convert string to byte arrays?
How can I convert a string to its byte value? I have a string "hello" and I want to change is to something like "/x68...".

答:
If you want to get hexadecimal string representation you could do:

```<code>"hello".encode("hex") # '68656c6c6f'
</code>```

And to meet your reference representation (don't take it seriously, guess this is not what you really want):

```<code>"".join(["/x%02x" % ord(c) for c in "hello"]) # '/x68/x65/x6c/x6c/x6f'
</code>```

Title: How to convert string to byte arrays?

Body:
If you want to get hexadecimal string representation you could do:

"hello".encode("hex") # '68656c6c6f'

And to meet your reference representation (don't take it seriously, guess this is not what you really want):

"".join(["/x%02x" % ord(c) for c in "hello"]) # '/x68/x65/x6c/x6c/x6f'

ContentLicense: CC BY-SA 2.5


问:
Can't run very first tracking.js example on Chrome
I'm trying to get familiar with tracking.js, but when I try to run the very same example given on the project's page (http://trackingjs.com/docs.html#introduction), nothing happens.
Google-chrome doesn't even shows the prompt asking if I want to allow the page to access to my webcam. The same thing happens for Firefox.

I have already ran the other examples from the tracking.js-master/ package, and the only one that fails is the one described on the tutorial, which I've added.

Below is the code which I copied and pasted from the tracking.js intro page to my first_tracking.html file.

```<code><!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>tracking.js - first tracking</title>
  <script src="../build/tracking-min.js"></script>
</head>
<body>
  <p>This shows in the browser</p>
  <video id="myVideo" width="400" height="300" preload autoplay loop muted></video>
  <script>
  var colors = new tracking.ColorTracker(['magenta', 'cyan', 'yellow']);

  colors.on('track', function(event) {
      if (event.data.length === 0) {
      // No colors were detected in this frame.
      } else {
      event.data.forEach(function(rect) {
        console.log(rect.x, rect.y, rect.height, rect.width, rect.color);
        });
      }
      });

  tracking.track('#myVideo', colors);
  </script>
</body>
</html>
</code>```

Has anyone tried and succeeded in running the introduction examples listed on the tracking.js page and have any pointers?

Research: Most of the stuff found on a google search relate to Google Analytics, Node.js and other JS  frameworks. I also found some people suggesting setting the preload option to auto, resulting in preload="auto", but it didn't work.

答: { camera: true } is missing from the example code. As previous answers mention, include tracking.track('#myVideo', colors, { camera: true });

Body:
I'm trying to get familiar with tracking.js, but when I try to run the very same example given on the project's page (http://trackingjs.com/docs.html#introduction), nothing happens.
Google-chrome doesn't even shows the prompt asking if I want to allow the page to access to my webcam. The same thing happens for Firefox.

I have already ran the other examples from the tracking.js-master/ package, and the only one that fails is the one described on the tutorial, which I've added.

Below is the code which I copied and pasted from the tracking.js intro page to my first_tracking.html file.

<!doctype html>

  <meta charset="utf-8">
  <title>tracking.js - first tracking</title>

This shows in the browser

  <video id="myVideo" width="400" height="300" preload autoplay loop muted></video>

Has anyone tried and succeeded in running the introduction examples listed on the tracking.js page and have any pointers?

Research: Most of the stuff found on a google search relate to Google Analytics, Node.js and other JS  frameworks. I also found some people suggesting setting the preload option to auto, resulting in preload="auto", but it didn't work.


问:
An uncaught Exception was encountered, Call to undefined method
I'm having this error and been trying to figure whats wrong for like 3 days straight with no luck:

An uncaught Exception was encountered

Type: Error

Message: Call to undefined method Nsbh::post()

Filename: application\controllers\nsbh.php

Line Number: 25

nsbh.php

```<code><?php
Class Nsbh extends CI_Controller{

    var $API ="";

    function __construct() {
        parent::__construct();
        $this->API="http://localhost/rest_ci/index.php";
        $this->load->library('session');
        $this->load->library('curl');
        $this->load->helper('form');
        $this->load->helper('url');
    }

    function index(){
        $data['datansbh'] = json_decode($this->curl->simple_get($this->API.'/nsbh'));
        $this->load->view('nsbh/list',$data);
    }

    function create(){
        if(isset($_POST['submit'])){
            $data = array(
                    'id'           => $this->post('id'),
                    'name'          => $this->post('name'),
                    'location'    => $this->post('location'),
                    'tgl'    => $this->post('tgl'),
                    'addrs'    => $this->post('addrs'));
            $insert =  $this->curl->simple_post($this->API.'/nsbh', $data, array(CURLOPT_BUFFERSIZE => 10));
            if($insert)
            {
                $this->session->set_flashdata('hasil','Insert Succeed');
            }else
            {
               $this->session->set_flashdata('hasil','Insert Failed');
            }
            redirect('nsbh');
        }else{

            $this->load->view('nsbh/create');
        }
    }

    function edit(){
        if(isset($_POST['submit'])){
            $data = array(
                    'id'           => $this->input->post('id'),
                    'name'          => $this->input->post('name'),
                    'location'    => $this->input->post('location'),
                    'tgl'    => $this->input->post('tgl'),
                    'addrs'    => $this->input->post('addrs'));
            $update =  $this->curl->simple_put($this->API.'/nsbh', $data, array(CURLOPT_BUFFERSIZE => 10));
            if($update)
            {
                $this->session->set_flashdata('hasil','Update Succeed');
            }else
            {
               $this->session->set_flashdata('hasil','Update Failed');
            }
            redirect('nsbh');
        }else{
            $params = array('id'=>  $this->uri->segment(3));
            $data['datansbh'] = json_decode($this->curl->simple_get($this->API.'/nsbh',$params));
            $this->load->view('nsbh/edit',$data);
        }
    }

    function delete($id){
        if(empty($id)){
            redirect('nsbh');
        }else{
            $delete =  $this->curl->simple_delete($this->API.'/nsbh', array('id'=>$id), array(CURLOPT_BUFFERSIZE => 10));
            if($delete)
            {
                $this->session->set_flashdata('hasil','Deleted');
            }else
            {
               $this->session->set_flashdata('hasil','Failed');
            }
            redirect('nsbh');
        }
    }
}
</code>```

And this is what's on line 25

```<code>'id'=> $this->post('id'),
</code>```

答:
In the constructor add  $this->load->library('form_validation');

So your constructor looks like this:

```<code>function __construct() {
    parent::__construct();
    $this->API="http://localhost/rest_ci/index.php";
    $this->load->helper('form');
    $this->load->helper('url');
    $this->load->library('session');
    $this->load->library('curl');
    $this->load->library('form_validation');
}
</code>```

Body:
I'm having this error and been trying to figure whats wrong for like 3 days straight with no luck:

An uncaught Exception was encountered

Type: Error

Message: Call to undefined method Nsbh::post()

Filename: application\controllers\nsbh.php

Line Number: 25

nsbh.php

<?php
Class Nsbh extends CI_Controller{

    var $API ="";

    function __construct() {
        parent::__construct();
        $this->API="http://localhost/rest_ci/index.php";
        $this->load->library('session');
        $this->load->library('curl');
        $this->load->helper('form');
        $this->load->helper('url');
    }

    function index(){
        $data['datansbh'] = json_decode($this->curl->simple_get($this->API.'/nsbh'));
        $this->load->view('nsbh/list',$data);
    }

    function create(){
        if(isset($_POST['submit'])){
            $data = array(
                    'id'           => $this->post('id'),
                    'name'          => $this->post('name'),
                    'location'    => $this->post('location'),
                    'tgl'    => $this->post('tgl'),
                    'addrs'    => $this->post('addrs'));
            $insert =  $this->curl->simple_post($this->API.'/nsbh', $data, array(CURLOPT_BUFFERSIZE => 10));
            if($insert)
            {
                $this->session->set_flashdata('hasil','Insert Succeed');
            }else
            {
               $this->session->set_flashdata('hasil','Insert Failed');
            }
            redirect('nsbh');
        }else{

            $this->load->view('nsbh/create');
        }
    }

    function edit(){
        if(isset($_POST['submit'])){
            $data = array(
                    'id'           => $this->input->post('id'),
                    'name'          => $this->input->post('name'),
                    'location'    => $this->input->post('location'),
                    'tgl'    => $this->input->post('tgl'),
                    'addrs'    => $this->input->post('addrs'));
            $update =  $this->curl->simple_put($this->API.'/nsbh', $data, array(CURLOPT_BUFFERSIZE => 10));
            if($update)
            {
                $this->session->set_flashdata('hasil','Update Succeed');
            }else
            {
               $this->session->set_flashdata('hasil','Update Failed');
            }
            redirect('nsbh');
        }else{
            $params = array('id'=>  $this->uri->segment(3));
            $data['datansbh'] = json_decode($this->curl->simple_get($this->API.'/nsbh',$params));
            $this->load->view('nsbh/edit',$data);
        }
    }

    function delete($id){
        if(empty($id)){
            redirect('nsbh');
        }else{
            $delete =  $this->curl->simple_delete($this->API.'/nsbh', array('id'=>$id), array(CURLOPT_BUFFERSIZE => 10));
            if($delete)
            {
                $this->session->set_flashdata('hasil','Deleted');
            }else
            {
               $this->session->set_flashdata('hasil','Failed');
            }
            redirect('nsbh');
        }
    }
}

And this is what's on line 25

'id'=> $this->post('id'),

Body:
In the constructor add  $this->load->library('form_validation');

So your constructor looks like this:

function __construct() {
    parent::__construct();
    $this->API="http://localhost/rest_ci/index.php";
    $this->load->helper('form');
    $this->load->helper('url');
    $this->load->library('session');
    $this->load->library('curl');
    $this->load->library('form_validation');
}


问:
Files inside the assets folder are not being loaded in sub pages
I have a folder structure like below

assets

bootstrap

css

style.css

js

jquery.min.js

views

partials

head.ejs

header.ejs

scripts.ejs

home.ejs

user_registration.ejs

In my app.js file I have set this assets folder like:

```<code>var app = express();
app.use('/static', express.static('assets'));
var routes = require('./routes/routes');
</code>```

In my routes.js file

```<code>exports.userLogin = function(req, res){
    var userLogin = req.params.userId;
    var users = memberData.users;
    res.render('user_registration', {
        title : 'Welcome',
        users : users
    });
};
</code>```

In my head.ejs file

```<code><meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="static/bootstrap/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link href='https://fonts.googleapis.com/css?family=Montserrat:400,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<link rel="stylesheet" href="static/css/style.css" type="text/css">
</code>```

Now inside in user_registration file, I have following code

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <% include partials/head.ejs %>
</head>
<body>
    <% include partials/scripts.ejs %>
</body>
</html>
</code>```

By using this my jQuery, bootstrap files that are inside assets folder are not being loaded. But the home.ejs page is working normally.

When I check at the console, the home.ejs page is taking those files in following format
http://localhost:3000/static/bootstrap/css/bootstrap.min.css

whereas user_registration page is taking following format

http://localhost:3000/user_registration/static/bootstrap/css/bootstrap.min.css

I am very new in express.js framework, so I could not figure out how to solve this problem. Can anybody please help me. Thank you.

答:
The problem is: the href link to static resource should be absolute, not relative. Specifically, in head.ejs it should be:

```<code>href="/static/bootstrap/css/bootstrap.min.css"
...
href="/static/css/style.css"
</code>```

NOT:

```<code>href="static/bootstrap/css/bootstrap.min.css"
...
href="static/css/style.css"
</code>```

As app.use('/static', express.static('assets')); stated, the static assets are hosted under /static namespace (absolute URL starting with /static), it doesn't make any sense to use relative URL any more.

Body:
I have a folder structure like below

assets

bootstrap

css

style.css

js

jquery.min.js

views

partials

head.ejs

header.ejs

scripts.ejs

home.ejs

user_registration.ejs

In my app.js file I have set this assets folder like:

var app = express();
app.use('/static', express.static('assets'));
var routes = require('./routes/routes');

In my routes.js file

exports.userLogin = function(req, res){
    var userLogin = req.params.userId;
    var users = memberData.users;
    res.render('user_registration', {
        title : 'Welcome',
        users : users
    });
};

In my head.ejs file

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="static/bootstrap/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link href='https://fonts.googleapis.com/css?family=Montserrat:400,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<link rel="stylesheet" href="static/css/style.css" type="text/css">

Now inside in user_registration file, I have following code

<!DOCTYPE html>

    <% include partials/head.ejs %>

    <% include partials/scripts.ejs %>

By using this my jQuery, bootstrap files that are inside assets folder are not being loaded. But the home.ejs page is working normally.

When I check at the console, the home.ejs page is taking those files in following format
http://localhost:3000/static/bootstrap/css/bootstrap.min.css

whereas user_registration page is taking following format

http://localhost:3000/user_registration/static/bootstrap/css/bootstrap.min.css

I am very new in express.js framework, so I could not figure out how to solve this problem. Can anybody please help me. Thank you.

Body:
The problem is: the href link to static resource should be absolute, not relative. Specifically, in head.ejs it should be:

href="/static/bootstrap/css/bootstrap.min.css"
...
href="/static/css/style.css"

NOT:

href="static/bootstrap/css/bootstrap.min.css"
...
href="static/css/style.css"

As app.use('/static', express.static('assets')); stated, the static assets are hosted under /static namespace (absolute URL starting with /static), it doesn't make any sense to use relative URL any more.


问:
c++ stl vector causing memory overflow?
I am making extensive use of stl vectors to manage memory (de-) allocation of large arrays of data. In particular I am generating perspective projections of anatomical structures from a large number of angles (180 in 2 degree steps), processing and analysing the results. The results are used to define radiation fields for radiotherapy.

It seems that if the arrays exceed a certain size (>3 anatomical structures) that the memory overflows. In particular the error is as follows

terminate called after throwing an instance of 'std::out_of_range'
  what():  vector::_M_range_check

This is the a result of using at, which does bounds checking, rather than the faster [] operator. If I have <=3 structures the error does not occur.

I have tracked the error down to the following block of code

```<code>bool dicomCP::assignBeamlet(int beamletNumber, Beamlet &b1)
{
 //std::cout << "\nInside dicomCP::assignBeamlet (int, Beamlet &)\n";

  if (!this->isSet)
  {
   this->beamlets.at(beamletNumber).setLeftRight(b1.left,b1.right);

   this->isSet=true;

   return true;

  }

  else if (!this->beamlets.at(beamletNumber-1).isOpen())
  {

   return false;

  }

  // left (outside) min(left) and right (outside) max(right) leaves
  else if ((this->beamlets.at(beamletNumber-1).right-b1.left >EPSILON2)&&(b1.right-this->beamlets.at(beamletNumber-1).left>EPSILON2))
  {

   if (this->beamlets.at(beamletNumber).open) return false;

   else if (!this->beamlets.at(beamletNumber).open)
   {
   this->beamlets.at(beamletNumber).setLeftRight(b1.left,b1.right);
   this->beamlets.at(beamletNumber).isAssigned=true;

   this->isSet=true;
   return true;
   }
  }

  else return false;

}
</code>```

Note that if the "this->isSet=true;" lines are commented out the error does not manifest itself regardless of the number of structures :yes it works with 6! The "isSet" boolean value is used to determine which objects have been set, and hence which objects need to be written out to a data file for further processing.

System and sodtware:

gcc (SUSE Linux) 4.4.1 [gcc-4_4-branch revision 150839]
SuSE 11.2 64bit
Intel Celsius with 4 Xeon 2.66GHz CPUs and 4GB RAM
Eclipse CDT (IDE) 64 bit Build 20100218-1602

答:
at() is throwing the exception. If the index is out of range, it throws an out_of_range exception.

Check if (beamletNumber/beamletNumber-1) correponds to an index in the vector where an element exists. at() checks it and is throwing an exception.

An exception of class out_of_range is used to report that an argument value is not in the expected range, such as when a wrong index is used in an array-like collection or string.

Title: c++ stl vector causing memory overflow?

Body:
I am making extensive use of stl vectors to manage memory (de-) allocation of large arrays of data. In particular I am generating perspective projections of anatomical structures from a large number of angles (180 in 2 degree steps), processing and analysing the results. The results are used to define radiation fields for radiotherapy.

It seems that if the arrays exceed a certain size (>3 anatomical structures) that the memory overflows. In particular the error is as follows

terminate called after throwing an instance of 'std::out_of_range'
  what():  vector::_M_range_check

This is the a result of using at, which does bounds checking, rather than the faster [] operator. If I have <=3 structures the error does not occur.

I have tracked the error down to the following block of code

bool dicomCP::assignBeamlet(int beamletNumber, Beamlet &b1)
{
 //std::cout << "\nInside dicomCP::assignBeamlet (int, Beamlet &)\n";

  if (!this->isSet)
  {
   this->beamlets.at(beamletNumber).setLeftRight(b1.left,b1.right);

   this->isSet=true;

   return true;

  }

  else if (!this->beamlets.at(beamletNumber-1).isOpen())
  {

   return false;

  }

  // left (outside) min(left) and right (outside) max(right) leaves
  else if ((this->beamlets.at(beamletNumber-1).right-b1.left >EPSILON2)&&(b1.right-this->beamlets.at(beamletNumber-1).left>EPSILON2))
  {

   if (this->beamlets.at(beamletNumber).open) return false;

   else if (!this->beamlets.at(beamletNumber).open)
   {
   this->beamlets.at(beamletNumber).setLeftRight(b1.left,b1.right);
   this->beamlets.at(beamletNumber).isAssigned=true;

   this->isSet=true;
   return true;
   }
  }

  else return false;

}

Note that if the "this->isSet=true;" lines are commented out the error does not manifest itself regardless of the number of structures :yes it works with 6! The "isSet" boolean value is used to determine which objects have been set, and hence which objects need to be written out to a data file for further processing.

System and sodtware:

gcc (SUSE Linux) 4.4.1 [gcc-4_4-branch revision 150839]
SuSE 11.2 64bit
Intel Celsius with 4 Xeon 2.66GHz CPUs and 4GB RAM
Eclipse CDT (IDE) 64 bit Build 20100218-1602


问:
Razor MVC numeric format for textbox
I have a textbox, in that i insert a number, the code are the following,

```<code>     @Html.TextBox("Semana1", "", new { @type = "number", @placeholder = "Ingrese Proyección", @maxlength = "15"   })
</code>```

this textbox display a number 12356

I need that the textbox display a number with the format 123.456

thanks for your help.

答:
@Html.TextBoxFor(m => m.TotalAmount, "{0:0.00}")

Useful link:https://stackoverflow.com/a/24669691/3397630

Title: Razor MVC numeric format for textbox

Body:
I have a textbox, in that i insert a number, the code are the following,

     @Html.TextBox("Semana1", "", new { @type = "number", @placeholder = "Ingrese Proyección", @maxlength = "15"   })

this textbox display a number 12356

I need that the textbox display a number with the format 123.456

thanks for your help.


问:
How to share a value between all docker containers spun op by the same "docker-compose up" call?

Context

We are migrating an older application to docker and as a first step we're working against some constraints. The database can not yet be put in a container, and moreover, it is shared between all developers in our team. So this question is to find a fix for a temporary problem.

To not clash with other developers using the same database, there is a system in place where each developer machine starts the application with a value that is unique to his machine. Each container should use this same value.

Question

We are using docker-compose to start the containers. Is there a way to provide a (environment) variable to it that gets propagated to all containers?

How I'm trying to do it:

My docker-compose.yml looks kind of like this:

```<code>my_service:
    image: my_service:latest
    command: ./my_service.sh
    extends:
        file: base.yml
        service: base
    environment:
        - batch.id=${BATCH_ID}
</code>```

then I thought running BATCH_ID=$somevalue docker-compose up my_service would fill in the ${BATCH_ID}, but it doesn't seem to work that way.

Is there another way? A better way?

Optional: Ideally everything should be contained so that a developer can just call docker-compose up my_service leading to compose itself calculating a value to pass to all the containers. But from what I see online, I think this is not possible.

答:
You are correct. Alternatively you can just specify the env var name:

```<code>my_service:

    environment:
        - BATCH_ID
</code>```

So the var BATCH_ID is defined from the current docker-compose execution scope; and passed to the container with the same name.

Body:
Context

We are migrating an older application to docker and as a first step we're working against some constraints. The database can not yet be put in a container, and moreover, it is shared between all developers in our team. So this question is to find a fix for a temporary problem.

To not clash with other developers using the same database, there is a system in place where each developer machine starts the application with a value that is unique to his machine. Each container should use this same value.

Question

We are using docker-compose to start the containers. Is there a way to provide a (environment) variable to it that gets propagated to all containers?

How I'm trying to do it:

My docker-compose.yml looks kind of like this:

my_service:
    image: my_service:latest
    command: ./my_service.sh
    extends:
        file: base.yml
        service: base
    environment:
        - batch.id=${BATCH_ID}

then I thought running BATCH_ID=$somevalue docker-compose up my_service would fill in the ${BATCH_ID}, but it doesn't seem to work that way.

Is there another way? A better way?

Optional: Ideally everything should be contained so that a developer can just call docker-compose up my_service leading to compose itself calculating a value to pass to all the containers. But from what I see online, I think this is not possible.

Body:
You are correct. Alternatively you can just specify the env var name:

my_service:

    environment:
        - BATCH_ID

So the var BATCH_ID is defined from the current docker-compose execution scope; and passed to the container with the same name.


问:
How to get actual HTML elements in Chrome extension, not original source code
I am making a Chrome extension,

In Chrome's Inspect Elements panel, at the bottom will show all elements of the HTML page.

How can I get all those elements in JavaScript?

The page's original source code not include all of the elements.

How can I get all elements shown in Inspect Elements in my Chrome extension?

See these pictures: this one is the elements I want, and this one is the original source code.

答:
I just use the JavaScript document.getElementsByTagName("html")[0] and I get all I want.

I don't know why I didn't get the right result yesterday.


问:
ERROR 1064 (42000) when creating database in mysql
in mysql interactive terminal, when I want to create a new database

```<code>mysql> create database albedo-new;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-new' at line 1
</code>```

I'm not sure whether mysql allow '-' in a database name.

答:
mysql does allow hyphens in database names

use backticks

```<code>create database `albedo-new`
</code>```

ContentLicense: CC BY-SA 4.0

Body:
in mysql interactive terminal, when I want to create a new database

mysql> create database albedo-new;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-new' at line 1

I'm not sure whether mysql allow '-' in a database name.

Body:
mysql does allow hyphens in database names

use backticks

create database `albedo-new`


问:
Buttons on form not working
So I'd like to start by saying this is my first time dealing with JS and I am working on a project for my class.

I have to create a form with three buttons, one that will store the form data, one that will display it and one that will clear the form.  I have been researching to all ends to try and figure out what I am doing wrong.  This is an online class so not much info is given other than here's the book and here's your assignment.

Here's what I have so far, any ideas as to why my store and display buttons are not working and also is there a way I can check to see if the store button is correctly storing the data in arrays and it's just the display button not working?!

I'm ripping my hair out, sorry for being terrible.

<DOCTYPE HTML!>

Internet Technologies Membership

<form name ="ratingForm">

Full Name:
<input type="text" id="FullName" name="FullName">
Date:
<input type="date" id="Date" name="Date">
Opinion:
<select name="opinion" id="opinion">
 <option value="excellent">Excellent</option>
 <option value="verygood">Very Good</option>
 <option value="good">Good</option>
 <option value="fair">Fair</option>
 <option value="poor">Poor</option>
 <option value="verybad">Very Bad</option>
</select>

<textarea name="list" id="list" rows="10" cols="100">
</textarea>

<input type="button" value="RATE" onClick="validateData();">
<input type="button" value="DISPLAY" onClick="displayData();">
<input type="reset" value="CLEAR" onClick="clearData();">

</form>

```

答:
The syntax is incorrect for this line

    document.getElementById("list").value += opinions[pos]"\n";

You forgot the + sign

    document.getElementById("list").value += opinions[pos]+"\n";

To look at the JS errors right click on you page, if you're using chrome, and click Inspect Element->Console. It tells you the errors that your page is throwing.

Title: Buttons on form not working


问:
The methods setText() and getText() are undefined for the type String in Java?
I'm building a calculator with in Java by using Eclipse - Luna, but when adding the code of "Entering the number" I get two error messages as follow:

The Code:

```<code>    JButton btn8 = new JButton("8");
    btn8.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {

            String EnterNumber = TxtDisplay.getText() + btn8.getText();
            TxtDisplay.setText(EnterNumber );
        }
    });
    btn8.setFont(new Font("Tahoma", Font.BOLD, 18));
    btn8.setBounds(79, 137, 50, 50);
    frame.getContentPane().add(btn8);
</code>```

The Error Messages:

```<code>The method getText() is undefined for the type String
The method setText(String) is undefined for the type String
</code>```

Could anyone help me please?

答:
Your TxtDisplay variable is a String which will explain the errors.

If your TxtDisplay is displayable in the frame, you need to change it to type JTextField.

```<code>String TxtDisplay;
</code>```

to

```<code>JTextField TxtDisplay;
</code>```

Body:
I'm building a calculator with in Java by using Eclipse - Luna, but when adding the code of "Entering the number" I get two error messages as follow:

The Code:

    JButton btn8 = new JButton("8");
    btn8.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {

            String EnterNumber = TxtDisplay.getText() + btn8.getText();
            TxtDisplay.setText(EnterNumber );
        }
    });
    btn8.setFont(new Font("Tahoma", Font.BOLD, 18));
    btn8.setBounds(79, 137, 50, 50);
    frame.getContentPane().add(btn8);

The Error Messages:

The method getText() is undefined for the type String
The method setText(String) is undefined for the type String

Could anyone help me please?

Body:
Your TxtDisplay variable is a String which will explain the errors.

If your TxtDisplay is displayable in the frame, you need to change it to type JTextField.

String TxtDisplay;

to

JTextField TxtDisplay;


问:
MySQL Join horizontal with vertical table
I have the following structure:

```<code>CREATE TABLE person {
    id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(30) NOT NULL,
    email VARCHAR(30) NOT NULL UNIQUE
}

CREATE TABLE field {
    id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(30) NOT NULL
}

CREATE TABLE fieldPerson {
    id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    fieldId INT(11) UNSIGNED,
    personId INT(11) UNSIGNED,
    value VARCHAR(30) NOT NULL,
    FOREIGN KEY (fieldId) REFERENCES field(id),
    FOREIGN KEY (personId) REFERENCES person(id)
}
</code>```

This is well summed up. Basically we have the default fields name and email, and we have the option to create custom fields, such as telephone, address, etc.
We can have n fields. I'm trying to figure out a way to do a SELECT query that returns all fields without making use of subqueries or extra work outside the database (it's ok using joins though).

Example (telephone is a custom field):

```<code>TABLE person:

id    name       email
1     Test 1     test1@gmail.com

----

TABLE field:

id    name
1     telephone
2     address

----

TABLE fieldPerson:

id    fieldId    personId    value
1     1          1           +1 555 555 555
2     2          1           First St.

----

RESULTING QUERY

personId   name          email            telephone       Address
1          Test 1        test1@gmail.com  +1 555 555 555  First St.
</code>```

Is that possible?

Thanks.

EDIT:

If not possible, you may suggest a optimal solution using subqueries, only with SQL though.

答:
```<code>SELECT p.*
     , group_concat(CASE f.name WHEN 'telephone' THEN fp.value END) telephone
     , group_concat(CASE f.name WHEN 'address'   THEN fp.value END) address
  FROM person p
  JOIN field f
    LEFT JOIN fieldPerson fp
      ON    fp.personId = p.id
        AND fp.fieldId = f.id
  GROUP BY p.id
</code>```

Body:
I have the following structure:

CREATE TABLE person {
    id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(30) NOT NULL,
    email VARCHAR(30) NOT NULL UNIQUE
}

CREATE TABLE field {
    id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(30) NOT NULL
}

CREATE TABLE fieldPerson {
    id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    fieldId INT(11) UNSIGNED,
    personId INT(11) UNSIGNED,
    value VARCHAR(30) NOT NULL,
    FOREIGN KEY (fieldId) REFERENCES field(id),
    FOREIGN KEY (personId) REFERENCES person(id)
}

This is well summed up. Basically we have the default fields name and email, and we have the option to create custom fields, such as telephone, address, etc.
We can have n fields. I'm trying to figure out a way to do a SELECT query that returns all fields without making use of subqueries or extra work outside the database (it's ok using joins though).

Example (telephone is a custom field):

TABLE person:

id    name       email
1     Test 1     test1@gmail.com

----

TABLE field:

id    name
1     telephone
2     address

----

TABLE fieldPerson:

id    fieldId    personId    value
1     1          1           +1 555 555 555
2     2          1           First St.

----

RESULTING QUERY

personId   name          email            telephone       Address
1          Test 1        test1@gmail.com  +1 555 555 555  First St.

Is that possible?

Thanks.

EDIT:

If not possible, you may suggest a optimal solution using subqueries, only with SQL though.


问:
Ghost featured image and iframe issue
HTML

```<code><div class="blog-post">
  <div class="blog-image">
    <a href="#"><img src="img/featured-img.jpg"/></a>
  </div>
  <div class="blog-details">
    <h3>Post Title Here</h3>
    <ul class="blog-meta">
      <li>Date</li>
      <li>Author</li>
    </ul>
    <div class="blog-excerpt">
      <iframe width="560" height="315" src="https://www.youtube.com/embed/yH4zLmi_6n0" frameborder="0" allowfullscreen></iframe>
    </div>
  </div>
</code>```

and i used the following js

```<code>  function iframe_posts() {
    var video_url = $(".blog-details").find("iframe").attr("src");
    $(".blog-image").html('<iframe width="560" height="315" src="' + video_url + '" frameborder="0" allowfullscreen></iframe>');
  }
}

iframe_posts();
</code>```

By this code Image replacing with iframe but same iframe showing in every "blog-post". I want to show the parent video only for each  "blog-post". Suppose i have 2 blog-post with 2 different iframe. Now i want to show the iframe in

are

Anyone can help me please.

答:
Try this code</p>

```<code>function iframe_posts() {
  var video_url = $(".blog-details").find("iframe").attr("src");
  $(".blog-excerpt").hide();
  $(".blog-image").html('<iframe width="560" height="315" src="' + video_url + '" frameborder="0" allowfullscreen></iframe>');
}
</code>```

Title: Ghost featured image and iframe issue

Body:
HTML

Post Title Here

Date

Author

and i used the following js

  function iframe_posts() {
    var video_url = $(".blog-details").find("iframe").attr("src");
    $(".blog-image").html('');
  }
}

iframe_posts();

By this code Image replacing with iframe but same iframe showing in every "blog-post". I want to show the parent video only for each  "blog-post". Suppose i have 2 blog-post with 2 different iframe. Now i want to show the iframe in

are

Anyone can help me please.

Body:
Try this code

function iframe_posts() {
  var video_url = $(".blog-details").find("iframe").attr("src");
  $(".blog-excerpt").hide();
  $(".blog-image").html('<iframe width="560" height="315" src="' + video_url + '" frameborder="0" allowfullscreen></iframe>');
}


问:
Jquery Updating input field value [Replace the old value with the new value]
For the current code,when the button's clicked, it'll get the value from the done input and display them to the 3 input field respectively.

Let say i'd like to change the value in the done input field, and when the value is updated, the old values from the 3 input fields will be replaced by the new.
Now, the updated value just added after the original value instead of replacing it. What's wrong with my code guys?

$(".ok").on('click', function() {
var set = $(this).closest('tr').find('.done').val();
if ( set ){
    $(this).closest('tr').find('.text').each(function(){
        $(this).val( $(this).val() + set );
    })
}
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr>

    <td>
      <input type="button"  value="ok" class="ok"></td>
    <td>done<input type="text" value="100" class="done" \> </td>
    <td>text1<textarea class="text">hi</textarea> </td>
    <td>text2<textarea class="text">hello</textarea> </td>
    <td>text3<textarea class="text">sup</textarea> </td>

  </tr>
  <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script></code>```

答:
$(".ok").on('click', function() {
  var set = $(this).closest('tr').find('.done').val();
  if (set) {
    $(this).closest('tr').find('.text').each(function() {
      $(this).val($(this).attr("data-value") + set);
    })
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr>

    <td>
      <input type="button" value="ok" class="ok"></td>
    <td>done<input type="text" value="100" class="done" \> </td>
    <td>text1<textarea class="text" data-value="hi">hi</textarea> </td>
    <td>text2<textarea class="text" data-value="hello">hello</textarea> </td>
    <td>text3<textarea class="text" data-value="sup">sup</textarea> </td>

  </tr>
  <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script></code>```

Add a data-* on each textarea.

Use that value instead of the actual value

Body:
For the current code,when the button's clicked, it'll get the value from the done input and display them to the 3 input field respectively.

Let say i'd like to change the value in the done input field, and when the value is updated, the old values from the 3 input fields will be replaced by the new.
Now, the updated value just added after the original value instead of replacing it. What's wrong with my code guys?

$(".ok").on('click', function() {
var set = $(this).closest('tr').find('.done').val();
if ( set ){
    $(this).closest('tr').find('.text').each(function(){
        $(this).val( $(this).val() + set );
    })
}
});

      <input type="button"  value="ok" class="ok">
    done<input type="text" value="100" class="done" \>
    text1<textarea class="text">hi</textarea>
    text2<textarea class="text">hello</textarea>
    text3<textarea class="text">sup</textarea>

Body:
$(".ok").on('click', function() {
  var set = $(this).closest('tr').find('.done').val();
  if (set) {
    $(this).closest('tr').find('.text').each(function() {
      $(this).val($(this).attr("data-value") + set);
    })
  }
});

<table>
  <tr>

    <td>
      <input type="button" value="ok" class="ok"></td>
    <td>done<input type="text" value="100" class="done" \> </td>
    <td>text1<textarea class="text" data-value="hi">hi</textarea> </td>
    <td>text2<textarea class="text" data-value="hello">hello</textarea> </td>
    <td>text3<textarea class="text" data-value="sup">sup</textarea> </td>

  </tr>
  <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>

Add a data-* on each textarea.

Use that value instead of the actual value


答:
You have to deal with individual instances by looping over repeating elements

Can do this numerous ways but I would start at the top level repeating containers ... class=blog-post

```<code>$('.blog-post').each(function(){
   // `this` is current instance of `blog-post`
   var $post = $(this);
   // use `find()` to look inside this `$post` instance
   var video_url = $post.find('iframe').attr('src');
   $post.find('.blog-image').html('....');
});
</code>```

Title: Ghost featured image and iframe issue

Body:
You have to deal with individual instances by looping over repeating elements

Can do this numerous ways but I would start at the top level repeating containers ... class=blog-post

$('.blog-post').each(function(){
   // `this` is current instance of `blog-post`
   var $post = $(this);
   // use `find()` to look inside this `$post` instance
   var video_url = $post.find('iframe').attr('src');
   $post.find('.blog-image').html('....');
});


答:
If you are willing to display the content of TxtDisplay on GUI, that implies TxtDisplay has to be a JTextField.

Look up your code you'll find String TxtDisplay; replace it by JTextField TxtDisplay;.

Once you do that you can access public methods of class JTextField such as getText() and setText(String).

Side note: Please next time choose a better title for your question, this is for your own benefit so our community can interact with you better.

Title: The methods setText() and getText() are undefined for the type String in Java?


问:
Core ML iOS 11 not recognizing images properly
I tried Core ML which was recently introduced in iOS to recognise and classify images. The problem is, it is not giving proper results for the images sent.

If i send an earth image(Globe) it is giving me the class as bubble. Below is the code i used,

```<code>            let model = Resnet50()

            let pixelBuffer: CVPixelBuffer =  (modelImg.pixelBuffer())!

            if let prediction = try? model.prediction(image: pixelBuffer) {
                print( "Found it!! It is a/an \(prediction.classLabel)")
            }
</code>```

Is it possible to train the Model with custom use cases on top of the existing Core ML model?(For ex. Resnet50)

答:
To expand on Matusalem's answer, when using an image classification network you can only get back results in one of the classes it was trained against. In this case, you appear to be using the pretrained ResNet50 Core ML model that Apple has made available for download.

That image classification network, like many others you'll find out there, has been trained on the ImageNet Large Scale Visual Recognition Challenge 2012 dataset, commonly referred to as ImageNet or ILSVRC2012. That dataset became the benchmark for convolutional neural network designs after the 2012 competition, so you'll find many pretrained networks using it. It has 1000 categories of things it can identify in images, with the full listing of labels here. You'll note that "globe" is not among those, so the network will provide the closest matching category of those it has been trained against.

If you'd never seen a globe before, or even been exposed to the word "globe", would you be able to identify one? These networks can generalize in surprising ways, but if they don't even have categories for what you want to classify, they're not going to be able to provide the results you want.

The ImageNet dataset is an interesting starting point, but probably isn't the best for real-world use. It has an odd distribution of classes, with something like 200 breeds of dog but no humans. It can be a great starting point for pretraining a network, and then using transfer learning to refine that network to your particular dataset, but you'll most likely want to train your own application-specific network. That's a whole other topic.

Body:
I tried Core ML which was recently introduced in iOS to recognise and classify images. The problem is, it is not giving proper results for the images sent.

If i send an earth image(Globe) it is giving me the class as bubble. Below is the code i used,

            let model = Resnet50()

            let pixelBuffer: CVPixelBuffer =  (modelImg.pixelBuffer())!

            if let prediction = try? model.prediction(image: pixelBuffer) {
                print( "Found it!! It is a/an \(prediction.classLabel)")
            }

Is it possible to train the Model with custom use cases on top of the existing Core ML model?(For ex. Resnet50)


答:
There is a way you can do this with only window functions.

For each row, get the previous type and value.  Also, enumerate the 70s in such a way that you can identify them as a group (you can do this with a cumulative sum).

In the next step, use a partitioned max to get the type and finally do your calculation.

```<code>select t.*,
       data / data_30 as result
from (select t.*,
             max(case when prev_type = 30 then prev_data end) over (partition by id, grp) as data_30
      from (select t.*,
                   sum(case when type <> 70 then 1 else 0 end) over (partition by id order by time) as grp,
                   lag(type) over (partition by id order by time) as prev_type,
                   lag(data) over (partition by id order by time) as prev_data
            from t
            where type in (30, 70)
           ) t
     ) t;
</code>```

One interesting aspect of this.  By limiting the types only to 30 and 70, we guarantee that each group of 70s is directly preceded by a 30.

Title: SQL query to compute calculations from different rows of the same table in SQL server

Body:
I want a SQL query for the following. I am a novice in SQL. And below table is just an example of the kind of data I have. I have very big data of about 30 million rows and would like to write a query to get the below output table.

   Id        type        data          time
-----------------------------------------------------------
    1          30          3.9          15:50:10.660555
    1          30          4.0          15:50:10.660777
    1          70          11.5         15:50:10.797966
    1          30          4.1          15:50:10.834444
    1          70          12.6         15:50:10.853114
    1          70          16.7         15:50:10.955086
    1          30          5            15:50:10.99
    11         30          3.8          15:50:11.660555
    11         30          4.1          15:50:11.660777
    11         70          12.5         15:50:11.797966
    11         30          4.7          15:50:11.834444
    11         70          12.68        15:50:11.853114
    11         70          16.76        15:50:11.955086
    11         30          5.1          15:50:11.99

I have a table like the above. For each type 70, I need to calculate something with the last known type 30. For instance, for Id = 1, for the first type = 70 data at 15:50:10.797966, I need to get type = 30 data at 15:50:10.660777 so that I can calculate result = 11.5/4.0. Similarly, for type = 70 at 15:50:10.853114, I want data of type = 30 at 15:50:10.834444, so my result = 12.6/4.1.

I want the output to look like this:

Id          type           result             time
------------------------------------------------------
1            70             11.5/4.0        15:50:10.797966
1            70             12.6/4.1        15:50:10.853114
1            70             16.7/4.1        15:50:10.955086
11           70             12.5/4.1        15:50:11.797966
11           70             12.68/4.7       15:50:11.853114
11           70             16.76/4.7       15:50:11.955086

I would like to be able to execute these SQL queries in python using pyodbc.

Any help would be greatly appreciated! Thanks in advance!!

Body:
There is a way you can do this with only window functions.

For each row, get the previous type and value.  Also, enumerate the 70s in such a way that you can identify them as a group (you can do this with a cumulative sum).

In the next step, use a partitioned max to get the type and finally do your calculation.

select t.*,
       data / data_30 as result
from (select t.*,
             max(case when prev_type = 30 then prev_data end) over (partition by id, grp) as data_30
      from (select t.*,
                   sum(case when type <> 70 then 1 else 0 end) over (partition by id order by time) as grp,
                   lag(type) over (partition by id order by time) as prev_type,
                   lag(data) over (partition by id order by time) as prev_data
            from t
            where type in (30, 70)
           ) t
     ) t;

One interesting aspect of this.  By limiting the types only to 30 and 70, we guarantee that each group of 70s is directly preceded by a 30.


问:
Unable to click on "New Application or Top Up" Text present inside  tag in watir/ruby
I'm trying to click on the "New Application or Top Up" text that's present inside the  tag:

```<code><button class="BIMG" tabindex="-1" id="T979" name="T979"style="border:0;background-color:transparent;left:14px;top:114px;width:193px;height`enter code here`:23px;z-index:2020; clip:rect(0px 193px 23px 0px);color:#28497b;">
<table class="T" style="top: 4px; left: 10px; width: 183px; height: 19px; font-weight: bold; font-size: 12px; font-family: Arial; color: rgb(40, 73, 123); text-decoration: underline;" cellpadding="0" cellspacing="0">
    <tbody>
          <tr>
              <td style="vertical-align:top;text-align:left;">New Application or Top Up</td>
          </tr>
    </tbody>
 </table>
</button>
</code>```

答:
Watir allows String & RegExp matching using the :text parameter:

browser.td(text: "New Application or Top Up")

browser.td(text: /New Application/)

Title: Unable to click on "New Application or Top Up" Text present inside <td> tag in watir/ruby

Body:
I'm trying to click on the "New Application or Top Up" text that's present inside the  tag:

<button class="BIMG" tabindex="-1" id="T979" name="T979"style="border:0;background-color:transparent;left:14px;top:114px;width:193px;height`enter code here`:23px;z-index:2020; clip:rect(0px 193px 23px 0px);color:#28497b;">

              New Application or Top Up

</button>


问:
In VSTS, How to constraint/restrict a team member's working capacity in case working in multiple projects
Assume a team member A works with multiple projects/applications(P1,P2,P3). While doing Capacity planning, i'm able to allocate him with 8hrs per day in each project(P1,P2,P3). Is there any availability to freeze/constraint a team member's capacity to 8hrs in all projects combined(capacity should be restricted to 8hrs in combined). Any provision to create such a rule/restriction on account level?</p>

答:
There isn’t the feature to constraint a team member’s capacity to 8hrs in all projects. You need to do it manually.

There is a similar user voice that you can vote and follow, you also can create a new user voice for this feature.

Ability for TFS sprint capacity and days off for a project to be inherited by teams


问:
Sphinx: How to generate documentation using Sphinx
When we enter the command sphinx-quickstart, we have to enter values for so many times.

For example:

```<code>> Root path for the documentation [.]:
> Separate source and build directories (y/n) [n]:
> Name prefix for templates and static dir [_]:
> Project name:
> Author name(s):
> Project version []:
> Project release []:
> Project language [en]:
> Source file suffix [.rst]:
> Name of your master document (without suffix) [index]:
> Do you want to use the epub builder (y/n) [n]:
> autodoc: automatically insert docstrings from modules (y/n) [n]:
> doctest: automatically test code snippets in doctest blocks (y/n) [n]:
> intersphinx: link between Sphinx documentation of different projects (y/n) [n]:
> todo: write "todo" entries that can be shown or hidden on build (y/n) [n]:
> coverage: checks for documentation coverage (y/n) [n]:
> imgmath: include math, rendered as PNG or SVG images (y/n) [n]:
> mathjax: include math, rendered in the browser by MathJax (y/n) [n]:
> ifconfig: conditional inclusion of content based on config values (y/n) [n]:
> viewcode: include links to the source code of documented Python objects (y/n) [n]:
> githubpages: create .nojekyll file to publish the document on GitHub pages (y/n) [n]:
> Create Makefile? (y/n) [y]:
> Create Windows command file? (y/n) [y]:
</code>```

Is there any way around that we don't have to this tiresome job?

For example any bash script or python script ?

The relevant arguments are:

```<code>> Project name: My Project
> Author name(s): My Name
> Project version []: 1
> autodoc: automatically insert docstrings from modules (y/n) [n]: y
> doctest: automatically test code snippets in doctest blocks (y/n) [n]: y
> viewcode: include links to the source code of documented Python objects (y/n) [n]: y
</code>```

All the rest are just empty strings.

My attempts

```<code>printf '\n\n\nMyProject\nBhishan Poudel\n1\n\n\n\n\n\ny\ny\n\n\n\n\n\n\ny\n\n\n\n' | sphinx-quickstart
</code>```

Attempt 2

```<code># run_sphinx_quickstart.py
#!/usr/bin/env python3
import subprocess

sphinx_args = {
'Root_path'        : '',
'Separate_source'  : '',
'Name_prefix'      : '',
'Project_name'     : 'My Project',
'Author_name'      : 'Bhishan Poudel',
'Project_version'  : '1',
'Project_release'  : '',
'Project_language' : 'en',
'Source_file'      : '.rst',
'master_document'  : 'index',
'epub'             : '',
'autodoc'          : 'y',
'doctest'          : 'y',
'intersphinx'      : 'n',
'todo'             : 'n',
'coverage'         : 'n',
'imgmath'          : 'n',
'mathjax'          : 'n',
'ifconfig'         : 'n',
'viewcode'         : 'y',
'githubpages'      : 'n',
'Makefile'         : 'y',
'Windows_Makefile ': 'n' }

for k,v in sphinx_args.items():
    print(k,'\t\t:', v)

subprocess.call('sphink-quickstart', shell=True)

# I don't know how to caputre the outputs of shell commands!!
</code>```

Help will be truly appreciated.

Related links:

答:
The link to the documentation is  Invocation of sphinx-quickstart.

How to Use Sphinx to Generate Documents?

Required Files:

~/.bash_profile

~/Applications/edit_sphinx_conf.py

~/Applications/custom.css

~/Applications/logos/logo.jpg

~/.config/geany/snippets.conf

~/.config/geany/filedefs/filetypes.restructuredtext

.bash_profile

```<code>##==============================================================================
# Sphinx documentation
##==============================================================================
alias sprm='rm -rf  docs/build docs/html docs/Makefile docs/rst docs/source docs/pdf'
alias spo='open docs/html/index.html'

# Documentation using sphinx
# Usage: spallf FOLDER
# Final output: docs/html/index.html
function spallf () {

    #1. Create folders
    mkdir -p docs/html docs/rst docs/rst/_static

    #2. Copy custom.css file to rst/_static
    cp ~/Applications/custom.css docs/rst/_static/

    #3. Quickstart
    # Outputs: docs
    # docs has three things: Makefile source build
    sphinx-quickstart -q -p "Research" -a "Bhishan Poudel" -v 1 -r 0 \
     --ext-autodoc --ext-doctest --ext-viewcode --ext-imgmath \
     --no-batchfile --sep docs

    #4. Copy edit_conf file
    cp ~/Applications/edit_sphinx_conf.py edit_sphinx_conf.py

    #5. Edit conf.py file.
    python3 edit_sphinx_conf.py; rm -rf edit_sphinx_conf.py

    #6. Create html folder (also creates doctrees).
    cd docs; make html; cd -; pwd

    #7. Auto create rst files.
    sphinx-apidoc -o docs/rst "$1"

    #8. Copy conf.py to docs/rst folder.
    cp docs/source/conf.py docs/rst/; mv docs/rst/modules.rst docs/rst/index.rst

    #9. Add path to conf.py
    awk -v n=23 -v s="sys.path.append('../$1')" 'NR == n {print s} {print}' \
    docs/rst/conf.py > docs/rst/conf_new.py;
    rm docs/rst/conf.py; mv docs/rst/conf_new.py docs/rst/conf.py

    #10. Add Table of Contents to index.rst
    awk -v n=1 -v s=".. contents:: Table of Contents\n   :depth: 3\n\n" \
                    'NR == n {print s} {print}' \
                  docs/rst/index.rst > docs/rst/tmp; mv docs/rst/tmp docs/rst/index.rst

    #11. Add Logo to index.rst
    mkdir -p docs/html/_images
    cp ~/Applications/logos/logo.jpg docs/html/_images/logo.jpg
    awk -v n=1 -v s=" .. image:: ../html/_images/logo.jpg\n   :height: 100px\n   :width: 3000 px\n   :align: center\n\n" \
                    'NR == n {print s} {print}' \
                  docs/rst/index.rst > docs/rst/tmp; mv docs/rst/tmp docs/rst/index.rst

    #12. Build to get html and pdf
    cd docs; sphinx-build -b html rst html; cd -

    # Also generate pdf
    #cd docs; sphinx-build -b latex rst latex; cd -; pwd
    #cd docs/latex; make;  cd - ; mkdir docs/pdf
    #cp docs/latex/Research.pdf docs/pdf/Research.pdf; rm -r docs/latex

    #12. Delete pycache
    rm -rf "$1"/__pycache__

    #13. Open html
    open docs/html/index.html
    }

# Add another folder to previous scripts.
# Usage: spallf2 Another_folder
function spallf2 () {
    sphinx-apidoc -o docs/rst "$1"
    echo "" >> docs/rst/index.rst
    echo "" >> docs/rst/index.rst
    cat docs/rst/modules.rst >> docs/rst/index.rst
    rm -rf docs/rst/modules.rst
    awk -v n=25 -v s="sys.path.append('../$1')" 'NR == n {print s} {print}' docs/rst/conf.py > docs/rst/conf_new.py
    cp docs/rst/conf_new.py docs/rst/tmp.py
    rm -rf docs/rst/conf.py; mv docs/rst/conf_new.py docs/rst/conf.py
    cd docs; make clean; cd -
    cd docs; sphinx-build -b html rst html; cd -
    rm -rf "$1"/__pycache__
    open docs/html/index.html
     }
</code>```

edit_sphinx_conf.py

```<code>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# File        : ~/Applications/edit_sphinx_conf.py
# Author      : Bhishan Poudel, Physics PhD Student, Ohio University
# Date        : Jul 04, 2017 Tue
# Ref:
# http://www.sphinx-doc.org/en/stable/theming.html
#
# Imports
import time
import os
import subprocess

def edit_sphinx_conf_py():
    """Edit sphinx conf.py file."""

    html_theme_options = """html_theme_options = { 'linkcolor': '#808000',
        'collapsiblesidebar': True,
        'sidebarbgcolor': 'fuchia',
        'sidebartextcolor': 'teal',
        'sidebarlinkcolor': 'gray',
        'relbarbgcolor': '#5D6D7E',
        'externalrefs': True
        }
    """

    conf, conf2 = 'docs/source/conf.py', 'docs/source/conf2.py'
    if os.path.isfile(conf): subprocess.call('mv %s %s '% (conf, conf2), shell=True)
    with open(conf2, 'r') as f, open(conf,'w') as fo:
        for line in f.readlines():
            olds = [r'# import os',
                    r'# import sys',
                    r"# sys.path.insert(0, os.path.abspath('.'))",
                    r"html_theme = 'alabaster'"]
            news = [r'import os',
                    r'import sys',
                    r"sys.path.insert(0, os.path.abspath('.'))",
                    r"html_theme = 'classic'",
                    html_theme_options,
                    r"html_style = 'custom.css'"]

            # os
            if olds[0] in line:
                print(line.replace(line, news[0]), file=fo, end='\n')

            # sys
            elif olds[1] in line:
                print(line.replace(line, news[1]), file=fo, end='\n')

            # path
            elif olds[2] in line:
                print(line.lstrip('#').lstrip(' '), file=fo, end='\n')

            # theme
            elif olds[3] in line:
                print(line.replace(line, news[3]), file=fo)
                print(news[4], file=fo)
                print(news[5], file=fo)

            # Other lines
            else:
                print(line, file=fo, end='')
    os.remove(conf2)
    print('Editing file: ', conf)

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

custom.css
File: ~/Applications/custom.css

```<code>@import url("classic.css");

div.admonition-todo {
    border-top: 2px solid red;
    border-bottom: 2px solid red;
    border-left: 2px solid red;
    border-right: 2px solid red;
    background-color: #ff6347
}

div.admonition-info {
    border-top: 2px solid green;
    border-bottom: 2px solid green;
    border-left: 2px solid green;
    border-right: 2px solid green;
    background-color: #63cc47
}

div.admonition-readme {
    border-top: 2px solid red;
    border-bottom: 2px solid red;
    border-left: 2px solid red;
    border-right: 2px solid red;
    background-color: #F08080
}
</code>```

Geany filetypes.restructuredtext
Geany > Tools > Configuration Files > Filetype Configuration > Markup Languages > filetypes.restructuredtext

```<code># Author    : Bhishan Poudel
# Date      : Jul 06, 2017 Thu
# Version   : 1.0
# File: ~/.config/geany/filedefs/filetypes.restructuredtext

[styling]
function=type
variable=keyword_1,bold
label=string
userdefined=keyword_1,bold

[keywords]
functions=toctree automodulue contents automodule
variables=depth maxdepth
lables=note warning todo seealso
userdefined=

[lexer_properties]
nsis.uservars=1
nsis.ignorecase=0

[settings]
# default extension used when saving files
extension=rst

# single comments, like # in this file
comment_single=..\s
comment_use_indent=true
lexer_filetype=NSIS

[build-menu]
EX_00_LB=Execute
EX_00_CM=cd ../ ; make clean; sphinx-build -b html rst html && xdg-open html/index.html
EX_00_WD=
FT_00_LB=Compile
FT_00_CM=pandoc -o %e.pdf %f && xdg-open %e.pdf
FT_00_WD=
EX_03_LB=
EX_03_CM=
EX_03_WD=
FT_01_LB=Build
FT_01_CM=
FT_01_WD=
</code>```

Geany snippets.conf

```<code>##***********************************************************************
##=======================================================================
##         reStructuredText (reST)
##=======================================================================
##***********************************************************************
[reStructuredText]
# https://www.youtube.com/watch?v=L-fXOoxrt0M
hdr=.. contents:: Table of Contents\n   :depth: 3\n\n
contents=.. contents:: Table of Contents\n   :depth: 3\n\n
toc=.. toctree::\n   :maxdepth: 4\n\n   %cursor%
h=%cursor%\n################################################################################\n\n
h2=%cursor%\n********************************************************************************\n\n
h3=%cursor%\n================================================================================\n\n
h4=%cursor%\n--------------------------------------------------------------------------------\n\n
h5=%cursor%\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n
h6=%cursor%\n""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""\n\n
img=.. image:: ../images/%cursor%.png\n   :height: 100px\n   :width: 400 px\n   :align: center\n
fig=\n.. figure:: ../images/a.png\n    :width: 200px\n    :align: center\n    :height: 100px\n    :alt: alternate text\n    :figclass: align-center\n\n    This is caption.\n
footnote=[#f1]_  \n\n.. rubric:: Footnotes\n\n.. [#f1] Text of the first footnote.\n\n
cite=[book]_ \n\n.. [book] Name of book
link=`Link text <%cursor%>`_
link2=`a link`_.\n\n.. _a link: %cursor%\n\n
table=\n\n=====  =====  =======\nA      B      A and B\n=====  =====  =======\nF      F      F\nT      F      F\nF      T      F\nT      T      T\n=====  =====  =======\n\n
table2=\n\n+------------------------+------------+----------+----------+\n| Header1                | Header 2   | Header 3 | Header 4 |\n+========================+============+==========+==========+\n| ..                     | 12         |   13     | 14       |\n+------------------------+------------+----------+----------+\n| 21                     | 22         | 23       |       24 |\n+------------------------+------------+----------+----------+\n\n
ss=|H2O|\n\n.. |H2O| replace:: H\ :sub:`2`\ O\n
superscript=|H2O|\n\n.. |H2O| replace:: H\ :sub:`2`\ O\n
code=::\n\n    This is code.
i=\n    %cursor%
# new line
nl=\n| %cursor%\n| %cursor%
doctest=>>> print 'this is a Doctest block'\nthis is a Doctest block
hlist=.. hlist::\n   :columns: 3\n\n   * A list of\n   * short items\n   * that should be\n   * displayed\n   * horizontally\n\n
note=.. note::\n\n   %cursor%.
seealso=.. seealso::\n\n   %cursor%.
seealso2=.. seealso::\n   Module :py:mod:`zipfile`\n      Documentation of the :py:mod:`zipfile` standard module.\n\n   `GNU tar manual, Basic Tar Format <http://link>`_\n      Documentation for tar archive files, including GNU tar extensions.\n
warning=.. warning::\n\n   Write complete sentence.
todo=.. admonition:: todo\n\n   %cursor%
info=.. admonition:: Info\n\n   %cursor%
info=.. admonition:: Readme\n\n   %cursor%
code=.. code-block:: c\n\n    printf("hi there");\n
math=\n:math:`\alpha > \beta`
math2=.. math::\n\n    n_{\mathrm{offset}} = \sum_{k=0}^{N-1} s_k n_k\n
topic=.. topic:: Topic\n\n    Indented text is the body.
sidebar=.. sidebar:: Sidebar\n\n   Body.
i=\n\n    %cursor%
test=.. testcode::\n\n    print("hi")\n\n.. testoutput::\n\n    hi\n
class=:class:`~fibonacci_doctest`
meth=:meth:`~fibonacci_doctest.fib`
paired_index=..  index::\npair: poetry; bad # gives bad>poetry and poetry>bad.
single_index=..  index::\nsingle: Pythagoras # gives bad>poetry and poetry>bad.
</code>```

Geany build commands

```<code>Open Geany text editor
open index.rst
Tools > Build > Set Build Commands > Execute >
cd ../; make clean; sphinx-build -b html rst html && open html/index.html
# For ubuntu use xdg-open instead of open
</code>```

Usage

```<code>pwd: Location of Scripts
spallf Scripts
Add another folder: spallf2 Scripts2
</code>```

Caveats

sphinx may not run good in python2, for me it only worked in anaconda3 version. Both standard python2 and python3 failed to run the command make html command with TemplatesNotFound error.

To run multiple versions of python put the PATH of anaconda3 in the bottom
of .bash_profile or .bashrc then sphinx will run good.

Also, by the way the program PHOSIM needs python2 and to run phosim put
the python2 PATH lines at the bottom of .bash_profile.

That's it! It's so nice and easy documenting with sphinx now.

And, of course, I should learn about rST, that will help my document look better.

Body:
When we enter the command sphinx-quickstart, we have to enter values for so many times.

For example:

> Root path for the documentation [.]:
> Separate source and build directories (y/n) [n]:
> Name prefix for templates and static dir [_]:
> Project name:
> Author name(s):
> Project version []:
> Project release []:
> Project language [en]:
> Source file suffix [.rst]:
> Name of your master document (without suffix) [index]:
> Do you want to use the epub builder (y/n) [n]:
> autodoc: automatically insert docstrings from modules (y/n) [n]:
> doctest: automatically test code snippets in doctest blocks (y/n) [n]:
> intersphinx: link between Sphinx documentation of different projects (y/n) [n]:
> todo: write "todo" entries that can be shown or hidden on build (y/n) [n]:
> coverage: checks for documentation coverage (y/n) [n]:
> imgmath: include math, rendered as PNG or SVG images (y/n) [n]:
> mathjax: include math, rendered in the browser by MathJax (y/n) [n]:
> ifconfig: conditional inclusion of content based on config values (y/n) [n]:
> viewcode: include links to the source code of documented Python objects (y/n) [n]:
> githubpages: create .nojekyll file to publish the document on GitHub pages (y/n) [n]:
> Create Makefile? (y/n) [y]:
> Create Windows command file? (y/n) [y]:

Is there any way around that we don't have to this tiresome job?

For example any bash script or python script ?

The relevant arguments are:

> Project name: My Project
> Author name(s): My Name
> Project version []: 1
> autodoc: automatically insert docstrings from modules (y/n) [n]: y
> doctest: automatically test code snippets in doctest blocks (y/n) [n]: y
> viewcode: include links to the source code of documented Python objects (y/n) [n]: y

All the rest are just empty strings.

My attempts

printf '\n\n\nMyProject\nBhishan Poudel\n1\n\n\n\n\n\ny\ny\n\n\n\n\n\n\ny\n\n\n\n' | sphinx-quickstart

Attempt 2

# run_sphinx_quickstart.py
#!/usr/bin/env python3
import subprocess

sphinx_args = {
'Root_path'        : '',
'Separate_source'  : '',
'Name_prefix'      : '',
'Project_name'     : 'My Project',
'Author_name'      : 'Bhishan Poudel',
'Project_version'  : '1',
'Project_release'  : '',
'Project_language' : 'en',
'Source_file'      : '.rst',
'master_document'  : 'index',
'epub'             : '',
'autodoc'          : 'y',
'doctest'          : 'y',
'intersphinx'      : 'n',
'todo'             : 'n',
'coverage'         : 'n',
'imgmath'          : 'n',
'mathjax'          : 'n',
'ifconfig'         : 'n',
'viewcode'         : 'y',
'githubpages'      : 'n',
'Makefile'         : 'y',
'Windows_Makefile ': 'n' }

for k,v in sphinx_args.items():
    print(k,'\t\t:', v)

subprocess.call('sphink-quickstart', shell=True)

# I don't know how to caputre the outputs of shell commands!!

Help will be truly appreciated.

Related links:

Body:
The link to the documentation is  Invocation of sphinx-quickstart.

How to Use Sphinx to Generate Documents?

Required Files:

~/.bash_profile

~/Applications/edit_sphinx_conf.py

~/Applications/custom.css

~/Applications/logos/logo.jpg

~/.config/geany/snippets.conf

~/.config/geany/filedefs/filetypes.restructuredtext

.bash_profile

##==============================================================================
# Sphinx documentation
##==============================================================================
alias sprm='rm -rf  docs/build docs/html docs/Makefile docs/rst docs/source docs/pdf'
alias spo='open docs/html/index.html'

# Documentation using sphinx
# Usage: spallf FOLDER
# Final output: docs/html/index.html
function spallf () {

    #1. Create folders
    mkdir -p docs/html docs/rst docs/rst/_static

    #2. Copy custom.css file to rst/_static
    cp ~/Applications/custom.css docs/rst/_static/

    #3. Quickstart
    # Outputs: docs
    # docs has three things: Makefile source build
    sphinx-quickstart -q -p "Research" -a "Bhishan Poudel" -v 1 -r 0 \
     --ext-autodoc --ext-doctest --ext-viewcode --ext-imgmath \
     --no-batchfile --sep docs

    #4. Copy edit_conf file
    cp ~/Applications/edit_sphinx_conf.py edit_sphinx_conf.py

    #5. Edit conf.py file.
    python3 edit_sphinx_conf.py; rm -rf edit_sphinx_conf.py

    #6. Create html folder (also creates doctrees).
    cd docs; make html; cd -; pwd

    #7. Auto create rst files.
    sphinx-apidoc -o docs/rst "$1"

    #8. Copy conf.py to docs/rst folder.
    cp docs/source/conf.py docs/rst/; mv docs/rst/modules.rst docs/rst/index.rst

    #9. Add path to conf.py
    awk -v n=23 -v s="sys.path.append('../$1')" 'NR == n {print s} {print}' \
    docs/rst/conf.py > docs/rst/conf_new.py;
    rm docs/rst/conf.py; mv docs/rst/conf_new.py docs/rst/conf.py

    #10. Add Table of Contents to index.rst
    awk -v n=1 -v s=".. contents:: Table of Contents\n   :depth: 3\n\n" \
                    'NR == n {print s} {print}' \
                  docs/rst/index.rst > docs/rst/tmp; mv docs/rst/tmp docs/rst/index.rst

    #11. Add Logo to index.rst
    mkdir -p docs/html/_images
    cp ~/Applications/logos/logo.jpg docs/html/_images/logo.jpg
    awk -v n=1 -v s=" .. image:: ../html/_images/logo.jpg\n   :height: 100px\n   :width: 3000 px\n   :align: center\n\n" \
                    'NR == n {print s} {print}' \
                  docs/rst/index.rst > docs/rst/tmp; mv docs/rst/tmp docs/rst/index.rst

    #12. Build to get html and pdf
    cd docs; sphinx-build -b html rst html; cd -

    # Also generate pdf
    #cd docs; sphinx-build -b latex rst latex; cd -; pwd
    #cd docs/latex; make;  cd - ; mkdir docs/pdf
    #cp docs/latex/Research.pdf docs/pdf/Research.pdf; rm -r docs/latex

    #12. Delete pycache
    rm -rf "$1"/__pycache__

    #13. Open html
    open docs/html/index.html
    }

# Add another folder to previous scripts.
# Usage: spallf2 Another_folder
function spallf2 () {
    sphinx-apidoc -o docs/rst "$1"
    echo "" >> docs/rst/index.rst
    echo "" >> docs/rst/index.rst
    cat docs/rst/modules.rst >> docs/rst/index.rst
    rm -rf docs/rst/modules.rst
    awk -v n=25 -v s="sys.path.append('../$1')" 'NR == n {print s} {print}' docs/rst/conf.py > docs/rst/conf_new.py
    cp docs/rst/conf_new.py docs/rst/tmp.py
    rm -rf docs/rst/conf.py; mv docs/rst/conf_new.py docs/rst/conf.py
    cd docs; make clean; cd -
    cd docs; sphinx-build -b html rst html; cd -
    rm -rf "$1"/__pycache__
    open docs/html/index.html
     }

edit_sphinx_conf.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# File        : ~/Applications/edit_sphinx_conf.py
# Author      : Bhishan Poudel, Physics PhD Student, Ohio University
# Date        : Jul 04, 2017 Tue
# Ref:
# http://www.sphinx-doc.org/en/stable/theming.html
#
# Imports
import time
import os
import subprocess

def edit_sphinx_conf_py():
    """Edit sphinx conf.py file."""

    html_theme_options = """html_theme_options = { 'linkcolor': '#808000',
        'collapsiblesidebar': True,
        'sidebarbgcolor': 'fuchia',
        'sidebartextcolor': 'teal',
        'sidebarlinkcolor': 'gray',
        'relbarbgcolor': '#5D6D7E',
        'externalrefs': True
        }
    """

    conf, conf2 = 'docs/source/conf.py', 'docs/source/conf2.py'
    if os.path.isfile(conf): subprocess.call('mv %s %s '% (conf, conf2), shell=True)
    with open(conf2, 'r') as f, open(conf,'w') as fo:
        for line in f.readlines():
            olds = [r'# import os',
                    r'# import sys',
                    r"# sys.path.insert(0, os.path.abspath('.'))",
                    r"html_theme = 'alabaster'"]
            news = [r'import os',
                    r'import sys',
                    r"sys.path.insert(0, os.path.abspath('.'))",
                    r"html_theme = 'classic'",
                    html_theme_options,
                    r"html_style = 'custom.css'"]

            # os
            if olds[0] in line:
                print(line.replace(line, news[0]), file=fo, end='\n')

            # sys
            elif olds[1] in line:
                print(line.replace(line, news[1]), file=fo, end='\n')

            # path
            elif olds[2] in line:
                print(line.lstrip('#').lstrip(' '), file=fo, end='\n')

            # theme
            elif olds[3] in line:
                print(line.replace(line, news[3]), file=fo)
                print(news[4], file=fo)
                print(news[5], file=fo)

            # Other lines
            else:
                print(line, file=fo, end='')
    os.remove(conf2)
    print('Editing file: ', conf)

if __name__ == '__main__':
    edit_sphinx_conf_py()

custom.css
File: ~/Applications/custom.css

@import url("classic.css");

div.admonition-todo {
    border-top: 2px solid red;
    border-bottom: 2px solid red;
    border-left: 2px solid red;
    border-right: 2px solid red;
    background-color: #ff6347
}

div.admonition-info {
    border-top: 2px solid green;
    border-bottom: 2px solid green;
    border-left: 2px solid green;
    border-right: 2px solid green;
    background-color: #63cc47
}

div.admonition-readme {
    border-top: 2px solid red;
    border-bottom: 2px solid red;
    border-left: 2px solid red;
    border-right: 2px solid red;
    background-color: #F08080
}

Geany filetypes.restructuredtext
Geany > Tools > Configuration Files > Filetype Configuration > Markup Languages > filetypes.restructuredtext

# Author    : Bhishan Poudel
# Date      : Jul 06, 2017 Thu
# Version   : 1.0
# File: ~/.config/geany/filedefs/filetypes.restructuredtext

[styling]
function=type
variable=keyword_1,bold
label=string
userdefined=keyword_1,bold

[keywords]
functions=toctree automodulue contents automodule
variables=depth maxdepth
lables=note warning todo seealso
userdefined=

[lexer_properties]
nsis.uservars=1
nsis.ignorecase=0

[settings]
# default extension used when saving files
extension=rst

# single comments, like # in this file
comment_single=..\s
comment_use_indent=true
lexer_filetype=NSIS

[build-menu]
EX_00_LB=Execute
EX_00_CM=cd ../ ; make clean; sphinx-build -b html rst html && xdg-open html/index.html
EX_00_WD=
FT_00_LB=Compile
FT_00_CM=pandoc -o %e.pdf %f && xdg-open %e.pdf
FT_00_WD=
EX_03_LB=
EX_03_CM=
EX_03_WD=
FT_01_LB=Build
FT_01_CM=
FT_01_WD=

Geany snippets.conf

##***********************************************************************
##=======================================================================
##         reStructuredText (reST)
##=======================================================================
##***********************************************************************
[reStructuredText]
# https://www.youtube.com/watch?v=L-fXOoxrt0M
hdr=.. contents:: Table of Contents\n   :depth: 3\n\n
contents=.. contents:: Table of Contents\n   :depth: 3\n\n
toc=.. toctree::\n   :maxdepth: 4\n\n   %cursor%
h=%cursor%\n################################################################################\n\n
h2=%cursor%\n********************************************************************************\n\n
h3=%cursor%\n================================================================================\n\n
h4=%cursor%\n--------------------------------------------------------------------------------\n\n
h5=%cursor%\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n
h6=%cursor%\n""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""\n\n
img=.. image:: ../images/%cursor%.png\n   :height: 100px\n   :width: 400 px\n   :align: center\n
fig=\n.. figure:: ../images/a.png\n    :width: 200px\n    :align: center\n    :height: 100px\n    :alt: alternate text\n    :figclass: align-center\n\n    This is caption.\n
footnote=[#f1]_  \n\n.. rubric:: Footnotes\n\n.. [#f1] Text of the first footnote.\n\n
cite=[book]_ \n\n.. [book] Name of book
link=`Link text <%cursor%>`_
link2=`a link`_.\n\n.. _a link: %cursor%\n\n
table=\n\n=====  =====  =======\nA      B      A and B\n=====  =====  =======\nF      F      F\nT      F      F\nF      T      F\nT      T      T\n=====  =====  =======\n\n
table2=\n\n+------------------------+------------+----------+----------+\n| Header1                | Header 2   | Header 3 | Header 4 |\n+========================+============+==========+==========+\n| ..                     | 12         |   13     | 14       |\n+------------------------+------------+----------+----------+\n| 21                     | 22         | 23       |       24 |\n+------------------------+------------+----------+----------+\n\n
ss=|H2O|\n\n.. |H2O| replace:: H\ :sub:`2`\ O\n
superscript=|H2O|\n\n.. |H2O| replace:: H\ :sub:`2`\ O\n
code=::\n\n    This is code.
i=\n    %cursor%
# new line
nl=\n| %cursor%\n| %cursor%
doctest=>>> print 'this is a Doctest block'\nthis is a Doctest block
hlist=.. hlist::\n   :columns: 3\n\n   * A list of\n   * short items\n   * that should be\n   * displayed\n   * horizontally\n\n
note=.. note::\n\n   %cursor%.
seealso=.. seealso::\n\n   %cursor%.
seealso2=.. seealso::\n   Module :py:mod:`zipfile`\n      Documentation of the :py:mod:`zipfile` standard module.\n\n   `GNU tar manual, Basic Tar Format <http://link>`_\n      Documentation for tar archive files, including GNU tar extensions.\n
warning=.. warning::\n\n   Write complete sentence.
todo=.. admonition:: todo\n\n   %cursor%
info=.. admonition:: Info\n\n   %cursor%
info=.. admonition:: Readme\n\n   %cursor%
code=.. code-block:: c\n\n    printf("hi there");\n
math=\n:math:`\alpha > \beta`
math2=.. math::\n\n    n_{\mathrm{offset}} = \sum_{k=0}^{N-1} s_k n_k\n
topic=.. topic:: Topic\n\n    Indented text is the body.
sidebar=.. sidebar:: Sidebar\n\n   Body.
i=\n\n    %cursor%
test=.. testcode::\n\n    print("hi")\n\n.. testoutput::\n\n    hi\n
class=:class:`~fibonacci_doctest`
meth=:meth:`~fibonacci_doctest.fib`
paired_index=..  index::\npair: poetry; bad # gives bad>poetry and poetry>bad.
single_index=..  index::\nsingle: Pythagoras # gives bad>poetry and poetry>bad.

Geany build commands

Open Geany text editor
open index.rst
Tools > Build > Set Build Commands > Execute >
cd ../; make clean; sphinx-build -b html rst html && open html/index.html
# For ubuntu use xdg-open instead of open

Usage

pwd: Location of Scripts
spallf Scripts
Add another folder: spallf2 Scripts2

Caveats

sphinx may not run good in python2, for me it only worked in anaconda3 version. Both standard python2 and python3 failed to run the command make html command with TemplatesNotFound error.

To run multiple versions of python put the PATH of anaconda3 in the bottom
of .bash_profile or .bashrc then sphinx will run good.

Also, by the way the program PHOSIM needs python2 and to run phosim put
the python2 PATH lines at the bottom of .bash_profile.

That's it! It's so nice and easy documenting with sphinx now.

And, of course, I should learn about rST, that will help my document look better.


问:
SendGrid Azure Issue
I'm trying to send an email with my Node JS app on Azure and get this error:

```<code>TypeError: sendgrid.Email is not a constructor
</code>```

Here is my code. I used the documentation from Microsoft (https://learn.microsoft.com/en-us/azure/store-sendgrid-nodejs-how-to-send-email).

```<code>var sendgrid = require('sendgrid')('SendGrid User ID', 'SendGrid password');
function createEmail() {
    console.log('CREATE EMAIL');

    var emailToSend = new sendgrid.Email({
        to: example@example.com,
        from: 'example@example.com',
        subject: 'Subject',
        text: 'some text';
    });

    sendEmail(emailToSend);
}

function sendEmail(email) {
    console.log('SEND EMAIL');
    sendgrid.send(email, function (err, json) {
        if (err) {
            return console.error(err);
        }
    });
}
</code>```

答:
As @David Tansey mentioned, the SendGrid team added a breaking change to support the v3 Web API since v3.0.0. Here is a working code example with the latest version (v5.1.2).

```<code>var helper = require('sendgrid').mail;
var fromEmail = new helper.Email('test@example.com');
var toEmail = new helper.Email('test@example.com');
var subject = 'Sending with SendGrid is Fun';
var content = new helper.Content('text/plain', 'and easy to do anywhere, even with Node.js');
var mail = new helper.Mail(fromEmail, subject, toEmail, content);

var sg = require('sendgrid')(process.env.SENDGRID_API_KEY);
var request = sg.emptyRequest({
  method: 'POST',
  path: '/v3/mail/send',
  body: mail.toJSON()
});

sg.API(request, function (error, response) {
  if (error) {
    console.log('Error response received');
  }
  console.log(response.statusCode);
  console.log(response.body);
  console.log(response.headers);
});
</code>```

However, if you want your provided code run smoothly, you'll need to revert the version to 2.0.0.

Title: SendGrid Azure Issue

Body:
I'm trying to send an email with my Node JS app on Azure and get this error:

TypeError: sendgrid.Email is not a constructor

Here is my code. I used the documentation from Microsoft (https://learn.microsoft.com/en-us/azure/store-sendgrid-nodejs-how-to-send-email).

var sendgrid = require('sendgrid')('SendGrid User ID', 'SendGrid password');
function createEmail() {
    console.log('CREATE EMAIL');

    var emailToSend = new sendgrid.Email({
        to: example@example.com,
        from: 'example@example.com',
        subject: 'Subject',
        text: 'some text';
    });

    sendEmail(emailToSend);
}

function sendEmail(email) {
    console.log('SEND EMAIL');
    sendgrid.send(email, function (err, json) {
        if (err) {
            return console.error(err);
        }
    });
}

Body:
As @David Tansey mentioned, the SendGrid team added a breaking change to support the v3 Web API since v3.0.0. Here is a working code example with the latest version (v5.1.2).

var helper = require('sendgrid').mail;
var fromEmail = new helper.Email('test@example.com');
var toEmail = new helper.Email('test@example.com');
var subject = 'Sending with SendGrid is Fun';
var content = new helper.Content('text/plain', 'and easy to do anywhere, even with Node.js');
var mail = new helper.Mail(fromEmail, subject, toEmail, content);

var sg = require('sendgrid')(process.env.SENDGRID_API_KEY);
var request = sg.emptyRequest({
  method: 'POST',
  path: '/v3/mail/send',
  body: mail.toJSON()
});

sg.API(request, function (error, response) {
  if (error) {
    console.log('Error response received');
  }
  console.log(response.statusCode);
  console.log(response.body);
  console.log(response.headers);
});

However, if you want your provided code run smoothly, you'll need to revert the version to 2.0.0.


问:
Multiple MySQL instances on a single machine
How to configure multiple MySQL instances on a single machine? There are a lot of information on the web, but they are not very useful.

Instead of generic information that can only be understood by a mind with years of MySQL administrative experience, I am looking for a tutorial that guides me from begin to end. I would appreciate answers or pointers that are self-sufficient, i.e., don't require a lot of knowledge from the user's part, instead of obscure references.

答:
OK, this question should be closed as not-programming-related, this is really a question for the upcoming "sister" site but I'm going to try and answer it anyway. Now I've never used MySQL and someone can probably do a better answer.

Lets start with a google search

(5 mins later... decided to take the plunge after only skim reading a couple of results)

download + install mysql essential package (mysql-essential-5.1.30-win32.msi)

run configuration wizard

run configuration wizard again (modifying db path, port no)

take a look at http://dev.mysql.com/doc/refman/5.1/en/multiple-windows-services.html

take a look at my.ini (and the backup)

figure out that I need to make a copy of the data dir and merge ini with backup ini file and didn't need to run the config wizard twice. Should have just edited the INI to begin with (but that would require reading the manual.. too much work! Ini file is pretty well documented anyway though)

merge ini files, make service name modifications

run commands: mysqld --install mysql1, mysqld --install mysql2, net start mysql1, net start mysql2

20 mins, done.

Now we have step by step instructions for running multiple MySQL instances on a single machine, which will probably turn up as the first result in google next time anyone searches for it ;)

OwnerDisplayName: Ngu Soon Hui

LastEditorDisplayName: sascha

OwnerDisplayName: sascha


答: Apparently, you are accessing the elements outside of container. It's impossible to say from this code, whether the indexes are correct or not, walk through this code in debugger and you will see. The suspicious looking piece: this->beamlets.at(beamletNumber-1).isOpen() What if beamletNumber is 0? You get invalid index.

Title: c++ stl vector causing memory overflow?

Body:
I am making extensive use of stl vectors to manage memory (de-) allocation of large arrays of data. In particular I am generating perspective projections of anatomical structures from a large number of angles (180 in 2 degree steps), processing and analysing the results. The results are used to define radiation fields for radiotherapy.

It seems that if the arrays exceed a certain size (>3 anatomical structures) that the memory overflows. In particular the error is as follows

terminate called after throwing an instance of 'std::out_of_range'
  what():  vector::_M_range_check

This is the a result of using at, which does bounds checking, rather than the faster [] operator. If I have <=3 structures the error does not occur.

I have tracked the error down to the following block of code

bool dicomCP::assignBeamlet(int beamletNumber, Beamlet &b1)
{
 //std::cout << "\nInside dicomCP::assignBeamlet (int, Beamlet &)\n";

  if (!this->isSet)
  {
   this->beamlets.at(beamletNumber).setLeftRight(b1.left,b1.right);

   this->isSet=true;

   return true;

  }

  else if (!this->beamlets.at(beamletNumber-1).isOpen())
  {

   return false;

  }

  // left (outside) min(left) and right (outside) max(right) leaves
  else if ((this->beamlets.at(beamletNumber-1).right-b1.left >EPSILON2)&&(b1.right-this->beamlets.at(beamletNumber-1).left>EPSILON2))
  {

   if (this->beamlets.at(beamletNumber).open) return false;

   else if (!this->beamlets.at(beamletNumber).open)
   {
   this->beamlets.at(beamletNumber).setLeftRight(b1.left,b1.right);
   this->beamlets.at(beamletNumber).isAssigned=true;

   this->isSet=true;
   return true;
   }
  }

  else return false;

}

Note that if the "this->isSet=true;" lines are commented out the error does not manifest itself regardless of the number of structures :yes it works with 6! The "isSet" boolean value is used to determine which objects have been set, and hence which objects need to be written out to a data file for further processing.

System and sodtware:

gcc (SUSE Linux) 4.4.1 [gcc-4_4-branch revision 150839]
SuSE 11.2 64bit
Intel Celsius with 4 Xeon 2.66GHz CPUs and 4GB RAM
Eclipse CDT (IDE) 64 bit Build 20100218-1602


问:
Make ValidationRule also apply to other list object
Suppose I have a object ListCollectionView and bind it to a datagrid. I bind the object's Name property to a TextBox(one of the datagrid's column)'s Text property and add my specific ValidationRule.

Now I want to the rule to check if the Name property is duplicated, I need to check other objects in the ListCollectionView, if there are objects' Name property equals to this Name, the validate result will be false.

My question is this check can apply only to the edited object, So only this object will become red when its Name is duplicated, but how can I also make check to other list objects, make the other objects which Name property equals to this edited one also become red? Thanks.

答:
You are correct that the ValidationRule only has access to the data it is bound to. However you can write a custom ValidationRule - I've got a blog post detailing it here, and you can then add extra properties to it so you can inject the appropriate data that your bound value should be checked against.

However you will strike one tricky problem - the cells in the datagrid have no natural access to the DataContext of the datagrid because datagrid columns are not in the visual tree. To get around that problem you can use a static proxy object which contains (binds to) the ListCollectionView, this proxy object can then be bound to by the ValidationRule (example 1, example 2).


问:
Jquery slimScroll issue with another scrollbar inside
I'm using slimScroll plugin to make a scrollbar in my div.

```<code>$('#sidebar-scroll').slimScroll({
    height: '500px',
    color: '#fff',
    size: '5px',
    opacity : .35,
    wheelStep : 15,
    distance : '2px',
    railVisible: false,
    railOpacity: 1
});
</code>```

But I also have another scrollbar without using this plugin. I use CSS to make a scrollbar. And finally, after I appplying this plugin to the outside div, scrollbar in inside div not working. Everytime I scroll, the inside div never scrolls, the outside div scrolls only. How can I solve this issue? This is my HTML and CSS. "nav-main" is the inside scroll.

```<code><div id="sidebar-scroll">
  <div class="side-content">
    <ul class="nav-main">
      <li></li>
      ...
    </ul>
  </div>
  ....
</div>

.nav-main {
  max-height: 171px;
  overflow-y: auto;
  overflow-x: hidden;
}
</code>```

答:
Suppose the inner DIV is "#inner", add this line after initialization:

```<code>$("#inner").on("mousewheel", function(e){e.stopPropagation();});
</code>```

Like this: http://jsfiddle.net/ZE8HK/42/

I faced the same problem and found this works.

Body:
I'm using slimScroll plugin to make a scrollbar in my div.

$('#sidebar-scroll').slimScroll({
    height: '500px',
    color: '#fff',
    size: '5px',
    opacity : .35,
    wheelStep : 15,
    distance : '2px',
    railVisible: false,
    railOpacity: 1
});

But I also have another scrollbar without using this plugin. I use CSS to make a scrollbar. And finally, after I appplying this plugin to the outside div, scrollbar in inside div not working. Everytime I scroll, the inside div never scrolls, the outside div scrolls only. How can I solve this issue? This is my HTML and CSS. "nav-main" is the inside scroll.

      ...

  ....

.nav-main {
  max-height: 171px;
  overflow-y: auto;
  overflow-x: hidden;
}

Body:
Suppose the inner DIV is "#inner", add this line after initialization:

$("#inner").on("mousewheel", function(e){e.stopPropagation();});

Like this: http://jsfiddle.net/ZE8HK/42/

I faced the same problem and found this works.


问:
Bootstrap-table text truncate
I’m currently using Bootstrap-table (http://bootstrap-table.wenzhixin.net.cn/) with the bootstrap-editable extension (https://github.com/wenzhixin/bootstrap-table/tree/master/src/extensions/editable) to create a table with editable fields. I have noticed that when a string contains qoutes for example: this is a "test" the string is being truncated on the first ". I have noticed that the text is correctly saved in the database, the JSON contains the full text (" not escaped).

How can I solve this?

答:
You need to set the text-overflow property to clip or initial for the cell where your text is being truncated.
This will help https://www.w3schools.com/cssref/css3_pr_text-overflow.asp

Title: Bootstrap-table text truncate