问:
Wait for $http result before initializing angular app
I have an angular app that needs to do a quick http request to get some config information before the rest of the application is initiated, at least before the controllers. Looked into using $UrlRouterProvider, but I did not figure out how to make the app wait for the http be done.

What I need to be finished:

```<code> $http({method: 'GET', url: '/config'}).then(function(res) {
      configProvider.setConfig(res.data.config);
 }
</code>```

答:
You can create a separate js file where you can make http request and then initialize/bootstrap your app via js code instead of ng-app in html code.

Refer the below code:

```<code>(function() {
  var application, bootstrapApplication, fetchData;
  application = angular.module('app');
  fetchData = function() {
    var $http, initInjector;
    initInjector = angular.injector(['ng']);
    $http = initInjector.get('$http');
    $http.get('<url>');
  };
  bootstrapApplication = function() {
    angular.element(document).ready(function() {
      angular.bootstrap(document, ['app']);
    });
  };
  fetchData().then(bootstrapApplication);
})();
</code>```

I hope it helps.

Body:
I have an angular app that needs to do a quick http request to get some config information before the rest of the application is initiated, at least before the controllers. Looked into using $UrlRouterProvider, but I did not figure out how to make the app wait for the http be done.

What I need to be finished:

 $http({method: 'GET', url: '/config'}).then(function(res) {
      configProvider.setConfig(res.data.config);
 }

Body:
You can create a separate js file where you can make http request and then initialize/bootstrap your app via js code instead of ng-app in html code.

Refer the below code:

(function() {
  var application, bootstrapApplication, fetchData;
  application = angular.module('app');
  fetchData = function() {
    var $http, initInjector;
    initInjector = angular.injector(['ng']);
    $http = initInjector.get('$http');
    $http.get('<url>');
  };
  bootstrapApplication = function() {
    angular.element(document).ready(function() {
      angular.bootstrap(document, ['app']);
    });
  };
  fetchData().then(bootstrapApplication);
})();

I hope it helps.


来源: stackexchange

问:
Using WHERE ... IN in a Postgres Function
I want to create a function in Postgres along the lines of this:

```<code>CREATE OR REPLACE FUNCTION public.getAvailableForms (
    get_form_names  TEXT[]
) RETURNS TABLE (
    id          INTEGER,
    name        TEXT,
    location    TEXT,
    created     TIMESTAMP
) AS $$
BEGIN
    RETURN QUERY
        SELECT *
          FROM form
         WHERE form.name IN get_form_names;
END;
$$  LANGUAGE plpgsql
    SECURITY DEFINER;
</code>```

However, it tells me that WHERE form.name IN get_form_names is syntactically incorrect.

I can't find any documentation on how to use array variables in a postgres function call.

Anyway, is it possible to use an array value passed as a function argument in a WHERE ... IN?

答:
Use any:

```<code>where form.name = any (get_form_names)
</code>```

in would be for a discrete list of items, but any is used for an array.

ContentLicense: CC BY-SA 3.0

Body:
I want to create a function in Postgres along the lines of this:

CREATE OR REPLACE FUNCTION public.getAvailableForms (
    get_form_names  TEXT[]
) RETURNS TABLE (
    id          INTEGER,
    name        TEXT,
    location    TEXT,
    created     TIMESTAMP
) AS $$
BEGIN
    RETURN QUERY
        SELECT *
          FROM form
         WHERE form.name IN get_form_names;
END;
$$  LANGUAGE plpgsql
    SECURITY DEFINER;

However, it tells me that WHERE form.name IN get_form_names is syntactically incorrect.

I can't find any documentation on how to use array variables in a postgres function call.

Anyway, is it possible to use an array value passed as a function argument in a WHERE ... IN?

Body:
Use any:

where form.name = any (get_form_names)

in would be for a discrete list of items, but any is used for an array.


问:
merge a column with one cell that rowspans other rows with foreach loop
I have a table whose records are populated with result from database and foreach loop is used.
I want few columns with a single cell value to be merged with other columns.
Like:

```<code>Leave Type | Max Days | Leave Taken | Leave Balance | Roll Over
Float      | 3        | 2           | 1             |
Personal   | 3        | 2           | 1             |   5
Sick       | 3        | 2           | 1             |
Mourning   | 3        | 2           | 1             |
</code>```

First four records are populated using foreach loop, and I need to separately calculate the fifth column and append it.

Here's my HTML:

```<code>     <table class="table table-striped table-hover" id="leave_balance_table">
        <thead>
            <tr>
                <th>Leave Type</th>
                <th>Max Days</th>
                <th>Leave Taken</th>
                <th>Leave Balance</th>
                <th>Roll Over</th>
            </tr>
        </thead>
        <tbody>
        <?php
        $totalLeaveTaken = 0.00;
        $totalBalance = 0.00;
        $totalRows = count($GetEmployeeLeaveBalance);
            foreach ($GetEmployeeLeaveBalance as $member):
                $totalLeaveTaken += $member['usedDays'];
                $totalBalance += $member['Remaining_Leave_Days'];
                $leaveBalance = floatval($member['Remaining_Leave_Days']);
            ?>
            <tr>
                <td><?php echo $member['title']; ?></td>
                <td><?php echo $member['maxDays']; ?></td>
                <td><?php echo $member['usedDays']; ?></td>
                <!-- <td><?php echo gettype($leaveBalance);?></td> -->
                <td
                <?=
                ($leaveBalance < 0) ?
                "style='background-color:red;font-weight:bold;color:white;'" : ""
                ?>
                >
                <?php echo $member['Remaining_Leave_Days']; ?>
                </td>
                <!-- <td rowspan="<?= $totalRows; ?>">Some computed value</td> -->
            </tr>
        <?php endforeach; ?>
        <tr>
            <td></td>
            <td></td>
            <td style="background-color: #33CCFF; font-weight: bold;">Total: <?php echo number_format($totalLeaveTaken, 2); ?></td>
            <td style="background-color: #33CCFF; font-weight: bold;">Total: <?php echo
            number_format($totalBalance, 2); ?></td>
        </tr>
        </tbody>
    </table>
</code>```

How do I get the fifth column out of foreach loop and append it?

答:
Just add a flag which can help you check if you have already printed the last column as shown below:</p>

```<code>$totalLeaveTaken = 0.00;
$totalBalance = 0.00;
$totalRows = count($GetEmployeeLeaveBalance);
$lastColumnPrinted = false; //Add This
    foreach ($GetEmployeeLeaveBalance as $member):
            $totalLeaveTaken += $member['usedDays'];
            $totalBalance += $member['Remaining_Leave_Days'];
            $leaveBalance = floatval($member['Remaining_Leave_Days']);
        ?>
        <tr>
            <td><?php echo $member['title']; ?></td>
            <td><?php echo $member['maxDays']; ?></td>
            <td><?php echo $member['usedDays']; ?></td>
            <!-- <td><?php echo gettype($leaveBalance);?></td> -->
            <td
            <?=
            ($leaveBalance < 0) ?
            "style='background-color:red;font-weight:bold;color:white;'" : ""
            ?>
            >
            <?php echo $member['Remaining_Leave_Days']; ?>
            </td>

            <!--Add The Line Below -->
            <?php if($lastColumnPrinted == false): $lastColumnPrinted = true;?>
              <td rowspan="<?= $totalRows; ?>">Some computed value</td>
            <?php endif; ?>
        </tr>
    <?php endforeach; ?>
</code>```

Body:
I have a table whose records are populated with result from database and foreach loop is used.
I want few columns with a single cell value to be merged with other columns.
Like:

Leave Type | Max Days | Leave Taken | Leave Balance | Roll Over
Float      | 3        | 2           | 1             |
Personal   | 3        | 2           | 1             |   5
Sick       | 3        | 2           | 1             |
Mourning   | 3        | 2           | 1             |

First four records are populated using foreach loop, and I need to separately calculate the fifth column and append it.

Here's my HTML:

                Leave Type
                Max Days
                Leave Taken
                Leave Balance
                Roll Over

        <?php
        $totalLeaveTaken = 0.00;
        $totalBalance = 0.00;
        $totalRows = count($GetEmployeeLeaveBalance);
            foreach ($GetEmployeeLeaveBalance as $member):
                $totalLeaveTaken += $member['usedDays'];
                $totalBalance += $member['Remaining_Leave_Days'];
                $leaveBalance = floatval($member['Remaining_Leave_Days']);
            ?>

                <?php echo $member['title']; ?>
                <?php echo $member['maxDays']; ?>
                <?php echo $member['usedDays']; ?>

                <td
                <?=
                ($leaveBalance < 0) ?
                "style='background-color:red;font-weight:bold;color:white;'" : ""
                ?>
                >
                <?php echo $member['Remaining_Leave_Days']; ?>

        <?php endforeach; ?>

            Total: <?php echo number_format($totalLeaveTaken, 2); ?>
            Total: <?php echo
            number_format($totalBalance, 2); ?>

How do I get the fifth column out of foreach loop and append it?

Body:
Just add a flag which can help you check if you have already printed the last column as shown below:

$totalLeaveTaken = 0.00;
$totalBalance = 0.00;
$totalRows = count($GetEmployeeLeaveBalance);
$lastColumnPrinted = false; //Add This
    foreach ($GetEmployeeLeaveBalance as $member):
            $totalLeaveTaken += $member['usedDays'];
            $totalBalance += $member['Remaining_Leave_Days'];
            $leaveBalance = floatval($member['Remaining_Leave_Days']);
        ?>
        <tr>
            <td><?php echo $member['title']; ?></td>
            <td><?php echo $member['maxDays']; ?></td>
            <td><?php echo $member['usedDays']; ?></td>
            <!-- <td><?php echo gettype($leaveBalance);?></td> -->
            <td
            <?=
            ($leaveBalance < 0) ?
            "style='background-color:red;font-weight:bold;color:white;'" : ""
            ?>
            >
            <?php echo $member['Remaining_Leave_Days']; ?>
            </td>

            <!--Add The Line Below -->
            <?php if($lastColumnPrinted == false): $lastColumnPrinted = true;?>
              <td rowspan="<?= $totalRows; ?>">Some computed value</td>
            <?php endif; ?>
        </tr>
    <?php endforeach; ?>


问:
How to insert 1 image in 2 different directories using codeigniter
I am trying to insert 1 image in 2 different directories but it is saving only in the first directory but not in the second directory.I am unable find the mistake in my code,please check the below code and help us.Thanks in advance.</p>

```<code>public function image()
{
    $data = array();
    $error = array();
    $config1=array(
        'upload_path'=>'upload/',
        'allowed_types'=>'jpg|jpeg|png|bmp',
        'max_size'=>0,
        'filename'=>url_title($this->input->post('file'))
    );

    $this->load->library('upload',$config1);
    if($this->upload->do_upload('file')){
        $error = array('error' => $this->upload->display_errors());
        echo "```";
        print_r($error);
        exit();
    }else {
        $fdata = $this->upload->data();
        $data['image'] = 'upload/' . $fdata['file_name'];
    }

    $config2=array(
        'upload_path'=>'upload/images/',
        'allowed_types'=>'jpg|jpeg|png|bmp',
        'max_size'=>0,
        'filename'=>url_title($this->input->post('file'))
    );
    $this->upload->initialize($config2);

    if (!$this->upload->do_upload('file')){
        $error = array('error' => $this->upload->display_errors());
        echo "```";
        print_r($error);
        exit();
    } else {
        $fdata = $this->upload->data();
        $data['file2'] = 'upload/images' . $fdata['file_name'];
    }

    $data['name'] = $this->input->post('dname', TRUE);
    $data['email'] = $this->input->post('demail', TRUE);
    $data['mobile'] = $this->input->post('dmobile', TRUE);
    $data['mobile'] = $this->input->post('daddress', TRUE);

    $result = $this->insert_model->insert($data);
    $sdata = array();
    $sdata['message'] = "Well done!</strong> You successfully add the
    Product Details.";
    $this->session->set_userdata($sdata);
    redirect('super_admin/add_product', 'refresh');
}
</code>```

答:
You should make a method for upload, so you can use it more times.

```<code>    /**
     * Upload a file.
     *
     * @param $field
     * @param $upload_path
     * @param string $allowed_types
     * @return bool | file_name
     */
    public function do_upload($field, $upload_path, $allowed_types = 'jpg|png|gif')
    {
        $config['upload_path']          = $upload_path;
        $config['allowed_types']        = $allowed_types;
        $config['max_size']             = 500;
        $config['max_width']            = 1024;
        $config['max_height']           = 1024;

        $this->load->library('upload', $config);

        if ( ! $this->upload->do_upload($field))
        {
            $this->upload = null; // Unload library
            return FALSE;
        }
        else
        {
            $data = $this->upload->data();
            $this->upload = null; // Unload library
            return $data["file_name"];
        }
    }
