问:
Javascript mocha testing "it" function never entered
I want to Test my JavaScript Code with the mocha and chai Library. I'm working from this tutorial.

I want to test the code at work, but i am not able to use node.js (security stuff).

The problem is that the describe function is entered but never called.

HTML:

```<code><!DOCTYPE html>
<html>
    <head>
        <meta charset="IST-8859-1">
        <title>Insert Title Here</title>
        <link rel="stylesheet" type="text/css" ref="./mocha.css">
    </head>
    <body>
        <div id="mocha"></div>
        <script type="text/javascript" src="./mocha.js"></script>
        <script type="text/javascript" src="./chai.js"></script>

        <script>mocha.setup('bdd');</script>

        <script type="text/javascript" src="./testmocha.js"></script>

        <script>mocha.run</script>
    </body>
</html>
</code>```

JS

```<code>var assert = chai.assert;

describe('Array', function(){
    console.log("inside2");

    it("teest", function() {
        console.log("it 01");
        var arr = [];
        assert.equal(arr.length, 0);
    });

    it("teests", function(){
        var arr = [];
        assert.equal(arr.length, 1);
    });

    console.log("inside3");
})
</code>```

The console log "it 01" will never be shown.. but the "inside 2" and the "inside 3".
the html files stays empty.

Have anyone a idea?

答:
You forgot the parentheses to invoke the .run function. Try this instead:

```<code><script>mocha.run();</script>
</code>```

Body:
I want to Test my JavaScript Code with the mocha and chai Library. I'm working from this tutorial.

I want to test the code at work, but i am not able to use node.js (security stuff).

The problem is that the describe function is entered but never called.

HTML:

<!DOCTYPE html>

        <meta charset="IST-8859-1">
        <title>Insert Title Here</title>
        <link rel="stylesheet" type="text/css" ref="./mocha.css">

JS

var assert = chai.assert;

describe('Array', function(){
    console.log("inside2");

    it("teest", function() {
        console.log("it 01");
        var arr = [];
        assert.equal(arr.length, 0);
    });

    it("teests", function(){
        var arr = [];
        assert.equal(arr.length, 1);
    });

    console.log("inside3");
})

The console log "it 01" will never be shown.. but the "inside 2" and the "inside 3".
the html files stays empty.

Have anyone a idea?

Body:
You forgot the parentheses to invoke the .run function. Try this instead:

<script>mocha.run();</script>


来源: stackexchange

问:
Change parameters used in function to be applied to dataframe
I would like to apply a function to a dataframe, but change the parameters used in that function. I want to:

assign the parameters (each row of the parameters_df) to be used in the calculation

perform the calculation using the parameters as inputs

calculate some summary inform from that round of calculation (mean score in this example) and record this in the parameters dataframe

repeat the above process using the next line of parameters from the parameters_df

My actual code is more complicated with many more parameters and a more complicated calculation with a variety of outputs, but this shows the principle:

```<code>>>> parameters_df # these are the parameters that I want to loop through
a   b   c  mean_output # (this is what I want to calculate)
1   2   3
1   3   5

>>> calc_df
name  category  score   # output(this is what I want to calculate)
John  a           50
Jill  c           60
Jenny b           70
Jeff  a           80
</code>```

This is my code:

```<code>def set_parameters(row):
    parameter_dict = {a: row['a'], 1:row['b'], 2:row['c']}
    parameter_df['output'] = parameter_df.apply(calc, axis=1)
    return parameter_df['output'].mean(axis = 1)

def calc(row):
    output = parameter_dict[row['parameter_df']] * 2
    return output

parameters_df['mean_score'] = parameters_df.apply(set_parameters, axis = 1)
</code>```

But I get this error code:

("name 'parameter_dict' is not defined", 'occurred at index 0', 'occurred at index 0')

It's like when performing the calc function, it cannot find the parameters dictionary I have defined in set_parameters function, even though the set parameters uses calc function in its calculation.

What am I doing wrong?

答:
You aren't passing the variable between the two functions.  You need to:</p>

```<code>def set_parameters(row):
    parameter_dict = {a: row['a'], 1:row['b'], 2:row['c']}
    parameter_df['output'] = parameter_df.apply(calc, args=(parameter_dict,), axis=1)
    return parameter_df['output'].mean(axis = 1)

def calc(row, parameter_dict):
    output = parameter_dict[row['parameter_df']] * 2
    return output
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I would like to apply a function to a dataframe, but change the parameters used in that function. I want to:

assign the parameters (each row of the parameters_df) to be used in the calculation

perform the calculation using the parameters as inputs

calculate some summary inform from that round of calculation (mean score in this example) and record this in the parameters dataframe

repeat the above process using the next line of parameters from the parameters_df

My actual code is more complicated with many more parameters and a more complicated calculation with a variety of outputs, but this shows the principle:

>>> parameters_df # these are the parameters that I want to loop through
a   b   c  mean_output # (this is what I want to calculate)
1   2   3
1   3   5

>>> calc_df
name  category  score   # output(this is what I want to calculate)
John  a           50
Jill  c           60
Jenny b           70
Jeff  a           80

This is my code:

def set_parameters(row):
    parameter_dict = {a: row['a'], 1:row['b'], 2:row['c']}
    parameter_df['output'] = parameter_df.apply(calc, axis=1)
    return parameter_df['output'].mean(axis = 1)

def calc(row):
    output = parameter_dict[row['parameter_df']] * 2
    return output

parameters_df['mean_score'] = parameters_df.apply(set_parameters, axis = 1)

But I get this error code:

("name 'parameter_dict' is not defined", 'occurred at index 0', 'occurred at index 0')

It's like when performing the calc function, it cannot find the parameters dictionary I have defined in set_parameters function, even though the set parameters uses calc function in its calculation.

What am I doing wrong?

Body:
You aren't passing the variable between the two functions.  You need to:

def set_parameters(row):
    parameter_dict = {a: row['a'], 1:row['b'], 2:row['c']}
    parameter_df['output'] = parameter_df.apply(calc, args=(parameter_dict,), axis=1)
    return parameter_df['output'].mean(axis = 1)

def calc(row, parameter_dict):
    output = parameter_dict[row['parameter_df']] * 2
    return output


问:
Linking errors with qt pcl and vtk
I am trying to compile the PCL tutorial described here and I am facing these linking errors.

Linking CXX executable pcl_visualizer usr/lib/libpq.so.5: undefined
  reference to SSL_get_peer_certificate@OPENSSL_1.0.0'
  usr/lib/libvtkIO.so.5.8.0: undefined reference to
  TIFFReadDirectory@LIBTIFF_4.0' usr/lib/libpq.so.5: undefined
  reference to CRYPTO_num_locks@OPENSSL_1.0.0' usr/lib/libpq.so.5:
  undefined reference to
  SSL_CTX_use_certificate_chain_file@OPENSSL_1.0.0'
  usr/lib/libvtkIO.so.5.8.0: undefined reference to
  TIFFIsTiled@LIBTIFF_4.0' usr/lib/libpq.so.5: undefined reference to
  SSL_use_certificate_file@OPENSSL_1.0.0' usr/lib/libpq.so.5: undefined
  reference to ENGINE_free@OPENSSL_1.0.0' usr/lib/libpq.so.5: undefined
  reference toOPENSSL_config@OPENSSL_1.0.0' usr/lib/libpq.so.5:
  undefined reference to SSL_get_error@OPENSSL_1.0.0'
  usr/lib/libpq.so.5: undefined reference to
  SSL_use_PrivateKey_file@OPENSSL_1.0.0' usr/lib/libpq.so.5: undefined
  reference to X509_STORE_load_locations@OPENSSL_1.0.0'
  usr/lib/libvtkIO.so.5.8.0: undefined reference to
  TIFFDefaultStripSize@LIBTIFF_4.0' usr/lib/libvtkIO.so.5.8.0:
  undefined reference to TIFFReadTile@LIBTIFF_4.0' usr/lib/libpq.so.5:
  undefined reference toSSL_set_ex_data@OPENSSL_1.0.0'
  usr/lib/libvtkIO.so.5.8.0: undefined reference to
  TIFFWriteScanline@LIBTIFF_4.0' usr/lib/libvtkIO.so.5.8.0: undefined
  reference to_TIFFfree@LIBTIFF_4.0' usr/lib/libpq.so.5: undefined
  reference to SSL_read@OPENSSL_1.0.0' usr/lib/libvtkIO.so.5.8.0:
  undefined reference toTIFFGetField@LIBTIFF_4.0'
  usr/lib/libvtkIO.so.5.8.0: undefined reference to
  TIFFScanlineSize@LIBTIFF_4.0' usr/lib/libpq.so.5: undefined reference
  toX509_STORE_set_flags@OPENSSL_1.0.0' usr/lib/libpq.so.5: undefined
  reference to SSLv23_method@OPENSSL_1.0.0' usr/lib/libpq.so.5:
  undefined reference toENGINE_load_private_key@OPENSSL_1.0.0'
  usr/lib/libpq.so.5: undefined reference to
  X509_get_subject_name@OPENSSL_1.0.0' usr/lib/libpq.so.5: undefined
  reference toCRYPTO_set_id_callback@OPENSSL_1.0.0'
  usr/lib/libvtkIO.so.5.8.0: undefined reference to
  TIFFClose@LIBTIFF_4.0' usr/lib/libvtkIO.so.5.8.0: undefined reference
  toTIFFClientOpen@LIBTIFF_4.0' usr/lib/libpq.so.5: undefined
  reference to SSL_CTX_new@OPENSSL_1.0.0' usr/lib/libpq.so.5: undefined
  reference toSSL_CTX_get_cert_store@OPENSSL_1.0.0'
  usr/lib/libpq.so.5: undefined reference to
  SSL_check_private_key@OPENSSL_1.0.0' usr/lib/libvtkIO.so.5.8.0:
  undefined reference toTIFFGetFieldDefaulted@LIBTIFF_4.0'
  usr/lib/libpq.so.5: undefined reference to
  ENGINE_by_id@OPENSSL_1.0.0' usr/lib/libvtkIO.so.5.8.0: undefined
  reference toTIFFNumberOfDirectories@LIBTIFF_4.0' usr/lib/libpq.so.5:
  undefined reference to ERR_get_error@OPENSSL_1.0.0'
  usr/lib/libpq.so.5: undefined reference to
  CRYPTO_set_locking_callback@OPENSSL_1.0.0' usr/lib/libpq.so.5:
  undefined reference to SSL_load_error_strings@OPENSSL_1.0.0'
  usr/lib/libpq.so.5: undefined reference toSSL_new@OPENSSL_1.0.0'
  usr/lib/libpq.so.5: undefined reference to
  X509_NAME_get_text_by_NID@OPENSSL_1.0.0' usr/lib/libvtkIO.so.5.8.0:
  undefined reference toTIFFOpen@LIBTIFF_4.0' usr/lib/libpq.so.5:
  undefined reference to SSL_write@OPENSSL_1.0.0' usr/lib/libpq.so.5:
  undefined reference toX509_free@OPENSSL_1.0.0' usr/lib/libpq.so.5:
  undefined reference to SSL_CTX_load_verify_locations@OPENSSL_1.0.0'
  usr/lib/libvtkIO.so.5.8.0: undefined reference to
  TIFFReadRGBAImage@LIBTIFF_4.0' usr/lib/libpq.so.5: undefined
  reference to SSL_free@OPENSSL_1.0.0' usr/lib/libpq.so.5: undefined
  reference toSSL_ctrl@OPENSSL_1.0.0' usr/lib/libvtkIO.so.5.8.0:
  undefined reference to TIFFSetField@LIBTIFF_4.0' usr/lib/libpq.so.5:
  undefined reference toSSL_set_verify@OPENSSL_1.0.0'
  usr/lib/libpq.so.5: undefined reference to ENGINE_init@OPENSSL_1.0.0'
  usr/lib/libpq.so.5: undefined reference toSSL_set_fd@OPENSSL_1.0.0'
  usr/lib/libpq.so.5: undefined reference to SSL_connect@OPENSSL_1.0.0'
  usr/lib/libpq.so.5: undefined reference to
  ERR_reason_error_string@OPENSSL_1.0.0' usr/lib/libpq.so.5: undefined
  reference to SSL_CTX_ctrl@OPENSSL_1.0.0' usr/lib/libpq.so.5:
  undefined reference toSSL_pending@OPENSSL_1.0.0' usr/lib/libpq.so.5:
  undefined reference to SSL_use_PrivateKey@OPENSSL_1.0.0'
  usr/lib/libvtkIO.so.5.8.0: undefined reference to
  TIFFSetWarningHandler@LIBTIFF_4.0' usr/lib/libpq.so.5: undefined
  reference to ENGINE_finish@OPENSSL_1.0.0' usr/lib/libvtkIO.so.5.8.0:
  undefined reference toTIFFSetErrorHandler@LIBTIFF_4.0'
  usr/lib/libvtkIO.so.5.8.0: undefined reference to
  _TIFFmalloc@LIBTIFF_4.0' usr/lib/libpq.so.5: undefined reference to
  SSL_library_init@OPENSSL_1.0.0' usr/lib/libvtkIO.so.5.8.0: undefined
  reference to TIFFSetDirectory@LIBTIFF_4.0' usr/lib/libvtkIO.so.5.8.0:
  undefined reference toTIFFReadScanline@LIBTIFF_4.0'
  usr/lib/libpq.so.5: undefined reference to
  SSL_shutdown@OPENSSL_1.0.0' usr/lib/libvtkIO.so.5.8.0: undefined
  reference toTIFFNumberOfTiles@LIBTIFF_4.0' collect2: error: ld
  returned 1 exit status make[2]: * [pcl_visualizer] Error 1 make1:
  * [CMakeFiles/pcl_visualizer.dir/all] Error 2 make: *** [all] Error 2

The CmakeList file is define as follow:

```<code>cmake_minimum_required (VERSION 2.6 FATAL_ERROR)

