问:
Camera Preview onPictureTaken return wrong data in android
I wrote a program in order to complete the camera overlay, I found when I set the variable “image_data” in onPictureTaken(),it don’t change the value immediately,it change the value when I call onPictureTaken again
I can't resolve it,Can anybody help me?

```<code>private PictureCallback jpegCallback = new PictureCallback()
{public void setImageData(byte[] b) {
  image_data = b;
}
  @Override
  public void onPictureTaken(byte[] data, Camera camera)
  {

    if (mCamera != null){
      mCamera.startPreview();}

    FileOutputStream outStream = null;
    try {
      // Write to SD Card
      outStream = new FileOutputStream(String.format("/sdcard/%d.jpg",
        System.currentTimeMillis()) );
      outStream.write(data);
      outStream.close();
      Log.d(TAG, "onPictureTaken - wrote bytes: " + data.length);

      Log.d(TAG, String.valueOf(data));
      image_data = data;
      setImageData(data);  //neither direct assign nor setImageData are invalid
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
    }

    Log.d(TAG, "onPictureTaken - jpeg");
  }
};
</code>```

CameraTestActivity code

```<code>mCamera.takePicture();
Toast toast = Toast.makeText(CameraTestActivity.this,
          "PhotoTaken"+mCamera.getImageData(), Toast.LENGTH_LONG);
  toast.show();
</code>```

and the first photo taken toast show is "PhotoTaken null"
secondary output is "PhotoTaken B@c4f05e2"

following is logcat data

```<code>12-03 22:19:20.416 21589-21589/com.example.acer.camerapreview
D/CameraTest.VersionedCamera: onPictureTaken - wrote bytes: 1644369
12-03 22:19:20.416 21589-21589/com.example.acer.camerapreview
D/CameraTest.VersionedCamera: [B@c4f05e2
12-03 22:19:29.631 21589-21589/com.example.acer.camerapreview
D/CameraTest.VersionedCamera: onPictureTaken - wrote bytes: 1622238
12-03 22:19:29.631 21589-21589/com.example.acer.camerapreview
D/CameraTest.VersionedCamera: [B@adb9e2e
</code>```

答:
mCamera.takePicture() need to pass a PictureCallback, so where do you pass your PictureCallback (in your code, I see your callback is jpegCallback) ?

Toast.makeText(CameraTestActivity.this, "PhotoTaken" + mCamera.getImageData(), Toast.LENGTH_LONG).show() It should be written correctly in the PictureCallback, not below it .

for example:

```<code>mCamera.takePicture(null, null, new Camera.PictureCallback() {
                @Override
                public void onPictureTaken(byte[] data, Camera camera) {
                    // your code in here is correct ✔
                }
            });
</code>```

but

```<code>mCamera.takePicture(null, null, new Camera.PictureCallback() {
                                    @Override
                                    public void onPictureTaken(byte[] data, Camera camera) {
                                    }
                                });
// your code in here is wrong ✕
</code>```

Body:
I wrote a program in order to complete the camera overlay, I found when I set the variable “image_data” in onPictureTaken(),it don’t change the value immediately,it change the value when I call onPictureTaken again
I can't resolve it,Can anybody help me?

private PictureCallback jpegCallback = new PictureCallback()
{public void setImageData(byte[] b) {
  image_data = b;
}
  @Override
  public void onPictureTaken(byte[] data, Camera camera)
  {

    if (mCamera != null){
      mCamera.startPreview();}

    FileOutputStream outStream = null;
    try {
      // Write to SD Card
      outStream = new FileOutputStream(String.format("/sdcard/%d.jpg",
        System.currentTimeMillis()) );
      outStream.write(data);
      outStream.close();
      Log.d(TAG, "onPictureTaken - wrote bytes: " + data.length);

      Log.d(TAG, String.valueOf(data));
      image_data = data;
      setImageData(data);  //neither direct assign nor setImageData are invalid
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
    }

    Log.d(TAG, "onPictureTaken - jpeg");
  }
};

CameraTestActivity code

mCamera.takePicture();
Toast toast = Toast.makeText(CameraTestActivity.this,
          "PhotoTaken"+mCamera.getImageData(), Toast.LENGTH_LONG);
  toast.show();

and the first photo taken toast show is "PhotoTaken null"
secondary output is "PhotoTaken B@c4f05e2"

following is logcat data