</code>```

Now you can use it in image().

Example

```<code>public function image()
{
    $data = array();

    // For 1st directory
    if ($data['image'] = $this->do_upload('your_filed_name', 'upload/')) {
       // Statements
        // $data['image'] = 'upload/' . $data['image']
    } else {
        $data['errors'] = array('error' => $this->upload->display_errors());
    }

    // For 2st directory
    if ($data['image'] = $this->do_upload('your_filed_name', 'upload/images/')) {
        // Statements
        // $data['image2'] = 'upload/images/' . $data['image']
    } else {
        $data['errors'] = array('error' => $this->upload->display_errors());
    }

    // Your rest of logic
}
</code>```

Body:
I am trying to insert 1 image in 2 different directories but it is saving only in the first directory but not in the second directory.I am unable find the mistake in my code,please check the below code and help us.Thanks in advance.

public function image()
{
    $data = array();
    $error = array();
    $config1=array(
        'upload_path'=>'upload/',
        'allowed_types'=>'jpg|jpeg|png|bmp',
        'max_size'=>0,
        'filename'=>url_title($this->input->post('file'))
    );

    $this->load->library('upload',$config1);
    if($this->upload->do_upload('file')){
        $error = array('error' => $this->upload->display_errors());
        echo "
";
        print_r($error);
        exit();
    }else {
        $fdata = $this->upload->data();
        $data['image'] = 'upload/' . $fdata['file_name'];
    }

    $config2=array(
        'upload_path'=>'upload/images/',
        'allowed_types'=>'jpg|jpeg|png|bmp',
        'max_size'=>0,
        'filename'=>url_title($this->input->post('file'))
    );
    $this->upload->initialize($config2);

    if (!$this->upload->do_upload('file')){
        $error = array('error' => $this->upload->display_errors());
        echo "
";
        print_r($error);
        exit();
    } else {
        $fdata = $this->upload->data();
        $data['file2'] = 'upload/images' . $fdata['file_name'];
    }

    $data['name'] = $this->input->post('dname', TRUE);
    $data['email'] = $this->input->post('demail', TRUE);
    $data['mobile'] = $this->input->post('dmobile', TRUE);
    $data['mobile'] = $this->input->post('daddress', TRUE);

    $result = $this->insert_model->insert($data);
    $sdata = array();
    $sdata['message'] = "Well done! You successfully add the
    Product Details.";
    $this->session->set_userdata($sdata);
    redirect('super_admin/add_product', 'refresh');
}

Body:
You should make a method for upload, so you can use it more times.

    /**
     * Upload a file.
     *
     * @param $field
     * @param $upload_path
     * @param string $allowed_types
     * @return bool | file_name
     */
    public function do_upload($field, $upload_path, $allowed_types = 'jpg|png|gif')
    {
        $config['upload_path']          = $upload_path;
        $config['allowed_types']        = $allowed_types;
        $config['max_size']             = 500;
        $config['max_width']            = 1024;
        $config['max_height']           = 1024;

        $this->load->library('upload', $config);

        if ( ! $this->upload->do_upload($field))
        {
            $this->upload = null; // Unload library
            return FALSE;
        }
        else
        {
            $data = $this->upload->data();
            $this->upload = null; // Unload library
            return $data["file_name"];
        }
    }

Now you can use it in image().

Example

public function image()
{
    $data = array();

    // For 1st directory
    if ($data['image'] = $this->do_upload('your_filed_name', 'upload/')) {
       // Statements
        // $data['image'] = 'upload/' . $data['image']
    } else {
        $data['errors'] = array('error' => $this->upload->display_errors());
    }

    // For 2st directory
    if ($data['image'] = $this->do_upload('your_filed_name', 'upload/images/')) {
        // Statements
        // $data['image2'] = 'upload/images/' . $data['image']
    } else {
        $data['errors'] = array('error' => $this->upload->display_errors());
    }

    // Your rest of logic
}


问:
Factory Model in C#
I have a bunch of MDI child nodes that are all created in the same way and to reduce redundant code I'd like to be able to call a method, pass it a string (name of child node), have it create the node and add it to the parent.

I can do all the stuff except create the class from a string of a class name, how can I do this?

答: If you have a string which is the name of the class, then you should be able to get a Type object therefrom, by calling Type.GetType(string).  From that type, you should be able to use reflection to generate an object.  </p>

OwnerDisplayName: Malfist

ContentLicense: CC BY-SA 2.5

Title: Factory Model in C#

LastEditorDisplayName: chris

OwnerDisplayName: GWLlosa


问:
Writing data from NSArray to Excel file?
I want to write all the values present in  an array to an excel sheet.Please suggest some way to do so.</p>

答: Write the values out to a CSV file, import the CSV into Excel.</p>


问:
Exception in thread "main" java.lang.NoClassDefFoundError: org/jvnet/staxex/XMLStreamReaderEx
I am getting an exception, but it isn't a code problem, it is a settings/dependencies problem.

I have a work and home computer.  The project files are synced via OneDrive.  Both computers are running Mac OSX 10.11.4, jdk1.8.0_66.jdk and IntelliJ IDEA 2016.1.1

The code works at my work but at home I get the exception:

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: org/jvnet/staxex/XMLStreamReaderEx
    at com.sun.xml.stream.buffer.stax.StreamReaderBufferCreator.storeElementAndChildren(StreamReaderBufferCreator.java:195)
    at com.sun.xml.stream.buffer.stax.StreamReaderBufferCreator.storeDocumentAndChildren(StreamReaderBufferCreator.java:179)
    at com.sun.xml.stream.buffer.stax.StreamReaderBufferCreator.store(StreamReaderBufferCreator.java:160)
    at com.sun.xml.stream.buffer.stax.StreamReaderBufferCreator.create(StreamReaderBufferCreator.java:103)
    at com.sun.xml.stream.buffer.MutableXMLStreamBuffer.createFromXMLStreamReader(MutableXMLStreamBuffer.java:134)
    at com.sun.xml.stream.buffer.XMLStreamBuffer.createNewBufferFromXMLStreamReader(XMLStreamBuffer.java:419)
    at com.sun.xml.ws.api.addressing.WSEndpointReference.<init>(WSEndpointReference.java:183)
    at com.sun.xml.ws.api.addressing.WSEndpointReference.<init>(WSEndpointReference.java:175)
    at com.sun.xml.ws.api.addressing.AddressingVersion.<init>(AddressingVersion.java:443)
    at com.sun.xml.ws.api.addressing.AddressingVersion.<init>(AddressingVersion.java:72)
    at com.sun.xml.ws.api.addressing.AddressingVersion$1.<init>(AddressingVersion.java:74)
    at com.sun.xml.ws.api.addressing.AddressingVersion.<clinit>(AddressingVersion.java:74)
    at com.sun.xml.ws.security.addressing.policy.WsawAddressingPrefixMapper.<clinit>(WsawAddressingPrefixMapper.java:63)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
......
</code>```

I have stax2-api.jar and stax-api.jar in the library/provided of my project. I have VPN'd to work and looked at the project setup and can't see any differences.

How can I work out what the difference is between the two machines to get the code to work at home?

答: This happends because there are conflicting jar files with same class but different implementations(think about different versions). Try removing all jars one by one until you stop receiving this error(target XML parser libraries - jaxws-rt ....etc).</p>

Body:
I am getting an exception, but it isn't a code problem, it is a settings/dependencies problem.

I have a work and home computer.  The project files are synced via OneDrive.  Both computers are running Mac OSX 10.11.4, jdk1.8.0_66.jdk and IntelliJ IDEA 2016.1.1

The code works at my work but at home I get the exception:

Exception in thread "main" java.lang.NoClassDefFoundError: org/jvnet/staxex/XMLStreamReaderEx
    at com.sun.xml.stream.buffer.stax.StreamReaderBufferCreator.storeElementAndChildren(StreamReaderBufferCreator.java:195)
    at com.sun.xml.stream.buffer.stax.StreamReaderBufferCreator.storeDocumentAndChildren(StreamReaderBufferCreator.java:179)
    at com.sun.xml.stream.buffer.stax.StreamReaderBufferCreator.store(StreamReaderBufferCreator.java:160)
    at com.sun.xml.stream.buffer.stax.StreamReaderBufferCreator.create(StreamReaderBufferCreator.java:103)
    at com.sun.xml.stream.buffer.MutableXMLStreamBuffer.createFromXMLStreamReader(MutableXMLStreamBuffer.java:134)
    at com.sun.xml.stream.buffer.XMLStreamBuffer.createNewBufferFromXMLStreamReader(XMLStreamBuffer.java:419)
    at com.sun.xml.ws.api.addressing.WSEndpointReference.<init>(WSEndpointReference.java:183)
    at com.sun.xml.ws.api.addressing.WSEndpointReference.<init>(WSEndpointReference.java:175)
    at com.sun.xml.ws.api.addressing.AddressingVersion.<init>(AddressingVersion.java:443)
    at com.sun.xml.ws.api.addressing.AddressingVersion.<init>(AddressingVersion.java:72)
    at com.sun.xml.ws.api.addressing.AddressingVersion$1.<init>(AddressingVersion.java:74)
    at com.sun.xml.ws.api.addressing.AddressingVersion.<clinit>(AddressingVersion.java:74)
    at com.sun.xml.ws.security.addressing.policy.WsawAddressingPrefixMapper.<clinit>(WsawAddressingPrefixMapper.java:63)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
......

I have stax2-api.jar and stax-api.jar in the library/provided of my project. I have VPN'd to work and looked at the project setup and can't see any differences.

How can I work out what the difference is between the two machines to get the code to work at home?


问:
sugarcrm users insert in magento
Hi  I have a sugarcrm instance and magento instance they two are separate
i mean they have different databases.  My requirement is when i create a user in the sugarcrm ,it should also insert the admin users in magento  How can i do that in sugar,where the code has to be executed in sugar. Any other way is a</p>

答: You will need to use logic hooks and "after_save" will work for you. So add a logic in after_save. Write you code in simple PHP which will get data from Sugar bean fields and will create Magento user accordingly. Read this link for logic hook: http://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_7.9/Architecture/Logic_Hooks/#Module_Hooks</p>

Title: sugarcrm users insert in magento