project      (pcl-visualizer)
find_package (Qt4 REQUIRED)
find_package (VTK REQUIRED)
find_package (PCL 1.7.1 REQUIRED)

include_directories (${PCL_INCLUDE_DIRS})
link_directories    (${PCL_LIBRARY_DIRS})
add_definitions     (${PCL_DEFINITIONS})

set  (project_SOURCES main.cpp pclviewer.cpp)
set  (project_HEADERS pclviewer.h)
set  (project_FORMS   pclviewer.ui)
set  (VTK_LIBRARIES   vtkRendering vtkGraphics vtkHybrid QVTK)

QT4_WRAP_CPP (project_HEADERS_MOC   ${project_HEADERS})
QT4_WRAP_UI  (project_FORMS_HEADERS ${project_FORMS})

INCLUDE         (${QT_USE_FILE})
ADD_DEFINITIONS (${QT_DEFINITIONS})

ADD_EXECUTABLE  (pcl_visualizer ${project_SOURCES}
                                ${project_FORMS_HEADERS}
                                ${project_HEADERS_MOC})

TARGET_LINK_LIBRARIES (pcl_visualizer ${QT_LIBRARIES} ${PCL_LIBRARIES} ${VTK_LIBRARIES})
</code>```

Is there anything missing in the CMakeList file?

答:
As mentioned in the comments, anaconda is the problem.

Rename your anaconda folder to anaconda-temp so that the link in your path variable is incorrect for cmake during its scan. Then install qt5-default using sudo apt-get install qt5-default as that solved both the errors in my case. Then rerun cmake and now it should detect qt5 in the correct location (i.e. not in the anaconda path).

Now run make and then finally you can rename anaconda-temp to anaconda so that it corresponds to your path and the value in bashrc and it's business as usual.

Title: Linking errors with qt pcl and vtk

Body:
I am trying to compile the PCL tutorial described here and I am facing these linking errors.

Linking CXX executable pcl_visualizer usr/lib/libpq.so.5: undefined
  reference to SSL_get_peer_certificate@OPENSSL_1.0.0'
  usr/lib/libvtkIO.so.5.8.0: undefined reference to
  TIFFReadDirectory@LIBTIFF_4.0' usr/lib/libpq.so.5: undefined
  reference to CRYPTO_num_locks@OPENSSL_1.0.0' usr/lib/libpq.so.5:
  undefined reference to
  SSL_CTX_use_certificate_chain_file@OPENSSL_1.0.0'
  usr/lib/libvtkIO.so.5.8.0: undefined reference to
  TIFFIsTiled@LIBTIFF_4.0' usr/lib/libpq.so.5: undefined reference to
  SSL_use_certificate_file@OPENSSL_1.0.0' usr/lib/libpq.so.5: undefined
  reference to ENGINE_free@OPENSSL_1.0.0' usr/lib/libpq.so.5: undefined
  reference toOPENSSL_config@OPENSSL_1.0.0' usr/lib/libpq.so.5:
  undefined reference to SSL_get_error@OPENSSL_1.0.0'
  usr/lib/libpq.so.5: undefined reference to
  SSL_use_PrivateKey_file@OPENSSL_1.0.0' usr/lib/libpq.so.5: undefined
  reference to X509_STORE_load_locations@OPENSSL_1.0.0'
  usr/lib/libvtkIO.so.5.8.0: undefined reference to
  TIFFDefaultStripSize@LIBTIFF_4.0' usr/lib/libvtkIO.so.5.8.0:
  undefined reference to TIFFReadTile@LIBTIFF_4.0' usr/lib/libpq.so.5:
  undefined reference toSSL_set_ex_data@OPENSSL_1.0.0'
  usr/lib/libvtkIO.so.5.8.0: undefined reference to
  TIFFWriteScanline@LIBTIFF_4.0' usr/lib/libvtkIO.so.5.8.0: undefined
  reference to_TIFFfree@LIBTIFF_4.0' usr/lib/libpq.so.5: undefined
  reference to SSL_read@OPENSSL_1.0.0' usr/lib/libvtkIO.so.5.8.0:
  undefined reference toTIFFGetField@LIBTIFF_4.0'
  usr/lib/libvtkIO.so.5.8.0: undefined reference to
  TIFFScanlineSize@LIBTIFF_4.0' usr/lib/libpq.so.5: undefined reference
  toX509_STORE_set_flags@OPENSSL_1.0.0' usr/lib/libpq.so.5: undefined
  reference to SSLv23_method@OPENSSL_1.0.0' usr/lib/libpq.so.5:
  undefined reference toENGINE_load_private_key@OPENSSL_1.0.0'
  usr/lib/libpq.so.5: undefined reference to
  X509_get_subject_name@OPENSSL_1.0.0' usr/lib/libpq.so.5: undefined
  reference toCRYPTO_set_id_callback@OPENSSL_1.0.0'
  usr/lib/libvtkIO.so.5.8.0: undefined reference to
  TIFFClose@LIBTIFF_4.0' usr/lib/libvtkIO.so.5.8.0: undefined reference
  toTIFFClientOpen@LIBTIFF_4.0' usr/lib/libpq.so.5: undefined
  reference to SSL_CTX_new@OPENSSL_1.0.0' usr/lib/libpq.so.5: undefined
  reference toSSL_CTX_get_cert_store@OPENSSL_1.0.0'
  usr/lib/libpq.so.5: undefined reference to
  SSL_check_private_key@OPENSSL_1.0.0' usr/lib/libvtkIO.so.5.8.0:
  undefined reference toTIFFGetFieldDefaulted@LIBTIFF_4.0'
  usr/lib/libpq.so.5: undefined reference to
  ENGINE_by_id@OPENSSL_1.0.0' usr/lib/libvtkIO.so.5.8.0: undefined
  reference toTIFFNumberOfDirectories@LIBTIFF_4.0' usr/lib/libpq.so.5:
  undefined reference to ERR_get_error@OPENSSL_1.0.0'
  usr/lib/libpq.so.5: undefined reference to
  CRYPTO_set_locking_callback@OPENSSL_1.0.0' usr/lib/libpq.so.5:
  undefined reference to SSL_load_error_strings@OPENSSL_1.0.0'
  usr/lib/libpq.so.5: undefined reference toSSL_new@OPENSSL_1.0.0'
  usr/lib/libpq.so.5: undefined reference to
  X509_NAME_get_text_by_NID@OPENSSL_1.0.0' usr/lib/libvtkIO.so.5.8.0:
  undefined reference toTIFFOpen@LIBTIFF_4.0' usr/lib/libpq.so.5:
  undefined reference to SSL_write@OPENSSL_1.0.0' usr/lib/libpq.so.5:
  undefined reference toX509_free@OPENSSL_1.0.0' usr/lib/libpq.so.5:
  undefined reference to SSL_CTX_load_verify_locations@OPENSSL_1.0.0'
  usr/lib/libvtkIO.so.5.8.0: undefined reference to
  TIFFReadRGBAImage@LIBTIFF_4.0' usr/lib/libpq.so.5: undefined
  reference to SSL_free@OPENSSL_1.0.0' usr/lib/libpq.so.5: undefined
  reference toSSL_ctrl@OPENSSL_1.0.0' usr/lib/libvtkIO.so.5.8.0:
  undefined reference to TIFFSetField@LIBTIFF_4.0' usr/lib/libpq.so.5:
  undefined reference toSSL_set_verify@OPENSSL_1.0.0'
  usr/lib/libpq.so.5: undefined reference to ENGINE_init@OPENSSL_1.0.0'
  usr/lib/libpq.so.5: undefined reference toSSL_set_fd@OPENSSL_1.0.0'
  usr/lib/libpq.so.5: undefined reference to SSL_connect@OPENSSL_1.0.0'
  usr/lib/libpq.so.5: undefined reference to
  ERR_reason_error_string@OPENSSL_1.0.0' usr/lib/libpq.so.5: undefined
  reference to SSL_CTX_ctrl@OPENSSL_1.0.0' usr/lib/libpq.so.5:
  undefined reference toSSL_pending@OPENSSL_1.0.0' usr/lib/libpq.so.5:
  undefined reference to SSL_use_PrivateKey@OPENSSL_1.0.0'
  usr/lib/libvtkIO.so.5.8.0: undefined reference to
  TIFFSetWarningHandler@LIBTIFF_4.0' usr/lib/libpq.so.5: undefined
  reference to ENGINE_finish@OPENSSL_1.0.0' usr/lib/libvtkIO.so.5.8.0:
  undefined reference toTIFFSetErrorHandler@LIBTIFF_4.0'
  usr/lib/libvtkIO.so.5.8.0: undefined reference to
  _TIFFmalloc@LIBTIFF_4.0' usr/lib/libpq.so.5: undefined reference to
  SSL_library_init@OPENSSL_1.0.0' usr/lib/libvtkIO.so.5.8.0: undefined
  reference to TIFFSetDirectory@LIBTIFF_4.0' usr/lib/libvtkIO.so.5.8.0:
  undefined reference toTIFFReadScanline@LIBTIFF_4.0'
  usr/lib/libpq.so.5: undefined reference to
  SSL_shutdown@OPENSSL_1.0.0' usr/lib/libvtkIO.so.5.8.0: undefined
  reference toTIFFNumberOfTiles@LIBTIFF_4.0' collect2: error: ld
  returned 1 exit status make[2]: * [pcl_visualizer] Error 1 make1:
  * [CMakeFiles/pcl_visualizer.dir/all] Error 2 make: *** [all] Error 2

The CmakeList file is define as follow:

cmake_minimum_required (VERSION 2.6 FATAL_ERROR)

project      (pcl-visualizer)
find_package (Qt4 REQUIRED)
find_package (VTK REQUIRED)
find_package (PCL 1.7.1 REQUIRED)

include_directories (${PCL_INCLUDE_DIRS})
link_directories    (${PCL_LIBRARY_DIRS})
add_definitions     (${PCL_DEFINITIONS})

set  (project_SOURCES main.cpp pclviewer.cpp)
set  (project_HEADERS pclviewer.h)
set  (project_FORMS   pclviewer.ui)
set  (VTK_LIBRARIES   vtkRendering vtkGraphics vtkHybrid QVTK)

QT4_WRAP_CPP (project_HEADERS_MOC   ${project_HEADERS})
QT4_WRAP_UI  (project_FORMS_HEADERS ${project_FORMS})

INCLUDE         (${QT_USE_FILE})
ADD_DEFINITIONS (${QT_DEFINITIONS})

ADD_EXECUTABLE  (pcl_visualizer ${project_SOURCES}
                                ${project_FORMS_HEADERS}
                                ${project_HEADERS_MOC})

TARGET_LINK_LIBRARIES (pcl_visualizer ${QT_LIBRARIES} ${PCL_LIBRARIES} ${VTK_LIBRARIES})

Is there anything missing in the CMakeList file?


问:
How to truncate each directory to n chars in a path using sed/awk?
For example with n being 3, p1ath/p2ath/p3ath would become p1a/p2a/p3?

I don't understand how to:

Truncate a capture group (\1, \2, etc..)   using sed.

How to make the capture groups 'dynamic' rather being a set static number of capture groups?

So far I have 's/\(.*\)\//\1\//g'

答:
With GNU sed:

```<code>echo "p1ath/p2ath/p3ath" | sed -r 's|([^/]{3})[^/]*|\1|g'
</code>```

Output:

```
p1a/p2a/p3a
```

See: The Stack Overflow Regular Expressions FAQ

Body:
With GNU sed:

echo "p1ath/p2ath/p3ath" | sed -r 's|([^/]{3})[^/]*|\1|g'

Output:

p1a/p2a/p3a

See: The Stack Overflow Regular Expressions FAQ


问:
Is it possible to have multiple strings in one position of an array?
For example if my array is

```<code>var cars = ["Saab", "Volvo", "BMW"];
var answer = cars[1];
</code>```

and I create a function where if I type 'Volvo' it says 'Correct'. Is it possible to do something like this:

```<code>var cars = ["Saab", "Volvo|volkswagen", "BMW"];
</code>```

So when I type what is at position 1, I can type Volvo or volkswagen and it will say 'correct'? (But not both)

答:
You can do the following.

function check( array, position, value){
        var values = array[position].split('|');
        if(values.indexOf(value) >= 0)
            alert("Right");
        else alert("wrong");
    }
    var cars = ["Saab", "Volvo|volkswagen", "BMW"];
    value = prompt("What is the value at position 1 ");
    check(cars, 1, value );```