12-03 22:19:20.416 21589-21589/com.example.acer.camerapreview
D/CameraTest.VersionedCamera: onPictureTaken - wrote bytes: 1644369
12-03 22:19:20.416 21589-21589/com.example.acer.camerapreview
D/CameraTest.VersionedCamera: [B@c4f05e2
12-03 22:19:29.631 21589-21589/com.example.acer.camerapreview
D/CameraTest.VersionedCamera: onPictureTaken - wrote bytes: 1622238
12-03 22:19:29.631 21589-21589/com.example.acer.camerapreview
D/CameraTest.VersionedCamera: [B@adb9e2e

Body:
mCamera.takePicture() need to pass a PictureCallback, so where do you pass your PictureCallback (in your code, I see your callback is jpegCallback) ?

Toast.makeText(CameraTestActivity.this, "PhotoTaken" + mCamera.getImageData(), Toast.LENGTH_LONG).show() It should be written correctly in the PictureCallback, not below it .

for example:

mCamera.takePicture(null, null, new Camera.PictureCallback() {
                @Override
                public void onPictureTaken(byte[] data, Camera camera) {
                    // your code in here is correct ✔
                }
            });

but

mCamera.takePicture(null, null, new Camera.PictureCallback() {
                                    @Override
                                    public void onPictureTaken(byte[] data, Camera camera) {
                                    }
                                });
// your code in here is wrong ✕


来源: stackexchange

问:
Take a snapshot of current screen with Metal in swift
I tried:

```<code>let scale = UIScreen.mainScreen().scale
UIGraphicsBeginImageContextWithOptions(metalLayer.bounds.size, false, scale)

// metalLayer.renderInContext(UIGraphicsGetCurrentContext()!)

// self.view.layer ...

metalLayer.presentationLayer()!.renderInContext(UIGraphicsGetCurrentContext()!)

let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
</code>```

But the result is an empty screenshot. Any help would be nice!

Please keep in mind that I want to take a snapshot of a CAMetalLayer.

答:
I didn't manage to get the accepted answer to work in Swift 4 / Metal 2 with XCode 9.1 on an iPhone 6s. Therefore I used a slightly different approach assuming lastDrawableDisplayed is saved as described in the accepted answer. Quick and dirty and without any exception handling:

```<code>let context = CIContext()
let texture = self.lastDrawableDisplayed!.texture
let cImg = CIImage(mtlTexture: texture, options: nil)!
let cgImg = context.createCGImage(cImg, from: cImg.extent)!
let uiImg = UIImage(cgImage: cgImg)
</code>```

This is based on the documentation on the used CIImage Initializer:

init(mtlTexture:options:) Initializes an image object with data supplied by a Metal texture.

and CIImage Processing which describes how to create a CGImage with the use of CIContext:

CIContext() Create[s] a CIContext object (with default options) [...] context.createCGImage Render[s] the output image to a Core Graphics image that you can display or save to a file.

Hope that helps for anyone using Swift 4.

Edit: Additionally, I have multiple overlaying CAMetalLayer in my project and want to combine them into one single UIImage. Therefore it is needed to have references to the last CAMetalDrawable object of each layer. Before a new layer is added (and therefore used as the provider of nextDrawable()) I simply add the lastDrawableDisplayed to an array [CAMetalDrawable]. When "exporting" the layers I simply write all UIImages subsequently into a bitmap-based graphics context and get the final image with UIGraphicsGetImageFromCurrentImageContext().

Edit: If you are having trouble with orientation, try the following:

```<code>let uiImg = UIImage(cgImage: cgImg, scale: 1.0, orientation: UIImageOrientation.downMirrored)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I tried:

let scale = UIScreen.mainScreen().scale
UIGraphicsBeginImageContextWithOptions(metalLayer.bounds.size, false, scale)

// metalLayer.renderInContext(UIGraphicsGetCurrentContext()!)

// self.view.layer ...

metalLayer.presentationLayer()!.renderInContext(UIGraphicsGetCurrentContext()!)

let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)

But the result is an empty screenshot. Any help would be nice!

Please keep in mind that I want to take a snapshot of a CAMetalLayer.

Body:
I didn't manage to get the accepted answer to work in Swift 4 / Metal 2 with XCode 9.1 on an iPhone 6s. Therefore I used a slightly different approach assuming lastDrawableDisplayed is saved as described in the accepted answer. Quick and dirty and without any exception handling:

let context = CIContext()
let texture = self.lastDrawableDisplayed!.texture
let cImg = CIImage(mtlTexture: texture, options: nil)!
let cgImg = context.createCGImage(cImg, from: cImg.extent)!
let uiImg = UIImage(cgImage: cgImg)

This is based on the documentation on the used CIImage Initializer:

init(mtlTexture:options:) Initializes an image object with data supplied by a Metal texture.

and CIImage Processing which describes how to create a CGImage with the use of CIContext:

CIContext() Create[s] a CIContext object (with default options) [...] context.createCGImage Render[s] the output image to a Core Graphics image that you can display or save to a file.

Hope that helps for anyone using Swift 4.

Edit: Additionally, I have multiple overlaying CAMetalLayer in my project and want to combine them into one single UIImage. Therefore it is needed to have references to the last CAMetalDrawable object of each layer. Before a new layer is added (and therefore used as the provider of nextDrawable()) I simply add the lastDrawableDisplayed to an array [CAMetalDrawable]. When "exporting" the layers I simply write all UIImages subsequently into a bitmap-based graphics context and get the final image with UIGraphicsGetImageFromCurrentImageContext().

Edit: If you are having trouble with orientation, try the following:

let uiImg = UIImage(cgImage: cgImg, scale: 1.0, orientation: UIImageOrientation.downMirrored)

ContentLicense: CC BY-SA 3.0


问:
SQL for applying conditions to multiple rows in a join
I think I found the answer to my question, I'm just unsure of the syntax, I keep getting SQL errors.

Basically, I want to do the opposite of IN. Take this example:

```<code>SELECT *
  FROM users INNER JOIN
       tags ON tags.user_id = users.id
 WHERE tags.name IN ('tag1', 'tag2');
</code>```

The above will return ANY users that have 'tag1' OR 'tag2'. I want users that have BOTH. They must have both tags to be returned. I'm assuming the keyword ALL should be used, but can't get it to work.

Thanks for your help.

答:
Give this a try</p>

```<code>SELECT *
FROM users
INNER JOIN tags ON tags.user_id = users.id
WHERE users.id in
    (
    SELECT user_id
    FROM tags
    WHERE name IN ('tag1', 'tag2')
    GROUP BY user_id
    HAVING COUNT(*) = 2
    )
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I think I found the answer to my question, I'm just unsure of the syntax, I keep getting SQL errors.

Basically, I want to do the opposite of IN. Take this example:

SELECT *
  FROM users INNER JOIN
       tags ON tags.user_id = users.id
 WHERE tags.name IN ('tag1', 'tag2');

The above will return ANY users that have 'tag1' OR 'tag2'. I want users that have BOTH. They must have both tags to be returned. I'm assuming the keyword ALL should be used, but can't get it to work.

Thanks for your help.

Body:
Give this a try

SELECT *
FROM users
INNER JOIN tags ON tags.user_id = users.id
WHERE users.id in
    (
    SELECT user_id
    FROM tags
    WHERE name IN ('tag1', 'tag2')
    GROUP BY user_id
    HAVING COUNT(*) = 2
    )


问:
Find bem class and replace by another
I search variant how with jQuery find BEM modificatory in
 with more classes, eg.

```<code><div class="xc-icon xs-icon--account-circle xs-font--big">
</code>```

I need detect to modificator xs-icon--account-circle but accoutn-cicle is variable, so I need detect only xs-icon--something-sometimes-with-dash

Can somebody help my how maybe via regular expression detect only variable BEM modificatory?

Thank you.

答:
You can pass jQuery a CSS "contains" selector, e.g.

$("[class*='xs-icon--']")

This should return you a collection of all the xs-icon elements that have a BEM modifier.

Title: Find bem class and replace by another

Body:
I search variant how with jQuery find BEM modificatory in
 with more classes, eg.

I need detect to modificator xs-icon--account-circle but accoutn-cicle is variable, so I need detect only xs-icon--something-sometimes-with-dash

Can somebody help my how maybe via regular expression detect only variable BEM modificatory?

Thank you.


问:
fetch multiple rows from mysql with one query and use them in php
Hi there i got stuck on this code and i don't seem to find a solution to it.
I have this now...
pdf download

and i want to display this...
enter image description here

all the PDFs are in a table and one product have 2-3 PDFs
here is my code:
enter image description here

and the table looks like this...
enter image description here

答:
Sorry for not placing the code:
here is the code i speak and the images is for a visual aspect of what i want the code to do...</p>

```<code><?php
$data_sheet = false;
$datasheet_query = $db->Execute("SELECT TECHLINK_ID, TECHLINK_INCODE, TECHLINK_URLID, TECHLINK_products_id, TECH_URL, TECH_TITLE
                                FROM FTECHLINK
                                LEFT JOIN FTECHSHEET_URL ON TECH_ID = TECHLINK_URLID
                                WHERE TECHLINK_products_id = ".(int)$_GET['products_id']."");
if (!$datasheet_query->EOF){
    $data_sheet = true;
    $pdf_title = $datasheet_query->fields['TECH_TITLE'];
    $pdf_file = $datasheet_query->fields['TECH_URL'];
    $pdf_path = "acrobat/".$pdf_file;
    $image_name = str_ireplace('.pdf','.jpg',$pdf_file);
    $image_path = "acrobat/".$image_name;
    $tech_image = '<div class="download_image_container"><a href="' . $pdf_path . '"target="_blank">' . zen_image($image_path, $products_name, "173", "245", 'class="box_image_pdf"') . '</a></div>';
    $tech_title = '<div class="download_title_container"><a class="document_title"href="' . $pdf_path . '"target="_blank">' . $pdf_title . '</a></div>';
}
?>

     <?php if ($data_sheet == true) { ?>
        <div id="datasheet" class="tab-pane">
            <div class="product-tab">
            <?php
                echo $tech_image;
                echo $tech_title;
            ?>
            </div>
        </div>
</code>```

Body:
Sorry for not placing the code:
here is the code i speak and the images is for a visual aspect of what i want the code to do...

<?php
$data_sheet = false;
$datasheet_query = $db->Execute("SELECT TECHLINK_ID, TECHLINK_INCODE, TECHLINK_URLID, TECHLINK_products_id, TECH_URL, TECH_TITLE
                                FROM FTECHLINK
                                LEFT JOIN FTECHSHEET_URL ON TECH_ID = TECHLINK_URLID
                                WHERE TECHLINK_products_id = ".(int)$_GET['products_id']."");
if (!$datasheet_query->EOF){
    $data_sheet = true;
    $pdf_title = $datasheet_query->fields['TECH_TITLE'];
    $pdf_file = $datasheet_query->fields['TECH_URL'];
    $pdf_path = "acrobat/".$pdf_file;
    $image_name = str_ireplace('.pdf','.jpg',$pdf_file);
    $image_path = "acrobat/".$image_name;
    $tech_image = '<div class="download_image_container"><a href="' . $pdf_path . '"target="_blank">' . zen_image($image_path, $products_name, "173", "245", 'class="box_image_pdf"') . '</a></div>';
    $tech_title = '<div class="download_title_container"><a class="document_title"href="' . $pdf_path . '"target="_blank">' . $pdf_title . '</a></div>';
}
?>

     <?php if ($data_sheet == true) { ?>
        <div id="datasheet" class="tab-pane">
            <div class="product-tab">
            <?php
                echo $tech_image;
                echo $tech_title;
            ?>
            </div>
        </div>


答:
You can try the following, it will look an element that contains a specific part of a class and remove the class.

```<code>$("[class*=xs-icon--]").removeClass(function(index, className) {
  return (className.match(/(^|\s)xs-icon--\S+/g) || []).join(' ');
});
</code>```

$("[class*=xs-icon--]") = if any element contains a class with xs-icon--

if you run the code class="xc-icon xs-icon--account-circle xs-font--big" would return class="xc-icon xs-font--big"

$("[class*=xs-icon--]").removeClass(function(index, className) {
  return (className.match(/(^|\s)xs-icon--\S+/g) || []).join(' ');
});```
<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>
<div class="xc-icon xs-icon--account-circle xs-font--big">test</div></code>```

Title: Find bem class and replace by another

Body:
You can try the following, it will look an element that contains a specific part of a class and remove the class.

$("[class*=xs-icon--]").removeClass(function(index, className) {
  return (className.match(/(^|\s)xs-icon--\S+/g) || []).join(' ');
});

$("[class*=xs-icon--]") = if any element contains a class with xs-icon--

if you run the code class="xc-icon xs-icon--account-circle xs-font--big" would return class="xc-icon xs-font--big"

$("[class*=xs-icon--]").removeClass(function(index, className) {
  return (className.match(/(^|\s)xs-icon--\S+/g) || []).join(' ');
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="xc-icon xs-icon--account-circle xs-font--big">test</div>


问:
java regex help
I can have one string with the following two formats:

```<code>"[HardCOdeText1 (HardCodeText2)].[HardCodeText3].[MatchString] between changeValue1 and changeValue2";
"[MatchString] between changeValue1 and changeValue2";
</code>```

I would like to match if the string have "[MatchString] between" expression.
ANd depending upon which string I match, The changed value format should be one of the following:
The changed format should be :

```<code>"[HardCOdeText1 (HardCodeText2)].[HardCodeText3].[MatchString] between chamged1 and changed2"; or
"[MatchString] between changed1 and changed2";
</code>```

I started to match "[MatchString] between" expression and I got stuck over there:
ANy help is appreciated.

答:
[ and ] are reserved chars in regular expressions and you need to escape them.
Also, here is a really nice online regular expression tester that uses java regexp:

http://www.regexplanet.com/simple/index.html

Title: java regex help

Body:
I can have one string with the following two formats:

"[HardCOdeText1 (HardCodeText2)].[HardCodeText3].[MatchString] between changeValue1 and changeValue2";
"[MatchString] between changeValue1 and changeValue2";

I would like to match if the string have "[MatchString] between" expression.
ANd depending upon which string I match, The changed value format should be one of the following:
The changed format should be :

"[HardCOdeText1 (HardCodeText2)].[HardCodeText3].[MatchString] between chamged1 and changed2"; or
"[MatchString] between changed1 and changed2";

I started to match "[MatchString] between" expression and I got stuck over there:
ANy help is appreciated.


问:
Tensorflow - Error while fetching data_set from MNIST_data
Please assist me in resolving this issue, I am a beginner in TF, it might be a silly mistake I am doing here -
I am getting below error while executing these two lines :

```<code>from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
</code>```

Error:

```<code>Traceback (most recent call last):
  File "/home/rishabh/PycharmProjects/TF/ReadDatasetFromMNIST.py", line 1, in <module>
    from tensorflow.examples.tutorials.mnist import input_data
  File "/home/rishabh/.local/lib/python3.5/site-packages/tensorflow/examples/tutorials/mnist/__init__.py", line 21, in <module>
    from tensorflow.examples.tutorials.mnist import input_data
  File "/home/rishabh/.local/lib/python3.5/site-packages/tensorflow/examples/tutorials/mnist/input_data.py", line 29, in <module>
    from tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets
  File "/home/rishabh/.local/lib/python3.5/site-packages/tensorflow/contrib/__init__.py", line 31, in <module>
    from tensorflow.contrib import distributions
  File "/home/rishabh/.local/lib/python3.5/site-packages/tensorflow/contrib/distributions/__init__.py", line 33, in <module>
    from tensorflow.contrib.distributions.python.ops.estimator import *
  File "/home/rishabh/.local/lib/python3.5/site-packages/tensorflow/contrib/distributions/python/ops/estimator.py", line 21, in <module>
    from tensorflow.contrib.learn.python.learn.estimators.head import _compute_weighted_loss
  File "/home/rishabh/.local/lib/python3.5/site-packages/tensorflow/contrib/learn/__init__.py", line 92, in <module>
    from tensorflow.contrib.learn.python.learn import *
  File "/home/rishabh/.local/lib/python3.5/site-packages/tensorflow/contrib/learn/python/__init__.py", line 23, in <module>
    from tensorflow.contrib.learn.python.learn import *
  File "/home/rishabh/.local/lib/python3.5/site-packages/tensorflow/contrib/learn/python/learn/__init__.py", line 25, in <module>
    from tensorflow.contrib.learn.python.learn import estimators
  File "/home/rishabh/.local/lib/python3.5/site-packages/tensorflow/contrib/learn/python/learn/estimators/__init__.py", line 297, in <module>
    from tensorflow.contrib.learn.python.learn.estimators.dnn import DNNClassifier
  File "/home/rishabh/.local/lib/python3.5/site-packages/tensorflow/contrib/learn/python/learn/estimators/dnn.py", line 30, in <module>
    from tensorflow.contrib.learn.python.learn.estimators import dnn_linear_combined
  File "/home/rishabh/.local/lib/python3.5/site-packages/tensorflow/contrib/learn/python/learn/estimators/dnn_linear_combined.py", line 31, in <module>
    from tensorflow.contrib.learn.python.learn.estimators import estimator
  File "/home/rishabh/.local/lib/python3.5/site-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py", line 49, in <module>
    from tensorflow.contrib.learn.python.learn.learn_io import data_feeder
  File "/home/rishabh/.local/lib/python3.5/site-packages/tensorflow/contrib/learn/python/learn/learn_io/__init__.py", line 21, in <module>
    from tensorflow.contrib.learn.python.learn.learn_io.dask_io import extract_dask_data
  File "/home/rishabh/.local/lib/python3.5/site-packages/tensorflow/contrib/learn/python/learn/learn_io/dask_io.py", line 26, in <module>
    import dask.dataframe as dd
  File "/home/rishabh/anaconda3/lib/python3.5/site-packages/dask/dataframe/__init__.py", line 3, in <module>
    from .core import (DataFrame, Series, Index, _Frame, map_partitions,
  File "/home/rishabh/anaconda3/lib/python3.5/site-packages/dask/dataframe/core.py", line 36, in <module>
    pd.computation.expressions.set_use_numexpr(False)
AttributeError: module 'pandas' has no attribute 'computation'

Process finished with exit code 1
</code>```

答:
Judging by this GitHub issue, you're using an outdated version of dask.

If you're using Anaconda, run conda update dask, otherwise run pip install dask --upgrade to upgrade to the latest dask version available. This should fix the pandas error.

Body:
Please assist me in resolving this issue, I am a beginner in TF, it might be a silly mistake I am doing here -
I am getting below error while executing these two lines :

from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

Error:

Traceback (most recent call last):
  File "/home/rishabh/PycharmProjects/TF/ReadDatasetFromMNIST.py", line 1, in <module>
    from tensorflow.examples.tutorials.mnist import input_data
  File "/home/rishabh/.local/lib/python3.5/site-packages/tensorflow/examples/tutorials/mnist/__init__.py", line 21, in <module>
    from tensorflow.examples.tutorials.mnist import input_data
  File "/home/rishabh/.local/lib/python3.5/site-packages/tensorflow/examples/tutorials/mnist/input_data.py", line 29, in <module>
    from tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets
  File "/home/rishabh/.local/lib/python3.5/site-packages/tensorflow/contrib/__init__.py", line 31, in <module>
    from tensorflow.contrib import distributions
  File "/home/rishabh/.local/lib/python3.5/site-packages/tensorflow/contrib/distributions/__init__.py", line 33, in <module>
    from tensorflow.contrib.distributions.python.ops.estimator import *
  File "/home/rishabh/.local/lib/python3.5/site-packages/tensorflow/contrib/distributions/python/ops/estimator.py", line 21, in <module>
    from tensorflow.contrib.learn.python.learn.estimators.head import _compute_weighted_loss
  File "/home/rishabh/.local/lib/python3.5/site-packages/tensorflow/contrib/learn/__init__.py", line 92, in <module>
    from tensorflow.contrib.learn.python.learn import *
  File "/home/rishabh/.local/lib/python3.5/site-packages/tensorflow/contrib/learn/python/__init__.py", line 23, in <module>
    from tensorflow.contrib.learn.python.learn import *
  File "/home/rishabh/.local/lib/python3.5/site-packages/tensorflow/contrib/learn/python/learn/__init__.py", line 25, in <module>
    from tensorflow.contrib.learn.python.learn import estimators
  File "/home/rishabh/.local/lib/python3.5/site-packages/tensorflow/contrib/learn/python/learn/estimators/__init__.py", line 297, in <module>
    from tensorflow.contrib.learn.python.learn.estimators.dnn import DNNClassifier
  File "/home/rishabh/.local/lib/python3.5/site-packages/tensorflow/contrib/learn/python/learn/estimators/dnn.py", line 30, in <module>
    from tensorflow.contrib.learn.python.learn.estimators import dnn_linear_combined
  File "/home/rishabh/.local/lib/python3.5/site-packages/tensorflow/contrib/learn/python/learn/estimators/dnn_linear_combined.py", line 31, in <module>
    from tensorflow.contrib.learn.python.learn.estimators import estimator
  File "/home/rishabh/.local/lib/python3.5/site-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py", line 49, in <module>
    from tensorflow.contrib.learn.python.learn.learn_io import data_feeder
  File "/home/rishabh/.local/lib/python3.5/site-packages/tensorflow/contrib/learn/python/learn/learn_io/__init__.py", line 21, in <module>
    from tensorflow.contrib.learn.python.learn.learn_io.dask_io import extract_dask_data
  File "/home/rishabh/.local/lib/python3.5/site-packages/tensorflow/contrib/learn/python/learn/learn_io/dask_io.py", line 26, in <module>
    import dask.dataframe as dd
  File "/home/rishabh/anaconda3/lib/python3.5/site-packages/dask/dataframe/__init__.py", line 3, in <module>
    from .core import (DataFrame, Series, Index, _Frame, map_partitions,
  File "/home/rishabh/anaconda3/lib/python3.5/site-packages/dask/dataframe/core.py", line 36, in <module>
    pd.computation.expressions.set_use_numexpr(False)
AttributeError: module 'pandas' has no attribute 'computation'

Process finished with exit code 1


问:
WPF ListBox, calls bound property twice
I'm trying to learn ObservableCollection<T> and ListBox's VirtualizingStackPanel.

There is an image inside MyTestData class, bound to Image (Thumbnail property) inside of the ListBox.ItemTemplate. The problem is, the Thumbnail property is called twice when I scroll. Is this a problem or how WPF works?

Window:

<Window x:ClassModifier="internal" x:Class="Virtual.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Title="MainWindow" SizeToContent="Height" Width="525" WindowStartupLocation="CenterScreen">
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"></ColumnDefinition>
        <ColumnDefinition Width="*"></ColumnDefinition>
    </Grid.ColumnDefinitions>

    <StackPanel Orientation="Vertical">
        <Button x:Name="btnAdd1" Content="Add 1" Click="btnAdd_Click"></Button>
        <Button x:Name="btnAdd10" Content="Add 10" Click="btnAdd_Click"></Button>
        <Button x:Name="btnAdd100" Content="Add 100" Click="btnAdd_Click"></Button>
        <Button x:Name="btnAdd1000" Content="Add 1000" Click="btnAdd_Click"></Button>
        <Button x:Name="btnAdd1000000" Content="Add 1.000.000" Click="btnAdd_Click"></Button>
        <TextBox x:Name="tbDebug" Margin="0,10,0,25" Height="250" AcceptsReturn="True">

        </TextBox>

    </StackPanel>
    <Button x:Name="btnAdd" Content="Add" VerticalAlignment="Bottom" Click="btnAdd_Click"></Button>

    <ListBox x:Name="lbList2" Margin="10,0,0,25" Height="350"
       Grid.Column="1"
       ScrollViewer.CanContentScroll="True"
       ScrollViewer.IsDeferredScrollingEnabled="False"
       VirtualizingStackPanel.IsVirtualizing="True"
       VirtualizingStackPanel.VirtualizationMode="Recycling">
        <ListBox.ItemsPanel>
            <ItemsPanelTemplate>
                <VirtualizingStackPanel></VirtualizingStackPanel>
            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <Border Margin="3,0,0,0" BorderBrush="Black" BorderThickness="1">
                        <Image VerticalAlignment="Top" HorizontalAlignment="Left" MaxWidth="30" MaxHeight="30" SnapsToDevicePixels="True" Source="{Binding Thumbnail, UpdateSourceTrigger=PropertyChanged}" />
                    </Border>

                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

    <Button x:Name="btnAdd2" Margin="10,0,0,0" Grid.Column="1" Content="Add" VerticalAlignment="Bottom" Click="btnAdd_Click"></Button>
</Grid>
</Window>
```

<p>Code:</p>

```using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Virtual
{
    internal class MyTestData
    {
        public string Name { get; set; }

        private BitmapSource _thumbnail = null;
        public BitmapSource Thumbnail
        {
            get
            {
                if (_thumbnail == null)
                    _thumbnail = new BitmapImage(new Uri("c:\\300.jpg"));

                Console.Text += "\n" + Name + " --> THUMBNAIL";
                Console.ScrollToEnd();

                return _thumbnail;
            }
        }

        public MyTestData(string oName)
        {
            Name = oName;
        }

        internal TextBox Console;
    }

    internal partial class MainWindow : Window
    {
        public List<string> OItems1 { get; set; }
        public ObservableCollection<MyTestData> OItems2 { get; set; }

        public MainWindow()
        {
            InitializeComponent();

            OItems1 = new List<string>();
            OItems2 = new ObservableCollection<MyTestData>();

            lbList2.ItemsSource = OItems2;
        }

        private void OAdd(int c)
        {
            for (int i = 0; i < c; i++)
            {
                OItems2.Add(new MyTestData("oDATA = " + (OItems2.Count + 1).ToString())
                {
                    Console = tbDebug
                });
            }
        }

        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            if (sender == btnAdd1)
                OAdd(1);
            else if (sender == btnAdd10)
                OAdd(10);
            else if (sender == btnAdd100)
                OAdd(100);
            else if (sender == btnAdd1000)
                OAdd(1000);
            else if (sender == btnAdd1000000)
                OAdd(1000000);
        }
    }
}
```

答:
Is this a problem or how WPF works?

The latter. Please refer to the following answer by Microsoft at Connect:

The framework (or anyone else) is entitled to call the property-getter as often as it likes, for any reason. There's no guarantee it will be called only once.

Unexpected behaviour: Binding engine getting ImageSource twice: https://connect.microsoft.com/VisualStudio/feedback/details/770169/unexpected-behaviour-binding-engine-getting-imagesource-twice

So this behaviour is expected.

Title: WPF ListBox, calls bound property twice

Body:
I'm trying to learn ObservableCollection<T> and ListBox's VirtualizingStackPanel.

There is an image inside MyTestData class, bound to Image (Thumbnail property) inside of the ListBox.ItemTemplate. The problem is, the Thumbnail property is called twice when I scroll. Is this a problem or how WPF works?

Window:

<Window x:ClassModifier="internal" x:Class="Virtual.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Title="MainWindow" SizeToContent="Height" Width="525" WindowStartupLocation="CenterScreen">
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"></ColumnDefinition>
        <ColumnDefinition Width="*"></ColumnDefinition>
    </Grid.ColumnDefinitions>

    <StackPanel Orientation="Vertical">
        <Button x:Name="btnAdd1" Content="Add 1" Click="btnAdd_Click"></Button>
        <Button x:Name="btnAdd10" Content="Add 10" Click="btnAdd_Click"></Button>
        <Button x:Name="btnAdd100" Content="Add 100" Click="btnAdd_Click"></Button>
        <Button x:Name="btnAdd1000" Content="Add 1000" Click="btnAdd_Click"></Button>
        <Button x:Name="btnAdd1000000" Content="Add 1.000.000" Click="btnAdd_Click"></Button>
        <TextBox x:Name="tbDebug" Margin="0,10,0,25" Height="250" AcceptsReturn="True">

        </TextBox>

    </StackPanel>
    <Button x:Name="btnAdd" Content="Add" VerticalAlignment="Bottom" Click="btnAdd_Click"></Button>

    <ListBox x:Name="lbList2" Margin="10,0,0,25" Height="350"
       Grid.Column="1"
       ScrollViewer.CanContentScroll="True"
       ScrollViewer.IsDeferredScrollingEnabled="False"
       VirtualizingStackPanel.IsVirtualizing="True"
       VirtualizingStackPanel.VirtualizationMode="Recycling">
        <ListBox.ItemsPanel>
            <ItemsPanelTemplate>
                <VirtualizingStackPanel></VirtualizingStackPanel>
            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <Border Margin="3,0,0,0" BorderBrush="Black" BorderThickness="1">
                        <Image VerticalAlignment="Top" HorizontalAlignment="Left" MaxWidth="30" MaxHeight="30" SnapsToDevicePixels="True" Source="{Binding Thumbnail, UpdateSourceTrigger=PropertyChanged}" />
                    </Border>

                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

    <Button x:Name="btnAdd2" Margin="10,0,0,0" Grid.Column="1" Content="Add" VerticalAlignment="Bottom" Click="btnAdd_Click"></Button>
</Grid>
</Window>

Code:

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Virtual
{
    internal class MyTestData
    {
        public string Name { get; set; }

        private BitmapSource _thumbnail = null;
        public BitmapSource Thumbnail
        {
            get
            {
                if (_thumbnail == null)
                    _thumbnail = new BitmapImage(new Uri("c:\\300.jpg"));

                Console.Text += "\n" + Name + " --> THUMBNAIL";
                Console.ScrollToEnd();

                return _thumbnail;
            }
        }

        public MyTestData(string oName)
        {
            Name = oName;
        }

        internal TextBox Console;
    }

    internal partial class MainWindow : Window
    {
        public List<string> OItems1 { get; set; }
        public ObservableCollection<MyTestData> OItems2 { get; set; }

        public MainWindow()
        {
            InitializeComponent();

            OItems1 = new List<string>();
            OItems2 = new ObservableCollection<MyTestData>();

            lbList2.ItemsSource = OItems2;
        }

        private void OAdd(int c)
        {
            for (int i = 0; i < c; i++)
            {
                OItems2.Add(new MyTestData("oDATA = " + (OItems2.Count + 1).ToString())
                {
                    Console = tbDebug
                });
            }
        }

        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            if (sender == btnAdd1)
                OAdd(1);
            else if (sender == btnAdd10)
                OAdd(10);
            else if (sender == btnAdd100)
                OAdd(100);
            else if (sender == btnAdd1000)
                OAdd(1000);
            else if (sender == btnAdd1000000)
                OAdd(1000000);
        }
    }
}


问:
Need some Help in modifying the query
I'm using the below query in order to split the value into another column and below is the output which I'm getting.

Query:

```<code>select distinct custom_attributes, REPLACE(REGEXP_SUBSTR (custom_attributes, 'LastChange=[0-9]{4}\/[0-9]{2}\/[0-9]{2}'), 'LastChange=', '')
as dates1 from table_name ;
</code>```

Output:

```<code>custom_attributes                                                                                dates1
Attributes: assetGroup=USVHILVSQL020\MSSQL_01; DBTimeStamp=2017/09/17; GSDServiceCount=1;  HSBCLocation=US Vernon Hills; DBCount=7; Environment=LIVE; LastChange=2017/09/17                      2017/09/17
Attributes: BusinessCriticality=TIER 2; Environment=LIVE; ViewPointName=DBA HTSA - DB2;  DBTimeStamp=9/16/2017; GSDServiceCount=1; LastChange=9/17/2017 20:00                                        NULL
Attributes: ServerId=100010000401; GSDServiceCount=0; Environment=LIVE; LastChange=16/11/2016 09:00;                                                                                NULL
ServerStatus=ACTIVE; CountryCode=TR; HSBCLocation=TR Istanbul Esentepe
Attributes: GSDServiceCount=0; CountryCode=MX; ServerId=100010000301; Environment=LIVE; ServerStatus=ACTIVE;                                                                                NULL
LastChange=10/7/2017 9:00; HSBCLocation=MX Chapultepec
</code>```

Required Output:

```<code>custom_attributes                                                                                dates1
Attributes: assetGroup=USVHILVSQL020\MSSQL_01; DBTimeStamp=2017/09/17; GSDServiceCount=1;  HSBCLocation=US Vernon Hills; DBCount=7; Environment=LIVE; LastChange=2017/09/17                      2017/09/17
Attributes: BusinessCriticality=TIER 2; Environment=LIVE; ViewPointName=DBA HTSA - DB2;  DBTimeStamp=9/16/2017; GSDServiceCount=1; LastChange=9/17/2017 20:00                                    9/17/2017
Attributes: ServerId=100010000401; GSDServiceCount=0; Environment=LIVE; LastChange=16/11/2016 09:00;                                                                                16/11/2016
ServerStatus=ACTIVE; CountryCode=TR; HSBCLocation=TR Istanbul Esentepe
Attributes: GSDServiceCount=0; CountryCode=MX; ServerId=100010000301; Environment=LIVE; ServerStatus=ACTIVE;                                                                                10/7/2017
LastChange=10/7/2017 9:00; HSBCLocation=MX Chapultepec
</code>```

答:
Use instr and substr instead :

```<code>select distinct custom_attributes,
substr( custom_attributes, instr(custom_attributes, 'LastChange=')+11, 10)
as dates1 from table_name ;
</code>```

Title: Need some Help in modifying the query

Body:
I'm using the below query in order to split the value into another column and below is the output which I'm getting.

Query:

select distinct custom_attributes, REPLACE(REGEXP_SUBSTR (custom_attributes, 'LastChange=[0-9]{4}\/[0-9]{2}\/[0-9]{2}'), 'LastChange=', '')
as dates1 from table_name ;

Output:

custom_attributes                                                                                dates1
Attributes: assetGroup=USVHILVSQL020\MSSQL_01; DBTimeStamp=2017/09/17; GSDServiceCount=1;  HSBCLocation=US Vernon Hills; DBCount=7; Environment=LIVE; LastChange=2017/09/17                      2017/09/17
Attributes: BusinessCriticality=TIER 2; Environment=LIVE; ViewPointName=DBA HTSA - DB2;  DBTimeStamp=9/16/2017; GSDServiceCount=1; LastChange=9/17/2017 20:00                                        NULL
Attributes: ServerId=100010000401; GSDServiceCount=0; Environment=LIVE; LastChange=16/11/2016 09:00;                                                                                NULL
ServerStatus=ACTIVE; CountryCode=TR; HSBCLocation=TR Istanbul Esentepe
Attributes: GSDServiceCount=0; CountryCode=MX; ServerId=100010000301; Environment=LIVE; ServerStatus=ACTIVE;                                                                                NULL
LastChange=10/7/2017 9:00; HSBCLocation=MX Chapultepec

Required Output:

custom_attributes                                                                                dates1
Attributes: assetGroup=USVHILVSQL020\MSSQL_01; DBTimeStamp=2017/09/17; GSDServiceCount=1;  HSBCLocation=US Vernon Hills; DBCount=7; Environment=LIVE; LastChange=2017/09/17                      2017/09/17
Attributes: BusinessCriticality=TIER 2; Environment=LIVE; ViewPointName=DBA HTSA - DB2;  DBTimeStamp=9/16/2017; GSDServiceCount=1; LastChange=9/17/2017 20:00                                    9/17/2017
Attributes: ServerId=100010000401; GSDServiceCount=0; Environment=LIVE; LastChange=16/11/2016 09:00;                                                                                16/11/2016
ServerStatus=ACTIVE; CountryCode=TR; HSBCLocation=TR Istanbul Esentepe
Attributes: GSDServiceCount=0; CountryCode=MX; ServerId=100010000301; Environment=LIVE; ServerStatus=ACTIVE;                                                                                10/7/2017
LastChange=10/7/2017 9:00; HSBCLocation=MX Chapultepec

Body:
Use instr and substr instead :

select distinct custom_attributes,
substr( custom_attributes, instr(custom_attributes, 'LastChange=')+11, 10)
as dates1 from table_name ;


问:
Is it Possible to make a button as File upload Button?
I am new in php. I have a form on which i place a button Value as Upload MB when user click on this button it redirects on a web form where i place a file upload control and user upload file here.
Here is image

After clicking this button user redirect on this form

here user upload file.

MY QUESTION

Is it possible that can i make my button Upload Mb as file upload button? Can it works like file upload control button?

Actually i want to save user time. I want that when user click on Upload MB button it not redirects on Form. But when user Click on Upload MB button it allow to user to upload file and open browsing window. After that when user upload file it redirects on form.

Can you guys tell me it is possible or not?

答:
Bootstrap Way

.choose_file {
    position: relative;
    display: inline-block;
    font: normal 14px Myriad Pro, Verdana, Geneva, sans-serif;
    color: #7f7f7f;
    margin-top: 2px;
    background: white
}
.choose_file input[type="file"]{
    -webkit-appearance:none;
    position:absolute;
    top:0;
    left:0;
    opacity:0;
    width: 100%;
    height: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="choose_file">
    <button type="button" class="btn btn-default" style="width: 125px;">Choose Image</button>
    <input name="img" type="file" accept="image/*" />
</div></code>```

Body:
Bootstrap Way

.choose_file {
    position: relative;
    display: inline-block;
    font: normal 14px Myriad Pro, Verdana, Geneva, sans-serif;
    color: #7f7f7f;
    margin-top: 2px;
    background: white
}
.choose_file input[type="file"]{
    -webkit-appearance:none;
    position:absolute;
    top:0;
    left:0;
    opacity:0;
    width: 100%;
    height: 100%;
}

<div class="choose_file">
    <button type="button" class="btn btn-default" style="width: 125px;">Choose Image</button>
    <input name="img" type="file" accept="image/*" />
</div>


问:
How to put session value store into database?
I wanted to retrieve session array and put into other model But throws `

Call to a member function pluck() on array

Controller I used :

```<code>$orders =  $request->session()->get('order');
$order = new Order();
$order->school_id = $orders->pluck('school_id');
$order->order_date = $orders->pluck('order_date');
$order->time_slot = $orders->pluck('time_slot');
</code>```

How do i access the session data and put into other model?

Here is the response I get when i dd() the session :

```<code>array:1 [▼
  0 => array:3 [▼
    "school_id" => "4"
    "order_date" => "11/25/2017"
    "time_slot" => "10am - 8pm"
  ]
]
</code>```

答:
it depends on how did you store it into session, so if you used push, then it will be stored as array.

anyways change your code to the following:

```<code>$orders =  $request->session()-> pull('order',$defaultOrdersArrayCanBeHere);
$order = new Order();
$order->school_id = $orders['school_id'];
$order->order_date = $orders['order_date'];
$order->time_slot = $orders['time_slot'];
</code>```

UPDATE:

Did you push it to session as so: session()->push('order', $order);

where:

```<code>$order = [
'school_id'=> $schoolId;
'order_date'=> $orderDate;
'time_slot'=> $timeSlot;
]
</code>```

Body:
I wanted to retrieve session array and put into other model But throws `

Call to a member function pluck() on array

Controller I used :

$orders =  $request->session()->get('order');
$order = new Order();
$order->school_id = $orders->pluck('school_id');
$order->order_date = $orders->pluck('order_date');
$order->time_slot = $orders->pluck('time_slot');

How do i access the session data and put into other model?

Here is the response I get when i dd() the session :

array:1 [▼
  0 => array:3 [▼
    "school_id" => "4"
    "order_date" => "11/25/2017"
    "time_slot" => "10am - 8pm"
  ]
]

Body:
it depends on how did you store it into session, so if you used push, then it will be stored as array.

anyways change your code to the following:

$orders =  $request->session()-> pull('order',$defaultOrdersArrayCanBeHere);
$order = new Order();
$order->school_id = $orders['school_id'];
$order->order_date = $orders['order_date'];
$order->time_slot = $orders['time_slot'];

UPDATE:

Did you push it to session as so: session()->push('order', $order);

where:

$order = [
'school_id'=> $schoolId;
'order_date'=> $orderDate;
'time_slot'=> $timeSlot;
]


问:
Oracle 10g NLS Parameters
Could people please let me know if there are any issues with setting Oracle 10g NLS Parameters at database level, specifically the NLS_TERRITORY to the country I am in together with setting the timezone to UTC.

Will there be any conflicts b/c as the moment, our NLS_TERRITORY is set to AMERICA which is not correct?

Thanks.

答:
With Oracle, you must be cautious with the NLS parameters in general.  Documentation is always a good idea:
NLS / Globalization stuff

Note that the NLS_TERRITORY parameter is derived from NLS_LANG.  So, you should be able to affect the NLS_TERRITORY parameter by changing NLS_LANG.  (This should be synched up in any case.)

After you get through that (please do read it), you will probably be thinking "Hey, we have existing data, will we need to perform any conversions on it after changing the parameter?"

TAKE A BACKUP!  BEFORE CHANGING
THE PARAMETER.  PLEASE

And yes, you may have to perform some data conversion, depending on how things have been stored, and what territory you change to.

Also keep in mind that any client software that uses this database should have its NLS_LANG (especially the characterset portion of it) set the same as the database - otherwise data can get mangled.

Title: Oracle 10g NLS Parameters


问:
Roll up ids and time series for forecasting - efficient method
I have a table like below

```<code>id time
1 2017-11-01 2:00:00
1 2017-11-01 2:00:20
1 2017-11-01 2:00:40
1 2017-11-01 2:01:00
.
.
.
123 2017-12-21 11:59:59
</code>```

I want to find total time per id per day. What is an effective method of doing this in R/Python?

Ideally get something like

```<code>id date minutes
1 2017-11-01 25
1 2017-11-01 22
.
.
</code>```

I do not want to do this using a nested for loop. Any better way to so it?

I was thinking using apply like below using a list of DFs for each ID

```<code>lapply(names(myDF), function(x) {aggregateTime())
</code>```

答:
In python you could use groupby.first and groupby.last in something like:

```<code>groupby = ('id', pd.Grouper(key='time', freq='d'))
begin = df.groupby(groupby ).first().astype('datetime64[ns]')
end = df.groupby(groupby ).last().astype('datetime64[ns]')
diff = (end - begin)['time']
diff = ((end - begin)['time'] / pd.Timedelta('1M')).round() # if you want it in minutes
</code>```

diff can be a Series of Timedelta or a series of minuts, depending on what you want

variation

```<code>def time_diff(group):
    diff = group['time'].max()- group['time'].min()
    return round(diff / pd.Timedelta('1M'))
df.groupby(groupby).apply(time_diff)
</code>```

Body:
I have a table like below

id time
1 2017-11-01 2:00:00
1 2017-11-01 2:00:20
1 2017-11-01 2:00:40
1 2017-11-01 2:01:00
.
.
.
123 2017-12-21 11:59:59

I want to find total time per id per day. What is an effective method of doing this in R/Python?

Ideally get something like

id date minutes
1 2017-11-01 25
1 2017-11-01 22
.
.

I do not want to do this using a nested for loop. Any better way to so it?

I was thinking using apply like below using a list of DFs for each ID

lapply(names(myDF), function(x) {aggregateTime())

Body:
In python you could use groupby.first and groupby.last in something like:

groupby = ('id', pd.Grouper(key='time', freq='d'))
begin = df.groupby(groupby ).first().astype('datetime64[ns]')
end = df.groupby(groupby ).last().astype('datetime64[ns]')
diff = (end - begin)['time']
diff = ((end - begin)['time'] / pd.Timedelta('1M')).round() # if you want it in minutes

diff can be a Series of Timedelta or a series of minuts, depending on what you want

variation

def time_diff(group):
    diff = group['time'].max()- group['time'].min()
    return round(diff / pd.Timedelta('1M'))
df.groupby(groupby).apply(time_diff)


问:
Drag and Drop with Protractor in AngularJS
I appreciate there's quite a bit of stuff already been said about automating drag and drop as part of E2E testing. However after many, many hours of fiddling around, I cannot get any of the methods described to work...that is using Functions, coordinates etc etc. Oddly enough, console.log maintains the tests have passed, but the screenshots clearly show nothing has happened.
Screenshots shows a portion of the application

The user selects a paper and drags onto the image. As the drag 'starts' the grey overlay on the image clears and the paper is rendered on the room.

The code snippet shows one of the more simple ideas I've tried and I would be very pleased to receive any help going!

```<code>const JS_HTML5_DND = 'function e(e,t,n,i){var r=a.createEvent("DragEvent");r.initMouseEvent(t,!0,!0,o,0,0,0,c,g,!1,!1,!1,!1,0,null),Object.defineProperty(r,"dataTransfer",{get:function(){return d}}),e.dispatchEvent(r),o.setTimeout(i,n)}var t=arguments[0],n=arguments[1],i=arguments[2]||0,r=arguments[3]||0;if(!t.draggable)throw new Error("Source element is not draggable.");var a=t.ownerDocument,o=a.defaultView,l=t.getBoundingClientRect(),u=n?n.getBoundingClientRect():l,c=l.left+(l.width>>1),g=l.top+(l.height>>1),s=u.left+(u.width>>1)+i,f=u.top+(u.height>>1)+r,d=Object.create(Object.prototype,{_items:{value:{}},effectAllowed:{value:"all",writable:!0},dropEffect:{value:"move",writable:!0},files:{get:function(){return this._items.Files}},types:{get:function(){return Object.keys(this._items)}},setData:{value:function(e,t){this._items[e]=t}},getData:{value:function(e){return this._items[e]}},clearData:{value:function(e){delete this._items[e]}},setDragImage:{value:function(e){}}});if(n=a.elementFromPoint(s,f),!n)throw new Error("The target element is not interactable and need to be scrolled into the view.");u=n.getBoundingClientRect(),e(t,"dragstart",101,function(){var i=n.getBoundingClientRect();c=i.left+s-u.left,g=i.top+f-u.top,e(n,"dragenter",1,function(){e(n,"dragover",101,function(){n=a.elementFromPoint(c,g),e(n,"drop",1,function(){e(t,"dragend",1,callback)})})})})';

describe('Drag and Drop Test', function() {
it('should drag', function () {

    var e1 = element(by.xpath('html/body/webapp-app/div/div/webapp-johnlewis-visualiser/div/div[2]/div/digitalbridge-shortlist/div/div/ul/li[1]/a/img'));
    var e2 = element(by.css('.db-project-designer'));

    element(by.xpath('html/body/webapp-app/div/div/webapp-johnlewis-visualiser/div/div[2]/div/digitalbridge-shortlist/div/div/ul/li[1]/a/img')).click();
    //element(by.xpath('html/body/webapp-app/div/div/webapp-johnlewis-visualiser/div/div[1]/div/div/digitalbridge-project/div/digitalbridge-project-designer/canvas')).click();

    browser.driver.actions().dragAndDrop(e1.getWebElement(),e2.getWebElement()).perform();

    browser.sleep(2000);
});
});
</code>```

The constant is showing an error 'const' is available in ES6 (use 'esversion: 6') or Mozilla JS extensions (use moz). (W104) - I do have ES6 installed in Node_Modules.

I inserted the click line to see if pre-selecting the item made any difference...it didn't!

Thank you

David

答:
Try this library https://github.com/SunGard-Labs/sg-protractor-tools

The library also includes functions that simplify common tasks like

Scrolling to an element
Drag and drop
Waiting for DOM elements to become visible or hidden

Body:
I appreciate there's quite a bit of stuff already been said about automating drag and drop as part of E2E testing. However after many, many hours of fiddling around, I cannot get any of the methods described to work...that is using Functions, coordinates etc etc. Oddly enough, console.log maintains the tests have passed, but the screenshots clearly show nothing has happened.
Screenshots shows a portion of the application

The user selects a paper and drags onto the image. As the drag 'starts' the grey overlay on the image clears and the paper is rendered on the room.

The code snippet shows one of the more simple ideas I've tried and I would be very pleased to receive any help going!

const JS_HTML5_DND = 'function e(e,t,n,i){var r=a.createEvent("DragEvent");r.initMouseEvent(t,!0,!0,o,0,0,0,c,g,!1,!1,!1,!1,0,null),Object.defineProperty(r,"dataTransfer",{get:function(){return d}}),e.dispatchEvent(r),o.setTimeout(i,n)}var t=arguments[0],n=arguments[1],i=arguments[2]||0,r=arguments[3]||0;if(!t.draggable)throw new Error("Source element is not draggable.");var a=t.ownerDocument,o=a.defaultView,l=t.getBoundingClientRect(),u=n?n.getBoundingClientRect():l,c=l.left+(l.width>>1),g=l.top+(l.height>>1),s=u.left+(u.width>>1)+i,f=u.top+(u.height>>1)+r,d=Object.create(Object.prototype,{_items:{value:{}},effectAllowed:{value:"all",writable:!0},dropEffect:{value:"move",writable:!0},files:{get:function(){return this._items.Files}},types:{get:function(){return Object.keys(this._items)}},setData:{value:function(e,t){this._items[e]=t}},getData:{value:function(e){return this._items[e]}},clearData:{value:function(e){delete this._items[e]}},setDragImage:{value:function(e){}}});if(n=a.elementFromPoint(s,f),!n)throw new Error("The target element is not interactable and need to be scrolled into the view.");u=n.getBoundingClientRect(),e(t,"dragstart",101,function(){var i=n.getBoundingClientRect();c=i.left+s-u.left,g=i.top+f-u.top,e(n,"dragenter",1,function(){e(n,"dragover",101,function(){n=a.elementFromPoint(c,g),e(n,"drop",1,function(){e(t,"dragend",1,callback)})})})})';

describe('Drag and Drop Test', function() {
it('should drag', function () {

    var e1 = element(by.xpath('html/body/webapp-app/div/div/webapp-johnlewis-visualiser/div/div[2]/div/digitalbridge-shortlist/div/div/ul/li[1]/a/img'));
    var e2 = element(by.css('.db-project-designer'));

    element(by.xpath('html/body/webapp-app/div/div/webapp-johnlewis-visualiser/div/div[2]/div/digitalbridge-shortlist/div/div/ul/li[1]/a/img')).click();
    //element(by.xpath('html/body/webapp-app/div/div/webapp-johnlewis-visualiser/div/div[1]/div/div/digitalbridge-project/div/digitalbridge-project-designer/canvas')).click();

    browser.driver.actions().dragAndDrop(e1.getWebElement(),e2.getWebElement()).perform();

    browser.sleep(2000);
});
});

The constant is showing an error 'const' is available in ES6 (use 'esversion: 6') or Mozilla JS extensions (use moz). (W104) - I do have ES6 installed in Node_Modules.

I inserted the click line to see if pre-selecting the item made any difference...it didn't!

Thank you

David


问:
Configuration of calling Python script using PHP
I am trying setup a project which will have a call between PHP and Python which will execute a script. I am using Mac OS and MAMP server. I read some blogs and documentation and there is mod_wsgi and mod_python but i'm not getting the any solution.

Thanks in advance.

答:
The following code executes python version command on the shell and returns the results of the version. You could do similarly like this to execute your python script.</p>

```<code>$python = "/usr/bin/python";
$output = array();
$cmd = $python . " -V 2>&1 ";
exec($cmd, $output);
$python_version = $output[0];
</code>```

Body:
The following code executes python version command on the shell and returns the results of the version. You could do similarly like this to execute your python script.

$python = "/usr/bin/python";
$output = array();
$cmd = $python . " -V 2>&1 ";
exec($cmd, $output);
$python_version = $output[0];


问:
tensorflow requires too much virtual main memory in GPU version

When I use the r1.4 GPU version of tensorflow, I found the virtual main memory it takes is too large, but when I use the CPU version, everything is ok. When I use top commands, here are the details:

VIRT: 15.726g, RES: 715824, SHR:295896, SWAP:0, CODE:2728, DATA:860644, MEM:2.2%

In the code, I use the following config:

```<code>config = tf.ConfigProto()
config.gpu_options.allow_growth = True
</code>```

I think it isn't related to the main virtual memory.

Has someone encountered similar problems? I see somebody says that it is the problem caused by cuda, but no solutions found.

答:
This is Unified Virtual Address space which is a normal behavior since compute capability 2.0

When the application is run as a 64-bit process, a single address space is used for the host and all the devices of compute capability 2.0 and higher.

So, it's expected to see the large amount of Virtual memory to be used by any CUDA program (such as TensorFlow gpu version)

Body:
When I use the r1.4 GPU version of tensorflow, I found the virtual main memory it takes is too large, but when I use the CPU version, everything is ok. When I use top commands, here are the details:

VIRT: 15.726g, RES: 715824, SHR:295896, SWAP:0, CODE:2728, DATA:860644, MEM:2.2%

In the code, I use the following config:

config = tf.ConfigProto()
config.gpu_options.allow_growth = True

I think it isn't related to the main virtual memory.

Has someone encountered similar problems? I see somebody says that it is the problem caused by cuda, but no solutions found.


问:
Sending JSON through JQuery to Java
I have a URL that accepts JSON through a post method. It should return a cookie and status.

When I try the following, (the username and password should be the JSON I'm trying to send) , I get no response, any ideas?

```<code><script>
$.post("https://login-url",{"username":"user","password":"1234567890"},
function(data){
     alert("Data Loaded: " + data);
   }, "JSON" );
</script>
</code>```

UPDATE:

After following DavidDorward's comment my code looks like this:

```<code><script>
$.ajax({
    url: 'https://loginurl',
    type: 'POST',
    data: '{"username":"user","password":"1234567890"}',
    contentType: 'application/json',
    dataType: 'text',
    success: function(msg){
     alert("Data Loaded win: " + msg);}
</code>```

});

```<code></script>
</code>```

To describe my error a little better, a status should be returned, and a cookie. When I load this page firefox, and watch using firebug, there is no response, and no cookie information loaded in the header. Although it does seem to hit the URL, this makes me think its still a problem with the data. Although if the username and password are incorrect it should return an error, which is doesn't. It just consistently returns "null".

And to answer mattb's question, the login URL is only expecting "username" and "password" in JSON format and string datatype

答: If you want to use jQuery make a POST request with a JSON body, then you have to use the ajax method rather then one of the simpler alternatives. Specify the contentType as "application/json", convert your JavaScript object to a String containing JSON before assigning it to the data property.

Title: Sending JSON through JQuery to Java

Body:
I have a URL that accepts JSON through a post method. It should return a cookie and status.

When I try the following, (the username and password should be the JSON I'm trying to send) , I get no response, any ideas?

UPDATE:

After following DavidDorward's comment my code looks like this:

To describe my error a little better, a status should be returned, and a cookie. When I load this page firefox, and watch using firebug, there is no response, and no cookie information loaded in the header. Although it does seem to hit the URL, this makes me think its still a problem with the data. Although if the username and password are incorrect it should return an error, which is doesn't. It just consistently returns "null".

And to answer mattb's question, the login URL is only expecting "username" and "password" in JSON format and string datatype


问:
Continuation is not displaying Result
The Following code does not display the resutl:

```<code>static void Main(string[] args)
{
    Task<DayOfWeek> taskA = Task.Run(() => DateTime.Today.DayOfWeek);
    Task continuation = taskA.ContinueWith(antecedent => Console.WriteLine("\n\nToday is {0}.", antecedent.Result));
}
</code>```

This can be solved by:

```<code>try
{
      taskA.Wait();
      continuation.Wait();
}
catch (AggregateException ae)
{
  foreach (var ex in ae.InnerExceptions)
  Console.WriteLine(ex.Message);
}
</code>```

答: Add Console.ReadKey() at the and of Main because you program exits before task prints anything.

Title: Continuation is not displaying Result

Body:
The Following code does not display the resutl:

static void Main(string[] args)
{
    Task<DayOfWeek> taskA = Task.Run(() => DateTime.Today.DayOfWeek);
    Task continuation = taskA.ContinueWith(antecedent => Console.WriteLine("\n\nToday is {0}.", antecedent.Result));
}

This can be solved by:

try
{
      taskA.Wait();
      continuation.Wait();
}
catch (AggregateException ae)
{
  foreach (var ex in ae.InnerExceptions)
  Console.WriteLine(ex.Message);
}


问:
Regex to match rails get index urls
I'm trying to create a regex to match only index urls (with or without parameters) in rails.

The following three match what I expect:

```<code>regex = /^http:\/\/localhost:3000\/v2\/manufacturers\/?(\S+)?$/
regex.match?('http://localhost:3000/v2/manufacturers?enabled=true')
#=> true
regex.match?('http://localhost:3000/v2/manufacturers/')
#=> true
regex.match?('http://localhost:3000/v2/manufacturers')
#=> true
</code>```

I expect the regex not to match these:

```<code>regex.match?('http://localhost:3000/v2/manufacturers/1')
#=> true
regex.match?('http://localhost:3000/v2/manufacturers/123')
#=> true
regex.match?('http://localhost:3000/v2/manufacturers/1?enabled=true')
#=> true
</code>```

Edit:

I'm so sorry but I forgot to mention that it should match:

```<code>regex.match?('http://localhost:3000/v2/manufacturers/1/models')
</code>```

as it is a valid index url

答:
You could change the end of your regex from:

```<code>\/?(\S+)?$/
</code>```

to:

```<code>\/?(?:\?\S+|\d+\/\S+)?$
</code>```

That would create an optional noncapturing group (?:\?\S+|\d+\/\S+)?.

Match \?\S+ for your questionmark and non whitespace chars

or |

Match \d+\/\S+for the added case of 1/models

Demo

Title: Regex to match rails get index urls

Body:
I'm trying to create a regex to match only index urls (with or without parameters) in rails.

The following three match what I expect:

regex = /^http:\/\/localhost:3000\/v2\/manufacturers\/?(\S+)?$/
regex.match?('http://localhost:3000/v2/manufacturers?enabled=true')
#=> true
regex.match?('http://localhost:3000/v2/manufacturers/')
#=> true
regex.match?('http://localhost:3000/v2/manufacturers')
#=> true

I expect the regex not to match these:

regex.match?('http://localhost:3000/v2/manufacturers/1')
#=> true
regex.match?('http://localhost:3000/v2/manufacturers/123')
#=> true
regex.match?('http://localhost:3000/v2/manufacturers/1?enabled=true')
#=> true

Edit:

I'm so sorry but I forgot to mention that it should match:

regex.match?('http://localhost:3000/v2/manufacturers/1/models')

as it is a valid index url

Body:
You could change the end of your regex from:

\/?(\S+)?$/

to:

\/?(?:\?\S+|\d+\/\S+)?$

That would create an optional noncapturing group (?:\?\S+|\d+\/\S+)?.

Match \?\S+ for your questionmark and non whitespace chars

or |

Match \d+\/\S+for the added case of 1/models

Demo


问:
Initialization of an ArrayList in one line
I wanted to create a list of options for testing purposes. At first, I did this:

```<code>ArrayList<String> places = new ArrayList<String>();
places.add("Buenos Aires");
places.add("Córdoba");
places.add("La Plata");
</code>```

Then, I refactored the code as follows:

```<code>ArrayList<String> places = new ArrayList<String>(
    Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));
</code>```

Is there a better way to do this?

答:
Why not make a simple utility function that does this?

```<code>static <A> ArrayList<A> ll(A... a) {
  ArrayList l = new ArrayList(a.length);
  for (A x : a) l.add(x);
  return l;
}
</code>```

"ll" stands for "literal list".

```<code>ArrayList<String> places = ll("Buenos Aires", "Córdoba", "La Plata");
</code>```

Body:
I wanted to create a list of options for testing purposes. At first, I did this:

ArrayList<String> places = new ArrayList<String>();
places.add("Buenos Aires");
places.add("Córdoba");
places.add("La Plata");

Then, I refactored the code as follows:

ArrayList<String> places = new ArrayList<String>(
    Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));

Is there a better way to do this?

Body:
Why not make a simple utility function that does this?

static <A> ArrayList<A> ll(A... a) {
  ArrayList l = new ArrayList(a.length);
  for (A x : a) l.add(x);
  return l;
}

"ll" stands for "literal list".

ArrayList<String> places = ll("Buenos Aires", "Córdoba", "La Plata");


问:
SQL for applying conditions to multiple rows in a join
I think I found the answer to my question, I'm just unsure of the syntax, I keep getting SQL errors.

Basically, I want to do the opposite of IN. Take this example:

```<code>SELECT *
  FROM users INNER JOIN
       tags ON tags.user_id = users.id
 WHERE tags.name IN ('tag1', 'tag2');
</code>```

The above will return ANY users that have 'tag1' OR 'tag2'. I want users that have BOTH. They must have both tags to be returned. I'm assuming the keyword ALL should be used, but can't get it to work.

Thanks for your help.

答:
```<code>SELECT Users.id, count(tags.*) as tagCount
FROM Users Inner join tags
ON tags.user_id = users.id
WHERE tags.name='tag1' OR tags.name='tag2'
GROUP BY Users.id
HAVING count(tags.*) = 2
</code>```

Body:
I think I found the answer to my question, I'm just unsure of the syntax, I keep getting SQL errors.

Basically, I want to do the opposite of IN. Take this example:

SELECT *
  FROM users INNER JOIN
       tags ON tags.user_id = users.id
 WHERE tags.name IN ('tag1', 'tag2');

The above will return ANY users that have 'tag1' OR 'tag2'. I want users that have BOTH. They must have both tags to be returned. I'm assuming the keyword ALL should be used, but can't get it to work.

Thanks for your help.


问:
React native infinite scrollview with next previous buttons
I want to create a Infinite ScrollView like react-native-infinte-scrollview in which views are created and deleted on scroll but this plugin doesn't provide next/previous buttons. I just want to add next and previous buttons because I have 10 gif files in my project and each gif is 7 to 10 MB in size and if I load all these gif files at the same time in scrollview, my app crashed.</p>

答:
i dont know about this but i have logic here </p>

```<code>constructor(){
  this.state = {
    pageNUmber:0,
    data:['url1','url2',url3]
  }
}

renderGif(){
  var data = this.state.data;
  return(
    <Image source={{uri:data[this.state.pageNUmber]}} ?>
  )
}

changePage(val){
  if(val=='next'){
    this.setState({
      pageNumber:this.state.pageNumber+1
    })
  }else{
    if(this.state.pageNumber!=0)
      this.setState({
        pageNumber:this.state.pageNumber-1
      })
  }

}

render(){
  return(
  <View>
    <ScrollView>
      {this.renderGif()}
    </ScrollView>
    <TouchableOpacity onPress={()=>{this.changePage('next')}}>
      <Text>next</Text>
    </TouchableOpacity>
    <TouchableOpacity onPress={()=>{this.changePage('previous')}}>
      <Text>previous</Text>
    </TouchableOpacity>
  </View>
  )
}
</code>```

Body:
i dont know about this but i have logic here

constructor(){
  this.state = {
    pageNUmber:0,
    data:['url1','url2',url3]
  }
}

renderGif(){
  var data = this.state.data;
  return(
    <Image source={{uri:data[this.state.pageNUmber]}} ?>
  )
}

changePage(val){
  if(val=='next'){
    this.setState({
      pageNumber:this.state.pageNumber+1
    })
  }else{
    if(this.state.pageNumber!=0)
      this.setState({
        pageNumber:this.state.pageNumber-1
      })
  }

}

render(){
  return(
  <View>
    <ScrollView>
      {this.renderGif()}
    </ScrollView>
    <TouchableOpacity onPress={()=>{this.changePage('next')}}>
      <Text>next</Text>
    </TouchableOpacity>
    <TouchableOpacity onPress={()=>{this.changePage('previous')}}>
      <Text>previous</Text>
    </TouchableOpacity>
  </View>
  )
}


问:
How can I switch to another branch in git?
Which one of these lines is correct?

```<code>git checkout 'another_branch'
</code>```

or

```<code>git checkout origin 'another_branch'
</code>```

or

```<code>git checkout origin/'another_branch'
</code>```

And what is the difference between them?

答:
Switching to another branch in git. Straightforward answer,

git-checkout - Switch branches or restore working tree files

```<code>git fetch origin         <----this will fetch the branch
git checkout branch_name <--- Switching the branch
</code>```

Before switching the branch make sure you don't have any modified files, in that case, you can commit the changes or you can stash it.

Body:
Which one of these lines is correct?

git checkout 'another_branch'

or

git checkout origin 'another_branch'

or

git checkout origin/'another_branch'

And what is the difference between them?

Body:
Switching to another branch in git. Straightforward answer,

git-checkout - Switch branches or restore working tree files

git fetch origin         <----this will fetch the branch
git checkout branch_name <--- Switching the branch

Before switching the branch make sure you don't have any modified files, in that case, you can commit the changes or you can stash it.


问:
Integrating New Relic with Celery
I am trying to configure New Relic to work with Celery.  I am working on a Django application hosted on Amazon EC2 w/ CentOS 7.

I thought all I needed to do to configure New Relic for celery was to edit the following line in /etc/systemd/system/celery.service

:

ExecStart=/home/myuser/project/venv/bin/celery -A project worker -l info -c 4

and change it to:

ExecStart=/home/myuser/project/newrelic.ini newrelic-admin run-program celery -A project worker -l info -c 4

But I see the following errors:

[root@ip-172-31-60-222 system]# systemctl daemon-reload
[root@ip-172-31-60-222 system]# systemctl restart celery
[root@ip-172-31-60-222 system]# systemctl status celery.service -l
● celery.service - datasidekick celery service
   Loaded: loaded (/etc/systemd/system/celery.service; enabled; vendor preset: disabled)
   Active: failed (Result: start-limit) since Wed 2017-03-01 04:16:33 UTC; 900ms ago
  Process: 22969 ExecStart=/home/datasidekick/datasidekick/newrelic.ini newrelic-admin run-program /home/datasidekick/datasidekick/venv/bin/celery -A datasidekick worker -l info -c 4 (code=exited, status=203/EXEC)
 Main PID: 22969 (code=exited, status=203/EXEC)

Mar 01 04:16:33 ip-172-31-60-222.ec2.internal systemd[1]: Unit celery.service entered failed state.
Mar 01 04:16:33 ip-172-31-60-222.ec2.internal systemd[1]: celery.service failed.
Mar 01 04:16:33 ip-172-31-60-222.ec2.internal systemd[1]: celery.service holdoff time over, scheduling restart.
Mar 01 04:16:33 ip-172-31-60-222.ec2.internal systemd[1]: start request repeated too quickly for celery.service
Mar 01 04:16:33 ip-172-31-60-222.ec2.internal systemd[1]: Failed to start datasidekick celery service.
Mar 01 04:16:33 ip-172-31-60-222.ec2.internal systemd[1]: Unit celery.service entered failed state.
Mar 01 04:16:33 ip-172-31-60-222.ec2.internal systemd[1]: celery.service failed.
```

I'm not sure what I'm doing wrong.  Any help is greatly appreciated!

答:
run journalctl -u celery -fand paste logs here
also have look at this links

https://docs.newrelic.com/docs/agents/python-agent/back-end-services/python-agent-celery

https://discuss.newrelic.com/t/need-some-help-setting-up-new-relic-with-our-celery-workers/30181

Title: Integrating New Relic with Celery

Body:
I am trying to configure New Relic to work with Celery.  I am working on a Django application hosted on Amazon EC2 w/ CentOS 7.

I thought all I needed to do to configure New Relic for celery was to edit the following line in /etc/systemd/system/celery.service

:

ExecStart=/home/myuser/project/venv/bin/celery -A project worker -l info -c 4

and change it to:

ExecStart=/home/myuser/project/newrelic.ini newrelic-admin run-program celery -A project worker -l info -c 4

But I see the following errors:

[root@ip-172-31-60-222 system]# systemctl daemon-reload
[root@ip-172-31-60-222 system]# systemctl restart celery
[root@ip-172-31-60-222 system]# systemctl status celery.service -l
● celery.service - datasidekick celery service
   Loaded: loaded (/etc/systemd/system/celery.service; enabled; vendor preset: disabled)
   Active: failed (Result: start-limit) since Wed 2017-03-01 04:16:33 UTC; 900ms ago
  Process: 22969 ExecStart=/home/datasidekick/datasidekick/newrelic.ini newrelic-admin run-program /home/datasidekick/datasidekick/venv/bin/celery -A datasidekick worker -l info -c 4 (code=exited, status=203/EXEC)
 Main PID: 22969 (code=exited, status=203/EXEC)

Mar 01 04:16:33 ip-172-31-60-222.ec2.internal systemd[1]: Unit celery.service entered failed state.
Mar 01 04:16:33 ip-172-31-60-222.ec2.internal systemd[1]: celery.service failed.
Mar 01 04:16:33 ip-172-31-60-222.ec2.internal systemd[1]: celery.service holdoff time over, scheduling restart.
Mar 01 04:16:33 ip-172-31-60-222.ec2.internal systemd[1]: start request repeated too quickly for celery.service
Mar 01 04:16:33 ip-172-31-60-222.ec2.internal systemd[1]: Failed to start datasidekick celery service.
Mar 01 04:16:33 ip-172-31-60-222.ec2.internal systemd[1]: Unit celery.service entered failed state.
Mar 01 04:16:33 ip-172-31-60-222.ec2.internal systemd[1]: celery.service failed.

I'm not sure what I'm doing wrong.  Any help is greatly appreciated!


问:
Dilema with heading, nav, and floating
I used another post (positioning an image next to a menu bar with html/css), and it worked well, but now my heading is acting really weird!  If you look at the result of the example code in full screen, you'll see some of it is stuck next to my menu bar. May someone please help me?  I want my heading to be BELOW my menu bar.

body {
    font-family: sans-serif;
}
h1 {
    font-family: comic sans ms;
    float: top;
}
nav ul {
    list-style-type: none;
    background-color: blue;
    border: 4px solid orange;
    border-radius: 500px;
    font-family: sans-serif;
    font-weight: bold;
    padding: 16px;
}
nav ul li {
    display: inline;
    border-right: 2px solid orange;
    padding-right: 8px;
    padding-left: 8px;
}
nav ul li:last-child {
    border-right: none;
}
nav ul li a {
    text-decoration: none;
    color: orange;
}
nav {
    display: inline;
}
div {
    float: left;
}
nav {
    float: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
    <title>Example</title>
    <link type="text/css" rel="stylesheet" href="css/example.css"/>
    <div>
        <img src="images/example.jpg">
    </div>
    <nav>
        <ul>
            <li>Home</li>
            <li>Example</li>
            <li>Random</li>
            <li>Blah Blah</li>
            <li>Other</li>
            <li>Something Else</li>
            <li>More</li>
        </ul>
    </nav>
</head>
<body>
    <h1>Example Example Example Example Example Example Example</h1>
</body>
</html></code>```

答:
Your html is invalid, you're not supposed to place those html tags inside the . Anyway, I think your css is way too invasive, setting a float for every div on the page? Definitely too aggressive, I removed some of those unnecessary floats and set the nav to be inline-block

body {
    font-family: sans-serif;
}
h1 {
    font-family: comic sans ms;
}
nav {
display: inline-block;
}
nav ul {
    list-style-type: none;
    background-color: blue;
    border: 4px solid orange;
    border-radius: 500px;
    font-family: sans-serif;
    font-weight: bold;
    padding: 16px;
}
nav ul li {
    display: inline;
    border-right: 2px solid orange;
    padding-right: 8px;
    padding-left: 8px;
}
nav ul li:last-child {
    border-right: none;
}
nav ul li a {
    text-decoration: none;
    color: orange;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
    <title>Example</title>
    <link type="text/css" rel="stylesheet" href="css/example.css"/>
</head>
<body>
  <div>
        <img src="images/example.jpg">
    </div>
    <nav>
        <ul>
            <li>Home</li>
            <li>Example</li>
            <li>Random</li>
            <li>Blah Blah</li>
            <li>Other</li>
            <li>Something Else</li>
            <li>More</li>
        </ul>
    </nav>
    <h1>Example Example Example Example Example Example Example</h1>
</body>
</html></code>```

Title: Dilema with heading, nav, and floating

Body:
I used another post (positioning an image next to a menu bar with html/css), and it worked well, but now my heading is acting really weird!  If you look at the result of the example code in full screen, you'll see some of it is stuck next to my menu bar. May someone please help me?  I want my heading to be BELOW my menu bar.

body {
    font-family: sans-serif;
}
h1 {
    font-family: comic sans ms;
    float: top;
}
nav ul {
    list-style-type: none;
    background-color: blue;
    border: 4px solid orange;
    border-radius: 500px;
    font-family: sans-serif;
    font-weight: bold;
    padding: 16px;
}
nav ul li {
    display: inline;
    border-right: 2px solid orange;
    padding-right: 8px;
    padding-left: 8px;
}
nav ul li:last-child {
    border-right: none;
}
nav ul li a {
    text-decoration: none;
    color: orange;
}
nav {
    display: inline;
}
div {
    float: left;
}
nav {
    float: left;
}

<!DOCTYPE html>

    <title>Example</title>
    <link type="text/css" rel="stylesheet" href="css/example.css"/>

Home

Example

Random

Blah Blah

Other

Something Else

More

Example Example Example Example Example Example Example

Body:
Your html is invalid, you're not supposed to place those html tags inside the <head>. Anyway, I think your css is way too invasive, setting a float for every div on the page? Definitely too aggressive, I removed some of those unnecessary floats and set the nav to be inline-block

body {
    font-family: sans-serif;
}
h1 {
    font-family: comic sans ms;
}
nav {
display: inline-block;
}
nav ul {
    list-style-type: none;
    background-color: blue;
    border: 4px solid orange;
    border-radius: 500px;
    font-family: sans-serif;
    font-weight: bold;
    padding: 16px;
}
nav ul li {
    display: inline;
    border-right: 2px solid orange;
    padding-right: 8px;
    padding-left: 8px;
}
nav ul li:last-child {
    border-right: none;
}
nav ul li a {
    text-decoration: none;
    color: orange;
}

<!DOCTYPE html>
<html>
<head>
    <title>Example</title>
    <link type="text/css" rel="stylesheet" href="css/example.css"/>
</head>
<body>
  <div>
        <img src="images/example.jpg">
    </div>
    <nav>
        <ul>
            <li><a href="home.html">Home</a></li>
            <li><a href="example.html">Example</a></li>
            <li><a href="random.html">Random</a></li>
            <li><a href="blah-blah.html">Blah Blah</a></li>
            <li><a href="other.html">Other</a></li>
            <li><a href="something-else.html">Something Else</a></li>
            <li><a href="more.html">More</a></li>
        </ul>
    </nav>
    <h1>Example Example Example Example Example Example Example</h1>
</body>
</html>


问:
WPF hide slider track
I'm using WPF (and the MVVM framework) to create an interface which has a slider on it.

```<code><Slider Value="{Binding MotorDemandSpeed}" Maximum="3500" />
</code>```

I'm trying to hide the track part on the slider so that you are left with just the 'thumb tack'. This is what the slider currently looks like (styles are controlled by a theme):

I've looked around at various methods, however I can't find a method that changes only a single slider.

Help is appreciated.

答:
In order to change the appearance of a control you will need to modify the control template. Each control is made up of many parts, and each part many objects. You can modify individual parts (such as the track) with the correct x:Key and TargetType.

This Question has an example of modifying a scrollbar control template, which is most likely similar to the template of this slider you have. The first step would be to identify the Xaml file in your theme which this slider uses and find the parts that define the trackbar, thumb, etc. From there you should be able to recreate the control to your liking, or just completely remove parts you do not need.

Are you using any third party controls that may have information on how to edit their themes? Perhaps try investigating Modifying Control Templates to get a better understanding of control templates.

Here is the MDSN page for the slider control template, you may find this useful.

Title: WPF hide slider track

Body:
I'm using WPF (and the MVVM framework) to create an interface which has a slider on it.

<Slider Value="{Binding MotorDemandSpeed}" Maximum="3500" />

I'm trying to hide the track part on the slider so that you are left with just the 'thumb tack'. This is what the slider currently looks like (styles are controlled by a theme):

I've looked around at various methods, however I can't find a method that changes only a single slider.

Help is appreciated.


问:
How can i get background colour decimals?

I'm trying to read background color which i set in decimals e.g rgb(44.9, 19.373737, 255)
using this code

```<code>$("p").css("background-color")
</code>```

but when used it keeps rounding it into rgb(45, 19, 255)

all i want to achieve is to get it in decimals

This is the sample code:

```<code><script>
$(document).ready(function(){
    $("button").click(function(){
        alert("Background color = " + $("p").css("background-color"));
    });
});
</script>
</head>
<body>

<h2>This is a heading</h2>

<p style="background-color:rgb(44.9, 19.373737, 255)">This is a paragraph.</p>

<button>Return background-color of p</button>
</code>```

答:
I'm fan of testing.

Let's pretend we don't know colours are made of integers and let's test:

Let's make 4 divs, one with your decimal values and 3 with red and green rounded up or down.

Next let's verify the output using a photo app like photofilter

https://jsfiddle.net/vgrtky7g/

The first div don't show in jsfiddle, don't show in chrome but shows in firefox and edge which is a good enough warning.

If you run the code in firefox you will get :

#2D13FF for both rgb(44.9, 19.373737, 255) and rgb(45, 19, 255) which means firefox was nice enough to round to the nearer integer.

Don't rely on browser kindness and use integers !

Body:
I'm trying to read background color which i set in decimals e.g rgb(44.9, 19.373737, 255)
using this code

$("p").css("background-color")

but when used it keeps rounding it into rgb(45, 19, 255)

all i want to achieve is to get it in decimals

This is the sample code:

This is a heading

This is a paragraph.

<button>Return background-color of p</button>


问:
What are the disadvantages of double ended dynamic array data structure?
Dynamic array is a well-known data structure: we allocate, for example, an array for 8 elements and use these slots while inserting to the end of the array. When we are out of slots, we allocate an array of size 16 and so on. And we get O(1) amortized complexity of inserting to the end. Dynamic arrays are implemented in a lot of languages and their standard libraries.

One of the limitations here is that inserting to the beginning of the array is O(n) because there are no free slots at the beginning. But why not to have some free slots both at the beginning and at the end of the array? It makes inserting on both ends O(1) and if we run out of free slots on either side we allocate a bigger array as usual.

It will be less memory efficient than one ended dynamic array (because we need to maintain free slots on both sides), but it's not a bad tradeoff for having O(1) inserts on both sides. Or is it? Are there any other disadvantages? I haven't seen this data structure implemented anywhere, what is its fatal flaw?

答:
Here's my personal take. Like you said, dynamic arrays are pretty straightforward and commonplace, but they definitely don't perform greatly with insertions at the beginning. Something like what you suggest, increasing the size of the array on both ends, is a possibility, and maybe it works fine in some cases, but the algorithm is not as clear as it may look. When growing the internal array, do you always add slack on both ends or only on the side that has been exhausted? Or do you try to keep both margins balanced? This may affect greatly the space efficiency of the structure, in a way that is probably not easy to predict.

On the other hand, if you are going to need insertions at both ends, you can probably use a dynamic circular array. Many implementations of circular arrays have a fixed maximum size, but there is nothing really stopping you from making it dynamic. You can even implement it on top of some dynamic array implementation. Circular arrays introduce a small overhead of adding the base index (which you would need anyway with double-ended slack) and computing the modulo, but they have a predictable and space-efficient behavior.


问:
Load balancing of process load balancer
I have a loadbalancer named LB1, which balance between my 2 ip when it receive a request on *.domain.com. I have put a max_fails and a fail_timeout in order to redirect trafic on the other when one is down :

```<code>upstream upstreamdomain {

   least_conn;

   server X.X.X.1 max_fails=1 fail_timeout=10s;
   server X.X.X.2 max_fails=1 fail_timeout=10s;

 }

server {

    listen 80;
    server_name ~^(?<subdomain>.+)\.domain.com;

    location / {

        proxy_set_header Host $subdomain.domain.com;

        proxy_pass http://upstreamdomain;

    }

}
</code>```

On each X.X.X.1 and X.X.X.2 i have my applications running on Y process, and i manage the loadbalancing between process with nginx too

```<code>upstream defaultupstream {
    least_conn;

    server 127.0.0.1:9000 max_fails=1 fail_timeout=10s;
    server 127.0.0.1:9001 max_fails=1 fail_timeout=10s;
    server 127.0.0.1:9002 max_fails=1 fail_timeout=10s;
 }
server {
    listen 80;
    server_name ~^(?<subdomain>.+)\.domain.com;

    location / {
       proxy_set_header Host $subdomain.domain.com;
       proxy_pass http://defaultupstream;
    }
 }
</code>```

When a server is crashing down i want that LB1 redirect trafic on the other, and it works well.

When a process is crashing on X.X.X.1 or X.X.X.2 i want that nginx redirect trafic on other process, and it works well.

The problem i have its when all process are crashing on X.X.X.1 or X.X.X.2 the nginx on X.X.X.1 or X.X.X.2 return 502 server unavailable

It seems that the 502 response not increasing the max_fails on LB1, LB1 is still considering the server with no working process as alive.

How can i configure nginx on LB1 in order to eval 502 as a fail ?
If its not possible, on X.X.X.1 and X.X.X.2 what i have to repond (503, 504 . ?) in order that my LB1 consider the server as down ?

---------------------- EDIT ------------------

Thanks to oklas, fix by adding the following line in LB1 configuration, in order to force nginx to change the upstream on error, timeout or http 502, 503 and 504:

```<code>proxy_next_upstream error timeout http_502 http_503 http_504;
</code>```

LB1 conf is now :

```<code>upstream upstreamdomain {

   least_conn;

   server X.X.X.1 max_fails=1 fail_timeout=10s;
   server X.X.X.2 max_fails=1 fail_timeout=10s;

 }

server {

    listen 80;
    server_name ~^(?<subdomain>.+)\.domain.com;

    location / {

        proxy_set_header Host $subdomain.domain.com;

        proxy_pass http://upstreamdomain;
        proxy_next_upstream error timeout http_502 http_503 http_504;
    }

}
</code>```

Thanks in advance.
Regards

答:
Specify directive which declare conditions to switch to another server in your frontend server:

```<code>proxy_next_upstream http_502;
</code>```

Also take into account relaited things:

to replace error code with another

```<code>error_page 404 =200 /.nop.html;
</code>```

close current connection by condition

```<code>if (condition) {
   return 444;
}
</code>```

where 444 is nginx special error code mean close current connection

Title: Load balancing of process load balancer

Body:
I have a loadbalancer named LB1, which balance between my 2 ip when it receive a request on *.domain.com. I have put a max_fails and a fail_timeout in order to redirect trafic on the other when one is down :

upstream upstreamdomain {

   least_conn;

   server X.X.X.1 max_fails=1 fail_timeout=10s;
   server X.X.X.2 max_fails=1 fail_timeout=10s;

 }

server {

    listen 80;
    server_name ~^(?<subdomain>.+)\.domain.com;

    location / {

        proxy_set_header Host $subdomain.domain.com;

        proxy_pass http://upstreamdomain;

    }

}

On each X.X.X.1 and X.X.X.2 i have my applications running on Y process, and i manage the loadbalancing between process with nginx too

upstream defaultupstream {
    least_conn;

    server 127.0.0.1:9000 max_fails=1 fail_timeout=10s;
    server 127.0.0.1:9001 max_fails=1 fail_timeout=10s;
    server 127.0.0.1:9002 max_fails=1 fail_timeout=10s;
 }
server {
    listen 80;
    server_name ~^(?<subdomain>.+)\.domain.com;

    location / {
       proxy_set_header Host $subdomain.domain.com;
       proxy_pass http://defaultupstream;
    }
 }

When a server is crashing down i want that LB1 redirect trafic on the other, and it works well.

When a process is crashing on X.X.X.1 or X.X.X.2 i want that nginx redirect trafic on other process, and it works well.

The problem i have its when all process are crashing on X.X.X.1 or X.X.X.2 the nginx on X.X.X.1 or X.X.X.2 return 502 server unavailable

It seems that the 502 response not increasing the max_fails on LB1, LB1 is still considering the server with no working process as alive.

How can i configure nginx on LB1 in order to eval 502 as a fail ?
If its not possible, on X.X.X.1 and X.X.X.2 what i have to repond (503, 504 . ?) in order that my LB1 consider the server as down ?

---------------------- EDIT ------------------

Thanks to oklas, fix by adding the following line in LB1 configuration, in order to force nginx to change the upstream on error, timeout or http 502, 503 and 504:

proxy_next_upstream error timeout http_502 http_503 http_504;

LB1 conf is now :

upstream upstreamdomain {

   least_conn;

   server X.X.X.1 max_fails=1 fail_timeout=10s;
   server X.X.X.2 max_fails=1 fail_timeout=10s;

 }

server {

    listen 80;
    server_name ~^(?<subdomain>.+)\.domain.com;

    location / {

        proxy_set_header Host $subdomain.domain.com;

        proxy_pass http://upstreamdomain;
        proxy_next_upstream error timeout http_502 http_503 http_504;
    }

}

Thanks in advance.
Regards

Body:
Specify directive which declare conditions to switch to another server in your frontend server:

proxy_next_upstream http_502;

Also take into account relaited things:

to replace error code with another

error_page 404 =200 /.nop.html;

close current connection by condition

if (condition) {
   return 444;
}

where 444 is nginx special error code mean close current connection