问:
Mono for Android, WebView input field filechooser doesn't work
I have the web page that uses to upload files. User selects file with <input type="file" /> and presses submit button, all works fine. Now I need to create android application (on C# with mono for android) which contains of simple webview and has to work like web version.

But I stumbled on the problem - when I click on Choose file button then file dialog doesn't open.

I googled this problem few days but I didn't find any solution. Looks like there is workaround on Java platform, but it doesn't work on C#.

Have someone any ideas how to make it work ?

答:
step1 =
    File upload will work , we need to give Read / Write permission in android manifest.
    in Main Activity.cs</p>

```<code>step2=
private Action<int, Result, Intent> resultCallbackvalue;

public void StartActivity(Intent intent, int requestCode, Action<int, Result, Intent> resultCallback)
{
this.resultCallbackvalue = resultCallback;
StartActivityForResult(intent, requestCode);
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
if (this.resultCallbackvalue != null)
{
this.resultCallbackvalue(requestCode, resultCode, data);
this.resultCallbackvalue = null;
}
}
step3= add ExtendedChromeClient,cs Inheriting from : WebChromeClient

private static int filechooser = 1;
private IValueCallback message;
private MainActivity activity = null;

  public ExtendedChromeClient(MainActivity context)
    {
        this.activity = context;
    }

  public override bool OnShowFileChooser(WebView webView, IValueCallback filePathCallback, FileChooserParams fileChooserParams)
    {
        this.message = filePathCallback;
        Intent chooserIntent = fileChooserParams.CreateIntent();
        chooserIntent.AddCategory(Intent.CategoryOpenable);
        this.activity.StartActivity(Intent.CreateChooser(chooserIntent, "File Chooser"), filechooser, this.OnActivityResult);
        return true;
    }

  private void OnActivityResult(int requestCode, Result resultCode, Intent data)
    {
        if (data != null)
        {
            if (requestCode == filechooser)
            {
                if (null == this.message)
                {
                    return;
                }

                this.message.OnReceiveValue(WebChromeClient.FileChooserParams.ParseResult((int)resultCode, data));
                this.message = null;
            }
        }
    }
</code>```

Body:
step1 =
    File upload will work , we need to give Read / Write permission in android manifest.
    in Main Activity.cs

step2=
private Action<int, Result, Intent> resultCallbackvalue;

public void StartActivity(Intent intent, int requestCode, Action<int, Result, Intent> resultCallback)
{
this.resultCallbackvalue = resultCallback;
StartActivityForResult(intent, requestCode);
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
if (this.resultCallbackvalue != null)
{
this.resultCallbackvalue(requestCode, resultCode, data);
this.resultCallbackvalue = null;
}
}
step3= add ExtendedChromeClient,cs Inheriting from : WebChromeClient

private static int filechooser = 1;
private IValueCallback message;
private MainActivity activity = null;

  public ExtendedChromeClient(MainActivity context)
    {
        this.activity = context;
    }

  public override bool OnShowFileChooser(WebView webView, IValueCallback filePathCallback, FileChooserParams fileChooserParams)
    {
        this.message = filePathCallback;
        Intent chooserIntent = fileChooserParams.CreateIntent();
        chooserIntent.AddCategory(Intent.CategoryOpenable);
        this.activity.StartActivity(Intent.CreateChooser(chooserIntent, "File Chooser"), filechooser, this.OnActivityResult);
        return true;
    }

  private void OnActivityResult(int requestCode, Result resultCode, Intent data)
    {
        if (data != null)
        {
            if (requestCode == filechooser)
            {
                if (null == this.message)
                {
                    return;
                }

                this.message.OnReceiveValue(WebChromeClient.FileChooserParams.ParseResult((int)resultCode, data));
                this.message = null;
            }
        }
    }


问:
In Emacs, can we maximize current active window, and then restore it back in multiple window environment?
I like to open multiple window, each with its own file opened. Sometimes, I want to maximize the one I edited to occupy whole screen, and then to restore it back to its previous size and position..

Is there a way?

According to the emacs menu, I can only figure out enlarge-window, shrink-window.. thats it..

答:
More or less - try using winner-mode. It will remember the last few (ca 200) window configurations, and will let you walk through them with a simple (C-c (right|left)) keystroke. And it's quite easy to turn on, since it's built in:

```<code>(when (fboundp 'winner-mode)
  (winner-mode 1))
</code>```

Combine it with windmove and moving between your windows will be even more awesome.

Body:
More or less - try using winner-mode. It will remember the last few (ca 200) window configurations, and will let you walk through them with a simple (C-c (right|left)) keystroke. And it's quite easy to turn on, since it's built in:

(when (fboundp 'winner-mode)
  (winner-mode 1))

Combine it with windmove and moving between your windows will be even more awesome.


问:
MSSQL temp table returns all rows when using IN subquery
I recently stumbled upon this example. Why does query return all rows when using non-defined column on temp table "id". This only works for id and it only works when using IN subquery.</p>

```<code>DECLARE @test TABLE
( Id INT)

INSERT INTO @test
SELECT 1 UNION ALL
SELECT 2 UNION ALL
SELECT 3

SELECT * FROM @test

SELECT 1 AS 'myid'
INTO #tmpId

--Returns one rows - OK
SELECT * FROM @test WHERE id in (SELECT myId FROM #tmpId)
--Returns all rowns - WHY
SELECT * FROM @test WHERE id in (SELECT id FROM #tmpId)
--ERROR - no column - OK
SELECT * FROM @test WHERE id in (SELECT asdf FROM #tmpId)
--ERROR - no column - OK
SELECT id FROM #tmpId

DROP TABLE #tmpId
</code>```

答: In the second query you are comparing the Id column to itself as doesn't exist in inner table, so always true </p>

Body:
I recently stumbled upon this example. Why does query return all rows when using non-defined column on temp table "id". This only works for id and it only works when using IN subquery.

DECLARE @test TABLE
( Id INT)

INSERT INTO @test
SELECT 1 UNION ALL
SELECT 2 UNION ALL
SELECT 3

SELECT * FROM @test

SELECT 1 AS 'myid'
INTO #tmpId

--Returns one rows - OK
SELECT * FROM @test WHERE id in (SELECT myId FROM #tmpId)
--Returns all rowns - WHY
SELECT * FROM @test WHERE id in (SELECT id FROM #tmpId)
--ERROR - no column - OK
SELECT * FROM @test WHERE id in (SELECT asdf FROM #tmpId)
--ERROR - no column - OK
SELECT id FROM #tmpId

DROP TABLE #tmpId


问:
With Java Spark how do I send a html file as a repsonse
How do I use spark to return an existing page

I have the example working where I just return some text

```<code>import static spark.Spark.*;

public class HelloWorld {
    public static void main(String[] args) {
        get("/hello", (req, res) -> "Hello World");
    }
}
</code>```

I have changed to

```<code>import spark.Service;
import static spark.Spark.*;

public class HelloWorld {
    public static void main(String[] args) {
        staticFiles.externalLocation("C:\\HtmlFolder\\"); // Static files
        init();
        get("/hello", (req, res) -> "Report00001.html");
    }
}
</code>```

and I want it to display the contents of HtmlFolder\Report00001.hml but it just displays Report0001.html

I cannot see any examples showing how to do this

So if I place a index.html within C:\HtmlFolder\ then that is now displayed when open browser at http://localhost:4567/ but I cannnot see how do a mapping for get requests to display other files

答:
I suppose that C:\\HtmlFolder\\is not in your classpath.

To serve external resources (out of the classpath) you need to use staticFiles.externalLocation() + System.getProperty()

Example:

```<code>staticFiles.externalLocation(System.getProperty("myDir"));
</code>```

Check Spark Static Files Documenation if you need to know more about this.

EDITED:

Configure external locatios as above and the, in your get, do something like

get("/hello", (req, res) -> {res.redirect("/Report00001.html");});

(I'm not sure now if shoul be "/Report00001.html" or "Report00001.html")

Body:
How do I use spark to return an existing page

I have the example working where I just return some text

import static spark.Spark.*;

public class HelloWorld {
    public static void main(String[] args) {
        get("/hello", (req, res) -> "Hello World");
    }
}

I have changed to

import spark.Service;
import static spark.Spark.*;

public class HelloWorld {
    public static void main(String[] args) {
        staticFiles.externalLocation("C:\\HtmlFolder\\"); // Static files
        init();
        get("/hello", (req, res) -> "Report00001.html");
    }
}

and I want it to display the contents of HtmlFolder\Report00001.hml but it just displays Report0001.html

I cannot see any examples showing how to do this

So if I place a index.html within C:\HtmlFolder\ then that is now displayed when open browser at http://localhost:4567/ but I cannnot see how do a mapping for get requests to display other files

Body:
I suppose that C:\\HtmlFolder\\is not in your classpath.

To serve external resources (out of the classpath) you need to use staticFiles.externalLocation() + System.getProperty()

Example:

staticFiles.externalLocation(System.getProperty("myDir"));

Check Spark Static Files Documenation if you need to know more about this.

EDITED:

Configure external locatios as above and the, in your get, do something like

get("/hello", (req, res) -> {res.redirect("/Report00001.html");});

(I'm not sure now if shoul be "/Report00001.html" or "Report00001.html")


问:
Check for newer Docker build for image
I'm running Jenkins from Docker with tag lts. behind this tag was version 2.73.2. Now there is a newer lts version available: 2.73.3. Docker doesn't automatically check for it. I had to do docker pull jenkins/jenkins:lts to get the new version.

But how can check if there is a newer build for a tag?

EDIT:
I want to make clear: This is not a duplicate! I asked how to check for a newer Docker image available. I know how to upgrade (as I said above).

答: There is a project called Watchtower (https://github.com/v2tec/watchtower), which watches the running container and if there is a new version with the same tag available, it will pull the new image and restart the container.</p>

ContentLicense: CC BY-SA 4.0

Title: Check for newer Docker build for image


问:
What is the purpose of Looper and how to use it?
I am new to Android. I want to know what the Looper class does and also how to use it. I have read the Android Looper class documentation but I am unable to completely understand it.
I have seen it in a lot of places but unable to understand its purpose. Can anyone help me by defining the purpose of Looper and also by giving a simple example if possible?

答:
This answer has nothing to do with the question, but the use of looper and the way people created the handler and looper in ALL the answers here are plain bad practice (some explanations are correct though), I have to post this:

```<code>HandlerThread thread = new HandlerThread(threadName);
thread.start();
Looper looper = thread.getLooper();
Handler myHandler = new Handler(looper);
</code>```

and for a full implementation

Body:
This answer has nothing to do with the question, but the use of looper and the way people created the handler and looper in ALL the answers here are plain bad practice (some explanations are correct though), I have to post this:

HandlerThread thread = new HandlerThread(threadName);
thread.start();
Looper looper = thread.getLooper();
Handler myHandler = new Handler(looper);

and for a full implementation


问:
cpu cores stuck on 100 percent cpu utilization
I am running a java web application in tomcat deployed on aws with 2 cores. The problem is after every 2-3 days both cpu cores get stuck on 100 percent cpu utilization and application becomes very slow. By taking the three thread dumps of tomcat within 10 sec interval when cpu was stuck 100 percent I found two threads which are causing the problem. Here is the stack trace .

```<code>Thread 1 :

http-bio-8080-exec-10 - priority:10 - threadId:0x00007fda4005a800 - nativeId:0x526e - state:RUNNABLE
stackTrace:
java.lang.Thread.State: RUNNABLE
at org.apache.coyote.http11.AbstractInputBuffer.nextRequest(AbstractInputBuffer.java:229)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1110)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313)
- locked <0x00000000f4102c60> (a org.apache.tomcat.util.net.SocketWrapper)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)

2nd thread :

http-bio-8080-exec-3 - priority:10 - threadId:0x00007fda24096800 - nativeId:0x524e - state:RUNNABLE
stackTrace:
java.lang.Thread.State: RUNNABLE
at org.apache.coyote.http11.AbstractInputBuffer.nextRequest(AbstractInputBuffer.java:229)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1110)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313)
- locked <0x00000000f4102ca0> (a org.apache.tomcat.util.net.SocketWrapper)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
</code>```

How to fix the problem.

答:
The symptoms look like this Tomcat bug:

https://bz.apache.org/bugzilla/show_bug.cgi?id=57544

The solution is to update your Tomcat to a more recent version.

Comment #5 - Mark Thomas 2015-02-06 18:03:54 UTC

This has been fixed in trunk (9.0.x development), 8.0.x for 8.0.19 onwards and 7.0.x for 7.0.60 onwards.

Body:
I am running a java web application in tomcat deployed on aws with 2 cores. The problem is after every 2-3 days both cpu cores get stuck on 100 percent cpu utilization and application becomes very slow. By taking the three thread dumps of tomcat within 10 sec interval when cpu was stuck 100 percent I found two threads which are causing the problem. Here is the stack trace .

Thread 1 :

http-bio-8080-exec-10 - priority:10 - threadId:0x00007fda4005a800 - nativeId:0x526e - state:RUNNABLE
stackTrace:
java.lang.Thread.State: RUNNABLE
at org.apache.coyote.http11.AbstractInputBuffer.nextRequest(AbstractInputBuffer.java:229)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1110)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313)
- locked <0x00000000f4102c60> (a org.apache.tomcat.util.net.SocketWrapper)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)

2nd thread :

http-bio-8080-exec-3 - priority:10 - threadId:0x00007fda24096800 - nativeId:0x524e - state:RUNNABLE
stackTrace:
java.lang.Thread.State: RUNNABLE
at org.apache.coyote.http11.AbstractInputBuffer.nextRequest(AbstractInputBuffer.java:229)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1110)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313)
- locked <0x00000000f4102ca0> (a org.apache.tomcat.util.net.SocketWrapper)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)

How to fix the problem.


问:
How to record macro in PhpStorm?
Currently I'm using PhpStorm and I want to make a macro like this:</p>

```<code>echo "<pre">;
var_dump(**paste last copied value here**);
die;
</code>```

答:
You can record a macro by using Edit | Macros | Start Macro Recording.

You will have to type that all text manually and use clipboard as you would normally do. When finished recording you can assign custom shortcut to the freshly recorded macro and use it where needed.

https://www.jetbrains.com/help/phpstorm/using-macros-in-the-editor.html

But I do not think that you actually need a macro here.

What you most likely need is code snippets .. which called Live Templates in IDEA-based IDEs -- it can work with clipboard content as well.

Once you create such Live Template .. you just type its' abbreviation in the text, hit the expand key (Tab should be the default one) and it will insert that code snippet instead.

https://confluence.jetbrains.com/display/PhpStorm/Live+Templates+%28Snippets%29+in+PhpStorm

https://www.jetbrains.com/help/phpstorm/live-templates.html

Title: How to record macro in PhpStorm?

Body:
Currently I'm using PhpStorm and I want to make a macro like this:

echo "
;
var_dump(**paste last copied value here**);
die;


问:
Match Column only if it is not empty
I want to match column only if it is not empty

```<code>select *
from users
where message = 'test' AND phone like '%813%'
</code>```

Where condition should be called only if phone column is not null

else below query should be called

```<code>select * from users where message = 'test'
</code>```

means AND phone like '%813%' should be called only if phone is not null

答:
Use CASE

```<code>select *
from users
where message = 'test' AND
    case when phone is not null
    then phone like '%813%'
    else 1 end
</code>```

Title: Match Column only if it is not empty

Body:
I want to match column only if it is not empty

select *
from users
where message = 'test' AND phone like '%813%'

Where condition should be called only if phone column is not null

else below query should be called

select * from users where message = 'test'

means AND phone like '%813%' should be called only if phone is not null

Body:
Use CASE

select *
from users
where message = 'test' AND
    case when phone is not null
    then phone like '%813%'
    else 1 end


问:
execute linux command in java
i want to execute the command crontab file.txt in java.

What is the procedure...?

答: ProcessBuilder is your friend.</p>

Title: execute linux command in java

Body: ProcessBuilder is your friend.


问:
RxJava2 toList() never emits
So I have following Disposable which doesn't work. I am using Room to get all rows from a table as a list, map each of them to something and create a list and then it doesn't continue from there.</p>

```<code>storedSuggestionDao
    .getSuggestionsOrderByType() //Flowable
    .doOnNext(storedSuggestions -> Timber.e("storedSuggestions: " + storedSuggestions)) //this work
    .flatMapIterable(storedSuggestions -> storedSuggestions)
    .map(Selection::create) ))
    .doOnNext(selection -> Timber.e("Selection: " + selection)) // works
    .toList()
    .toObservable() // nothing works after this...
    .doOnNext(selections -> Timber.d("selections: " + selections))
    .map(SuggestionUiModel::create)
    .doOnNext(suggestionUiModel -> Timber.d("suggestionUiModel: " + suggestionUiModel))
    .subscribe();
</code>```

答:
These types of data sources from 3rd parties are usually infinite sources but toList() requires a finite source. I guess you wanted to process that collection of storedSuggestions and keep it together. You can achieve this via an inner transformation:

```<code>storedSuggestionDao
.getSuggestionsOrderByType() //Flowable
.doOnNext(storedSuggestions -> Timber.e("storedSuggestions: " + storedSuggestions)) //this work
// -------------------------------------
.flatMapSingle(storedSuggestions ->
    Flowable.fromIterable(storedSuggestions)
    .map(Selection::create)
    .doOnNext(selection -> Timber.e("Selection: " + selection))
    .toList()
)
// -------------------------------------
.doOnNext(selections -> Timber.d("selections: " + selections))
.map(SuggestionUiModel::create)
.doOnNext(suggestionUiModel -> Timber.d("suggestionUiModel: " + suggestionUiModel))
.subscribe();
</code>```

Title: RxJava2 toList() never emits

Body:
So I have following Disposable which doesn't work. I am using Room to get all rows from a table as a list, map each of them to something and create a list and then it doesn't continue from there.

storedSuggestionDao
    .getSuggestionsOrderByType() //Flowable
    .doOnNext(storedSuggestions -> Timber.e("storedSuggestions: " + storedSuggestions)) //this work
    .flatMapIterable(storedSuggestions -> storedSuggestions)
    .map(Selection::create) ))
    .doOnNext(selection -> Timber.e("Selection: " + selection)) // works
    .toList()
    .toObservable() // nothing works after this...
    .doOnNext(selections -> Timber.d("selections: " + selections))
    .map(SuggestionUiModel::create)
    .doOnNext(suggestionUiModel -> Timber.d("suggestionUiModel: " + suggestionUiModel))
    .subscribe();