Body:
For example if my array is

var cars = ["Saab", "Volvo", "BMW"];
var answer = cars[1];

and I create a function where if I type 'Volvo' it says 'Correct'. Is it possible to do something like this:

var cars = ["Saab", "Volvo|volkswagen", "BMW"];

So when I type what is at position 1, I can type Volvo or volkswagen and it will say 'correct'? (But not both)


问:
C# winforms, How can I make a Combobox open upwards / Is there one that does?
In C#, a winforms application,

How can I make a Combobox that opens upwards / Is there one that opens upwards?

I see some questions like this but they refer to a WPF application rather than  a winforms one. I'm asking about a winforms application.

答:
This is not easy when working with WinForms, but I could give you my idea.

You should know that even when the combobox visible property is set to false, its' dropdown menu can still be displayed programmatically.
So the idea is that creating a user control that contains 2 comboboxs:

Example of my user control

The upper combobox is invisible. When user clicks the main, below one, the upper one will be relocated and drop down.

```<code>        private void cbb_main_Click(object sender, EventArgs e)
    {
        cbb_2.Location = new Point(cbb_main.Location.X, cbb_main.Location.Y - cbb_2.Size.Height - (cbb_2.ItemHeight *cbb_2.Items.Count));
        cbb_main.DroppedDown = false;
        cbb_2.DroppedDown = true;
    }
</code>```

Finally, add your custom control to the form and give it a try!
Result image here!

I hope this is what you're looking for.

Body:
This is not easy when working with WinForms, but I could give you my idea.

You should know that even when the combobox visible property is set to false, its' dropdown menu can still be displayed programmatically.
So the idea is that creating a user control that contains 2 comboboxs:

Example of my user control

The upper combobox is invisible. When user clicks the main, below one, the upper one will be relocated and drop down.

        private void cbb_main_Click(object sender, EventArgs e)
    {
        cbb_2.Location = new Point(cbb_main.Location.X, cbb_main.Location.Y - cbb_2.Size.Height - (cbb_2.ItemHeight *cbb_2.Items.Count));
        cbb_main.DroppedDown = false;
        cbb_2.DroppedDown = true;
    }

Finally, add your custom control to the form and give it a try!
Result image here!

I hope this is what you're looking for.


问:
How do I get a server timestamp from Firebase's iOS API?
I have an iOS app that uses Firebase and currently has a few dictionaries with keys that are NSDate objects.  The obvious issue with this is that NSDate draws from the device's system time, which is not universal.

With that, what's the best way to get a server timestamp (similar to Firebase.ServerValue.TIMESTAMP for the Web API) using Firebase's iOS API so that I can sort my dictionary keys chronologically?

I'm also aware of the chronological nature of IDs generated by childByAutoID, but I can't figure out the proper way to sort these in code.  While they may be returned in chronological order, any time something like allKeys is called on them, the order goes out the window.

Any help with this issue would be greatly appreciated!

答:
As of Firebase 4.0 you can use ServerValue.timestamp()

for example:

```<code>    let ref = Database.database().reference().child("userExample")
    let values = ["fullName": "Joe Bloggs", "timestamp": ServerValue.timestamp()] as [String : Any]

    ref.updateChildValues(values) { (err, ref) in

        if let err = err {
            print("failed to upload user data", err)
            return
        }

    }
</code>```

Body:
As of Firebase 4.0 you can use ServerValue.timestamp()

for example:

    let ref = Database.database().reference().child("userExample")
    let values = ["fullName": "Joe Bloggs", "timestamp": ServerValue.timestamp()] as [String : Any]

    ref.updateChildValues(values) { (err, ref) in

        if let err = err {
            print("failed to upload user data", err)
            return
        }

    }


问:
Make awk keep ending whitespace
I have a file list with two columns. I need to remove the first column and keep a list of filenames. If I happen to have a file that ends with a space, eg "some file ", the space is removed by awk.

Example with file "input" (notice the space at the end of "some file ")

```<code>abc some file
def some other file
</code>```

Running

```<code>cat input | awk '{$1=""; print substr($0, 2)}' > output
</code>```

will produce the file output

```<code>some file
some other file
</code>```

where "some file " is now "some file" resulting in a non existent file when processing the file list.

Any portable solution is appreciated :)

[EDIT] Tried to simplify the example above in order to make it more clear, but in fact there are more columns so some solutions may not apply.

Actual file is an rsync --list-only output:

```<code>drwxr-xr-x        4096 2017/06/04 11:24:21 .
drwxr-xr-x      234234 2017/06/04 11:24:19 some file
drwxr-xr-x     1341212 2017/06/04 11:24:19 some other file
</code>```

The column that shows filesizes may expand so removing a fixed amount of trailing characters will lead to errors.

Filenames can indeed contain paths and multiple spaces.

Example test file (keep in mind that filesize may vary, so the second column might increase in size):

```<code>drwxr-xr-x        4096 2017/06/04 11:24:21 .
drwxr-xr-x        4096 2017/06/04 11:24:19 another
drwxr-xr-x        4096 2017/06/04 11:24:19 another/one
drwxr-xr-x        4096 2017/06/04 11:24:19 another/one/bites
drwxr-xr-x        4096 2017/06/04 11:24:19 another/one/bites/ de_dust
-rw-r--r--           0 2017/06/04 11:24:19 another/one/bites/ de_dust/ 2017/06/04 11:24:19 Iron Rhapsody
drwxr-xr-x        4096 2017/06/04 11:24:19 phantom of
drwxr-xr-x        4096 2017/06/04 11:24:19 phantom of /the opera
-rw-r--r--           0 2017/06/04 11:24:19 phantom of /the opera/Bohemian Maiden
</code>```

[/EDIT]

答:
```<code>$ awk '{sub(/[^/]+\/.{15}/,"")}1' file
.
another
another/one
another/one/bites
another/one/bites/ de_dust
another/one/bites/ de_dust/ 2017/06/04 11:24:19 Iron Rhapsody
phantom of
phantom of /the opera
phantom of /the opera/Bohemian Maiden
</code>```

or with GNU or OSX sed for -E (with strictly POSIX seds you'd escape the +, {, and }):

```<code>$ sed -E 's:[^/]+/.{15}::' file
.
another
another/one
another/one/bites
another/one/bites/ de_dust
another/one/bites/ de_dust/ 2017/06/04 11:24:19 Iron Rhapsody
phantom of
phantom of /the opera
phantom of /the opera/Bohemian Maiden
</code>```

Title: Make awk keep ending whitespace

Body:
I have a file list with two columns. I need to remove the first column and keep a list of filenames. If I happen to have a file that ends with a space, eg "some file ", the space is removed by awk.

Example with file "input" (notice the space at the end of "some file ")

abc some file
def some other file

Running

cat input | awk '{$1=""; print substr($0, 2)}' > output

will produce the file output

some file
some other file

where "some file " is now "some file" resulting in a non existent file when processing the file list.

Any portable solution is appreciated :)

[EDIT] Tried to simplify the example above in order to make it more clear, but in fact there are more columns so some solutions may not apply.

Actual file is an rsync --list-only output:

drwxr-xr-x        4096 2017/06/04 11:24:21 .
drwxr-xr-x      234234 2017/06/04 11:24:19 some file
drwxr-xr-x     1341212 2017/06/04 11:24:19 some other file

The column that shows filesizes may expand so removing a fixed amount of trailing characters will lead to errors.

Filenames can indeed contain paths and multiple spaces.

Example test file (keep in mind that filesize may vary, so the second column might increase in size):

drwxr-xr-x        4096 2017/06/04 11:24:21 .
drwxr-xr-x        4096 2017/06/04 11:24:19 another
drwxr-xr-x        4096 2017/06/04 11:24:19 another/one
drwxr-xr-x        4096 2017/06/04 11:24:19 another/one/bites
drwxr-xr-x        4096 2017/06/04 11:24:19 another/one/bites/ de_dust
-rw-r--r--           0 2017/06/04 11:24:19 another/one/bites/ de_dust/ 2017/06/04 11:24:19 Iron Rhapsody
drwxr-xr-x        4096 2017/06/04 11:24:19 phantom of
drwxr-xr-x        4096 2017/06/04 11:24:19 phantom of /the opera
-rw-r--r--           0 2017/06/04 11:24:19 phantom of /the opera/Bohemian Maiden

[/EDIT]

Body:
$ awk '{sub(/[^/]+\/.{15}/,"")}1' file
.
another
another/one
another/one/bites
another/one/bites/ de_dust
another/one/bites/ de_dust/ 2017/06/04 11:24:19 Iron Rhapsody
phantom of
phantom of /the opera
phantom of /the opera/Bohemian Maiden