Body:
These types of data sources from 3rd parties are usually infinite sources but toList() requires a finite source. I guess you wanted to process that collection of storedSuggestions and keep it together. You can achieve this via an inner transformation:

storedSuggestionDao
.getSuggestionsOrderByType() //Flowable
.doOnNext(storedSuggestions -> Timber.e("storedSuggestions: " + storedSuggestions)) //this work
// -------------------------------------
.flatMapSingle(storedSuggestions ->
    Flowable.fromIterable(storedSuggestions)
    .map(Selection::create)
    .doOnNext(selection -> Timber.e("Selection: " + selection))
    .toList()
)
// -------------------------------------
.doOnNext(selections -> Timber.d("selections: " + selections))
.map(SuggestionUiModel::create)
.doOnNext(suggestionUiModel -> Timber.d("suggestionUiModel: " + suggestionUiModel))
.subscribe();


问:
Fixed width buttons with Bootstrap
Does Bootstrap support fixed width buttons? Currently if I have 2 buttons, "Save" and "Download", the button size changes based on content.

Also what is the right way of extending Bootstrap?

答:
Just came upon the same need and was not satified with defining fixed width.

So did it with jquery:

    var max = Math.max ($("#share_cancel").width (), $("#share_commit").width ());
    $("#share_cancel").width (max);
    $("#share_commit").width (max); ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    <button type="button" class="btn btn-secondary" id="share_cancel">SHORT</button>
    <button type="button" class="btn btn-success" id="share_commit">LOOOOOOOOONG</button></code>```

Title: Fixed width buttons with Bootstrap

Body:
Just came upon the same need and was not satified with defining fixed width.

So did it with jquery:

    var max = Math.max ($("#share_cancel").width (), $("#share_commit").width ());
    $("#share_cancel").width (max);
    $("#share_commit").width (max);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    <button type="button" class="btn btn-secondary" id="share_cancel">SHORT</button>
    <button type="button" class="btn btn-success" id="share_commit">LOOOOOOOOONG</button>


问:
Filling jqplot charts with data from an Ajax call
I have a layout with 3 jqplot charts, and I need to fill these with data from an ajax call.

If I hard code the data into my variables, the charts render fine, but when I use the data returned from my ajax call, the charts do not render.

Why is this?

My full code that renders the jqplots is as follows:

```<code>var url = "ajax_loadplotdata.php";
var result;

$.ajaxSetup({ async: false });

$.ajax({
 cache: false,
 url: url,
 dataType: 'json',
 success: function(data) {
 result = data;
 },
});

var options = {
 height: 200, width: 300,
 axesDefaults: { labelRenderer: $.jqplot.CanvasAxisLabelRenderer },
 seriesDefaults: { rendererOptions: { smooth: true } },
 axes: { xaxis: { min:1, max:30, tickInterval:1, pad:0, tickOptions:{fontFamily:'Arial', fontSize:'10px'} }, yaxis: { tickOptions:{show:false} } }
};

var dayplot = result.daydata;
var weekplot = [2,2,2,2,4,4,4,6,6,6,8,8,8,4,2];
var monthplot = [2,2,2,2,4,4,4,6,6,6,8,8,8,4,2];

var plot1 = $.jqplot('graph_day', [dayplot], options);
var plot2 = $.jqplot('graph_week', [weekplot], options);
var plot3 = $.jqplot('graph_month', [monthplot], options);

plot1.replot({ resetAxes:false });
plot2.replot({ resetAxes:false });
plot3.replot({ resetAxes:false });
</code>```

With this code, the week and month plots show, but the day plot does not. I hard coded sample data into the week and month variables as a test.

The data returned from my ajax call is like this:

```<code>{"daydata":"[2.08E-8,2.08E-8,3.358E-7,3.258E-7,3.258E-7,3.308E-7,3.358E-7,3.408E-7,3.408E-7,1.808E-7,1.708E-7,3.158E-7,3.158E-7,3.158E-7,3.158E-7,3.158E-7,3.158E-7,3.158E-7,3.308E-7,1.108E-7,1.108E-7,1.108E-7,1.108E-7,1.158E-7]","weekdata":"[-2.304E-7,-2.304E-7,-2.304E-7,-2.304E-7,-2.304E-7,-2.304E-7,-2.304E-7]","monthdata":"[6.6E-7,2.55E-7,2.4E-7,4.7E-7,4.4E-7,5.8E-7,6.7E-7,6.3E-7,6.7E-7,7.75E-7,7.4E-7,7.5E-7,1.13E-6,7.2E-7,1.25E-6,1.42E-6,9.15E-7,2.2E-7,1.005E-6,2.06E-6,2.09E-6,1.59E-6,1.43E-6,1.19E-6,2.45E-6,2.49E-6,2.575E-6,2.755E-6,3.05E-6,2.84E-6]"}
</code>```

I cant understand why the plots show if I manually fill in the data, but not when I use the ajax variables.

答:
I cant explain why this works, but I found that if I split my function into two separate functions, then I can get this to work!

First function:

```<code>function ajaxCall(){

var url = "ajax_loadplotdata.php";
var result;

$.ajaxSetup({ async: false });

$.ajax({
 cache: false,
 url: url,
 dataType: 'json',
 success: function(data) {
 r = data;
 },
  complete: function(data) {
   drawPlot(r[0],r[1],r[2],r[3],r[4],r[5],r[6],r[7],r[8],r[9],r[10],r[11],r[12],r[13],r[14],r[15],r[16],r[17],r[18],r[19],r[20]);
  }
});

}
</code>```

Second function, called from first:

```<code>function drawPlot(r0,r1,r2,r3,r4,r5,r6,r7,r8,r9,r10,r11,r12,r13,r14,r15,r16,r17,r18,r19,r20){

var options = {
 height: 200, width: 300,
 axesDefaults: { labelRenderer: $.jqplot.CanvasAxisLabelRenderer },
 seriesDefaults: { rendererOptions: { smooth: true } },
 axes: { xaxis: { min:1, max:30, tickInterval:1, pad:0, tickOptions:{fontFamily:'Arial', fontSize:'10px'} }, yaxis: { tickOptions:{show:false} } }
};

var plot1 = $.jqplot('graph_day', [r0,r1,r2,r3,r4,r5,r6,r7,r8,r9,r10,r11,r12,r13,r14,r15,r16,r17,r18,r19,r20], options);
plot1.replot({ resetAxes:false });

}
</code>```

Body:
I have a layout with 3 jqplot charts, and I need to fill these with data from an ajax call.

If I hard code the data into my variables, the charts render fine, but when I use the data returned from my ajax call, the charts do not render.

Why is this?

My full code that renders the jqplots is as follows:

var url = "ajax_loadplotdata.php";
var result;

$.ajaxSetup({ async: false });

$.ajax({
 cache: false,
 url: url,
 dataType: 'json',
 success: function(data) {
 result = data;
 },
});

var options = {
 height: 200, width: 300,
 axesDefaults: { labelRenderer: $.jqplot.CanvasAxisLabelRenderer },
 seriesDefaults: { rendererOptions: { smooth: true } },
 axes: { xaxis: { min:1, max:30, tickInterval:1, pad:0, tickOptions:{fontFamily:'Arial', fontSize:'10px'} }, yaxis: { tickOptions:{show:false} } }
};

var dayplot = result.daydata;
var weekplot = [2,2,2,2,4,4,4,6,6,6,8,8,8,4,2];
var monthplot = [2,2,2,2,4,4,4,6,6,6,8,8,8,4,2];

var plot1 = $.jqplot('graph_day', [dayplot], options);
var plot2 = $.jqplot('graph_week', [weekplot], options);
var plot3 = $.jqplot('graph_month', [monthplot], options);

plot1.replot({ resetAxes:false });
plot2.replot({ resetAxes:false });
plot3.replot({ resetAxes:false });

With this code, the week and month plots show, but the day plot does not. I hard coded sample data into the week and month variables as a test.

The data returned from my ajax call is like this:

{"daydata":"[2.08E-8,2.08E-8,3.358E-7,3.258E-7,3.258E-7,3.308E-7,3.358E-7,3.408E-7,3.408E-7,1.808E-7,1.708E-7,3.158E-7,3.158E-7,3.158E-7,3.158E-7,3.158E-7,3.158E-7,3.158E-7,3.308E-7,1.108E-7,1.108E-7,1.108E-7,1.108E-7,1.158E-7]","weekdata":"[-2.304E-7,-2.304E-7,-2.304E-7,-2.304E-7,-2.304E-7,-2.304E-7,-2.304E-7]","monthdata":"[6.6E-7,2.55E-7,2.4E-7,4.7E-7,4.4E-7,5.8E-7,6.7E-7,6.3E-7,6.7E-7,7.75E-7,7.4E-7,7.5E-7,1.13E-6,7.2E-7,1.25E-6,1.42E-6,9.15E-7,2.2E-7,1.005E-6,2.06E-6,2.09E-6,1.59E-6,1.43E-6,1.19E-6,2.45E-6,2.49E-6,2.575E-6,2.755E-6,3.05E-6,2.84E-6]"}

I cant understand why the plots show if I manually fill in the data, but not when I use the ajax variables.

Body:
I cant explain why this works, but I found that if I split my function into two separate functions, then I can get this to work!

First function:

function ajaxCall(){

var url = "ajax_loadplotdata.php";
var result;

$.ajaxSetup({ async: false });

$.ajax({
 cache: false,
 url: url,
 dataType: 'json',
 success: function(data) {
 r = data;
 },
  complete: function(data) {
   drawPlot(r[0],r[1],r[2],r[3],r[4],r[5],r[6],r[7],r[8],r[9],r[10],r[11],r[12],r[13],r[14],r[15],r[16],r[17],r[18],r[19],r[20]);
  }
});

}

Second function, called from first:

function drawPlot(r0,r1,r2,r3,r4,r5,r6,r7,r8,r9,r10,r11,r12,r13,r14,r15,r16,r17,r18,r19,r20){

var options = {
 height: 200, width: 300,
 axesDefaults: { labelRenderer: $.jqplot.CanvasAxisLabelRenderer },
 seriesDefaults: { rendererOptions: { smooth: true } },
 axes: { xaxis: { min:1, max:30, tickInterval:1, pad:0, tickOptions:{fontFamily:'Arial', fontSize:'10px'} }, yaxis: { tickOptions:{show:false} } }
};

var plot1 = $.jqplot('graph_day', [r0,r1,r2,r3,r4,r5,r6,r7,r8,r9,r10,r11,r12,r13,r14,r15,r16,r17,r18,r19,r20], options);
plot1.replot({ resetAxes:false });

}


问:
How to display image on full div in html css
I try to display the image on full div but it display only center of the div
 i am using the following code
my html code is

.all-stores .store-logo {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    border: 1px solid red
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="white-block all-stores">
 <div class="embed-responsive embed-responsive-4by3">
  <div class="store-logo">

    <img src="http://via.placeholder.com/350x350" class="img-responsive wp-post-image">

  </div>
 </div>
</div></code>```

thanks

答:
Add this css: https://jsfiddle.net/cq8v0rjr/

It sets the inline-block elements to 100% (which will fill its parent).

```<code>.store-logo > a, .store-logo > a > img {
    display: inline-block;
    width: 100%;
}
</code>```

Body:
I try to display the image on full div but it display only center of the div
 i am using the following code
my html code is

.all-stores .store-logo {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    border: 1px solid red
    }

thanks

Body:
Add this css: https://jsfiddle.net/cq8v0rjr/

It sets the inline-block elements to 100% (which will fill its parent).

.store-logo > a, .store-logo > a > img {
    display: inline-block;
    width: 100%;
}


答: linux commands are essentially programs. You can simply run them using Runtime.getRuntime().exec("crontab file.txt");

Title: execute linux command in java

Body:
i want to execute the command crontab file.txt in java.

What is the procedure...?


问:
label appears from the GoPro SDK dependency
I have a string resource for an application label:

```<code> <string name="app_name">My application</string>
</code>```

My AndroidManifest.xml is classical:

```<code><manifest.. >
 <application
        android:name="my.package"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:largeHeap="true"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        tools:replace="android:icon">
        <activity ...
</code>```

I have GoPro SDK as a dependency. And on some devices (HTC U Play) my application is signed not as "My application", but as "GoPro SDK".

I have figured out that GoPro SDK valuses are realy containing resource:

```<code><string name="app_name">GoPro SDK</string>
</code>```

GoPro SDK is an .arr archive.

How to fix it without renaming of the variable app_name?

答:
Try to add to application tag the following attribute:

```<code><application
    tools:replace="label, icon"/>
</code>```

also I found that some of activities may contain label without tools:replace="label"

```<code><activity android:label="@string/app_name" />
</code>```

Just remove label from activities or add tools:replace="label" attribute

Body:
I have a string resource for an application label:

 <string name="app_name">My application</string>

My AndroidManifest.xml is classical:

<manifest.. >
 <application
        android:name="my.package"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:largeHeap="true"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        tools:replace="android:icon">
        <activity ...

I have GoPro SDK as a dependency. And on some devices (HTC U Play) my application is signed not as "My application", but as "GoPro SDK".

I have figured out that GoPro SDK valuses are realy containing resource:

<string name="app_name">GoPro SDK</string>

GoPro SDK is an .arr archive.

How to fix it without renaming of the variable app_name?

Body:
Try to add to application tag the following attribute:

<application
    tools:replace="label, icon"/>

also I found that some of activities may contain label without tools:replace="label"

<activity android:label="@string/app_name" />

Just remove label from activities or add tools:replace="label" attribute


问:
Simply return a value from another component
Wondering if you guys can help. I am trying to create a generic component which when called, will return a value.

The code currently stands as follows:

```<code>import React, {Component} from 'react'

class Clients extends Component {
   render () {
      var userEnum = {
      SMALL: 1,
      MEDIUM: 2,
      LARGE: 3,
      properties: {
        1: {name: "Admin", value: 1},
        2: {name: "Manager", value: 2},
        3: {name: "Standard", value: 3}
      }
    };

    const clientName = (value) => {
      return userEnum.properties[value].name
    }
    return null
  }
}

export default Clients
</code>```

and in another component, I try calling the clientName function (done an import too).

```<code>import ClientHelper from '../../helpers/clients'

    ...
      const test =  ClientHelper.clientName(2)
      console.log(test)
</code>```

I should expect a return value of 'Manager' but I get

TypeError: WEBPACK_IMPORTED_MODULE_9__helpers_clients.a.clientName
  is not a function

答:
the function clientName is not a property of your class, but a local function inside the render function and therefore not accessible from the outside.

To solve this, you have to make clientName as well as your userEnum properties of the Clients object, for example in the constructor:

import React, {Component} from 'react'

class Clients extends Component {
  constructor(props){
    super(props);
    this.userEnum = {
      SMALL: 1,
      MEDIUM: 2,
      LARGE: 3,
      properties: {
        1: {name: "Admin", value: 1},
        2: {name: "Manager", value: 2},
        3: {name: "Standard", value: 3}
      }
    };
  }

  function clientName (value) {
    return this.userEnum.properties[value].name
  }

  function render () {
    return null
  }
}

export default Clients```

Body:
Wondering if you guys can help. I am trying to create a generic component which when called, will return a value.

The code currently stands as follows:

import React, {Component} from 'react'

class Clients extends Component {
   render () {
      var userEnum = {
      SMALL: 1,
      MEDIUM: 2,
      LARGE: 3,
      properties: {
        1: {name: "Admin", value: 1},
        2: {name: "Manager", value: 2},
        3: {name: "Standard", value: 3}
      }
    };

    const clientName = (value) => {
      return userEnum.properties[value].name
    }
    return null
  }
}

export default Clients

and in another component, I try calling the clientName function (done an import too).

import ClientHelper from '../../helpers/clients'

    ...
      const test =  ClientHelper.clientName(2)
      console.log(test)

I should expect a return value of 'Manager' but I get

TypeError: WEBPACK_IMPORTED_MODULE_9__helpers_clients.a.clientName
  is not a function


问:
Regex multiple exclusions
I would like to make a regex that matches groups like abbc, where each letter is a different character.

it should contain three capture groups

all the capture groups should contain different characters

the second one should be matched exactly twice

Example:

bank (not matched, because the second and the third character is not the same)

rook (matched)

book (matched)

poop (not matched, because the first and the last character is the same)

So far I have been trying something like this:

```<code>(.)(.(?!\1))\2(.(?!\1)(?!\2))
</code>```

This however matches poop too. How do I correct this?

答:
Your positioning of the lookaheads is a bit off, you can do it like

```<code>(.)(?!\1)(.)\2(?!\1|\2)(.)
</code>```

See https://regex101.com/r/heBJar/1

You might need to apply anchors or word boundaries as needed. You should also consider using [a-z] or [[:alpha:]] or similar instead of the ..

Title: Regex multiple exclusions

Body:
I would like to make a regex that matches groups like abbc, where each letter is a different character.

it should contain three capture groups

all the capture groups should contain different characters

the second one should be matched exactly twice

Example:

bank (not matched, because the second and the third character is not the same)

rook (matched)

book (matched)

poop (not matched, because the first and the last character is the same)

So far I have been trying something like this:

(.)(.(?!\1))\2(.(?!\1)(?!\2))

This however matches poop too. How do I correct this?

Body:
Your positioning of the lookaheads is a bit off, you can do it like

(.)(?!\1)(.)\2(?!\1|\2)(.)

See https://regex101.com/r/heBJar/1

You might need to apply anchors or word boundaries as needed. You should also consider using [a-z] or [[:alpha:]] or similar instead of the ..


问:
Python, Selenium + stale element reference
I'm trying to go on a webpage,
save a set of links of the page I would like to click on, and then
I would like to click on each of the link if a for loop (going back and forth on the page. Here is the code:

```<code>from selenium import webdriver