or with GNU or OSX sed for -E (with strictly POSIX seds you'd escape the +, {, and }):

$ sed -E 's:[^/]+/.{15}::' file
.
another
another/one
another/one/bites
another/one/bites/ de_dust
another/one/bites/ de_dust/ 2017/06/04 11:24:19 Iron Rhapsody
phantom of
phantom of /the opera
phantom of /the opera/Bohemian Maiden


问:
Javascript check value does not exist
In Javascript I can do this...

```<code>myvalue = "greenapples"

if ( myvalue ) {
    alert ("My Value is " + myvalue )
}
</code>```

But how do I do the opposite?  I want to display an alert if myvalue is not set.

Anyone have an example I can see?

答:
typeof myvalue === 'undefined' and !myvalue are two ways of checking if a variable exists.

```<code>if ( typeof myvalue === 'undefined' ) {
  alert ("variable does not exist");
}

if ( !myvalue ) {
  alert ("variable does not exist");
}
</code>```

Title: Javascript check value does not exist

Body:
In Javascript I can do this...

myvalue = "greenapples"

if ( myvalue ) {
    alert ("My Value is " + myvalue )
}

But how do I do the opposite?  I want to display an alert if myvalue is not set.

Anyone have an example I can see?

Body:
typeof myvalue === 'undefined' and !myvalue are two ways of checking if a variable exists.

if ( typeof myvalue === 'undefined' ) {
  alert ("variable does not exist");
}

if ( !myvalue ) {
  alert ("variable does not exist");
}


问:
Scenebuilder has no ButtonBar
I'm starting to work with SceneBuilder and want to add a ButtonBar. But the interface doesn't show the ButtonBar.

I am using SceneBuilder 2.0.

I can add the ButtonBar in the FXML file manually.

How can I add the ButtonBar in SceneBuilder?

Thanks for your help!

答: It turned out that the problem was that I downloaded from Oracle. Now I found out that I needed the one from Gluon, there I can add the ButtonBar.</p>

Title: Scenebuilder has no ButtonBar


问:
check if string contains only unique chars using .at(int)
Really basic question but I can't figure this out.  My program checks if a string is unique by setting flags for each ASCII in an array to true if found in the string.  It's not working(it compiles, but doesn't give correct answer), and I can't for the life of my figure out why.

The output I get is 0:

main.cpp

```<code>#include "main.hpp"
#include <iostream>

bool isUnique(std::string str) {

    if(str.length() > 128)
        return false;

    bool theChars[128];

    for(int i = 0; i < str.length(); i++) {
        int loc = str.at(i);

        if(theChars[loc])
            return false;
        else
            theChars[loc] = true;
    }

    return true;
}

int main() {

    std::string timmy = "abcdefghijklmnop";
    std::cout << isUnique(timmy);

    return 0;
}
</code>```

答:
You forgot to initialize the bool array:

```<code>bool theChars[128] = {};
</code>```

The empty initializer means "use the default value" which is zero, aka false for bool.

P.S. Your code produces undefined behavior if you have any character outside [0, 127].  You could fix this by making theChars 256 long and casting the character to uint8_t before indexing.  Or use std::array<char, 128> and theChars.at(loc) to throw an exception if out of bounds.

Body:
Really basic question but I can't figure this out.  My program checks if a string is unique by setting flags for each ASCII in an array to true if found in the string.  It's not working(it compiles, but doesn't give correct answer), and I can't for the life of my figure out why.

The output I get is 0:

main.cpp

#include "main.hpp"
#include <iostream>

bool isUnique(std::string str) {

    if(str.length() > 128)
        return false;

    bool theChars[128];

    for(int i = 0; i < str.length(); i++) {
        int loc = str.at(i);

        if(theChars[loc])
            return false;
        else
            theChars[loc] = true;
    }

    return true;
}

int main() {

    std::string timmy = "abcdefghijklmnop";
    std::cout << isUnique(timmy);

    return 0;
}

Body:
You forgot to initialize the bool array:

bool theChars[128] = {};

The empty initializer means "use the default value" which is zero, aka false for bool.

P.S. Your code produces undefined behavior if you have any character outside [0, 127].  You could fix this by making theChars 256 long and casting the character to uint8_t before indexing.  Or use std::array<char, 128> and theChars.at(loc) to throw an exception if out of bounds.


问:
Magento - Add custom modules to Google sitemap
I have custom modules (that I bought or developed) that have frontend pages in my store.
How can I include these pages in the Google sitemap Magento generates? </p>

答:
Magento did add the events sitemap_products_generating_before and sitemap_categories_generating_before in later versions (I don't know when, my version is 1.9.2). So in case you stumple upon this thread like me, looking for the best way to add custom modules' pages to the Google Sitemap, this is how simple it is with these events:

In my case I have a custom module that creates dynamic "News" pages, so I add an event listener to the <global> tag in my module's config.xml. I chose to go with the product sitemap event*:

```<code>    <events>
        <sitemap_products_generating_before>
            <observers>
                <{your_unique_event_observer_name}>
                    <class>{Brand}_{Module}_Model_Observer</class>
                    <method>addPagesToSitemap</method>
                </{your_unique_event_observer_name}>
            </observers>
        </sitemap_products_generating_before>
    </events>
</code>```

And then, in my module's Observer, I let the method addPagesToSitemap add extra items to the product collection (or category collecton, if you went with the category sitemap event):

```<code>class {Brand}_{Module}_Model_Observer
{
    function addPagesToSitemap(Varien_Event_Observer $observer){

        $sitemapItems = $observer->getEvent()->getCollection()->getItems();

        // Get your module's page collection including their urls
        // Adjust the following lines to your needs
        $collection = Mage::getModel('{brand}_{module}/pages')->getCollection()
            ->addFieldToSelect(array('page_id','url'))
            ->addFieldToFilter('display', 1);
        // My module stores the page path separately,
        // you might don't need this:
        $modulePagePath = Mage::helper('{my-modules-helper}')->getNewsPath();

        foreach($collection as $_item){
            $varienObject = new Varien_Object();
            // We don't want to override
            // any existing product/category items
            $uniqueId = '{module}'.$_item->getPageId();
            $varienObject->setId($uniqueId);

            // You might want to adjust this if your item
            // stores the complete url. Don't add the base url tho,
            // Mage_Sitemap_Model_Sitemap::generateXml adds it
            $varienObject->setUrl($modulePagePath . DS . $_item->getUrl());

            $sitemapItems[$uniqueId] = $varienObject;
        }
        $observer->getEvent()->getCollection()->setItems($sitemapItems);

        return $this;
    }
}
</code>```

That's it. You can test it by manually generating your sitemap under Catalog > Google Sitemap.

*For some reasons Magento did not add an event "sitemap_pages_generating_before", so you have to either choose the products' or category's event to go with. For both events Magento takes the respective changefreq- and priority-value set for category & product pages in your Magento configuration. So just choose the event which values fit better.

Body:
Magento did add the events sitemap_products_generating_before and sitemap_categories_generating_before in later versions (I don't know when, my version is 1.9.2). So in case you stumple upon this thread like me, looking for the best way to add custom modules' pages to the Google Sitemap, this is how simple it is with these events:

In my case I have a custom module that creates dynamic "News" pages, so I add an event listener to the <global> tag in my module's config.xml. I chose to go with the product sitemap event*:

    <events>
        <sitemap_products_generating_before>
            <observers>
                <{your_unique_event_observer_name}>
                    <class>{Brand}_{Module}_Model_Observer</class>
                    <method>addPagesToSitemap</method>
                </{your_unique_event_observer_name}>
            </observers>
        </sitemap_products_generating_before>
    </events>

And then, in my module's Observer, I let the method addPagesToSitemap add extra items to the product collection (or category collecton, if you went with the category sitemap event):

class {Brand}_{Module}_Model_Observer
{
    function addPagesToSitemap(Varien_Event_Observer $observer){

        $sitemapItems = $observer->getEvent()->getCollection()->getItems();

        // Get your module's page collection including their urls
        // Adjust the following lines to your needs
        $collection = Mage::getModel('{brand}_{module}/pages')->getCollection()
            ->addFieldToSelect(array('page_id','url'))
            ->addFieldToFilter('display', 1);
        // My module stores the page path separately,
        // you might don't need this:
        $modulePagePath = Mage::helper('{my-modules-helper}')->getNewsPath();

        foreach($collection as $_item){
            $varienObject = new Varien_Object();
            // We don't want to override
            // any existing product/category items
            $uniqueId = '{module}'.$_item->getPageId();
            $varienObject->setId($uniqueId);

            // You might want to adjust this if your item
            // stores the complete url. Don't add the base url tho,
            // Mage_Sitemap_Model_Sitemap::generateXml adds it
            $varienObject->setUrl($modulePagePath . DS . $_item->getUrl());

            $sitemapItems[$uniqueId] = $varienObject;
        }
        $observer->getEvent()->getCollection()->setItems($sitemapItems);

        return $this;
    }
}

That's it. You can test it by manually generating your sitemap under Catalog > Google Sitemap.

*For some reasons Magento did not add an event "sitemap_pages_generating_before", so you have to either choose the products' or category's event to go with. For both events Magento takes the respective changefreq- and priority-value set for category & product pages in your Magento configuration. So just choose the event which values fit better.


问:
Java unique ID generator
How to generator unique order id for customer order, check mysql primary keys.
I need ids like this,

OID000001

OID000002

OID000003

When 2 clients open order form next id shown as OID000004 but when save 2 oders I got error - primary key duplication.

I need when 1st client open order form id should be OID000004 and 2nd client's order form id should be OID000005.

How to fix this bug?

答: You mentioned MySQL. If you are using SQL, you can use  AUTO_INCREMENT to automatically assign id's when a new one is added to the database.

Title: Java unique ID generator


问:
Help beginner understand threads
I have an array of MyThreads (seen below) running, but they produce incorrect results. What is the problem here?

```<code>import java.util.*;
class MyThread extends Thread {
  public static long N;
  public static long sum = 0;
  synchronized public void inc() {
    sum++;
  }
  public void run() {
    for (long i = 0; i < N; i++) {
      inc();
    }
  }
  public MyThread(long num) {
    N = num;
  }
}
</code>```

My guess is that the threads are interrupting each other, causing the incorrect results, but I don't understand where or how.

答:
First, it appears that N is a per-thread iteration count, so it shouldn't be static.

Second, since sum is a static member, your inc method should also be static, otherwise you won't be synchronizing on the static fields of the class.

ContentLicense: CC BY-SA 2.5

Title: Help beginner understand threads

Body:
I have an array of MyThreads (seen below) running, but they produce incorrect results. What is the problem here?

import java.util.*;
class MyThread extends Thread {
  public static long N;
  public static long sum = 0;
  synchronized public void inc() {
    sum++;
  }
  public void run() {
    for (long i = 0; i < N; i++) {
      inc();
    }
  }
  public MyThread(long num) {
    N = num;
  }
}

My guess is that the threads are interrupting each other, causing the incorrect results, but I don't understand where or how.


问:
Filter records in a list based on DateTime in Linq
Below is my list I want to find the recent and the most transacted branch based on datetime.ie: A branch which has got 100 deposits in the last  2 months would come first comparing to a bank which has about 150 deposits in the last 5 months</p>

```<code>     List<Branches> _branches = new List< Branches >
                {
                    new Branch
                    {
                        Id = 1,
                        Name = "Branch:1",
                        Deposits = new List<Deposit>(){
                        new Deposit{
                            Id=1,
                            DateOfDeposit="01/01/2016",
                            Amount=50
                        },
    ,
                        new Deposit{
                            Id=2,
                            DateOfDeposit="05/02/2017",
                            Price=30
                        },
                        new Deposit{
                            Id=3,
                            DateOfDeposit="01/01/2017",
                            Price=30
                        }
                    }
                    },continues...
</code>```

答:
What you are comparing can't be done.  You are asking to change two comparisons at the same time.  You can only compare items with the same criteria.  Using code below will get you started.</p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Data;
using System.Globalization;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Branch> branches = new List<Branch>() {
                new Branch() {
                    Id = 1,
                    Name = "Branch:1",
                    Deposits = new List<Deposit>(){
                        new Deposit{
                            Id=1,
                            DateOfDeposit = DateTime.ParseExact("01/01/2016","dd/MM/yyyy",CultureInfo.InvariantCulture),
                            Amount=50
                        },
                        new Deposit() {
                            Id=2,
                            DateOfDeposit = DateTime.ParseExact("05/02/2017","dd/MM/yyyy",CultureInfo.InvariantCulture),
                            Amount = 30
                        },
                        new Deposit() {
                            Id=3,
                            DateOfDeposit = DateTime.ParseExact("01/01/2017","dd/MM/yyyy",CultureInfo.InvariantCulture),
                            Amount = 30
                        }
                    }
                },
                new Branch() {
                    Id = 2,
                    Name = "Branch:2",
                    Deposits = new List<Deposit>() {
                        new Deposit{
                            Id=1,
                            DateOfDeposit = DateTime.ParseExact("01/01/2016","dd/MM/yyyy",CultureInfo.InvariantCulture),
                            Amount=50
                        },
                        new Deposit() {
                            Id=2,
                            DateOfDeposit = DateTime.ParseExact("05/02/2017","dd/MM/yyyy",CultureInfo.InvariantCulture),
                            Amount = 30
                        },
                        new Deposit() {
                            Id=3,
                            DateOfDeposit = DateTime.ParseExact("01/01/2017","dd/MM/yyyy",CultureInfo.InvariantCulture),
                            Amount = 30
                        }
                    }
                }
            };

            var results = branches.Select(x => new {
                Id = x.Id,
                month1Deposits = x.Deposits.Where(y => y.DateOfDeposit >= DateTime.Now.AddMonths(-1)).Count(),
                month2Deposits = x.Deposits.Where(y => y.DateOfDeposit >= DateTime.Now.AddMonths(-2)).Count(),
                month3Deposits = x.Deposits.Where(y => y.DateOfDeposit >= DateTime.Now.AddMonths(-3)).Count(),
                month4Deposits = x.Deposits.Where(y => y.DateOfDeposit >= DateTime.Now.AddMonths(-4)).Count(),
                month5Deposits = x.Deposits.Where(y => y.DateOfDeposit >= DateTime.Now.AddMonths(-5)).Count(),
                month6Deposits = x.Deposits.Where(y => y.DateOfDeposit >= DateTime.Now.AddMonths(-6)).Count(),
                month7Deposits = x.Deposits.Where(y => y.DateOfDeposit >= DateTime.Now.AddMonths(-7)).Count(),
                month8Deposits = x.Deposits.Where(y => y.DateOfDeposit >= DateTime.Now.AddMonths(-8)).Count(),
                month9Deposits = x.Deposits.Where(y => y.DateOfDeposit >= DateTime.Now.AddMonths(-8)).Count(),
                month10Deposits = x.Deposits.Where(y => y.DateOfDeposit >= DateTime.Now.AddMonths(-10)).Count(),
                month11Deposits = x.Deposits.Where(y => y.DateOfDeposit >= DateTime.Now.AddMonths(-11)).Count(),
                month12Deposits = x.Deposits.Where(y => y.DateOfDeposit >= DateTime.Now.AddMonths(-12)).Count()
            }).ToList();

        }
    }
    public class Branch
    {
        public int Id { get; set;}
        public string Name { get; set;}
        public List<Deposit> Deposits { get; set;}

    }
    public class Deposit
    {
        public int Id { get; set;}
        public DateTime  DateOfDeposit { get; set;}
        public int Amount { get; set;}
    }

}
</code>```

Body:
Below is my list I want to find the recent and the most transacted branch based on datetime.ie: A branch which has got 100 deposits in the last  2 months would come first comparing to a bank which has about 150 deposits in the last 5 months

     List<Branches> _branches = new List< Branches >
                {
                    new Branch
                    {
                        Id = 1,
                        Name = "Branch:1",
                        Deposits = new List<Deposit>(){
                        new Deposit{
                            Id=1,
                            DateOfDeposit="01/01/2016",
                            Amount=50
                        },
    ,
                        new Deposit{
                            Id=2,
                            DateOfDeposit="05/02/2017",
                            Price=30
                        },
                        new Deposit{
                            Id=3,
                            DateOfDeposit="01/01/2017",
                            Price=30
                        }
                    }
                    },continues...

Body:
What you are comparing can't be done.  You are asking to change two comparisons at the same time.  You can only compare items with the same criteria.  Using code below will get you started.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Data;
using System.Globalization;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Branch> branches = new List<Branch>() {
                new Branch() {
                    Id = 1,
                    Name = "Branch:1",
                    Deposits = new List<Deposit>(){
                        new Deposit{
                            Id=1,
                            DateOfDeposit = DateTime.ParseExact("01/01/2016","dd/MM/yyyy",CultureInfo.InvariantCulture),
                            Amount=50
                        },
                        new Deposit() {
                            Id=2,
                            DateOfDeposit = DateTime.ParseExact("05/02/2017","dd/MM/yyyy",CultureInfo.InvariantCulture),
                            Amount = 30
                        },
                        new Deposit() {
                            Id=3,
                            DateOfDeposit = DateTime.ParseExact("01/01/2017","dd/MM/yyyy",CultureInfo.InvariantCulture),
                            Amount = 30
                        }
                    }
                },
                new Branch() {
                    Id = 2,
                    Name = "Branch:2",
                    Deposits = new List<Deposit>() {
                        new Deposit{
                            Id=1,
                            DateOfDeposit = DateTime.ParseExact("01/01/2016","dd/MM/yyyy",CultureInfo.InvariantCulture),
                            Amount=50
                        },
                        new Deposit() {
                            Id=2,
                            DateOfDeposit = DateTime.ParseExact("05/02/2017","dd/MM/yyyy",CultureInfo.InvariantCulture),
                            Amount = 30
                        },
                        new Deposit() {
                            Id=3,
                            DateOfDeposit = DateTime.ParseExact("01/01/2017","dd/MM/yyyy",CultureInfo.InvariantCulture),
                            Amount = 30
                        }
                    }
                }
            };

            var results = branches.Select(x => new {
                Id = x.Id,
                month1Deposits = x.Deposits.Where(y => y.DateOfDeposit >= DateTime.Now.AddMonths(-1)).Count(),
                month2Deposits = x.Deposits.Where(y => y.DateOfDeposit >= DateTime.Now.AddMonths(-2)).Count(),
                month3Deposits = x.Deposits.Where(y => y.DateOfDeposit >= DateTime.Now.AddMonths(-3)).Count(),
                month4Deposits = x.Deposits.Where(y => y.DateOfDeposit >= DateTime.Now.AddMonths(-4)).Count(),
                month5Deposits = x.Deposits.Where(y => y.DateOfDeposit >= DateTime.Now.AddMonths(-5)).Count(),
                month6Deposits = x.Deposits.Where(y => y.DateOfDeposit >= DateTime.Now.AddMonths(-6)).Count(),
                month7Deposits = x.Deposits.Where(y => y.DateOfDeposit >= DateTime.Now.AddMonths(-7)).Count(),
                month8Deposits = x.Deposits.Where(y => y.DateOfDeposit >= DateTime.Now.AddMonths(-8)).Count(),
                month9Deposits = x.Deposits.Where(y => y.DateOfDeposit >= DateTime.Now.AddMonths(-8)).Count(),
                month10Deposits = x.Deposits.Where(y => y.DateOfDeposit >= DateTime.Now.AddMonths(-10)).Count(),
                month11Deposits = x.Deposits.Where(y => y.DateOfDeposit >= DateTime.Now.AddMonths(-11)).Count(),
                month12Deposits = x.Deposits.Where(y => y.DateOfDeposit >= DateTime.Now.AddMonths(-12)).Count()
            }).ToList();

        }
    }
    public class Branch
    {
        public int Id { get; set;}
        public string Name { get; set;}
        public List<Deposit> Deposits { get; set;}

    }
    public class Deposit
    {
        public int Id { get; set;}
        public DateTime  DateOfDeposit { get; set;}
        public int Amount { get; set;}
    }

}


问:
babel preset-env with electron & react
To create an electron & react application I was using the react and node7 presents as follows (which works)

```<code>  "babel": {
    "sourceMaps": "inline",
    "presets": [
      "react",
      "node7"
    ]
  },
</code>```

But I wanted to go with something more future proof so I tried out the preset-env

```<code>  "babel": {
    "sourceMaps": "inline",
    "presets": [
      [
        "env",
        {
          "targets": {
            "electron": "1.6.7"
          },
          "debug": true,
          "useBuiltIns": true
        }
      ]
    ]
  },
</code>```

However this is not working for me. It seems that es7 object spread is not being found, and there are issues with react JSX. What simple thing did I miss?

```<code>babel-preset-env: `DEBUG` option

Using targets:
{
  "electron": "1.6.7"
}

Modules transform: commonjs

Using plugins:
  syntax-trailing-function-commas {"electron":"1.6.7"}

Using polyfills:
  es7.string.pad-start {"electron":"1.6.7"}
  es7.string.pad-end {"electron":"1.6.7"}
  web.timers {"electron":"1.6.7"}
  web.immediate {"electron":"1.6.7"}
  web.dom.iterable {"electron":"1.6.7"}
src\dash\actions.js -> dist\dash\actions.js
src\dash\actionTypes.js -> dist\dash\actionTypes.js
SyntaxError: src/dash/dash.js: Unexpected token (29:18)
  27 |     let stats = remote.getGlobal('DASH').stats
  28 |     //stats.jobStats = (stats.jobStats == "") ? "0" : stats.jobStats  -- we only needed this if the folder was m
issing
> 29 |     let state = { ...STORE.getState().ServerStats }
     |                   ^
  30 |     let original = { ...state }
  31 |     state.WatsonInstalled = (state.WatsonInstalled != stats.watsonInstalled) ? stats.watsonInstalled : state.Wat
sonInstalled
  32 |     state.WatsonRunning = (state.WatsonRunning != stats.watsonRunning) ? stats.watsonRunning : state.WatsonRunni
ng
SyntaxError: src/dash/reducers.js: Unexpected token (18:25)
  16 |     switch (action.type) {
  17 |         case A.SetUpdating:
> 18 |             newState = { ...state, isUpdating: action.payload }
     |                          ^
  19 |             return newState
  20 |         case A.SetChanger:
  21 |             newState = { ...state, fieldName: action.payload }
SyntaxError: src/jsx/Configuration.jsx: Unexpected token (19:4)
  17 |     resetForm,
  18 |     isUpdating,
> 19 |     ...props }) => {
     |     ^
  20 |     COMPONENTS["Configuration"] = props // Register this component in the Dash Components list (so we can get th
e change() function)
  21 |     return (
  22 |         <Form horizontal onSubmit={(e) => { alert('foobar'); handleSubmit(doSubmit) }}>
SyntaxError: src/jsx/Controls.jsx: Unexpected token (7:8)
   5 | const Control = ({ WatsonInstalled, WatsonRunning, FMERunning, buttonAction }) => {
   6 |     return (
>  7 |         <Grid>
     |         ^
   8 |             <Row className="propRow">
   9 |                 <Col sm={3}>
  10 |                     <OverlayTrigger placement="bottom"
SyntaxError: src/jsx/Dashboard.jsx: Unexpected token (12:4)
  10 | const App = ({ GLVersion }) => {
  11 |   return (
> 12 |     <Grid>
|         ^
   8 |             <Row className="propRow">
   9 |                 <Col sm={3}>
  10 |                     <OverlayTrigger placement="bottom"
SyntaxError: src/jsx/Dashboard.jsx: Unexpected token (12:4)
  10 | const App = ({ GLVersion }) => {
  11 |   return (
> 12 |     <Grid>
     |     ^
  13 |       <Row className="versionRow">
  14 |         <Col smOffset={10} sm={1} className="fieldLabel">Version:</Col>
  15 |         <Col sm={1} className="fieldLabel">{GLVersion}</Col>
SyntaxError: src/jsx/FieldInputs.jsx: Unexpected token (9:8)
   7 | const FieldControl = ({ input, meta, type, min, max, tip, cid }) => {
   8 |     return (
>  9 |         <OverlayTrigger placement="left" overlay={(<Tooltip id={cid + "-tip"}>{tip}</Tooltip>)}>
     |         ^
  10 |             <FormControl
  11 |                 type={type}
  12 |                 min={min}
SyntaxError: src/jsx/Utilities.jsx: Unexpected token (9:8)
   7 | const Util = ({ JobsDirSize, killAction }) => {
   8 |     return (
>  9 |         <Grid>
     |         ^
  10 |             <Row className="propRow">
  11 |                 <Col sm={3} className="fieldLabel">Job Folder Size:</Col>
  12 |                 <Col sm={9} className="fieldLabel">{JobsDirSize} MB</Col>
src\main\main.js -> dist\main\main.js
src\main\monitor.js -> dist\main\monitor.js
src\main\utils.js -> dist\main\utils.js
src\main\watson.js -> dist\main\watson.js
</code>```

答: It turns out this is an open issue with this preset:   https://github.com/babel/babel-preset-env/issues/326</p>

Title: babel preset-env with electron & react

Body:
To create an electron & react application I was using the react and node7 presents as follows (which works)

  "babel": {
    "sourceMaps": "inline",
    "presets": [
      "react",
      "node7"
    ]
  },

But I wanted to go with something more future proof so I tried out the preset-env

  "babel": {
    "sourceMaps": "inline",
    "presets": [
      [
        "env",
        {
          "targets": {
            "electron": "1.6.7"
          },
          "debug": true,
          "useBuiltIns": true
        }
      ]
    ]
  },

However this is not working for me. It seems that es7 object spread is not being found, and there are issues with react JSX. What simple thing did I miss?

babel-preset-env: `DEBUG` option

Using targets:
{
  "electron": "1.6.7"
}

Modules transform: commonjs

Using plugins:
  syntax-trailing-function-commas {"electron":"1.6.7"}

Using polyfills:
  es7.string.pad-start {"electron":"1.6.7"}
  es7.string.pad-end {"electron":"1.6.7"}
  web.timers {"electron":"1.6.7"}
  web.immediate {"electron":"1.6.7"}
  web.dom.iterable {"electron":"1.6.7"}
src\dash\actions.js -> dist\dash\actions.js
src\dash\actionTypes.js -> dist\dash\actionTypes.js
SyntaxError: src/dash/dash.js: Unexpected token (29:18)
  27 |     let stats = remote.getGlobal('DASH').stats
  28 |     //stats.jobStats = (stats.jobStats == "") ? "0" : stats.jobStats  -- we only needed this if the folder was m
issing
> 29 |     let state = { ...STORE.getState().ServerStats }
     |                   ^
  30 |     let original = { ...state }
  31 |     state.WatsonInstalled = (state.WatsonInstalled != stats.watsonInstalled) ? stats.watsonInstalled : state.Wat
sonInstalled
  32 |     state.WatsonRunning = (state.WatsonRunning != stats.watsonRunning) ? stats.watsonRunning : state.WatsonRunni
ng
SyntaxError: src/dash/reducers.js: Unexpected token (18:25)
  16 |     switch (action.type) {
  17 |         case A.SetUpdating:
> 18 |             newState = { ...state, isUpdating: action.payload }
     |                          ^
  19 |             return newState
  20 |         case A.SetChanger:
  21 |             newState = { ...state, fieldName: action.payload }
SyntaxError: src/jsx/Configuration.jsx: Unexpected token (19:4)
  17 |     resetForm,
  18 |     isUpdating,
> 19 |     ...props }) => {
     |     ^
  20 |     COMPONENTS["Configuration"] = props // Register this component in the Dash Components list (so we can get th
e change() function)
  21 |     return (
  22 |         <Form horizontal onSubmit={(e) => { alert('foobar'); handleSubmit(doSubmit) }}>
SyntaxError: src/jsx/Controls.jsx: Unexpected token (7:8)
   5 | const Control = ({ WatsonInstalled, WatsonRunning, FMERunning, buttonAction }) => {
   6 |     return (
>  7 |         <Grid>
     |         ^
   8 |             <Row className="propRow">
   9 |                 <Col sm={3}>
  10 |                     <OverlayTrigger placement="bottom"
SyntaxError: src/jsx/Dashboard.jsx: Unexpected token (12:4)
  10 | const App = ({ GLVersion }) => {
  11 |   return (
> 12 |     <Grid>
|         ^
   8 |             <Row className="propRow">
   9 |                 <Col sm={3}>
  10 |                     <OverlayTrigger placement="bottom"
SyntaxError: src/jsx/Dashboard.jsx: Unexpected token (12:4)
  10 | const App = ({ GLVersion }) => {
  11 |   return (
> 12 |     <Grid>
     |     ^
  13 |       <Row className="versionRow">
  14 |         <Col smOffset={10} sm={1} className="fieldLabel">Version:</Col>
  15 |         <Col sm={1} className="fieldLabel">{GLVersion}</Col>
SyntaxError: src/jsx/FieldInputs.jsx: Unexpected token (9:8)
   7 | const FieldControl = ({ input, meta, type, min, max, tip, cid }) => {
   8 |     return (
>  9 |         <OverlayTrigger placement="left" overlay={(<Tooltip id={cid + "-tip"}>{tip}</Tooltip>)}>
     |         ^
  10 |             <FormControl
  11 |                 type={type}
  12 |                 min={min}
SyntaxError: src/jsx/Utilities.jsx: Unexpected token (9:8)
   7 | const Util = ({ JobsDirSize, killAction }) => {
   8 |     return (
>  9 |         <Grid>
     |         ^
  10 |             <Row className="propRow">
  11 |                 <Col sm={3} className="fieldLabel">Job Folder Size:</Col>
  12 |                 <Col sm={9} className="fieldLabel">{JobsDirSize} MB</Col>
src\main\main.js -> dist\main\main.js
src\main\monitor.js -> dist\main\monitor.js
src\main\utils.js -> dist\main\utils.js
src\main\watson.js -> dist\main\watson.js


答:
You can do this in two ways :

one is you can simply use the !(not) operator:

var myvalue = "greenapples";

```<code>if ( !myvalue ) {
    alert ("My Value not set" );
}
</code>```

OR

You can also an else statement:

```<code>var myvalue = "greenapples";

if ( myvalue ) {
   }
else{
    alert ("My Value not set " );
}
</code>```

This is saying if the value of a variable is undefined, then do nothing else alert the user. Or if you want in the context of the first code, it says if the value of variable is not undefined, then execute the program

Using the !(not) operator just saves a little bit of control shift in your program.So you will most likely use the !(not) operator

Title: Javascript check value does not exist

Body:
You can do this in two ways :

one is you can simply use the !(not) operator:

var myvalue = "greenapples";

if ( !myvalue ) {
    alert ("My Value not set" );
}

OR

You can also an else statement:

var myvalue = "greenapples";

if ( myvalue ) {
   }
else{
    alert ("My Value not set " );
}

This is saying if the value of a variable is undefined, then do nothing else alert the user. Or if you want in the context of the first code, it says if the value of variable is not undefined, then execute the program

Using the !(not) operator just saves a little bit of control shift in your program.So you will most likely use the !(not) operator


问:
mysql query regex between 2 words to loop
I need a regex to use in the query select * from table where field regex *** in order to match the record only if my "Gamma" and "Alpha" are, at least in 1, of the same ;between;

I have a text filed in table like:

```<code>... ;Model Alpha Beta Gamma; Model Hitch Gamma Alpha; Model Pi Alpha Gamma; ...
</code>```

or (i can change structure if it is easier)

```<code>....
;Model Alpha Beta Gamma;
;Model Hitch Pi Alpha;
;Model Pi Alpha Gamma;
....
</code>```

So i have different sentences (separeted by ;) in the same field and I need a regex role that consider any sentence as a group in witch looking the presence of some words.

I m using a cms so i need change the query: changing the DB means months of work.

Body:
I need a regex to use in the query select * from table where field regex *** in order to match the record only if my "Gamma" and "Alpha" are, at least in 1, of the same ;between;

I have a text filed in table like:

... ;Model Alpha Beta Gamma; Model Hitch Gamma Alpha; Model Pi Alpha Gamma; ...

or (i can change structure if it is easier)

....
;Model Alpha Beta Gamma;
;Model Hitch Pi Alpha;
;Model Pi Alpha Gamma;
....

So i have different sentences (separeted by ;) in the same field and I need a regex role that consider any sentence as a group in witch looking the presence of some words.

I m using a cms so i need change the query: changing the DB means months of work.

Body:
I believe what you are trying to do is select rows that have a field with a semi-colon-separated-value that has both Alpha & Gamma AND those two values can possibly be in any order respective to each other AND there can be other words between them.

So considering rows that have fields like this:

|field                                                            |
|-----------------------------------------------------------------|
|Model Alpha Beta Gamma;Model Hitch Pi Alpha;Model Pi Alpha Gamma |
|-----------------------------------------------------------------|
|Model Beta Gamma;Model Hitch Pi Alpha;Model Pi Gamma             |
|-----------------------------------------------------------------|
|Model Beta Omega                                                 |
|-----------------------------------------------------------------|
|Model Alpha Gamma                                                |
|-----------------------------------------------------------------|
|Model Pi Beta Gamma;Model Hitch Pi Gamma                         |
|-----------------------------------------------------------------|
|Model Hitch Gamma Sigma Sigma                                    |
|-----------------------------------------------------------------|
|Model Zeta Tau Alpha;Model Alpha Xi Delta                        |
|-----------------------------------------------------------------|
|Model Alpha Epsilon Phi;Model Gamma Phi Alpha                    |
|-----------------------------------------------------------------|
|Model Sigma Gamma Alpha; Model Lambda Lambda Lambda              |
|-----------------------------------------------------------------|
|Model Beta Beta Phi; Model Hitch Lambda Pi; Model Phi Pi         |
|-----------------------------------------------------------------|

You can use this query:

SELECT field FROM `table` WHERE `field` REGEXP 'Alpha[^;]+Gamma|Gamma[^;]+Alpha'

To put these rows in the resultset:

|field                                                            |
|-----------------------------------------------------------------|
|Model Alpha Beta Gamma;Model Hitch Pi Alpha;Model Pi Alpha Gamma |
|-----------------------------------------------------------------|
|Model Alpha Gamma                                                |
|-----------------------------------------------------------------|
|Model Alpha Epsilon Phi;Model Gamma Phi Alpha                    |
|-----------------------------------------------------------------|
|Model Sigma Gamma Alpha; Model Lambda Lambda Lambda              |
|-----------------------------------------------------------------|


问:
How to set same height and width of image using css? Not background image
I have to set images with same height and width.I have three images with different height and width. I have to display the same size in the box. Would you help me in this?

ul {
  list-style: none;
}

ul li {
  width: 200px;
  height: 200px;
  display: inline-block;
  border: 1px solid #000;
}

ul li img {
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li><img src="http://i.imgur.com/tI5jq2c.jpg"></li>
  <li><img src="http://i.imgur.com/37w80TG.jpg"></li>
  <li><img src="http://i.imgur.com/B1MCOtx.jpg"></li>
</ul></code>```

答:
Just add height: 100%; of class ul li img and it will work

ul{
   list-style: none;
}
ul li{
 width: 200px;
 height: 200px;
 display: inline-block;
 border: 1px solid #000;
}
ul li img{
 width: 100%;
 height: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
    <li><img src="http://i.imgur.com/tI5jq2c.jpg"></li>
    <li><img src="http://i.imgur.com/37w80TG.jpg"></li>
    <li><img src="http://i.imgur.com/B1MCOtx.jpg"></li>
</ul></code>```

Body:
Just add height: 100%; of class ul li img and it will work

ul{
   list-style: none;
}
ul li{
 width: 200px;
 height: 200px;
 display: inline-block;
 border: 1px solid #000;
}
ul li img{
 width: 100%;
 height: 100%;
}

<ul>
    <li><img src="http://i.imgur.com/tI5jq2c.jpg"></li>
    <li><img src="http://i.imgur.com/37w80TG.jpg"></li>
    <li><img src="http://i.imgur.com/B1MCOtx.jpg"></li>
</ul>


问:
why there is "ï»¿" when doing file comparison
in the beginning of the file when doing diff.</p>

答:
I've experienced that when the content-encoding is set to something other than UTF8 and the file has been written in utf-8

in php, i used iconv to convert between the types


问:
Convert string to OffsetDateTime in Java
I am trying to convert a string in OffsetDateTime but getting below error.

java.time.format.DateTimeParseException: Text '20150101' could not be parsed: Unable to obtain OffsetDateTime from TemporalAccessor: {},ISO resolved to 2015-01-01 of type java.time.format.Parsed

Code : OffsetDateTime.parse("20150101", DateTimeFormatter.ofPattern("yyyyMMdd"));

Expected output: OffsetDateTime object with date 20150101.

I really appreciate any help you can provide.

Thanks,

答:
Thanks everyone for your reply.
Earlier I was using joda datetime (look at below method) to handle date and datetime both but I wanted to use Java8 libraries instead of the external libraries.

```<code>static public DateTime convertStringInDateFormat(String date, String dateFormat){
    DateTimeFormatter formatter = DateTimeFormat.forPattern(dateFormat);
return formatter.parseDateTime(date);
}
</code>```

I was expecting same with OffsetDateTime but got to know we can use ZonedDateTime or OffsetDateTime if we want to work with a date/time in a certain time zone.
As I am working on Period and Duration for which LocalDate can help.

String to DateTime:

```<code>LocalDate date =
LocalDate.parse("20150101", DateTimeFormatter.ofPattern("yyyyMMdd"));
</code>```

LocalDate to desired string format:

```<code>String dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'";
date.atStartOfDay().format(DateTimeFormatter.ofPattern(dateFormat));
</code>```

Body:
Thanks everyone for your reply.
Earlier I was using joda datetime (look at below method) to handle date and datetime both but I wanted to use Java8 libraries instead of the external libraries.

static public DateTime convertStringInDateFormat(String date, String dateFormat){
    DateTimeFormatter formatter = DateTimeFormat.forPattern(dateFormat);
return formatter.parseDateTime(date);
}

I was expecting same with OffsetDateTime but got to know we can use ZonedDateTime or OffsetDateTime if we want to work with a date/time in a certain time zone.
As I am working on Period and Duration for which LocalDate can help.

String to DateTime:

LocalDate date =
LocalDate.parse("20150101", DateTimeFormatter.ofPattern("yyyyMMdd"));

LocalDate to desired string format:

String dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'";
date.atStartOfDay().format(DateTimeFormatter.ofPattern(dateFormat));


问:
How to check limit range from csv file in python script
I am trying to fetch some values from database and need to check some lower and upper limits of a variables which are store in a text file like this and they are separated by \t. the text file looks like

```<code>Variable      lower_limit   upper_limit
temperature   20            40
pressure      0             100
temperature2  0             30
temperature3  20            25
</code>```

and the data in database looks like

```<code>usec        temperature_data    temperature2_data
1456411800  25                  15
1456412400  45                  25
1456413000  28                  19
</code>```

So i start with checking first whether the variable is in the text file, if yes then i would need to check the limits of that variable. until now i am only successful in verifying the name of the variable, but i am unable to check the limits.
my code is as follow

```<code>#!/usr/bin/env python
# -*- coding: utf-8 -*-

import datetime as dt
import sys
import time
import datetime
import calendar
import numpy as np
import mysql.connector
import datetime
import numpy as np
import pandas as pd
import mysql.connector
from mysql.connector import errorcode

# starting day, month and year
start_day = dt.datetime(2016, 02, 25)
# total number of dates to visualize
number = 11
num_total = 11
# enter limit range
upper_limit = 250 # these are hardcode values which i want to
                    replace and instead of hard code , i want to
                    check these limits values from the text file
lower_limit = 0
# start day in epoch time format
start_time = 1456411800

# variable name and filepath
filepath = '/home/robbyy/files/limit.txt'
vari_name = 'temperature2'

# database name, user and password details and query to fetch   respective data
usr = 'roby'
password = 'xxxx'
db_name = 'roby_data'
insert_query = ("SELECT usec , temperature2_data "
            "FROM rob_table WHERE usec >= %s "
            "AND usec <= %s")

def generate_data():
    num = num_total
    cnx = mysql.connector.connect(user=usr, password=password,
                              database=db_name)
    cursor = cnx.cursor()
    query = insert_query

    for i in range(number):
        current_start_ts = (start_time + (i*86400))
        current_day =   datetime.datetime.fromtimestamp(current_start_ts)
        # print 'cd: ', current_day
        current_end_ts = (start_time + (i*86400)) + 86399
        cursor.execute(query, (current_start_ts * 1000000,
                           current_end_ts * 1000000))
        rows = cursor.fetchall()
        rows_arr = np.array(rows)
        # print 'rows all here li: ', rows
        with open(filepath, 'r') as f:
            limit_file = f.read()
        limits = {}
        for line in limit_file.splitlines():
            print 'line to see:', line
            variable, lower, upper = line.split()
            if not variable == 'Variable':
                limits[variable] = {'lower': int(lower),
                                    'upper': int(upper)}
        print 'limits: ', limits
        if vari_name in data:
            pass
                if len(rows_arr) == 0:
                    continue
                    # print 'no data is here'
                else:
                    for item, index in rows_arr:
                        if index >= upper_limit or index <= lower_limit:
                            print 'data exceeds limit: ', index
                        else:
                            continue
                            # print 'data is within range: ', index
        else:
            print 'sorry: this variable name is invalid'

    start = start_day
    dates = [start + dt.timedelta(days=i) for i in range(num)]
    return dates

def main():
    dates = generate_data()

main()
</code>```

If someone helps me or guide me how to check the lower and upper limits from the text file for the required variable instead of giving hard coded values in the script. i would be grateful
thanks

答:
just parse the limits file and for example create a dict out of it. Something like this.

```<code>def parse_limits(file):
    with open(file, 'r') as f:
       limit_file = f.read()
    limits = {}
    for line in limit_file.splitlines():
        variable, lower, upper = line.split()
        if not variable == 'Variable':
            limits[variable] = {'lower': int(lower),
                                'upper': int(upper)}
    return limits
</code>```

That would result in a nested dict as follows:

```<code>{
    'pressure': {'upper': 100, 'lower': 0},
    'temperature2': {'upper': 30, 'lower': 0},
    'temperature': {'upper': 40, 'lower': 20},
    'temperature3': {'upper': 25, 'lower': 20}
}
</code>```

Edit:

As requested your final code might look s.th. like this:

```<code>#!/usr/bin/env python
# -*- coding: utf-8 -*-

import datetime as dt
import sys
import time
import datetime
import calendar
import numpy as np
import mysql.connector
import datetime
import numpy as np
import pandas as pd
import mysql.connector
from mysql.connector import errorcode

# starting day, month and year
start_day = dt.datetime(2016, 02, 25)
# total number of dates to visualize
number = 11
num_total = 11
# enter limit range
upper_limit = 250 # these are hardcode values which i want to
                    replace and instead of hard code , i want to
                    check these limits values from the text file
lower_limit = 0
# start day in epoch time format
start_time = 1456411800

# variable name and filepath
filepath = '/home/robbyy/files/limit.txt'
vari_name = 'temperature2'

# database name, user and password details and query to fetch   respective data
usr = 'roby'
password = 'xxxx'
db_name = 'roby_data'
insert_query = ("SELECT usec , temperature2_data "
            "FROM rob_table WHERE usec >= %s "
            "AND usec <= %s")

def parse_limits(file):
    with open(file, 'r') as f:
       limit_file = f.read()
    limits = {}
    for line in limit_file.splitlines():
        variable, lower, upper = line.split()
        if not variable == 'Variable':
            limits[variable] = {'lower': int(lower),
                                'upper': int(upper)}
    return limits

limits = parse_limits(filepath)

def generate_data():
    num = num_total
    cnx = mysql.connector.connect(user=usr, password=password,
                              database=db_name)
    cursor = cnx.cursor()
    query = insert_query

    for i in range(number):
        current_start_ts = (start_time + (i*86400))
        current_day =   datetime.datetime.fromtimestamp(current_start_ts)
        # print 'cd: ', current_day
        current_end_ts = (start_time + (i*86400)) + 86399
        cursor.execute(query, (current_start_ts * 1000000,
                           current_end_ts * 1000000))
        rows = cursor.fetchall()
        rows_arr = np.array(rows)
        # print 'rows all here li: ', rows
        print 'limits: ', limits
        if vari_name in data:
                if len(rows_arr) == 0:
                    continue
                    # print 'no data is here'
                else:
                    for item, index in rows_arr:
                        if index >= limits[vari_name]['upper'] or
                                index <= limits[vari_name]['lower']:
                            print 'data exceeds limit: ', index
                        else:
                            continue
                            # print 'data is within range: ', index
        else:
            print 'sorry: this variable name is invalid'

    start = start_day
    dates = [start + dt.timedelta(days=i) for i in range(num)]
    return dates

def main():
    dates = generate_data()

main()
</code>```

Body:
I am trying to fetch some values from database and need to check some lower and upper limits of a variables which are store in a text file like this and they are separated by \t. the text file looks like

Variable      lower_limit   upper_limit
temperature   20            40
pressure      0             100
temperature2  0             30
temperature3  20            25

and the data in database looks like

usec        temperature_data    temperature2_data
1456411800  25                  15
1456412400  45                  25
1456413000  28                  19

So i start with checking first whether the variable is in the text file, if yes then i would need to check the limits of that variable. until now i am only successful in verifying the name of the variable, but i am unable to check the limits.
my code is as follow

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import datetime as dt
import sys
import time
import datetime
import calendar
import numpy as np
import mysql.connector
import datetime
import numpy as np
import pandas as pd
import mysql.connector
from mysql.connector import errorcode

# starting day, month and year
start_day = dt.datetime(2016, 02, 25)
# total number of dates to visualize
number = 11
num_total = 11
# enter limit range
upper_limit = 250 # these are hardcode values which i want to
                    replace and instead of hard code , i want to
                    check these limits values from the text file
lower_limit = 0
# start day in epoch time format
start_time = 1456411800

# variable name and filepath
filepath = '/home/robbyy/files/limit.txt'
vari_name = 'temperature2'

# database name, user and password details and query to fetch   respective data
usr = 'roby'
password = 'xxxx'
db_name = 'roby_data'
insert_query = ("SELECT usec , temperature2_data "
            "FROM rob_table WHERE usec >= %s "
            "AND usec <= %s")

def generate_data():
    num = num_total
    cnx = mysql.connector.connect(user=usr, password=password,
                              database=db_name)
    cursor = cnx.cursor()
    query = insert_query

    for i in range(number):
        current_start_ts = (start_time + (i*86400))
        current_day =   datetime.datetime.fromtimestamp(current_start_ts)
        # print 'cd: ', current_day
        current_end_ts = (start_time + (i*86400)) + 86399
        cursor.execute(query, (current_start_ts * 1000000,
                           current_end_ts * 1000000))
        rows = cursor.fetchall()
        rows_arr = np.array(rows)
        # print 'rows all here li: ', rows
        with open(filepath, 'r') as f:
            limit_file = f.read()
        limits = {}
        for line in limit_file.splitlines():
            print 'line to see:', line
            variable, lower, upper = line.split()
            if not variable == 'Variable':
                limits[variable] = {'lower': int(lower),
                                    'upper': int(upper)}
        print 'limits: ', limits
        if vari_name in data:
            pass
                if len(rows_arr) == 0:
                    continue
                    # print 'no data is here'
                else:
                    for item, index in rows_arr:
                        if index >= upper_limit or index <= lower_limit:
                            print 'data exceeds limit: ', index
                        else:
                            continue
                            # print 'data is within range: ', index
        else:
            print 'sorry: this variable name is invalid'

    start = start_day
    dates = [start + dt.timedelta(days=i) for i in range(num)]
    return dates

def main():
    dates = generate_data()

main()

If someone helps me or guide me how to check the lower and upper limits from the text file for the required variable instead of giving hard coded values in the script. i would be grateful
thanks

Body:
just parse the limits file and for example create a dict out of it. Something like this.

def parse_limits(file):
    with open(file, 'r') as f:
       limit_file = f.read()
    limits = {}
    for line in limit_file.splitlines():
        variable, lower, upper = line.split()
        if not variable == 'Variable':
            limits[variable] = {'lower': int(lower),
                                'upper': int(upper)}
    return limits

That would result in a nested dict as follows:

{
    'pressure': {'upper': 100, 'lower': 0},
    'temperature2': {'upper': 30, 'lower': 0},
    'temperature': {'upper': 40, 'lower': 20},
    'temperature3': {'upper': 25, 'lower': 20}
}

Edit:

As requested your final code might look s.th. like this:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import datetime as dt
import sys
import time
import datetime
import calendar
import numpy as np
import mysql.connector
import datetime
import numpy as np
import pandas as pd
import mysql.connector
from mysql.connector import errorcode

# starting day, month and year
start_day = dt.datetime(2016, 02, 25)
# total number of dates to visualize
number = 11
num_total = 11
# enter limit range
upper_limit = 250 # these are hardcode values which i want to
                    replace and instead of hard code , i want to
                    check these limits values from the text file
lower_limit = 0
# start day in epoch time format
start_time = 1456411800

# variable name and filepath
filepath = '/home/robbyy/files/limit.txt'
vari_name = 'temperature2'

# database name, user and password details and query to fetch   respective data
usr = 'roby'
password = 'xxxx'
db_name = 'roby_data'
insert_query = ("SELECT usec , temperature2_data "
            "FROM rob_table WHERE usec >= %s "
            "AND usec <= %s")

def parse_limits(file):
    with open(file, 'r') as f:
       limit_file = f.read()
    limits = {}
    for line in limit_file.splitlines():
        variable, lower, upper = line.split()
        if not variable == 'Variable':
            limits[variable] = {'lower': int(lower),
                                'upper': int(upper)}
    return limits

limits = parse_limits(filepath)

def generate_data():
    num = num_total
    cnx = mysql.connector.connect(user=usr, password=password,
                              database=db_name)
    cursor = cnx.cursor()
    query = insert_query

    for i in range(number):
        current_start_ts = (start_time + (i*86400))
        current_day =   datetime.datetime.fromtimestamp(current_start_ts)
        # print 'cd: ', current_day
        current_end_ts = (start_time + (i*86400)) + 86399
        cursor.execute(query, (current_start_ts * 1000000,
                           current_end_ts * 1000000))
        rows = cursor.fetchall()
        rows_arr = np.array(rows)
        # print 'rows all here li: ', rows
        print 'limits: ', limits
        if vari_name in data:
                if len(rows_arr) == 0:
                    continue
                    # print 'no data is here'
                else:
                    for item, index in rows_arr:
                        if index >= limits[vari_name]['upper'] or
                                index <= limits[vari_name]['lower']:
                            print 'data exceeds limit: ', index
                        else:
                            continue
                            # print 'data is within range: ', index
        else:
            print 'sorry: this variable name is invalid'

    start = start_day
    dates = [start + dt.timedelta(days=i) for i in range(num)]
    return dates

def main():
    dates = generate_data()

main()


问:
If statement doesn't work, the program enters directly the "else" statement
I am trying to write a program which detects "idle" status but I don't see the problem in my code. Could someone help me please with an useful tip? Here's my code:</p>

```<code>package idlestatus;

import java.awt.MouseInfo;

public class Idlestatus {

    public static void main(String[] args) throws InterruptedException {
        Integer firstPointX = MouseInfo.getPointerInfo().getLocation().x;
        Integer firstPointY = MouseInfo.getPointerInfo().getLocation().y;
        Integer afterPointX;
        Integer afterPointY;
        while (true) {
            Thread.sleep(10000);
            afterPointX = MouseInfo.getPointerInfo().getLocation().x;
            afterPointY = MouseInfo.getPointerInfo().getLocation().y;
            if (firstPointX == afterPointX && firstPointY == afterPointY) {
                System.out.println("Idle status");
            } else {
                System.out.println("(" + firstPointX + ", " + firstPointY + ")");
            }
            firstPointX = afterPointX;
            firstPointY = afterPointY;

        }

    }
}
</code>```

答:
If is working but your condition is always getting false, because you are using Integer instead of primitive int. Note that when you use Object, compare them with .equals() method instead of ==.

Therefore :

```<code>if (firstPointX.equals(afterPointX) && firstPointY.equals(afterPointY)) {
    //your code...
}
</code>```

See this for difference between == and Object.equals() method.

And as mentioned in comments, you can always use int for such purposes, instead of Integer.

See this for difference between Integer and int.

Body:
I am trying to write a program which detects "idle" status but I don't see the problem in my code. Could someone help me please with an useful tip? Here's my code:

package idlestatus;

import java.awt.MouseInfo;

public class Idlestatus {

    public static void main(String[] args) throws InterruptedException {
        Integer firstPointX = MouseInfo.getPointerInfo().getLocation().x;
        Integer firstPointY = MouseInfo.getPointerInfo().getLocation().y;
        Integer afterPointX;
        Integer afterPointY;
        while (true) {
            Thread.sleep(10000);
            afterPointX = MouseInfo.getPointerInfo().getLocation().x;
            afterPointY = MouseInfo.getPointerInfo().getLocation().y;
            if (firstPointX == afterPointX && firstPointY == afterPointY) {
                System.out.println("Idle status");
            } else {
                System.out.println("(" + firstPointX + ", " + firstPointY + ")");
            }
            firstPointX = afterPointX;
            firstPointY = afterPointY;

        }

    }
}

Body:
If is working but your condition is always getting false, because you are using Integer instead of primitive int. Note that when you use Object, compare them with .equals() method instead of ==.

Therefore :

if (firstPointX.equals(afterPointX) && firstPointY.equals(afterPointY)) {
    //your code...
}

See this for difference between == and Object.equals() method.

And as mentioned in comments, you can always use int for such purposes, instead of Integer.

See this for difference between Integer and int.


问:
How to use flake8 for Python 3 ?
In this code snippet,

```<code>def add(x:int, y:int) -> int:
    return x + y
</code>```

there are function annotations that are only supported after python 3.0

When I execute flake8 for this python code:

```<code>$ flake8 7.3.py -vv
checking 7.3.py
def add(x: int, y: int) -> int:
return x + y
7.3.py:1:11: E901 SyntaxError: invalid syntax
</code>```

I got the invalid syntax error, but it should be valid syntax. How can I use flake8 to check the syntax that is only supported in Python 3.x?

答:
I've got the answer on reddit(here):

It uses whatever flake8 is installed in the Python in your path.

so you need to install flake8 by pip3, not pip.

on OSX for me,

```<code>pip3 install flake8
</code>```

this works for me. :)

Title: How to use flake8 for Python 3 ?

Body:
In this code snippet,

def add(x:int, y:int) -> int:
    return x + y

there are function annotations that are only supported after python 3.0

When I execute flake8 for this python code:

$ flake8 7.3.py -vv
checking 7.3.py
def add(x: int, y: int) -> int:
return x + y
7.3.py:1:11: E901 SyntaxError: invalid syntax

I got the invalid syntax error, but it should be valid syntax. How can I use flake8 to check the syntax that is only supported in Python 3.x?

Body:
I've got the answer on reddit(here):

It uses whatever flake8 is installed in the Python in your path.

so you need to install flake8 by pip3, not pip.

on OSX for me,

pip3 install flake8

this works for me. :)

ContentLicense: CC BY-SA 4.0


问:
Sharing a storyboard across multiple targets in Swift
I've got an app with two targets which have almost identical user interfaces and functionality (pay up front vs. IAPs). For that reason, they share a storyboard. In Objective-C this has been no problem.

However now I'm beginning to implement new view controllers using Swift. The problem I'm having is that I need to specify a "Module" for my custom view controllers implemented in my Storyboard.

The custom view controller's Identity Inspector looks like:

I am forced to designate one of my targets. Whichever target I select, the other target will crash with a message such as:

2017-01-15 17:26:32.284 TapTyping[85802:15083599] Unknown class _TtC13TapTypingLite19EntryViewController in Interface Builder file.

How can I set up my shared Storyboard so that it will build for both targets (as it use to, in Objective-C)?

答:
Awolf, I also have a project with multiple targets and I have begun converting it from Objective-C to Swift gradually.  Through much testing I found that for the modules that have been extended from Objective-C to Swift as soon as I change the Class from the Objective-C name to the Swift name I also had this error 'Unknown Class XXX in Interface Builder File'.  I found through trial and error that the Module has to be specified for the views/tableviews with Swift files or they will not be found.  The Module needs to be blank for the views/tableviews with Objective-C files or they will not be found.  I did these changes on the raw XML source code by Control-clicking on MainStoryboard.storyboard and choosing Open As, Source Code.  My naming convention is that the files converted to swift start with 'ProjectOrganizer' and the modules that are still Objective-C start with 'StatusReport'.  Here are two examples:

Objective-C example:

Swift example:

After you are done editing the raw XML source you can switch back to the GUI view of Interface Builder by Control-Clicking on the MainStoryBoard.storyboard and selecting Open As, Interface Builder - Storyboard.

If you resolve the Objective - C vs. Swift setting for the Module all the targets will build successfully despite all the Swift files being specified as only one of your targets.  Make sure all the custom module settings are set to the same target.

[Swift Example in Interface Builder GUI][3]

[Objective-C Example in Interface Builder GUI][4]


问:
Access value in OleDbDataApter
Using OleDbDataAdapter SQL query to search for secific entry in access database.

```<code>OleDbDataAdapter adapter1 = new OleDbDataAdapter(@"SELECT Gallery_Number  FROM Paintings WHERE Painting Number = '" + searchString + "'", myDB);
searchString = Convert.ToString( adapter);
</code>```

searchString returns System.Data.OleDb.OleDbDataAdapter and not a Gallery number.

I would like to know how to get the value of this adapter and put it into a textbox.

答:
First of all, I'd use a Scalar for this, since you only return a single value.

```<code>OleDbCommand command = new OleDbCommand(queryString, connection);
command.Connection.Open();
int galeryNumber = (int)command.ExecuteScalar();
</code>```

But let's take a look at your code:

```<code>DataSet galNum = new DataSet();
oledbAdapter.Fill(galNum);
int galeryNumber = int.Parse(ds.Tables[0].Rows[0].ItemArray[0].ToString());
</code>```

The best way to gain access to a OleDbDataAdapter is by converting the result set into a `DataSet. Then you can iterate through this set.

```<code>for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
      DataRow dr = ds.Tables[0].Rows[i]; //One result line in your set
      //DataRow contains n columns
      for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
      {
         string someEntry = dr[i].ToString();
      }
}
</code>```

Title: Access value in OleDbDataApter

Body:
Using OleDbDataAdapter SQL query to search for secific entry in access database.

OleDbDataAdapter adapter1 = new OleDbDataAdapter(@"SELECT Gallery_Number  FROM Paintings WHERE Painting Number = '" + searchString + "'", myDB);
searchString = Convert.ToString( adapter);

searchString returns System.Data.OleDb.OleDbDataAdapter and not a Gallery number.

I would like to know how to get the value of this adapter and put it into a textbox.

Body:
First of all, I'd use a Scalar for this, since you only return a single value.

OleDbCommand command = new OleDbCommand(queryString, connection);
command.Connection.Open();
int galeryNumber = (int)command.ExecuteScalar();

But let's take a look at your code:

DataSet galNum = new DataSet();
oledbAdapter.Fill(galNum);
int galeryNumber = int.Parse(ds.Tables[0].Rows[0].ItemArray[0].ToString());

The best way to gain access to a OleDbDataAdapter is by converting the result set into a `DataSet. Then you can iterate through this set.

for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
      DataRow dr = ds.Tables[0].Rows[i]; //One result line in your set
      //DataRow contains n columns
      for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
      {
         string someEntry = dr[i].ToString();
      }
}