driver = webdriver.Chrome(executable_path='/Applications/chromedriver')
driver.get("webpage link") #insert link to webpage
list_links = driver.find_elements_by_xpath("//a[contains(@href,'activities')]")

for link in list_links:
    print(link)
    link.click()
    driver.goback()
    driver.implicitly_wait(10) # seconds
driver.quit()
</code>```

However, the first time I go back to the homepage I get the error message:

```<code>StaleElementReferenceException: stale element reference: element is not attached to the page document.
</code>```

Can anyone help me to understand why? Suggest a solution?
Thank you. much appreciated.

答: Its simple, you trying to save the elements of an html(links) which cannot be referenced anymore by the code(the loop logic), thats why it throws this error. Most of all those are selenium objects you trying to save which you should not do. It should be that you save the exact value of the link in an array and then loop them.</p>

Body:
I'm trying to go on a webpage,
save a set of links of the page I would like to click on, and then
I would like to click on each of the link if a for loop (going back and forth on the page. Here is the code:

from selenium import webdriver

driver = webdriver.Chrome(executable_path='/Applications/chromedriver')
driver.get("webpage link") #insert link to webpage
list_links = driver.find_elements_by_xpath("//a[contains(@href,'activities')]")

for link in list_links:
    print(link)
    link.click()
    driver.goback()
    driver.implicitly_wait(10) # seconds
driver.quit()

However, the first time I go back to the homepage I get the error message:

StaleElementReferenceException: stale element reference: element is not attached to the page document.

Can anyone help me to understand why? Suggest a solution?
Thank you. much appreciated.


答:
You are declaring the function clientName inside the render method of the class Clients. This function is only accessible inside it's scope, the render method.
To access the function like you would, by calling the class Clients static method clientName, you should write it like this:

```<code>import React, { Component } from 'react'

class Clients extends Component {
    static userEnum = {
        SMALL: 1,
        MEDIUM: 2,
        LARGE: 3,
        properties: {
            1: { name: "Admin", value: 1 },
            2: { name: "Manager", value: 2 },
            3: { name: "Standard", value: 3 }
        }
    };

    static clientName(value) {
        return Clients.userEnum.properties[value].name;
    }
    render() {

        return null;
    }
}

export default Clients
</code>```

If you do not intend to render anything with this class, you do not need react, and can simply create a utility/static class like below:

```<code>export default class Clients {
    static userEnum = {
        SMALL: 1,
        MEDIUM: 2,
        LARGE: 3,
        properties: {
            1: { name: "Admin", value: 1 },
            2: { name: "Manager", value: 2 },
            3: { name: "Standard", value: 3 }
        }
    };

    static clientName(value) {
        return Clients.userEnum.properties[value].name;
    }
}
</code>```

Title: Simply return a value from another component

Body:
You are declaring the function clientName inside the render method of the class Clients. This function is only accessible inside it's scope, the render method.
To access the function like you would, by calling the class Clients static method clientName, you should write it like this:

import React, { Component } from 'react'

class Clients extends Component {
    static userEnum = {
        SMALL: 1,
        MEDIUM: 2,
        LARGE: 3,
        properties: {
            1: { name: "Admin", value: 1 },
            2: { name: "Manager", value: 2 },
            3: { name: "Standard", value: 3 }
        }
    };

    static clientName(value) {
        return Clients.userEnum.properties[value].name;
    }
    render() {

        return null;
    }
}

export default Clients

If you do not intend to render anything with this class, you do not need react, and can simply create a utility/static class like below:

export default class Clients {
    static userEnum = {
        SMALL: 1,
        MEDIUM: 2,
        LARGE: 3,
        properties: {
            1: { name: "Admin", value: 1 },
            2: { name: "Manager", value: 2 },
            3: { name: "Standard", value: 3 }
        }
    };

    static clientName(value) {
        return Clients.userEnum.properties[value].name;
    }
}


问:
Draw a filled triangle in DrawingContext
This is a follow up from this question.

Question:

I am trying to draw a filled triangle using DrawingContext, which is rendered on a DrawingVisual

Currently, I have managed to draw the outline of a triangle using the following C# code:

```<code>private DrawingVisual CreateTriangle()
  {
     DrawingVisual triangle = new DrawingVisual();
     using ( DrawingContext dc = triangle.RenderOpen() )
     {
         Pen drawingPen = new Pen(Brushes.Black,3);
         dc.DrawLine(drawingPen, new Point(0, 50), new Point(50, 0));
         dc.DrawLine(drawingPen, new Point(50, 0), new Point(50, 100));
         dc.DrawLine(drawingPen, new Point(50, 100), new Point(0, 50));

     }
     return triangle;
  }
</code>```

I get this:

How do I draw a triangle that, in addition to th border I have drawn also has a red fill?

答:
Use dc.DrawGeometry to create filled-in shapes.

Edit: This:

```<code>private DrawingVisual CreateTriangle()
{
    var triangle = new DrawingVisual();
    using (DrawingContext dc = triangle.RenderOpen())
    {
       var start = new Point(0, 50);

       var segments = new []
       {
          new LineSegment(new Point(50,0), true),
          new LineSegment(new Point(50, 100), true)
       };

       var figure = new PathFigure(start, segments, true);
       var geo = new PathGeometry(new [] { figure });
       dc.DrawGeometry(Brushes.Red, null, geo);

       var drawingPen = new Pen(Brushes.Black, 3);
       dc.DrawLine(drawingPen, new Point(0, 50), new Point(50, 0));
       dc.DrawLine(drawingPen, new Point(50, 0), new Point(50, 100));
       dc.DrawLine(drawingPen, new Point(50, 100), new Point(0, 50));
    }

    return triangle;
}
</code>```

On a side note, if you have to create the PathGeometry anyway and you use DrawGeometry you might as well stroke it too, then you don't need your original line drawings.

```<code>dc.DrawGeometry(Brushes.Red, new Pen(Brushes.Black, 3), geo);
</code>```

Body:
This is a follow up from this question.

Question:

I am trying to draw a filled triangle using DrawingContext, which is rendered on a DrawingVisual

Currently, I have managed to draw the outline of a triangle using the following C# code:

private DrawingVisual CreateTriangle()
  {
     DrawingVisual triangle = new DrawingVisual();
     using ( DrawingContext dc = triangle.RenderOpen() )
     {
         Pen drawingPen = new Pen(Brushes.Black,3);
         dc.DrawLine(drawingPen, new Point(0, 50), new Point(50, 0));
         dc.DrawLine(drawingPen, new Point(50, 0), new Point(50, 100));
         dc.DrawLine(drawingPen, new Point(50, 100), new Point(0, 50));

     }
     return triangle;
  }

I get this:

How do I draw a triangle that, in addition to th border I have drawn also has a red fill?

Body:
Use dc.DrawGeometry to create filled-in shapes.

Edit: This:

private DrawingVisual CreateTriangle()
{
    var triangle = new DrawingVisual();
    using (DrawingContext dc = triangle.RenderOpen())
    {
       var start = new Point(0, 50);

       var segments = new []
       {
          new LineSegment(new Point(50,0), true),
          new LineSegment(new Point(50, 100), true)
       };

       var figure = new PathFigure(start, segments, true);
       var geo = new PathGeometry(new [] { figure });
       dc.DrawGeometry(Brushes.Red, null, geo);

       var drawingPen = new Pen(Brushes.Black, 3);
       dc.DrawLine(drawingPen, new Point(0, 50), new Point(50, 0));
       dc.DrawLine(drawingPen, new Point(50, 0), new Point(50, 100));
       dc.DrawLine(drawingPen, new Point(50, 100), new Point(0, 50));
    }

    return triangle;
}

On a side note, if you have to create the PathGeometry anyway and you use DrawGeometry you might as well stroke it too, then you don't need your original line drawings.

dc.DrawGeometry(Brushes.Red, new Pen(Brushes.Black, 3), geo);


问:
python update a list of dictionaries using another list of the same length
I am trying to update a list a of dictionaries using another list b of the same length that each dict should add a key which corresponds to a value in b at the same position,

```<code>for x in range(len(a)):
    a[x]['val'] = b[x]
</code>```

I am wondering is there a more efficient/concise way to do it

答:
```<code>#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7}
dict2 = {'Sex': 'female', 'Age': 17 }

dict.update(dict2)
</code>```

check here

Body:
I am trying to update a list a of dictionaries using another list b of the same length that each dict should add a key which corresponds to a value in b at the same position,

for x in range(len(a)):
    a[x]['val'] = b[x]

I am wondering is there a more efficient/concise way to do it

Body:
#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7}
dict2 = {'Sex': 'female', 'Age': 17 }

dict.update(dict2)

check here


答:
Your list_links works only on page where it was defined. After you made first click on link DOM re-created and references to elements of list_links becomes invalid. You can apply below solution:

```<code>driver.implicitly_wait(10) # seconds
list_links = [link.get_attribute('href') for link in driver.find_elements_by_xpath("//a[contains(@href,'activities')]")]

for link in list_links:
    print(link)
    driver.get(link)
    driver.goback()
driver.quit()
</code>```

P.S. I assume that goback() is your custom method that was defined already as there is no such method in Selenium built-ins, but just back()

P.P.S. Note that you can call driver.implicitly_wait(10) only once in your code and it will be applicable for all next find_element...() calls

Title: Python, Selenium + stale element reference

Body:
Your list_links works only on page where it was defined. After you made first click on link DOM re-created and references to elements of list_links becomes invalid. You can apply below solution:

driver.implicitly_wait(10) # seconds
list_links = [link.get_attribute('href') for link in driver.find_elements_by_xpath("//a[contains(@href,'activities')]")]

for link in list_links:
    print(link)
    driver.get(link)
    driver.goback()
driver.quit()

P.S. I assume that goback() is your custom method that was defined already as there is no such method in Selenium built-ins, but just back()

P.P.S. Note that you can call driver.implicitly_wait(10) only once in your code and it will be applicable for all next find_element...() calls


问:
How to draw a circle with text in the middle?
I found this example on stackoverflow:

Draw Circle using css alone

Which is great.  But I'd like to know how to modify that example so that I can include text in the middle of the circle?

I also found this:  Vertically and horizontally centering text in circle in CSS (like iphone notification badge)

but for some reason, its not working for me.  When I create the following test code:

```<code><div class="badge">1</div>
</code>```

instead of a circle, I get a oval shape.
I'm trying to play around with the code to see how I can get it to work.

答:
Got this from YouTube page which has a really simple set up. Absolutely maintainable and reusable.

.circle {
    position: absolute;
    top: 4px;
    color: white;
    background-color: red;
    width: 18px;
    height: 18px;
    border-radius: 50%;
    line-height: 18px;
    font-size: 10px;
    text-align: center;
    cursor: pointer;
    z-index: 999;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="circle">2</div></code>```

Body:
I found this example on stackoverflow:

Draw Circle using css alone

Which is great.  But I'd like to know how to modify that example so that I can include text in the middle of the circle?

I also found this:  Vertically and horizontally centering text in circle in CSS (like iphone notification badge)

but for some reason, its not working for me.  When I create the following test code:

1

instead of a circle, I get a oval shape.
I'm trying to play around with the code to see how I can get it to work.

Body:
Got this from YouTube page which has a really simple set up. Absolutely maintainable and reusable.

.circle {
    position: absolute;
    top: 4px;
    color: white;
    background-color: red;
    width: 18px;
    height: 18px;
    border-radius: 50%;
    line-height: 18px;
    font-size: 10px;
    text-align: center;
    cursor: pointer;
    z-index: 999;
}

<div class="circle">2</div>


问:
Subtract numbers from the results of an SQL query
So what the title says.

My results look like these [100, 200, 300], i have multiple of these, around 2000.

From each one i want to subtract [50, 50, 50], so that the results would be something like [50, 150, 250] and so on and so on.

I guess it is easy for most people, but i cannot find any example and i could not do it myself. how can i subtract a specific number from a query.

My sql uses ST_AsGeoJSON, something like:

```<code>SELECT ST_AsGeoJSON(ST_Transform(geom, 32633)) FROM "database";
</code>```

being read via:

```<code>using (var reader = command.ExecuteReader()) {
    while (reader.Read()) {
      // ...
      resultTable[col].Add(reader[col].ToString());
    }
}
</code>```

答:
Since we can not use the * for this query

First, you identify the column from which you want to subtract and then fire query

```<code>select (Col1-50),(Col2-50),(Col3-50),(col4 -non integer column as it is)
from  TableName
where condition;
</code>```

Body:
So what the title says.

My results look like these [100, 200, 300], i have multiple of these, around 2000.

From each one i want to subtract [50, 50, 50], so that the results would be something like [50, 150, 250] and so on and so on.

I guess it is easy for most people, but i cannot find any example and i could not do it myself. how can i subtract a specific number from a query.

My sql uses ST_AsGeoJSON, something like:

SELECT ST_AsGeoJSON(ST_Transform(geom, 32633)) FROM "database";

being read via:

using (var reader = command.ExecuteReader()) {
    while (reader.Read()) {
      // ...
      resultTable[col].Add(reader[col].ToString());
    }
}

Body:
Since we can not use the * for this query

First, you identify the column from which you want to subtract and then fire query

select (Col1-50),(Col2-50),(Col3-50),(col4 -non integer column as it is)
from  TableName
where condition;


问:
Basic Auto Layout - nested width and dynamic height
Simple goal, but it demonstrates situations where Auto Layout gives me a headache. I want to have a stack view with a width of 256pt and a dynamic height based on layout (I shouldn't have to manually specify the height).
Inside it should be an image view sized 64pt x 64pt, which should also be centered horizontally as well as constrained 8pt from the superview's top. Note that the image view isn't the only child, hence why the stack view's height must be sized dynamically.

Auto Layout now tells me there's a conflict between the 256pt width constraint of the stack view and the 64pt width constraint of the image, as well as some mysterious "leading = Image.leading" and "trailing = Image.trailing" conflict which I can't even delete nor find.

Am I missing out something here regarding Auto Layout? I expect all logic to be contained in the interface builder, so no code should be required.

Running Xcode 9.1

Layout image

答:
There is nothing to confuse. iOS clearly telling you the issue.

StackViews take size based on the size of child components (this is called implicit size) unless its been overriden manually as in your case which is 256pt.

Because stackView is just a container for multiple childViews stacked either horizontally or vertically, now because you have added only one imageView to it, it adds the leading and trailing constraint to it which makes absolute sense because you added a single view to the stack of view's , now what should stackView do? stretch childView (in your case imageView) to its own size.

But then you did not allow it because you added width constraint to imageView now when it tries to increase the imageView's width imageView's constraint wont allow it.

Hence it is complaining that there are too many conflicting constraints. Thats all :)

some mysterious "leading = Image.leading" and "trailing =
  Image.trailing" conflict which I can't even delete nor find.

You cant delete them because, imageView is the only view inside stackView. Because there is only one child view to stack, stackView will start from left side (leading) to right side (trailing). Because now stackView has its own width it tries to change the width of imageView to reflect the same! But images width constraint prevents it from happening.

What are you trying to achieve with imageView added to stackView. If there is only one view in stackView, adding stackView does not make any sense. Reconsider what you are doing.

Finally, when you have only one childView in stack view, adding horizontal center does not make any sense (no matter vertical/horizontal stackView).


问:
MS ACCESS VBA, working days function incl. holiday when faling on weekend
When deploying MSDN function for calculating working days, beside a problem with date formatting I found an issue with Holiday count.

Calculation is correct, but only if Holiday is on working day. If it is on a saturday or sunday, it also substract it and produce a false result.
illustration of a false reading

A Function for Workdays:

```<code>Public Function Workdays(ByRef startDate As Date, ByRef endDate As Date, Optional ByRef strHolidays As String = "Holidays") As Integer
On Error GoTo Workdays_Error
Dim nWeekdays, nHolidays As Integer
Dim strWhere As String

startDate = DateValue(startDate)
endDate = DateValue(endDate)
nWeekdays = Weekdays(startDate, endDate)

If nWeekdays = -1 Then
    Workdays = -1
    GoTo Workdays_Exit
End If

strWhere = "[Holiday] >= #" & Format(startDate, "yyyy\/mm\/dd") & "# AND [Holiday] <= #" & Format(endDate, "yyyy\/mm\/dd") & "#"
nHolidays = DCount(Expr:="[Holiday]", Domain:=strHolidays, Criteria:=strWhere)
Workdays = nWeekdays - nHolidays

Workdays_Exit:
    Exit Function
    Resume Workdays_Exit

End Function
</code>```

And here is a function for calculating weekdays:

```<code>Public Function Weekdays(ByRef startDate As Date, ByRef endDate As Date) As Integer
' Returns the number of weekdays in the period from startDate
' to endDate inclusive. Returns -1 if an error occurs.

On Error GoTo Weekdays_Error
Const ncNumberOfWeekendDays As Integer = 2 'The number of weekend days per week.
Dim varDays As Variant                  'The number of days inclusive.
Dim varWeekendDays As Variant     'The number of weekend days.
Dim dtmX As Date                          'Temporary storage for datetime.

' If the end date is earlier, swap the dates.
If endDate < startDate Then
    dtmX = startDate
    startDate = endDate
    endDate = dtmX
End If

' Calculate the number of days inclusive (+ 1 is to add back startDate).
varDays = DateDiff(Interval:="d", date1:=startDate, date2:=endDate) + 1

' Calculate the number of weekend days.
varWeekendDays = (DateDiff(Interval:="ww", date1:=startDate, date2:=endDate) _
    * ncNumberOfWeekendDays) + IIf(DatePart(Interval:="w", _
    Date:=startDate) = vbSunday, 1, 0) + IIf(DatePart(Interval:="w", Date:=endDate) = vbSaturday, 1, 0)

' Calculate the number of weekdays.
Weekdays = (varDays - varWeekendDays)

Weekdays_Exit:
    Exit Function

Weekdays_Error:
    Weekdays = -1
    MsgBox "Error " & Err.Number & ": " & Err.Description, vbCritical, "Weekdays"
    Resume Weekdays_Exit
</code>```

Please advise how to ignore holiday if holiday = 1 or holiday = 7.
Plus, in extended period of time, there could be more than one holidays, falling or not on weekend.

答:
You can use the function below to get the number of working days (excluding public holidays) between two dates.

It requires a table named tbHolidays with a single field named _Date which holds the public holidays.

```<code>Public Function WorkingDaysInDateRange(ByVal DateFrom As Date, _
                                       ByVal DateTo As Date, _
                                       Optional ByVal includeStartDate As Long = 0) As Long
    On Error GoTo ErrorTrap

    'Calculate the number of days
    Dim lngTotalDays As Long
        lngTotalDays = DateDiff("y", DateFrom, DateTo) + includeStartDate

    'Calculate the number of weekend days.
    Dim lngWeekendDays As Long
        lngWeekendDays = (DateDiff("ww", DateFrom, DateTo) * 2) + _
                          IIf(DatePart("w", DateFrom) = vbSunday, 1, 0) + _
                          IIf(DatePart("w", DateTo) = vbSaturday, 1, 0)

    'Get Non working days count from tbHolidays excluding weekends
    Dim lngHolidays As Long
        lngHolidays = DCount("[_Date]", "tbHolidays", _
                             StringFormat("[_Date] Between #{0}# AND #{1}# AND Weekday([_Date]) Not In ({2}, {3})", Format(DateFrom, "mm/dd/yyyy"), _
                                                                                Format(DateTo, "mm/dd/yyyy"), _
                                                                                vbSaturday, vbSunday))
    Dim lngWrkDays As Long
        lngWrkDays = lngTotalDays - (lngWeekendDays + lngHolidays)

    'Return
    WorkingDaysInDateRange = lngWrkDays

Leave:
    On Error GoTo 0
    Exit Function

ErrorTrap:
    MsgBox Err.Description, vbCritical
    Resume Leave
End Function
</code>```

The helper StringFormat function:

```<code>Public Function StringFormat(ByVal Item As String, ParamArray args() As Variant) As String

    Dim idx As Long
    For idx = LBound(args) To UBound(args)
        Item = Replace(Item, "{" & idx & "}", args(idx))
    Next idx

    StringFormat = Item
End Function
</code>```

Body:
When deploying MSDN function for calculating working days, beside a problem with date formatting I found an issue with Holiday count.

Calculation is correct, but only if Holiday is on working day. If it is on a saturday or sunday, it also substract it and produce a false result.
illustration of a false reading

A Function for Workdays:

Public Function Workdays(ByRef startDate As Date, ByRef endDate As Date, Optional ByRef strHolidays As String = "Holidays") As Integer
On Error GoTo Workdays_Error
Dim nWeekdays, nHolidays As Integer
Dim strWhere As String

startDate = DateValue(startDate)
endDate = DateValue(endDate)
nWeekdays = Weekdays(startDate, endDate)

If nWeekdays = -1 Then
    Workdays = -1
    GoTo Workdays_Exit
End If

strWhere = "[Holiday] >= #" & Format(startDate, "yyyy\/mm\/dd") & "# AND [Holiday] <= #" & Format(endDate, "yyyy\/mm\/dd") & "#"
nHolidays = DCount(Expr:="[Holiday]", Domain:=strHolidays, Criteria:=strWhere)
Workdays = nWeekdays - nHolidays

Workdays_Exit:
    Exit Function
    Resume Workdays_Exit

End Function

And here is a function for calculating weekdays:

Public Function Weekdays(ByRef startDate As Date, ByRef endDate As Date) As Integer
' Returns the number of weekdays in the period from startDate
' to endDate inclusive. Returns -1 if an error occurs.

On Error GoTo Weekdays_Error
Const ncNumberOfWeekendDays As Integer = 2 'The number of weekend days per week.
Dim varDays As Variant                  'The number of days inclusive.
Dim varWeekendDays As Variant     'The number of weekend days.
Dim dtmX As Date                          'Temporary storage for datetime.

' If the end date is earlier, swap the dates.
If endDate < startDate Then
    dtmX = startDate
    startDate = endDate
    endDate = dtmX
End If

' Calculate the number of days inclusive (+ 1 is to add back startDate).
varDays = DateDiff(Interval:="d", date1:=startDate, date2:=endDate) + 1

' Calculate the number of weekend days.
varWeekendDays = (DateDiff(Interval:="ww", date1:=startDate, date2:=endDate) _
    * ncNumberOfWeekendDays) + IIf(DatePart(Interval:="w", _
    Date:=startDate) = vbSunday, 1, 0) + IIf(DatePart(Interval:="w", Date:=endDate) = vbSaturday, 1, 0)

' Calculate the number of weekdays.
Weekdays = (varDays - varWeekendDays)

Weekdays_Exit:
    Exit Function

Weekdays_Error:
    Weekdays = -1
    MsgBox "Error " & Err.Number & ": " & Err.Description, vbCritical, "Weekdays"
    Resume Weekdays_Exit

Please advise how to ignore holiday if holiday = 1 or holiday = 7.
Plus, in extended period of time, there could be more than one holidays, falling or not on weekend.

Body:
You can use the function below to get the number of working days (excluding public holidays) between two dates.

It requires a table named tbHolidays with a single field named _Date which holds the public holidays.

Public Function WorkingDaysInDateRange(ByVal DateFrom As Date, _
                                       ByVal DateTo As Date, _
                                       Optional ByVal includeStartDate As Long = 0) As Long
    On Error GoTo ErrorTrap

    'Calculate the number of days
    Dim lngTotalDays As Long
        lngTotalDays = DateDiff("y", DateFrom, DateTo) + includeStartDate

    'Calculate the number of weekend days.
    Dim lngWeekendDays As Long
        lngWeekendDays = (DateDiff("ww", DateFrom, DateTo) * 2) + _
                          IIf(DatePart("w", DateFrom) = vbSunday, 1, 0) + _
                          IIf(DatePart("w", DateTo) = vbSaturday, 1, 0)

    'Get Non working days count from tbHolidays excluding weekends
    Dim lngHolidays As Long
        lngHolidays = DCount("[_Date]", "tbHolidays", _
                             StringFormat("[_Date] Between #{0}# AND #{1}# AND Weekday([_Date]) Not In ({2}, {3})", Format(DateFrom, "mm/dd/yyyy"), _
                                                                                Format(DateTo, "mm/dd/yyyy"), _
                                                                                vbSaturday, vbSunday))
    Dim lngWrkDays As Long
        lngWrkDays = lngTotalDays - (lngWeekendDays + lngHolidays)

    'Return
    WorkingDaysInDateRange = lngWrkDays

Leave:
    On Error GoTo 0
    Exit Function

ErrorTrap:
    MsgBox Err.Description, vbCritical
    Resume Leave
End Function

The helper StringFormat function:

Public Function StringFormat(ByVal Item As String, ParamArray args() As Variant) As String

    Dim idx As Long
    For idx = LBound(args) To UBound(args)
        Item = Replace(Item, "{" & idx & "}", args(idx))
    Next idx

    StringFormat = Item
End Function


问:
MySQL BETWEEN query w/ BETWEEN ? AND?
Can anyone guide me to or provide how the dual question marks work in a BETWEEN comparison.. I can't get it to work and I can't locate or search these data on the MySQL site and Google - bunches of random results.</p>

答:
Your question is not clear for me, but it seems what you want is know what the interrogation marks are for.

It seems that the interrogation marks are placeholders. They are replaced by constants (be it integers or sql-escaped strings) when querying, with a vector of values.

Title: MySQL BETWEEN query w/ BETWEEN ? AND?


问:
Extract top features by frequency per document from a dtm in R
I have a dtm and want to extract the top 5 terms by frequency for each document from the document term matrix.

I have a dtm built using the tm package

```<code>  Terms
Docs aaaa aac abrt abused accept accepted
1 0 0 0 0 0 0
2 0 0 0 0 0 0
3 0 0 0 0 0 0
4 0 0 0 0 0 0
5 0 0 0 0 0 0
6 0 0 0 0 0 0
</code>```

required output should be of the form:

```<code>Id
1   Term1 Term2 Term3 Term4 Term5
2   Term1 Term2 Term3 Term4 Term5
and so on for all the documents.
</code>```

I have tried all the solutions available from stackoverflow ans other sources
like Make dataframe of top N frequent terms for multiple corpora using tm package in R (converted to tdm and tried to bring to the output form but did not work)and others but noting seem to work.

答:
Using Quanteda:

```<code>library(quanteda)
txt <- c("hello world world fizz", "foo bar bar buzz")
dfm <- dfm(txt)
topfeatures(dfm, n = 2, groups = seq_len(ndoc(dfm)))
# $`1`
# world hello
# 2     1
#
# $`2`
# bar foo
# 2   1
</code>```

You can also convert between DocumentTermMatrix and dfm.

Or using the classical tm:

```<code>library(tm)
packageVersion("tm")
# [1] ‘0.7.1’
txt <- c(doc1="hello world world", doc2="foo bar bar fizz buzz")
dtm <- DocumentTermMatrix(Corpus(VectorSource(txt)))
n <- 5
(top <- findMostFreqTerms(dtm, n = n))
# $doc1
# world hello
# 2     1
#
# $doc2
# bar buzz fizz  foo
# 2    1    1    1
do.call(rbind, lapply(top, function(x) { x <- names(x);length(x)<-n;x }))
# [,1]    [,2]    [,3]   [,4]  [,5]
# doc1 "world" "hello" NA     NA    NA
# doc2 "bar"   "buzz"  "fizz" "foo" NA
</code>```

findMostFreqTerms is available since tm version 0.7-1.

Body:
I have a dtm and want to extract the top 5 terms by frequency for each document from the document term matrix.

I have a dtm built using the tm package

  Terms
Docs aaaa aac abrt abused accept accepted
1 0 0 0 0 0 0
2 0 0 0 0 0 0
3 0 0 0 0 0 0
4 0 0 0 0 0 0
5 0 0 0 0 0 0
6 0 0 0 0 0 0

required output should be of the form:

Id
1   Term1 Term2 Term3 Term4 Term5
2   Term1 Term2 Term3 Term4 Term5
and so on for all the documents.

I have tried all the solutions available from stackoverflow ans other sources
like Make dataframe of top N frequent terms for multiple corpora using tm package in R (converted to tdm and tried to bring to the output form but did not work)and others but noting seem to work.

Body:
Using Quanteda:

library(quanteda)
txt <- c("hello world world fizz", "foo bar bar buzz")
dfm <- dfm(txt)
topfeatures(dfm, n = 2, groups = seq_len(ndoc(dfm)))
# $`1`
# world hello
# 2     1
#
# $`2`
# bar foo
# 2   1

You can also convert between DocumentTermMatrix and dfm.

Or using the classical tm:

library(tm)
packageVersion("tm")
# [1] ‘0.7.1’
txt <- c(doc1="hello world world", doc2="foo bar bar fizz buzz")
dtm <- DocumentTermMatrix(Corpus(VectorSource(txt)))
n <- 5
(top <- findMostFreqTerms(dtm, n = n))
# $doc1
# world hello
# 2     1
#
# $doc2
# bar buzz fizz  foo
# 2    1    1    1
do.call(rbind, lapply(top, function(x) { x <- names(x);length(x)<-n;x }))
# [,1]    [,2]    [,3]   [,4]  [,5]
# doc1 "world" "hello" NA     NA    NA
# doc2 "bar"   "buzz"  "fizz" "foo" NA

findMostFreqTerms is available since tm version 0.7-1.


问:
How to automatically open show / hide javascript tab and re-hide on second click
I have some tabs which show hidden information when clicked. But as they are now, they will open but only close when a new tab is clicked. If possible could I get help with these two issues:

1- I want to make the tab close again when you click it a second time.

2- I have links set up to open the page where each section starts. Is there anyway I can make the tab open automatically when that link is clicked?

I appreciate the help.

Edited to show the full code I have now:

$('.drop a').click(function() {
  var $content = $(this).parent().next().toggle();

  //HIDE THIS LINE IF YOU DO NOT WANT TO HIDE OTHER TABS ON CLICK
 $('.droptab').not($content).hide();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.droptab {
  display: none
}</code>```

post_title; ?>">

<?php echo $child->post_title; ?>

<?php echo apply_filters('the_content', $child->post_content); ?>

                ID ); ?>" class="button left">Get More Info

```

答:
Use toggle instead of hide show.

The toggle() method toggles between hide() and show() for the selected elements.

Hide this line "$('.droptab').not($content).hide();" IF YOU DO NOT WANT TO HIDE OTHER TABS ON CLICK

$('.drop a').click(function() {
  var $content = $(this).parent().next().toggle();

  //HIDE THIS LINE IF YOU DO NOT WANT TO HIDE OTHER TABS ON CLICK
  $('.droptab').not($content).hide();
});

//ADD THIS LINE IF YOU WANT TO OPEN FIRST TAB BY DEFAULT ON PAGE LOAD
$('.droptab').first().toggle();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.droptab {
  display: none
}</code>```

    MAIN TITLE

MAIN TITLE CONTENT

    SECOND TITLE

SECOND TITLE CONTENT

```

Body:
I have some tabs which show hidden information when clicked. But as they are now, they will open but only close when a new tab is clicked. If possible could I get help with these two issues:

1- I want to make the tab close again when you click it a second time.

2- I have links set up to open the page where each section starts. Is there anyway I can make the tab open automatically when that link is clicked?

I appreciate the help.

Edited to show the full code I have now:

$('.drop a').click(function() {
  var $content = $(this).parent().next().toggle();

  //HIDE THIS LINE IF YOU DO NOT WANT TO HIDE OTHER TABS ON CLICK
 $('.droptab').not($content).hide();
});

.droptab {
  display: none
}

<a class="anchor" id="<?php echo $child->post_title; ?>">

<?php echo $child->post_title; ?>

<?php echo apply_filters('the_content', $child->post_content); ?>

                <a href="<?php the_field( 'get_more_url', $child->ID ); ?>" class="button left">Get More Info

Body:
Use toggle instead of hide show.

The toggle() method toggles between hide() and show() for the selected elements.

Hide this line "$('.droptab').not($content).hide();" IF YOU DO NOT WANT TO HIDE OTHER TABS ON CLICK

$('.drop a').click(function() {
  var $content = $(this).parent().next().toggle();

  //HIDE THIS LINE IF YOU DO NOT WANT TO HIDE OTHER TABS ON CLICK
  $('.droptab').not($content).hide();
});

//ADD THIS LINE IF YOU WANT TO OPEN FIRST TAB BY DEFAULT ON PAGE LOAD
$('.droptab').first().toggle();

.droptab {
  display: none
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="dropdowntabs">
  <a class="anchor" id="main-tab"></a>
  <h2 class="drop">
    <a>MAIN TITLE</a>
  </h2>
  <div class="droptab">
    <p>MAIN TITLE CONTENT</p>
  </div>
  <a class="anchor" id="second-tab"></a>
  <h2 class="drop">
    <a>SECOND TITLE</a>
  </h2>
  <div class="droptab">
    <p>SECOND TITLE CONTENT</p>
  </div>
</div>


问:
Tkinker Replace the bottom taskbar icon with something else
I am wanting to replace the icon at the bottom of the screen.
Example:
I am aware of how to remove the icon in the toolbar this is at the bottom of the screen.

```<code>import ctypes

def Mbox(title, text, style):
    root = root.iconbitmap(default='app.ico')

    return ctypes.windll.user32.MessageBoxW(0, text, title, style)

    root = Mbox('Your title', 'Your text', 1)
</code>```

I keep getting –

```<code>NameError: name 'root' is not defined
</code>```

答:
import tkinter and set your root variable to Tk()

```<code>from tkinter import *

root = Tk()
</code>```

Body:
I am wanting to replace the icon at the bottom of the screen.
Example:
I am aware of how to remove the icon in the toolbar this is at the bottom of the screen.

import ctypes

def Mbox(title, text, style):
    root = root.iconbitmap(default='app.ico')

    return ctypes.windll.user32.MessageBoxW(0, text, title, style)

    root = Mbox('Your title', 'Your text', 1)

I keep getting –

NameError: name 'root' is not defined

Body:
import tkinter and set your root variable to Tk()

from tkinter import *

root = Tk()