答:
You can map the array to apply replace on each item.

console.log(
[{value :'$10,000', region: 'NY'},{value :'$600,000', region: 'NY'}]
    .map(({value,...rest}) => ({value: value.replace('$', ''), ...rest}))
);```

Title: String slicing in javascript

Body:
export class Prices{
value : string;
}

const PRICES : Prices[] =[
{value :'$10,000'},{value :'$20,000'},{value :'$30,000'},{value
:'$40,000'},{value :'$50,000'},
{value :'$60,000'},{value :'$70,000'},{value :'$80,000'},{value
:'$90,000'},{value :'$100,000'},
{value :'$125,000'},{value :'$150,000'},{value :'$175,000'},{value
:'$200,000'},{value :'$225,000'},
{value :'$250,000'},{value :'$275,000'},{value :'$300,000'},{value
:'$325,000'},{value :'$350,000'},
{value :'$375,000'},{value :'$400,000'},{value :'$425,000'},{value
:'$450,000'},{value :'$475,000'},
{value :'$500,000'},{value :'$525,000'},{value :'$550,000'},{value
:'$575,000'},{value :'$600,000'}]

export class ConstantProperty implements OnInit{
prices=PRICES;
selectedPriceMin : Prices;
}

I am selecting the price from a drop down menu in html,
Now I want to slice that selected price in order to remove dollar sign.


来源: stackexchange

问:
Error Loading Enclave: Couldn't open file with CreateFile()
I'm trying to write a simple SGX project for a start. So I have this main host application routine that I've pretty much copied from Lars Richter's blog:

```<code>#define ENCLAVE_FILE _T("Enclave.signed.dll")
#include <tchar.h>
#include <cstdio>
#include "sgx_urts.h"
#include "Enclave_u.h"

int main()
{
    sgx_enclave_id_t   eid;
    sgx_status_t       ret = SGX_SUCCESS;
    sgx_launch_token_t token = { 0 };
    int updated = 0;

    ret = sgx_create_enclave(ENCLAVE_FILE, SGX_DEBUG_FLAG, &token, &updated, &eid, NULL);

    if (ret != SGX_SUCCESS) {
        printf("\nApp: error %#x, failed to create enclave.\n", ret);
    }

    scanf("\n");

    return 0;
}
</code>```

It compiles fine (I'm using the Intel C++ 17.0 compiler with Visual Studio 2015) but it doesn't load the enclave. I get the following error message:

```<code>[sgx_create_enclavew ..\urts\win\urts.cpp:195] Couldn't open file with CreateFile()

App: error 0x200f, failed to create enclave.
</code>```

答: Go to app_test_save project setting. Under Debugging, change working directory to $(SolutionDir)Debug. This answer assumes that both projects app_test_save and enclave_test_save belong to the same solution.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to write a simple SGX project for a start. So I have this main host application routine that I've pretty much copied from Lars Richter's blog:

#define ENCLAVE_FILE _T("Enclave.signed.dll")
#include <tchar.h>
#include <cstdio>
#include "sgx_urts.h"
#include "Enclave_u.h"

int main()
{
    sgx_enclave_id_t   eid;
    sgx_status_t       ret = SGX_SUCCESS;
    sgx_launch_token_t token = { 0 };
    int updated = 0;

    ret = sgx_create_enclave(ENCLAVE_FILE, SGX_DEBUG_FLAG, &token, &updated, &eid, NULL);

    if (ret != SGX_SUCCESS) {
        printf("\nApp: error %#x, failed to create enclave.\n", ret);
    }

    scanf("\n");

    return 0;
}

It compiles fine (I'm using the Intel C++ 17.0 compiler with Visual Studio 2015) but it doesn't load the enclave. I get the following error message:

[sgx_create_enclavew ..\urts\win\urts.cpp:195] Couldn't open file with CreateFile()

App: error 0x200f, failed to create enclave.


问:
Tkinter Scrollbar jumps to top of listbox after selection
I have a scrollbar for a listbox, and when a selection is made past the original view of the listbox (you scroll down to select something), after the selection, the scrollbar jumps to the top of the listbox.  I  want the listbox to stay in the location it's currently at just how any other general scrollbar works. Here's the definition of the listbox</p>

```<code>def createListBox(self):
    self.frame = Frame(self)#Frame that holds the scrollbar and listbox
    self.scrollbar = Scrollbar(self.frame)
    self.waiver_menu = Listbox(self.frame, width = 20, height = 9, yscrollcommand = self.scrollbar.set)
    self.scrollbar.config(command = self.waiver_menu.yview)
    self.frame.grid(row = self.row_count, column = self.col_count, rowspan = 3)
    self.waiver_menu.grid(row = self.row_count, column = self.col_count, rowspan = 3)
    self.scrollbar.grid(row = self.row_count, column = self.col_count+1, rowspan = 3, sticky = N+S+W)

    self.waiver_menu.bind("<Double-Button-1>", self.chosen)
</code>```

答: I found that I was refreshing the listbox in another location by deleting and inserting new items which is why it brings you back to the top. This definition of the listbox with scrollbar implementation works!</p>

Body:
I have a scrollbar for a listbox, and when a selection is made past the original view of the listbox (you scroll down to select something), after the selection, the scrollbar jumps to the top of the listbox.  I  want the listbox to stay in the location it's currently at just how any other general scrollbar works. Here's the definition of the listbox

def createListBox(self):
    self.frame = Frame(self)#Frame that holds the scrollbar and listbox
    self.scrollbar = Scrollbar(self.frame)
    self.waiver_menu = Listbox(self.frame, width = 20, height = 9, yscrollcommand = self.scrollbar.set)
    self.scrollbar.config(command = self.waiver_menu.yview)
    self.frame.grid(row = self.row_count, column = self.col_count, rowspan = 3)
    self.waiver_menu.grid(row = self.row_count, column = self.col_count, rowspan = 3)
    self.scrollbar.grid(row = self.row_count, column = self.col_count+1, rowspan = 3, sticky = N+S+W)

    self.waiver_menu.bind("<Double-Button-1>", self.chosen)


问:
Generated recursive object based on array
I have an array, which is a list of keys: ['one', 'two', 'three'].

I need to generate an object, of the following format:

```<code>{
  path: 'one',
  nested: {
    path: 'two',
    nested: {
      path: 'three'
    }
  }
}
</code>```

So far I've tried a couple of approaches, but they seem quite messy (I have one method which uses while(current = array.pop()) but it requires several conditionals to handle the first and last elements.

Is there a neater recursive strategy?

答:
You can use a decrementing for loop to solve this problem:

var props = ['one','two','three'],
    obj;

for(var a = props.length;a--;) {
    var temp = { path: props[a] };
    if(obj) {
        temp.nested = obj;
    }
    obj = temp;
}

console.log(obj);```

Body:
I have an array, which is a list of keys: ['one', 'two', 'three'].

I need to generate an object, of the following format:

{
  path: 'one',
  nested: {
    path: 'two',
    nested: {
      path: 'three'
    }
  }
}

So far I've tried a couple of approaches, but they seem quite messy (I have one method which uses while(current = array.pop()) but it requires several conditionals to handle the first and last elements.

Is there a neater recursive strategy?


问:
std::ifstream data type?
The variable "read" in this program needs to be passed through a function and i don't know what data type it is. I have used http://www.cplusplus.com/reference/fstream/ifstream/ifstream/
and http://www.cplusplus.com/reference/fstream/ifstream/ but I'm struggling to find anything, is this just not possible?</p>

```<code>int main()
{
string line = " ", ans = " ", ans2 = " ", data = " ";
int i = 0, j = 0;
cout << "What file do you want to read? : ";
cin >> ans;
cout << "What do you want the new file to be called? : ";
cin >> ans2;
ifstream read(ans.c_str());
for (i = 0; !read.eof(); i++)
{
    read_function(line, read);
    write_function(line, ans2);
}
return 0;
}

string read_function(string line, string read)
{
        getline(read, line, ' ');
        cout << line;
}

void write_function(string line, string ans2)
{
    ofstream write(ans2.c_str(), ios::app);
    write << line;
    write.close();
}
</code>```

答:
You have ifstream read but a function

```<code>string read_function(string line, string read)
                                 // ^------
</code>```

If you change the function to

```<code> string read_function(string line, ifstream & read)
                                 // ^------
</code>```

the read_function then expects a stream as the second parameter, not a string.

You will have a similar problem with the next function.

The comments point out other problems.

If you get an error about types, sit back and look at what you are passing to functions and what they expect.

Title: std::ifstream data type?

Body:
The variable "read" in this program needs to be passed through a function and i don't know what data type it is. I have used http://www.cplusplus.com/reference/fstream/ifstream/ifstream/
and http://www.cplusplus.com/reference/fstream/ifstream/ but I'm struggling to find anything, is this just not possible?

int main()
{
string line = " ", ans = " ", ans2 = " ", data = " ";
int i = 0, j = 0;
cout << "What file do you want to read? : ";
cin >> ans;
cout << "What do you want the new file to be called? : ";
cin >> ans2;
ifstream read(ans.c_str());
for (i = 0; !read.eof(); i++)
{
    read_function(line, read);
    write_function(line, ans2);
}
return 0;
}

string read_function(string line, string read)
{
        getline(read, line, ' ');
        cout << line;
}

void write_function(string line, string ans2)
{
    ofstream write(ans2.c_str(), ios::app);
    write << line;
    write.close();
}

Body:
You have ifstream read but a function

string read_function(string line, string read)
                                 // ^------

If you change the function to

 string read_function(string line, ifstream & read)
                                 // ^------

the read_function then expects a stream as the second parameter, not a string.

You will have a similar problem with the next function.

The comments point out other problems.

If you get an error about types, sit back and look at what you are passing to functions and what they expect.


问:
Creating Promises in for...of loop instead forEach?
I want to execute an array of Promises in parallel and then wait until all Promises are executed.

This works:

```<code>var promises = [];

objects.forEach(function(object) {

    let promise = new Parse.Promise.as()
    .then(
        function() {
            return destroy(object);
        }
    );

    promises.push(promise);
});

return Parse.Promise.when(promises);
</code>```

But if I use for (object of objects) {...} instead of objects.forEach(function(object) {...}); it doesn't work. For every Promise in the array the destroy(object); is executed on the first object in the array:

```<code>var promises = [];

for (object of objects) {

    let promise = new Parse.Promise.as()
    .then(
        function() {
            return destroy(object);
        }
    );

    promises.push(promise);
});

return Parse.Promise.when(promises);
</code>```

Why is that?

答:
Yes, you forgot to declare the object variable as local to the loop body (see also the canonical explanation):

```<code>var promises = [];
for (let object of objects) {
//   ^^^
    promises.push(new Parse.Promise.as().then(function() {
        return destroy(object);
    }));
}
return Parse.Promise.when(promises);
</code>```

Of course you should not do this either, you should just use map:

```<code>var promises = objects.map(function(object) {
    return new Parse.Promise.as().then(function() {
        return destroy(object);
    });
});
return Parse.Promise.when(promises);
</code>```

Body:
I want to execute an array of Promises in parallel and then wait until all Promises are executed.

This works:

var promises = [];

objects.forEach(function(object) {

    let promise = new Parse.Promise.as()
    .then(
        function() {
            return destroy(object);
        }
    );

    promises.push(promise);
});

return Parse.Promise.when(promises);

But if I use for (object of objects) {...} instead of objects.forEach(function(object) {...}); it doesn't work. For every Promise in the array the destroy(object); is executed on the first object in the array:

var promises = [];

for (object of objects) {

    let promise = new Parse.Promise.as()
    .then(
        function() {
            return destroy(object);
        }
    );

    promises.push(promise);
});

return Parse.Promise.when(promises);

Why is that?

Body:
Yes, you forgot to declare the object variable as local to the loop body (see also the canonical explanation):

var promises = [];
for (let object of objects) {
//   ^^^
    promises.push(new Parse.Promise.as().then(function() {
        return destroy(object);
    }));
}
return Parse.Promise.when(promises);

Of course you should not do this either, you should just use map:

var promises = objects.map(function(object) {
    return new Parse.Promise.as().then(function() {
        return destroy(object);
    });
});
return Parse.Promise.when(promises);


问:
Why can't I use the import syntax to import a coffeescript file from typescript
I have a typescript file and I am importing various typescript files as follows:

```<code>import ThingAMajig from '../../../libs/stuffs/ThingAMajig'; // a typescript file
</code>```

But I have to import my coffeescript files in this way:

```<code>const CoolThing = require('../../../libs/coolDir/CoolThing');
</code>```

When I try to use the import syntax, I get an error error TS2307: Cannot find module.

答:
I can half answer this..I'm know a bit about babel, webpack and typescript.

You'd need to investigate coffee-loader a bit more.

https://github.com/webpack-contrib/coffee-loader

I'm used to using brew on a Mac.

You can probably sudo npm install webpack too,

or do it as administrator on Windows machine.

run npm init first inside new empty project folder

npm install -g webpack

brew install webpack

npm install --save-dev babel-loader

webpack.config.js

```<code>module.exports =  {
    entry: '/scripts.js'
    output: {filename 'bundle.js'}
    module: {
       loaders: [
        {test: /\.js?/, loader: 'babel-loader', exclude: /node_modules}
    ]
    }
}
</code>```

webpack -> bundle.js

add bundle.js to index.html within script tag

You probably need to add the loaders for your coffee script in the webpack.config.js

Body:
I have a typescript file and I am importing various typescript files as follows:

import ThingAMajig from '../../../libs/stuffs/ThingAMajig'; // a typescript file

But I have to import my coffeescript files in this way:

const CoolThing = require('../../../libs/coolDir/CoolThing');

When I try to use the import syntax, I get an error error TS2307: Cannot find module.

Body:
I can half answer this..I'm know a bit about babel, webpack and typescript.

You'd need to investigate coffee-loader a bit more.

https://github.com/webpack-contrib/coffee-loader

I'm used to using brew on a Mac.

You can probably sudo npm install webpack too,

or do it as administrator on Windows machine.

run npm init first inside new empty project folder

npm install -g webpack

brew install webpack

npm install --save-dev babel-loader

webpack.config.js

module.exports =  {
    entry: '/scripts.js'
    output: {filename 'bundle.js'}
    module: {
       loaders: [
        {test: /\.js?/, loader: 'babel-loader', exclude: /node_modules}
    ]
    }
}

webpack -> bundle.js

add bundle.js to index.html within script tag

You probably need to add the loaders for your coffee script in the webpack.config.js


问:
In python, how can I find "# The Scenes" from "Behind # The Scenes" with regex?
I want to get the string ## The Scenes from Behind ## The Scenes with regex.

This is the regex I have made.

```<code>pattern = re.compile("#+\s\w+")
</code>```

When I run the script, I get d ## The Scenes string.

How can I?

答:
As others have pointed out, your regex pattern isn't matching "d ## The Scenes", it's matching "## The". If you want "## The Scenes", this pattern adds an extra space and word to yours and should work:

"#+\s\w+\s\w+"

Body:
I want to get the string ## The Scenes from Behind ## The Scenes with regex.

This is the regex I have made.

pattern = re.compile("#+\s\w+")

When I run the script, I get d ## The Scenes string.

How can I?


问:
Can't create a table and select from it while in a plsql procedure in oracle
```<code>create or replace procedure sp_test as
begin
CREATE TABLE T AS SELECT col1,col2 FROM t1;
FOR N IN (SELECT * FROM T) LOOP
     UPDATE t1 SET t1.col1='value' where col2='value2';
END LOOP;
drop table T;
end;
/
</code>```

I need to select data into t table from a t1 table in order to apply some modifications, and merge those modifications in t1 table (origin table) before deleting table t.

I m getting this error : PLS-00103

答:
You need to use execute immediate for any ddl inside any pl/sql block. Try the below code:

```<code>create or replace procedure sp_test
is
begin
Execute Immediate 'CREATE TABLE T AS SELECT col1,col2 FROM t1';

FOR N IN (SELECT * FROM T) LOOP
     Execute immediate 'UPDATE t1 SET t1.col1=''value'' where col2=''value2''';
END LOOP;
execute immediate 'drop table T';
end;
/
</code>```

Body:
create or replace procedure sp_test as
begin
CREATE TABLE T AS SELECT col1,col2 FROM t1;
FOR N IN (SELECT * FROM T) LOOP
     UPDATE t1 SET t1.col1='value' where col2='value2';
END LOOP;
drop table T;
end;
/

I need to select data into t table from a t1 table in order to apply some modifications, and merge those modifications in t1 table (origin table) before deleting table t.

I m getting this error : PLS-00103

Body:
You need to use execute immediate for any ddl inside any pl/sql block. Try the below code:

create or replace procedure sp_test
is
begin
Execute Immediate 'CREATE TABLE T AS SELECT col1,col2 FROM t1';

FOR N IN (SELECT * FROM T) LOOP
     Execute immediate 'UPDATE t1 SET t1.col1=''value'' where col2=''value2''';
END LOOP;
execute immediate 'drop table T';
end;
/


问:
Android - Debugging prebuilt native libraries with lldb
How can I get lldb to see a prebuilt native library's symbols when using the latest Android Studio tools?

I'm working on an Android app using Android Studio 2.2.2. My app has a native component and also depends on a prebuilt native library that my native component links to. When I break into some native code with the debugger, the debugger has symbols for my native code but not for the prebuilt library, which I built with symbols. The documentation that I've found on debugging prebuilt native libraries (https://developer.android.com/ndk/guides/prebuilts.html#dp) appears to be outdated, as it refers to Android.mk and ndk-gdb, as opposed to build.gradle, CMakeLists.txt, and lldb, which are what I'm using.

Here's a bit more info for anyone who's familiar with lldb (which is not to say that I am familiar with it). I think it reflects the fact that the debugger is looking at the non-symbol-stripped version of my native code, in libnative-lib.so, which is stored on my machine, but is looking at the symbol-stripped version of the prebuilt library, libaws-cpp-sdk-vitalservices.so, which is stored on the android device:

```<code>(lldb) image list
...
[107] B8FC838B-0000-0000-0000-000000000000            /Users/christophersimmons/.lldb/module_cache/remote-android/.cache/B8FC838B-0000-0000-0000-000000000000/libaws-cpp-sdk-vitalservices.so
[108] A7AD2397-02E5-5AE9-0192-F2353B51C362-C40832C9            /Users/christophersimmons/Documents/repos/DoclilyAndroid/app/build/intermediates/cmake/debug/obj/x86/libnative-lib.so
</code>```

答:
How large is your executable ?

It seems that the lldb client for Android Studio is a 32b application so it cannot handle large so files!

https://issuetracker.google.com/issues/37324018

It seems it will be fixed soon !

Body:
How can I get lldb to see a prebuilt native library's symbols when using the latest Android Studio tools?

I'm working on an Android app using Android Studio 2.2.2. My app has a native component and also depends on a prebuilt native library that my native component links to. When I break into some native code with the debugger, the debugger has symbols for my native code but not for the prebuilt library, which I built with symbols. The documentation that I've found on debugging prebuilt native libraries (https://developer.android.com/ndk/guides/prebuilts.html#dp) appears to be outdated, as it refers to Android.mk and ndk-gdb, as opposed to build.gradle, CMakeLists.txt, and lldb, which are what I'm using.

Here's a bit more info for anyone who's familiar with lldb (which is not to say that I am familiar with it). I think it reflects the fact that the debugger is looking at the non-symbol-stripped version of my native code, in libnative-lib.so, which is stored on my machine, but is looking at the symbol-stripped version of the prebuilt library, libaws-cpp-sdk-vitalservices.so, which is stored on the android device:

(lldb) image list
...
[107] B8FC838B-0000-0000-0000-000000000000            /Users/christophersimmons/.lldb/module_cache/remote-android/.cache/B8FC838B-0000-0000-0000-000000000000/libaws-cpp-sdk-vitalservices.so
[108] A7AD2397-02E5-5AE9-0192-F2353B51C362-C40832C9            /Users/christophersimmons/Documents/repos/DoclilyAndroid/app/build/intermediates/cmake/debug/obj/x86/libnative-lib.so


问:
Anko Logging with verbose and debug isn't working
I'm trying to use Anko Commons – Logging

but for some reason the verbose and debug not showing on the logcat

however, when I use Log.d it works as expected.

when I'm trying this code

```<code>verbose("-------------verbose--------------")
debug("-------------debug--------------")
info("-------------info--------------")
warn("-------------warn--------------")
error("-------------error--------------")
wtf("-------------wtf--------------")
</code>```

the log logcat is as following

I'm using Anko 0.10.0 android studio 3.0 canary-5

when I tried to search for a solution I found this one

All Log.* will log to logcat regardless of what the current log level is. However, AnkoLogger.* will only log to logcat when its log level is loggable.

but I don't know how to change the log level, and if even it's my problem is the same.

答:
It turns out The default log level is INFO.

From the ADB shell, you can change the log level to DEBUG, VERBOSE etc. using this command:

```<code>setprop  log.tag.MyApp  DEBUG
</code>```

so As far as know by AnkoLogger uses Log.isLoggable() under the hood which ignores VERBOSE and DEBUG log levels by default.

for more info you can read more about it here

Body:
I'm trying to use Anko Commons – Logging

but for some reason the verbose and debug not showing on the logcat

however, when I use Log.d it works as expected.

when I'm trying this code

verbose("-------------verbose--------------")
debug("-------------debug--------------")
info("-------------info--------------")
warn("-------------warn--------------")
error("-------------error--------------")
wtf("-------------wtf--------------")

the log logcat is as following

I'm using Anko 0.10.0 android studio 3.0 canary-5

when I tried to search for a solution I found this one

All Log.* will log to logcat regardless of what the current log level is. However, AnkoLogger.* will only log to logcat when its log level is loggable.

but I don't know how to change the log level, and if even it's my problem is the same.

Body:
It turns out The default log level is INFO.

From the ADB shell, you can change the log level to DEBUG, VERBOSE etc. using this command:

setprop  log.tag.MyApp  DEBUG

so As far as know by AnkoLogger uses Log.isLoggable() under the hood which ignores VERBOSE and DEBUG log levels by default.

for more info you can read more about it here


问:
How to read chunks for a text file based on a word as a key delimiter?
I have a .txt file with this format:

```<code>Part #368 - XXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Part #369 - XXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Part #370 - XXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
</code>```

I read the file like this:

```<code>var lines = fs.readFileSync('file.txt', 'utf-8')
.split('\n')
.filter(Boolean);
</code>```

So it returns an array of the lines of the file. How can I get the chunks of the file starting with the "Part" string?

```<code>var parts = _.filter(lines,function( s ) { return s.indexOf( 'Part' ) !== -1; });
</code>```

Something like this but instead of getting the strings starting with "Part" I want all the lines from "Part" string to next "Part" string.

答:
JSON Stream

As per @Brad's suggestion, here is a class extended from stream.Transform that delimits the file into a JSON array stream:

```<code>const { Transform } = require('stream');

class Delimited extends Transform {
  constructor({ delimiter = /\r?\n/g, encoding = 'utf8' } = {}) {
    super();

    // initialize internal values
    this._delimiter = delimiter instanceof RegExp ? delimiter : new RegExp(delimiter, 'g');
    this._encoding = encoding;
    this._buffer = '';
    this._first = true;
  }

  _transform(chunk, encoding, callback) {
    // convert input encoding into output encoding
    // and append to internal buffer
    if (encoding === 'buffer') {
      this._buffer += chunk.toString(this._encoding);
    } else if (encoding === this._encoding) {
      this._buffer += chunk;
    } else {
      this._buffer += Buffer.from(chunk, encoding).toString(this._encoding);
    }

    let partialJSON = '';

    // check if delimiter is found
    if (this._delimiter.test(this._buffer)) {
      // split internal buffer by delimiter
      let sections = this._buffer.split(this._delimiter);
      // put possibly incomplete section from array back into internal buffer
      this._buffer = sections.pop();
      // add each section to partial json array
      sections.forEach(section => {
        partialJSON += `${this._first ? '[' : ','}${JSON.stringify(section)}`;
        this._first = false;
      });
    }

    // push partial json array to readable stream
    callback(null, partialJSON);
  }

  _flush(callback) {
    // add remaining buffer as last section to json array
    callback(null, `${this._first ? '[' : ','}${JSON.stringify(this._buffer)}]`);
  }
}
</code>```

Example usage:

```<code>const fs = require('fs');

let stream = fs.createReadStream('file.txt', 'utf8');
let transform = new Delimited({ delimiter: /\n\n(?=Part #\d)/g });
let json = '';

transform.on('data', (chunk) => json += chunk);
transform.on('end', () => console.log(JSON.parse(json)));

stream.pipe(transform);
</code>```

Try it online!

String Stream

Alternatively, if you prefer not to transfer the JSON to another file, process, or as a client response, you can emit each section as a chunk by setting the output stream to objectMode: true:

```<code>const { Transform } = require('stream');

class Delimited extends Transform {
  constructor(delimiter = /\r?\n/g) {
    super({ objectMode: true });

    // initialize internal values
    this._delimiter = delimiter instanceof RegExp ? delimiter : new RegExp(delimiter, 'g');
    this._encoding = 'utf8';
    this._buffer = '';
    this._first = true;
  }

  _transform(chunk, encoding, callback) {
    // convert input encoding into output encoding
    // and append to internal buffer
    if (encoding === 'buffer') {
      this._buffer += chunk.toString(this._encoding);
    } else if (encoding === this._encoding) {
      this._buffer += chunk;
    } else {
      this._buffer += Buffer.from(chunk, encoding).toString(this._encoding);
    }

    if (this._delimiter.test(this._buffer)) {
      // split internal buffer by delimiter
      let sections = this._buffer.split(this._delimiter);
      // put possibly incomplete section from array back into internal buffer
      this._buffer = sections.pop();
      // push each section to readable stream in object mode
      sections.forEach(this.push, this);
    }

    callback();
  }

  _flush(callback) {
    // push remaining buffer to readable stream
    callback(null, this._buffer);
  }
}
</code>```

Example usage:

```<code>const fs = require('fs');

let stream = fs.createReadStream('file.txt', 'utf8');
let transform = new Delimited(/\n\n(?=Part #\d)/g);
let array = [];

transform.on('data', (chunk) => array.push(chunk));
transform.on('end', () => console.log(array));

stream.pipe(transform);
</code>```

Try it online!

Body:
I have a .txt file with this format:

Part #368 - XXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Part #369 - XXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Part #370 - XXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

I read the file like this:

var lines = fs.readFileSync('file.txt', 'utf-8')
.split('\n')
.filter(Boolean);

So it returns an array of the lines of the file. How can I get the chunks of the file starting with the "Part" string?

var parts = _.filter(lines,function( s ) { return s.indexOf( 'Part' ) !== -1; });

Something like this but instead of getting the strings starting with "Part" I want all the lines from "Part" string to next "Part" string.

Body:
JSON Stream

As per @Brad's suggestion, here is a class extended from stream.Transform that delimits the file into a JSON array stream:

const { Transform } = require('stream');

class Delimited extends Transform {
  constructor({ delimiter = /\r?\n/g, encoding = 'utf8' } = {}) {
    super();

    // initialize internal values
    this._delimiter = delimiter instanceof RegExp ? delimiter : new RegExp(delimiter, 'g');
    this._encoding = encoding;
    this._buffer = '';
    this._first = true;
  }

  _transform(chunk, encoding, callback) {
    // convert input encoding into output encoding
    // and append to internal buffer
    if (encoding === 'buffer') {
      this._buffer += chunk.toString(this._encoding);
    } else if (encoding === this._encoding) {
      this._buffer += chunk;
    } else {
      this._buffer += Buffer.from(chunk, encoding).toString(this._encoding);
    }

    let partialJSON = '';

    // check if delimiter is found
    if (this._delimiter.test(this._buffer)) {
      // split internal buffer by delimiter
      let sections = this._buffer.split(this._delimiter);
      // put possibly incomplete section from array back into internal buffer
      this._buffer = sections.pop();
      // add each section to partial json array
      sections.forEach(section => {
        partialJSON += `${this._first ? '[' : ','}${JSON.stringify(section)}`;
        this._first = false;
      });
    }

    // push partial json array to readable stream
    callback(null, partialJSON);
  }

  _flush(callback) {
    // add remaining buffer as last section to json array
    callback(null, `${this._first ? '[' : ','}${JSON.stringify(this._buffer)}]`);
  }
}

Example usage:

const fs = require('fs');

let stream = fs.createReadStream('file.txt', 'utf8');
let transform = new Delimited({ delimiter: /\n\n(?=Part #\d)/g });
let json = '';

transform.on('data', (chunk) => json += chunk);
transform.on('end', () => console.log(JSON.parse(json)));

stream.pipe(transform);

<a href="https://tio.run/##7ZXfb9MwEMff81ecxKQ4okuRkGCsKpUQe@EBEONhEkWbmzitN9cOtjPWVfnby9n5Ubcrm3hFy0OV2ufv3X18d7mmt9Rkmpf2WKqcbTIljYU1fNdUmkLpJdQwBs1@VVwzEhurGV3GySiKMkGNgY9M8CW3LAd2Z5nMTXByHQF4PV1lVmmyhry11qg5nOrJVA7nA2AyUzmXc1yMK1ucxN7nuk68AoCpSqaJ8@n@DYfAJbecCn7P8BXVJBVwS0XFjLewC27Sy9DX9p1jOFRmTBXwjc3P7kqYBLunINnvdoP0ywOI5y7lrXYQcfcabs@qovB@4zhcLrhGtmNAHsyt1y6hS9vxItmikjdbHAPIqBAzmt10IDB15HnLtMU8yspuySEGBaqy4WJ3hMocaFni5QAa9cCaIL0RL4BsUxpj3M1m3DneS@zlGHysqVXnVuMhsoulZVUDE4Y9VN8zftzHjtTfLD/4t7TQ6gHF5Kkg/a//EcxCSbUrrU/nXz4H99fTX7DsxiUUFJSBQlUy70HuVV9qmbEkDDjZZoySphTc7t8KzFZbF62ti86wzHLsKBjvIEi9yL7nNkHvxdVFqYzhM7FCZ5lalqjHOkFw5IBqTVfgCq6pp0Ol8qDEu5DSUpUkdElznAk0W/Q@ULGlC9cG/3t3rX2vgo1whodId2j8vocFO5eDt351tA4bawLxjxhbOB7E9dHaGaXGXzwvVp1eUl@NerndriwoVli3WffVEfUEzeJA/C4rHIk5nQmk6aejP9G1LpGVEIMw8qRpfV9Ul4VAWXKgzx09zZYURx12TUubGsCha0OieyT33P4LoZ0SrX9etXHWG194PjOkVGqVMWPwHPbQKHJ7/QDDbTc@@09COPBPcd7LqSST8VdEAS@meTKce8xOwmfRtFvUy6VKkjinlsYDaLo6ceXgbbvpgOd37XHKOXNv6b49SrBUqDnxyeItGEacQJK4z0mTVVrykpFeJhltNk2Mr9@cwDFcHH6ii6ef/9Ym6gC9ewb0KKC3r54BHXr@AA" rel="nofollow noreferrer" title="JavaScript (Node.js) – Try It Online">Try it online!

String Stream

Alternatively, if you prefer not to transfer the JSON to another file, process, or as a client response, you can emit each section as a chunk by setting the output stream to objectMode: true:

const { Transform } = require('stream');

class Delimited extends Transform {
  constructor(delimiter = /\r?\n/g) {
    super({ objectMode: true });

    // initialize internal values
    this._delimiter = delimiter instanceof RegExp ? delimiter : new RegExp(delimiter, 'g');
    this._encoding = 'utf8';
    this._buffer = '';
    this._first = true;
  }

  _transform(chunk, encoding, callback) {
    // convert input encoding into output encoding
    // and append to internal buffer
    if (encoding === 'buffer') {
      this._buffer += chunk.toString(this._encoding);
    } else if (encoding === this._encoding) {
      this._buffer += chunk;
    } else {
      this._buffer += Buffer.from(chunk, encoding).toString(this._encoding);
    }

    if (this._delimiter.test(this._buffer)) {
      // split internal buffer by delimiter
      let sections = this._buffer.split(this._delimiter);
      // put possibly incomplete section from array back into internal buffer
      this._buffer = sections.pop();
      // push each section to readable stream in object mode
      sections.forEach(this.push, this);
    }

    callback();
  }

  _flush(callback) {
    // push remaining buffer to readable stream
    callback(null, this._buffer);
  }
}

Example usage:

const fs = require('fs');

let stream = fs.createReadStream('file.txt', 'utf8');
let transform = new Delimited(/\n\n(?=Part #\d)/g);
let array = [];

transform.on('data', (chunk) => array.push(chunk));
transform.on('end', () => console.log(array));

stream.pipe(transform);

<a href="https://tio.run/##7VRNbxMxEL3vrxiJw3pFukFCgtJqqYToEQkBh0oEVc7ubOLWsY3tLS1VfnsYez@STQK9o@4hsew37808z/iG33FXWmH8idIVbkqtnIdH@Ga5crW2K1hDARZ/NsIiS523yFdpdp4kpeTOwUeUYiU8VoD3HlXldiIfE4DIZ5vSa8uqDmuJcTqzFzM1XWQRBeAag5Y9gp7fYOk/USpnQHEI66AVENMpCCW84FL8RloSj@IS7rhs0EWEXwqXX@@qbNeC0uCqRF3DF1xc3hu42Dk9A4W/uoNtmhNIF6HULTeqUldCLYg6bXx9mu4ezpu6jqrpaLsWlhwtYjVhfx3Kufa9S6xcNup2Aj31BEou5ZyXt701VDi5eIfWUxWm8QM0mKBBN353sw/hqgJuDF0JEGiwq00ygkQNbFtQQXm3h2kvvFfYywJirrnXX72lIDY2pXNqDSgdHrLvgf@tMaL6G/JDXOW11QcuZk8lGX8HG/Y6J/foPNuVy7b5krfOSOH3PYX5w7ajOqxED476WdAUQDEqII8k@8pdelEl3KrRzom5fCCxUq8M8WFPCKFu4NbyBwjt0nbDsYs@aNA@pdxow8aSbgnIy@UgQpQ08RWfSxKOw08S3ZTCisa0Cx4oqacviaAtLPBNovrge/zrW7wVD5cRZqKWBGdH2j@mZXHF6QGgburqOExtzK0aKSej0ju19SbeS1tNAcbqEp3LnacGOU/C2TCddBxehuGVY9OZmil2UXzmNI4vZlU2DS0VYtqbKOD7D3qwBoJcK5ZW3PN0Am2TZlC8b8HRnm6TSMYxNLghJKLDI6ol5lIvWIwM8KQtIDfCIBtis/PNps3t9ZtTOIGr419y9fT332KS3qB3zwb906C3r54NOvb9AQ" rel="nofollow noreferrer" title="JavaScript (Node.js) – Try It Online">Try it online!


问:
Store huge std::map, mostly on disk
I've got a C++ program that's likely to generate a HUGE amount of data -- billions of binary records of varying sizes, most probably less than 256 bytes but a few stretching to several K. Most of the records will seldom be looked at by the program after they're created, but some will be accessed and modified regularly. There's no way to tell which are which when they're created.

Considering the volume of data, there's no way I can store it all in memory. But as the data only needs to be indexed and accessed by its number (a 64-bit integer), I don't want the overhead of a full-fledged database program. Ideally I'd like to treat it as an std::map with its data stored on disk until requested.

Is there an already-written library that will do what I'm looking for, or do I need to write it myself?

EDIT: After some thought, I realized that Rob Walker's answer had a valid point: I'd be hard-pressed to get anywhere near the same kind of data integrity out of a home-brew class that I'd get from a real database.

Although BerkeleyDB (as suggested by RHM) looks like it would do exactly what we're looking for, the dual-licensing is a headache that we don't want to deal with. When we're done with the code and can prove that it would benefit noticeably from BerkeleyDB (which it probably would), we'll reexamine the issue.

I did look at Ferruccio's suggestion of stxxl, but I wasn't able to tell how it would handle the program being interrupted and restarted (maybe with changes). With that much data, I'd hate to just scrap what it had already completed and start over every time, if some of the data could be saved.

So we've decided to use an SQLite database, at least for the initial development. Thanks to everyone who answered or voted.

答:
You could use SQLLite which is a Open Source Database released to the public domain.

http://www.sqlite.org/

I`ll quote their page:

SQLite is a software library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine. SQLite is the most widely deployed SQL database engine in the world. The source code for SQLite is in the public domain.

And

Ongoing development and maintenance of SQLite is sponsored in part by SQLite Consortium members, including: Adobe, Symbian, Bloomberg, Mozilla

If you need a lightweight db this might just be it

OwnerDisplayName: Head Geek

ContentLicense: CC BY-SA 2.5

Title: Store huge std::map, mostly on disk

LastEditorDisplayName: Head Geek

OwnerDisplayName: mellowF


问:
help me in wxpython drag and drop file/folder
Excuse the previous post, but I'm learning wxpython before A month ago and I am new to use this language and I wanted some help in order to learn this language and it seems I am Aktit in the way of Subtractive Question ... Excuse me again
i found program in http://zetcode.com/wxpython/draganddrop/
and i want make copy from folder/file to an other folder by drag and drop </p>

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

# dragdrop.py

import os
import wx

class MyTextDropTarget(wx.TextDropTarget):
    def __init__(self, object):
        wx.TextDropTarget.__init__(self)
        self.object = object

    def OnDropText(self, x, y, data):
        self.object.InsertStringItem(0, data)

class DragDrop(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, size=(650, 500))

        splitter1 = wx.SplitterWindow(self, -1, style=wx.SP_3D)
        splitter2 = wx.SplitterWindow(splitter1, -1, style=wx.SP_3D)
        self.dir = wx.GenericDirCtrl(splitter1, -1, dir='/home/', style=wx.DIRCTRL_DIR_ONLY)
        self.lc1 = wx.ListCtrl(splitter2, -1, style=wx.LC_LIST)
        self.lc2 = wx.ListCtrl(splitter2, -1, style=wx.LC_LIST)

        dt = MyTextDropTarget(self.lc2)
        self.lc2.SetDropTarget(dt)
        self.Bind(wx.EVT_LIST_BEGIN_DRAG, self.OnDragInit, id=self.lc1.GetId())

        tree = self.dir.GetTreeCtrl()

        splitter2.SplitHorizontally(self.lc1, self.lc2)
        splitter1.SplitVertically(self.dir, splitter2)

        self.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelect, id=tree.GetId())

        self.OnSelect(0)
        self.Centre()
        self.Show(True)

    def OnSelect(self, event):
        list = os.listdir(self.dir.GetPath())
        self.lc1.ClearAll()
        self.lc2.ClearAll()
        for i in range(len(list)):
            if list[i][0] != '.':
                self.lc1.InsertStringItem(0, list[i])

    def OnDragInit(self, event):
        text = self.lc1.GetItemText(event.GetIndex())
        tdo = wx.TextDataObject(text)
        tds = wx.DropSource(self.lc1)
        tds.SetData(tdo)
        tds.DoDragDrop(True)

app = wx.App()
DragDrop(None, -1, 'dragdrop.py')
app.MainLoop()
</code>```

答: To do DnD of files you'll want to use wx.FileDropTarget and wx.FileDataObject.  There is an example in the wxPython demo.</p>

Body:
Excuse the previous post, but I'm learning wxpython before A month ago and I am new to use this language and I wanted some help in order to learn this language and it seems I am Aktit in the way of Subtractive Question ... Excuse me again
i found program in http://zetcode.com/wxpython/draganddrop/
and i want make copy from folder/file to an other folder by drag and drop

#!/usr/bin/python

# dragdrop.py

import os
import wx

class MyTextDropTarget(wx.TextDropTarget):
    def __init__(self, object):
        wx.TextDropTarget.__init__(self)
        self.object = object

    def OnDropText(self, x, y, data):
        self.object.InsertStringItem(0, data)

class DragDrop(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, size=(650, 500))

        splitter1 = wx.SplitterWindow(self, -1, style=wx.SP_3D)
        splitter2 = wx.SplitterWindow(splitter1, -1, style=wx.SP_3D)
        self.dir = wx.GenericDirCtrl(splitter1, -1, dir='/home/', style=wx.DIRCTRL_DIR_ONLY)
        self.lc1 = wx.ListCtrl(splitter2, -1, style=wx.LC_LIST)
        self.lc2 = wx.ListCtrl(splitter2, -1, style=wx.LC_LIST)

        dt = MyTextDropTarget(self.lc2)
        self.lc2.SetDropTarget(dt)
        self.Bind(wx.EVT_LIST_BEGIN_DRAG, self.OnDragInit, id=self.lc1.GetId())

        tree = self.dir.GetTreeCtrl()

        splitter2.SplitHorizontally(self.lc1, self.lc2)
        splitter1.SplitVertically(self.dir, splitter2)

        self.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelect, id=tree.GetId())

        self.OnSelect(0)
        self.Centre()
        self.Show(True)

    def OnSelect(self, event):
        list = os.listdir(self.dir.GetPath())
        self.lc1.ClearAll()
        self.lc2.ClearAll()
        for i in range(len(list)):
            if list[i][0] != '.':
                self.lc1.InsertStringItem(0, list[i])

    def OnDragInit(self, event):
        text = self.lc1.GetItemText(event.GetIndex())
        tdo = wx.TextDataObject(text)
        tds = wx.DropSource(self.lc1)
        tds.SetData(tdo)
        tds.DoDragDrop(True)

app = wx.App()
DragDrop(None, -1, 'dragdrop.py')
app.MainLoop()


问:
PHP CURL "NSS: client certificate not found (nickname not specified)" Issue
Request to a single specific https endpoint fails on one of my servers with "NSS: client certificate not found (nickname not specified)" error from PHP CURL.

When I ran the same query from the command line with verbose option I got the same error, but after that I also got a valid response (after the error in the same CURL request).

Then I've enabled verbose option for my PHP CURL request and displayed it for testing like this:

```<code>$error = curl_error($curl);

if ($error) {
        echo "cURL Error #:" . $error;

        rewind($verbose);
        $verboseLog = htmlspecialchars(stream_get_contents($verbose));

        echo "```";
        print_r($verboseLog);
} else {
  echo $response;
}
```

<p>And got this as output:</p>

```cURL Error #:NSS: client certificate not found (nickname not specified)
* About to connect() to <address> port 8001 (#0)
*   Trying <ip>... * connected
* Connected to <address> (<ip>) port 8001 (#0)
* skipping SSL peer certificate verification
* NSS: client certificate not found (nickname not specified)
* SSL connection using TLS_RSA_WITH_AES_128_GCM_SHA256
* Server certificate:
*   subject: CN=*.<address>m,O=XXX A.S.,OU=IT,L=Umraniye,ST=Istanbul,C=TR
*   start date: Jun 11 12:52:03 2015 GMT
*   expire date: Jun 09 14:16:13 2018 GMT
*   common name: *.<address>
*   issuer: CN=GlobalSign Organization Validation CA - SHA256 - G2,O=GlobalSign nv-sa,C=BE
> POST /<url_part> HTTP/1.1
Host: <address>:8001
Accept: */*
Accept-Encoding: deflate, gzip
authorization: Basic UlBlahBlahnJrcjEyMzQ1Ng==
cache-control: no-cache
content-type: application/json
postman-token: eeefe018-7cac-1706-7b6d-847800a7ad0f
Content-Length: 333

< HTTP/1.1 200 OK
< set-cookie: sap-usercontext=sap-client=100; path=/
< set-cookie: SAP_SESSIONID_CFP_100=ohZvfO5ZOwq_LTE76Zgz9L-C0NdhlRHngM0AF6R3IFY%3d; path=/
< content-type: application/json; charset=utf-8
< content-length: 1150
< cache-control: max-age=0
< sap-cache-control: +180
< sap-isc-uagent: 0
<
* Connection #0 to host <address> left intact
* Closing connection #0
```

<p>So, CURL request finished with the error, but in verbose log we see that after the error valid response was also fetched.</p>

<p>Here's my questions:</p>

<ol>
<li>Is there any way to overcome this NSS issue as long as other different <code>https</code> endpoints work completely fine? Is it connected with endpoint's server configuration and can be resolved there?</li>
<li>If the first item fails, is it possible not to throw CURL NSS error, but get the response instead? <code>CURLOPT_FAILONERROR</code> option does not help.</li>
</ol>

<hr>

<p>CURL was built with NSS:</p>

```curl 7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.27.1 zlib/1.2.3 libidn/1.18 libssh2/1.4.2
Protocols: tftp ftp telnet dict ldap ldaps http file https ftps scp sftp
Features: GSS-Negotiate IDN IPv6 Largefile NTLM SSL libz
```

Update:

The second item can be closed, because this error is really strange: curl_error returns the error, but curl_exec returns valid response at the same time.

答: Try giving a absolute path to the certificate and add a "./" prefix. For example "./path-to-your-cert"</p>

Body:
Request to a single specific https endpoint fails on one of my servers with "NSS: client certificate not found (nickname not specified)" error from PHP CURL.

When I ran the same query from the command line with verbose option I got the same error, but after that I also got a valid response (after the error in the same CURL request).

Then I've enabled verbose option for my PHP CURL request and displayed it for testing like this:

$error = curl_error($curl);

if ($error) {
        echo "cURL Error #:" . $error;

        rewind($verbose);
        $verboseLog = htmlspecialchars(stream_get_contents($verbose));

        echo "
";
        print_r($verboseLog);
} else {
  echo $response;
}

And got this as output:

cURL Error #:NSS: client certificate not found (nickname not specified)
* About to connect() to <address> port 8001 (#0)
*   Trying <ip>... * connected
* Connected to <address> (<ip>) port 8001 (#0)
* skipping SSL peer certificate verification
* NSS: client certificate not found (nickname not specified)
* SSL connection using TLS_RSA_WITH_AES_128_GCM_SHA256
* Server certificate:
*   subject: CN=*.<address>m,O=XXX A.S.,OU=IT,L=Umraniye,ST=Istanbul,C=TR
*   start date: Jun 11 12:52:03 2015 GMT
*   expire date: Jun 09 14:16:13 2018 GMT
*   common name: *.<address>
*   issuer: CN=GlobalSign Organization Validation CA - SHA256 - G2,O=GlobalSign nv-sa,C=BE
> POST /<url_part> HTTP/1.1
Host: <address>:8001
Accept: */*
Accept-Encoding: deflate, gzip
authorization: Basic UlBlahBlahnJrcjEyMzQ1Ng==
cache-control: no-cache
content-type: application/json
postman-token: eeefe018-7cac-1706-7b6d-847800a7ad0f
Content-Length: 333

< HTTP/1.1 200 OK
< set-cookie: sap-usercontext=sap-client=100; path=/
< set-cookie: SAP_SESSIONID_CFP_100=ohZvfO5ZOwq_LTE76Zgz9L-C0NdhlRHngM0AF6R3IFY%3d; path=/
< content-type: application/json; charset=utf-8
< content-length: 1150
< cache-control: max-age=0
< sap-cache-control: +180
< sap-isc-uagent: 0
<
* Connection #0 to host <address> left intact
* Closing connection #0

So, CURL request finished with the error, but in verbose log we see that after the error valid response was also fetched.

Here's my questions:

Is there any way to overcome this NSS issue as long as other different https endpoints work completely fine? Is it connected with endpoint's server configuration and can be resolved there?

If the first item fails, is it possible not to throw CURL NSS error, but get the response instead? CURLOPT_FAILONERROR option does not help.

CURL was built with NSS:

curl 7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.27.1 zlib/1.2.3 libidn/1.18 libssh2/1.4.2
Protocols: tftp ftp telnet dict ldap ldaps http file https ftps scp sftp
Features: GSS-Negotiate IDN IPv6 Largefile NTLM SSL libz

Update:

The second item can be closed, because this error is really strange: curl_error returns the error, but curl_exec returns valid response at the same time.


问:
Disable Zoom effect on Hover for Mobile devices in elevateZoom
when you check the elevateZoom on Mobile, the page scroll option does not work when we click on the image although we off the zoom option. which is a trouble.

We want to disable zoom option for Mobile devices or responsive sizes.

Is there any value or variable we can use to ONLY disable Zoom effect completely for mobile devices?

Can anyone suggest how to do this or if someone did it for their theme in past?

答:
Or you could just hide .zoomContainer using media queries?

For example:

```<code>@media screen and (max-width: 425px) {
    .zoomContainer {
        display: none;
    }
}
</code>```

Body:
Or you could just hide .zoomContainer using media queries?

For example:

@media screen and (max-width: 425px) {
    .zoomContainer {
        display: none;
    }
}


答:
How did you get "## The Scenes"? I don't know. Having used your pattern, I got "## The".

But the code like this:

```<code>pattern = re.compile("#+[\s\w]+")
</code>```

works perfectly.

I think, it is what you need.

Title: In python, how can I find "# The Scenes" from "Behind # The Scenes" with regex?

Body:
How did you get "## The Scenes"? I don't know. Having used your pattern, I got "## The".

But the code like this:

pattern = re.compile("#+[\s\w]+")

works perfectly.

I think, it is what you need.


问:
UISearchController search bar overlap first cell when active
I am using UISearchController to search for data in my tableview. I am not using table view controller. I would like to hide the navigation bar when my search bar is active therefore I set self.searchController.hidesNavigationBarDuringPresentation = YES; to yes.

However when I do this and want to search, my active search bar covers part of the first cell. the covered part has same height as status bar.

I tried other articles and questions similar to this one but nothing helped me to solve it. Then I started to play with the table view header size. I did this

```<code> -(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

  return 20.0f;
}
</code>```

The result was that when I tapped search bar an started to search problem was not there anymore.

However when the search bar is not active there was a gab between searchbar and first cell

Any ideas how to fix this issue?

Edit: after adding self.automaticallyAdjustsScrollViewInsets = false;

答: I have seen similar behavior. Most probably, your table view controller is not implementing heightForHeaderInSection. Precise height of cell is not known, this leads to number of issues like yours.</p>

Body:
I am using UISearchController to search for data in my tableview. I am not using table view controller. I would like to hide the navigation bar when my search bar is active therefore I set self.searchController.hidesNavigationBarDuringPresentation = YES; to yes.

However when I do this and want to search, my active search bar covers part of the first cell. the covered part has same height as status bar.

I tried other articles and questions similar to this one but nothing helped me to solve it. Then I started to play with the table view header size. I did this

 -(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

  return 20.0f;
}

The result was that when I tapped search bar an started to search problem was not there anymore.

However when the search bar is not active there was a gab between searchbar and first cell

Any ideas how to fix this issue?

Edit: after adding self.automaticallyAdjustsScrollViewInsets = false;


问:
Remove box shadow from bottom and right
Im Using box-shadow to achieve the borders between list elements. I made a flexbox of .nav-tabs to enforce consist layout for the list elements.
but i dont want to right and bottom line i want remove it, how can i remove it
what i change  box-shadow: 25px 0 0 -23px gray, 0 25px 0 -23px gray;

.nav-tabs {
  display: flex;
  flex-wrap: wrap;
}

.nav-tabs li {
  box-shadow: 25px 0 0 -23px gray, 0 25px 0 -23px gray;
  padding: 50px;
}

#container .nav-tabs {
  background-image: image(bg-line-bar.png);
  width: auto;
  height: auto;
}

#container .nav-tabs>li.active>a,
.nav-tabs>li.active>a:focus,
.nav-tabs>li.active>a:hover {
  border-width: 0;
}

#container .nav-tabs>li>a {
  border: none;
  color: #666;
}

#container .tab-pane {
  padding: 15px 0;
}

#container .tab-content {
  padding: 20px
}

#container .nav-tabs li.active a {
  border: none;
}

.block {
  width: 203px;
  height: 90px;
  /* margin-left: -45px; */
  margin: -28px -15px;
  padding: 34px 47px;
  text-align: center;
  display: inline-block;
  background: ;
  color: #a6a6a6;
}

.block:hover h1 {
  color: #000000;
}

.block:hover h5 {
  color: #A48973;
}

#base {
  background: #eee;
  display: inline-block;
  height: 120px;
  margin-left: -15px;
  margin-top: -25px;
  position: relative;
  text-align: center;
  width: 111%;
  padding: 5px 10px;
}

#base2 {
  background: #eee;
  display: inline-block;
  height: 120px;
  margin-left: -15px;
  margin-top: -25px;
  position: relative;
  text-align: center;
  width: 111%;
  padding: 5px 10px;
}

#base:before {
  border-bottom: 21px solid #eee;
  border-left: 26px solid transparent;
  border-right: 26px solid transparent;
  content: "";
  height: 0;
  left: 182px;
  position: absolute;
  top: -19px;
  width: 0;
}

#base2:before {
  border-bottom: 21px solid #eee;
  border-left: 26px solid transparent;
  border-right: 26px solid transparent;
  content: "";
  height: 0;
  left: 182px;
  position: absolute;
  top: -19px;
  width: 0;
}

.base-block {
  display: inline-block;
  height: 120px;
  width: 200px;
  margin: -15px;
  display: inline-block;
  text-align: center;
  margin-top: 25px;
}

.base-block h1,
h4 {
  color: #000000;
}

.base-block h5 {
  color: #A48973;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div id="container">
  <ul class="nav nav-tabs" role="tablist">
    <li role="presentation" class="active">

        <div class="block block-1">
          <h1>$ 2,300</h1>
          <h5>Today Revenue</h5>
        </div>

    </li>
    <li role="presentation">

        <div class="block block-2">
          <h1>$ 53,100</h1>
          <h5>Expected Revenue for this month
          </h5>
        </div>

    </li>

    <li role="presentation">

        <div class="block block-3">
          <h1>12
          </h1>
          <h5>Bookings taken today
          </h5>
        </div>

    </li>

    <li role="presentation">

        <div class="block block-4">
          <h1>68%
          </h1>
          <h5>Total monthly occupancy
          </h5>
        </div>

    </li>
  </ul>
  <!--Menu Part 02-->

  <div class="tab-content">
    <div role="tabpanel" class="tab-pane active" id="home">
      <div id="base">
        <div class="base-block">
          <h4>Today’s revenue
          </h4>
          <h1>$ 2,300</h1>
          <h5>5 Rooms sold
          </h5>
        </div>
        <div class="base-block">
          <h4>Todate/Month
          </h4>
          <h1>$ 41,000
          </h1>
          <h5>230 Rooms sold
          </h5>
        </div>

      </div>
    </div>
    <div role="tabpanel" class="tab-pane" id="profile">
      <div id="base2">
        <div class="base-block">
          <h4>Tentative bookings

          </h4>
          <h1>$ 4,500
          </h1>
          <h5>12 Bookings

          </h5>
        </div>
        <div class="base-block">
          <h4>Confirmed Bookings

          </h4>
          <h1>$ 43,000

          </h1>
          <h5>300 Bookings

          </h5>
        </div>

      </div>

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

答:
You could reverse the box-shadow side and hide overflow on parent.

This is what's been modified from original css:

```<code>.nav-tabs {
  overflow:hidden;/*added*/
}

.nav-tabs li {
  box-shadow: -25px 0 0 -23px gray, 0 25px 0 -23px gray;/*update*/
}
</code>```

.nav-tabs {
  display: flex;
  flex-wrap: wrap;
  overflow:hidden;/*added*/
}

.nav-tabs li {
  box-shadow: -25px 0 0 -23px gray, 0 25px 0 -23px gray;/*update*/
  padding: 50px;
}

#container .nav-tabs {
  background-image: image(bg-line-bar.png);
  width: auto;
  height: auto;
}

#container .nav-tabs>li.active>a,
.nav-tabs>li.active>a:focus,
.nav-tabs>li.active>a:hover {
  border-width: 0;
}

#container .nav-tabs>li>a {
  border: none;
  color: #666;
}

#container .tab-pane {
  padding: 15px 0;
}

#container .tab-content {
  padding: 20px
}

#container .nav-tabs li.active a {
  border: none;
}

.block {
  width: 203px;
  height: 90px;
  /* margin-left: -45px; */
  margin: -28px -15px;
  padding: 34px 47px;
  text-align: center;
  display: inline-block;
  background: ;
  color: #a6a6a6;
}

.block:hover h1 {
  color: #000000;
}

.block:hover h5 {
  color: #A48973;
}

#base {
  background: #eee;
  display: inline-block;
  height: 120px;
  margin-left: -15px;
  margin-top: -25px;
  position: relative;
  text-align: center;
  width: 111%;
  padding: 5px 10px;
}

#base2 {
  background: #eee;
  display: inline-block;
  height: 120px;
  margin-left: -15px;
  margin-top: -25px;
  position: relative;
  text-align: center;
  width: 111%;
  padding: 5px 10px;
}

#base:before {
  border-bottom: 21px solid #eee;
  border-left: 26px solid transparent;
  border-right: 26px solid transparent;
  content: "";
  height: 0;
  left: 182px;
  position: absolute;
  top: -19px;
  width: 0;
}

#base2:before {
  border-bottom: 21px solid #eee;
  border-left: 26px solid transparent;
  border-right: 26px solid transparent;
  content: "";
  height: 0;
  left: 182px;
  position: absolute;
  top: -19px;
  width: 0;
}

.base-block {
  display: inline-block;
  height: 120px;
  width: 200px;
  margin: -15px;
  display: inline-block;
  text-align: center;
  margin-top: 25px;
}

.base-block h1,
h4 {
  color: #000000;
}

.base-block h5 {
  color: #A48973;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div id="container">
  <ul class="nav nav-tabs" role="tablist">
    <li role="presentation" class="active">

        <div class="block block-1">
          <h1>$ 2,300</h1>
          <h5>Today Revenue</h5>
        </div>

    </li>
    <li role="presentation">

        <div class="block block-2">
          <h1>$ 53,100</h1>
          <h5>Expected Revenue for this month
          </h5>
        </div>

    </li>

    <li role="presentation">

        <div class="block block-3">
          <h1>12
          </h1>
          <h5>Bookings taken today
          </h5>
        </div>

    </li>

    <li role="presentation">

        <div class="block block-4">
          <h1>68%
          </h1>
          <h5>Total monthly occupancy
          </h5>
        </div>

    </li>
  </ul>
  <!--Menu Part 02-->

  <div class="tab-content">
    <div role="tabpanel" class="tab-pane active" id="home">
      <div id="base">
        <div class="base-block">
          <h4>Today’s revenue
          </h4>
          <h1>$ 2,300</h1>
          <h5>5 Rooms sold
          </h5>
        </div>
        <div class="base-block">
          <h4>Todate/Month
          </h4>
          <h1>$ 41,000
          </h1>
          <h5>230 Rooms sold
          </h5>
        </div>

      </div>
    </div>
    <div role="tabpanel" class="tab-pane" id="profile">
      <div id="base2">
        <div class="base-block">
          <h4>Tentative bookings

          </h4>
          <h1>$ 4,500
          </h1>
          <h5>12 Bookings

          </h5>
        </div>
        <div class="base-block">
          <h4>Confirmed Bookings

          </h4>
          <h1>$ 43,000

          </h1>
          <h5>300 Bookings

          </h5>
        </div>

      </div>

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

Title: Remove box shadow from bottom and right

Body:
Im Using box-shadow to achieve the borders between list elements. I made a flexbox of .nav-tabs to enforce consist layout for the list elements.
but i dont want to right and bottom line i want remove it, how can i remove it
what i change  box-shadow: 25px 0 0 -23px gray, 0 25px 0 -23px gray;

.nav-tabs {
  display: flex;
  flex-wrap: wrap;
}

.nav-tabs li {
  box-shadow: 25px 0 0 -23px gray, 0 25px 0 -23px gray;
  padding: 50px;
}

#container .nav-tabs {
  background-image: image(bg-line-bar.png);
  width: auto;
  height: auto;
}

#container .nav-tabs>li.active>a,
.nav-tabs>li.active>a:focus,
.nav-tabs>li.active>a:hover {
  border-width: 0;
}

#container .nav-tabs>li>a {
  border: none;
  color: #666;
}

#container .tab-pane {
  padding: 15px 0;
}

#container .tab-content {
  padding: 20px
}

#container .nav-tabs li.active a {
  border: none;
}

.block {
  width: 203px;
  height: 90px;
  /* margin-left: -45px; */
  margin: -28px -15px;
  padding: 34px 47px;
  text-align: center;
  display: inline-block;
  background: ;
  color: #a6a6a6;
}

.block:hover h1 {
  color: #000000;
}

.block:hover h5 {
  color: #A48973;
}

#base {
  background: #eee;
  display: inline-block;
  height: 120px;
  margin-left: -15px;
  margin-top: -25px;
  position: relative;
  text-align: center;
  width: 111%;
  padding: 5px 10px;
}

#base2 {
  background: #eee;
  display: inline-block;
  height: 120px;
  margin-left: -15px;
  margin-top: -25px;
  position: relative;
  text-align: center;
  width: 111%;
  padding: 5px 10px;
}

#base:before {
  border-bottom: 21px solid #eee;
  border-left: 26px solid transparent;
  border-right: 26px solid transparent;
  content: "";
  height: 0;
  left: 182px;
  position: absolute;
  top: -19px;
  width: 0;
}

#base2:before {
  border-bottom: 21px solid #eee;
  border-left: 26px solid transparent;
  border-right: 26px solid transparent;
  content: "";
  height: 0;
  left: 182px;
  position: absolute;
  top: -19px;
  width: 0;
}

.base-block {
  display: inline-block;
  height: 120px;
  width: 200px;
  margin: -15px;
  display: inline-block;
  text-align: center;
  margin-top: 25px;
}

.base-block h1,
h4 {
  color: #000000;
}

.base-block h5 {
  color: #A48973;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

$ 2,300

Today Revenue

$ 53,100

Expected Revenue for this month

12

Bookings taken today

68%

Total monthly occupancy

Today’s revenue

$ 2,300

5 Rooms sold

Todate/Month

$ 41,000

230 Rooms sold

Tentative bookings

$ 4,500

12 Bookings

Confirmed Bookings

$ 43,000

300 Bookings

Body:
You could reverse the box-shadow side and hide overflow on parent.

This is what's been modified from original css:

.nav-tabs {
  overflow:hidden;/*added*/
}

.nav-tabs li {
  box-shadow: -25px 0 0 -23px gray, 0 25px 0 -23px gray;/*update*/
}

.nav-tabs {
  display: flex;
  flex-wrap: wrap;
  overflow:hidden;/*added*/
}

.nav-tabs li {
  box-shadow: -25px 0 0 -23px gray, 0 25px 0 -23px gray;/*update*/
  padding: 50px;
}

#container .nav-tabs {
  background-image: image(bg-line-bar.png);
  width: auto;
  height: auto;
}

#container .nav-tabs>li.active>a,
.nav-tabs>li.active>a:focus,
.nav-tabs>li.active>a:hover {
  border-width: 0;
}

#container .nav-tabs>li>a {
  border: none;
  color: #666;
}

#container .tab-pane {
  padding: 15px 0;
}

#container .tab-content {
  padding: 20px
}

#container .nav-tabs li.active a {
  border: none;
}

.block {
  width: 203px;
  height: 90px;
  /* margin-left: -45px; */
  margin: -28px -15px;
  padding: 34px 47px;
  text-align: center;
  display: inline-block;
  background: ;
  color: #a6a6a6;
}

.block:hover h1 {
  color: #000000;
}

.block:hover h5 {
  color: #A48973;
}

#base {
  background: #eee;
  display: inline-block;
  height: 120px;
  margin-left: -15px;
  margin-top: -25px;
  position: relative;
  text-align: center;
  width: 111%;
  padding: 5px 10px;
}

#base2 {
  background: #eee;
  display: inline-block;
  height: 120px;
  margin-left: -15px;
  margin-top: -25px;
  position: relative;
  text-align: center;
  width: 111%;
  padding: 5px 10px;
}

#base:before {
  border-bottom: 21px solid #eee;
  border-left: 26px solid transparent;
  border-right: 26px solid transparent;
  content: "";
  height: 0;
  left: 182px;
  position: absolute;
  top: -19px;
  width: 0;
}

#base2:before {
  border-bottom: 21px solid #eee;
  border-left: 26px solid transparent;
  border-right: 26px solid transparent;
  content: "";
  height: 0;
  left: 182px;
  position: absolute;
  top: -19px;
  width: 0;
}

.base-block {
  display: inline-block;
  height: 120px;
  width: 200px;
  margin: -15px;
  display: inline-block;
  text-align: center;
  margin-top: 25px;
}

.base-block h1,
h4 {
  color: #000000;
}

.base-block h5 {
  color: #A48973;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div id="container">
  <ul class="nav nav-tabs" role="tablist">
    <li role="presentation" class="active">
      <a href="#home" aria-controls="home" role="tab" data-toggle="tab">
        <div class="block block-1">
          <h1>$ 2,300</h1>
          <h5>Today Revenue</h5>
        </div>
      </a>
    </li>
    <li role="presentation">
      <a href="#profile" aria-controls="profile" role="tab" data-toggle="tab">
        <div class="block block-2">
          <h1>$ 53,100</h1>
          <h5>Expected Revenue for this month
          </h5>
        </div>
      </a>
    </li>

    <li role="presentation">
      <a href="#messages" aria-controls="messages" role="tab" data-toggle="tab">
        <div class="block block-3">
          <h1>12
          </h1>
          <h5>Bookings taken today
          </h5>
        </div>
      </a>
    </li>

    <li role="presentation">
      <a href="#settings" aria-controls="settings" role="tab" data-toggle="tab">
        <div class="block block-4">
          <h1>68%
          </h1>
          <h5>Total monthly occupancy
          </h5>
        </div>
      </a>
    </li>
  </ul>
  <!--Menu Part 02-->

  <div class="tab-content">
    <div role="tabpanel" class="tab-pane active" id="home">
      <div id="base">
        <div class="base-block">
          <h4>Today’s revenue
          </h4>
          <h1>$ 2,300</h1>
          <h5>5 Rooms sold
          </h5>
        </div>
        <div class="base-block">
          <h4>Todate/Month
          </h4>
          <h1>$ 41,000
          </h1>
          <h5>230 Rooms sold
          </h5>
        </div>

      </div>
    </div>
    <div role="tabpanel" class="tab-pane" id="profile">
      <div id="base2">
        <div class="base-block">
          <h4>Tentative bookings

          </h4>
          <h1>$ 4,500
          </h1>
          <h5>12 Bookings

          </h5>
        </div>
        <div class="base-block">
          <h4>Confirmed Bookings

          </h4>
          <h1>$ 43,000

          </h1>
          <h5>300 Bookings

          </h5>
        </div>

      </div>

    </div>
  </div>
</div>


问:
AngularJS ng-repeat long array, sorted by date but limiting to only 10 rows
I've got a long array with over 100 objects. Each object has a member.date, but some are null, and some have a date string.

my problem is I only want to show the latest 10, but when I add limitTo:10 I get zero results (because the first entry that is displayed is the 42nd object in the array.

答:
I ended up resorting the array by end date, then simply limiting the ng-repeat to 10.

```<code>// sort all members by ended date
$rootScope.provider.allMembers.sort(function(a,b){
   return new Date(b.ended) - new Date(a.ended);
});
</code>```

then using this ng-repeat:

```<code><tr ng-repeat="(k, member) in provider.allMembers | limitTo:10">
</code>```

Body:
I ended up resorting the array by end date, then simply limiting the ng-repeat to 10.

// sort all members by ended date
$rootScope.provider.allMembers.sort(function(a,b){
   return new Date(b.ended) - new Date(a.ended);
});

then using this ng-repeat:

<tr ng-repeat="(k, member) in provider.allMembers | limitTo:10">


问:
Choose which browser Webpack opens?
I installed Vue.js using the CLI as found here:

```<code># install vue-cli
$ npm install --global vue-cli
# create a new project using the "webpack" template
$ vue init webpack my-project
# install dependencies and go!
$ cd my-project
$ npm install
$ npm run dev
</code>```

When I run it opens Safari, my default browser. I would like to specify Chrome (used only for development) without changing the OS default browser.

The webpack.dev.conf.js is as follows:

```<code>var utils = require('./utils')
var webpack = require('webpack')
var config = require('../config')
var merge = require('webpack-merge')
var baseWebpackConfig = require('./webpack.base.conf')
var HtmlWebpackPlugin = require('html-webpack-plugin')
var FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')

// add hot-reload related code to entry chunks
Object.keys(baseWebpackConfig.entry).forEach(function (name) {
  baseWebpackConfig.entry[name] = ['./build/dev-client'].concat(baseWebpackConfig.entry[name])
})

module.exports = merge(baseWebpackConfig, {
  module: {
    rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap })
  },
  // cheap-module-eval-source-map is faster for development
  devtool: '#source-map',
  plugins: [
    new webpack.DefinePlugin({
      'process.env': config.dev.env
    }),
    // https://github.com/glenjamin/webpack-hot-middleware#installation--usage
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoEmitOnErrorsPlugin(),
    // https://github.com/ampedandwired/html-webpack-plugin
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: 'index.html',
      inject: true
    }),
    new FriendlyErrorsPlugin()
  ]
})
</code>```

Anybody know how to specify Chrome in this configuration?

答:
There is already a issue assigned for it on github but it's still under development.

Issue Link

Update

The issue finally got merged. Now you can specify the browser using CLI or webpack.dev.conf.

Using CLI  "start": "webpack-dev-server --config webpack.dev.js --open chrome"

Using  webpack.config.js:

```<code>module.exports = {
  //...
  devServer: {
    open: 'Google Chrome'
  }
};
</code>```

Documentation Link

ContentLicense: CC BY-SA 4.0

Title: Choose which browser Webpack opens?

Body:
I installed Vue.js using the CLI as found here:

# install vue-cli
$ npm install --global vue-cli
# create a new project using the "webpack" template
$ vue init webpack my-project
# install dependencies and go!
$ cd my-project
$ npm install
$ npm run dev

When I run it opens Safari, my default browser. I would like to specify Chrome (used only for development) without changing the OS default browser.

The webpack.dev.conf.js is as follows:

var utils = require('./utils')
var webpack = require('webpack')
var config = require('../config')
var merge = require('webpack-merge')
var baseWebpackConfig = require('./webpack.base.conf')
var HtmlWebpackPlugin = require('html-webpack-plugin')
var FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')

// add hot-reload related code to entry chunks
Object.keys(baseWebpackConfig.entry).forEach(function (name) {
  baseWebpackConfig.entry[name] = ['./build/dev-client'].concat(baseWebpackConfig.entry[name])
})

module.exports = merge(baseWebpackConfig, {
  module: {
    rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap })
  },
  // cheap-module-eval-source-map is faster for development
  devtool: '#source-map',
  plugins: [
    new webpack.DefinePlugin({
      'process.env': config.dev.env
    }),
    // https://github.com/glenjamin/webpack-hot-middleware#installation--usage
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoEmitOnErrorsPlugin(),
    // https://github.com/ampedandwired/html-webpack-plugin
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: 'index.html',
      inject: true
    }),
    new FriendlyErrorsPlugin()
  ]
})

Anybody know how to specify Chrome in this configuration?

Body:
There is already a issue assigned for it on github but it's still under development.

Issue Link

Update

The issue finally got merged. Now you can specify the browser using CLI or webpack.dev.conf.

Using CLI  "start": "webpack-dev-server --config webpack.dev.js --open chrome"

Using  webpack.config.js:

module.exports = {
  //...
  devServer: {
    open: 'Google Chrome'
  }
};

Documentation Link


问:
c# To check if a year is a leap year without DateTime
Having some trouble with a program, currently in my 2nd week of programming course so sorry if this isn't the best place to ask.

```<code>class Program
{
    static void Main(string[] args)
    {
        int a;
        Console.WriteLine("Enter the year");
        a = int.Parse(Console.ReadLine());
        {
            if ((a % 4)  == 0)
                Console.WriteLine("It's a leap year.");
            else
                Console.WriteLine("It's not a leap year.");
        }
        Console.ReadLine();
    }
}
</code>```

Having lots of trouble with the formula for this.

答:
You can try this..</p>

```<code>class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Please Enter The Year:");
            int year = int.Parse(Console.ReadLine());
            if (year%400 == 0 || (year%4 == 0 && year%100 != 0))
            {
                Console.WriteLine("Leap Year");
            }
            else
            {
                Console.WriteLine("Not Leap Year");
            }
            Console.ReadLine();
        }
    }
</code>```

Body:
Having some trouble with a program, currently in my 2nd week of programming course so sorry if this isn't the best place to ask.

class Program
{
    static void Main(string[] args)
    {
        int a;
        Console.WriteLine("Enter the year");
        a = int.Parse(Console.ReadLine());
        {
            if ((a % 4)  == 0)
                Console.WriteLine("It's a leap year.");
            else
                Console.WriteLine("It's not a leap year.");
        }
        Console.ReadLine();
    }
}

Having lots of trouble with the formula for this.

Body:
You can try this..

class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Please Enter The Year:");
            int year = int.Parse(Console.ReadLine());
            if (year%400 == 0 || (year%4 == 0 && year%100 != 0))
            {
                Console.WriteLine("Leap Year");
            }
            else
            {
                Console.WriteLine("Not Leap Year");
            }
            Console.ReadLine();
        }
    }


问:
Running XCUITest on device gives "Too many instance of this service are already running"
I have a UI test suite that I am trying to run on device. But XCode always reports an error

Things I have already tried:

Clean and build

Clean and clear derived data and build

Uninstall the app from device

Restart the XCode

Restart the mac

Is anyone is also having such issue? Please help.

答: Restarting the device helped me.</p>

Body: Restarting the device helped me.


问:
Change Background Color with jQuery
I have a form with multiple drop downs... I would like to set the background color of the visible dropdowns to gray when they are disabled. All of these dropdown's id's begin with usrControl. Here is what I have this far..

```<code>    $('select[id ^= "usrControl"]:visible').each(function(){
this.css("background-color")
});
</code>```

Not sure how to get the disabled/enabled selectors.

Thanks in advance

```<code>Protected _picklistColorScriptText As String = "$(document).ready(function(){ " + _
                                                "$('[id ^= ""usrControl""]:visible:disabled').css(""background-color"", '#DCDCDC'); " + _
                                                "$('[id ^= ""usrControl""]:visible:enabled').css(""background-color"", '#FFFFFF');" + _
                                                "});"
</code>```

This works. However, this sets the background for the entire control to gray, how can I change the color of the selected item to gray?

答:
You are only getting the CSS property.
Try this: </p>

```<code>$(this).css( "property", "value" );
</code>```

Title: Change Background Color with jQuery

Body:
I have a form with multiple drop downs... I would like to set the background color of the visible dropdowns to gray when they are disabled. All of these dropdown's id's begin with usrControl. Here is what I have this far..

    $('select[id ^= "usrControl"]:visible').each(function(){
this.css("background-color")
});

Not sure how to get the disabled/enabled selectors.

Thanks in advance

Protected _picklistColorScriptText As String = "$(document).ready(function(){ " + _
                                                "$('[id ^= ""usrControl""]:visible:disabled').css(""background-color"", '#DCDCDC'); " + _
                                                "$('[id ^= ""usrControl""]:visible:enabled').css(""background-color"", '#FFFFFF');" + _
                                                "});"

This works. However, this sets the background for the entire control to gray, how can I change the color of the selected item to gray?

Body:
You are only getting the CSS property.
Try this:

$(this).css( "property", "value" );


问:
How to create array of object in node.js
My Class look like this:

```<code>var Coin = {
    _id: null,
    createGame: function(id) {
     this._id = id;
    },
    start: function() {

    }
};
</code>```

I'm trying to create an array of objects, but I can create only one.
Could someone tell what i'm doing wrong?

I create array like this:

```<code>CoinArray = [];
CoinArray['123'] = new Coin.createGame(123);
CoinArray['333'] = new Coin.createGame(333);
CoinArray['333'].start
</code>```

At the end I want to have array with object and for example I will take first el of array, and execute other method from Coin class.

答:
You need to push a newly created item to your array like below:

```<code>CoinArray.push(new Coin.Create('123));
</code>```

On the other hand if you want to create an object with keys ids and values corresponding Coin objects, you should try this:

```<code>CoinDictionary = {};
CoinDictionary['123'] = new Coin.Create('123');
</code>```

Note:

I think that you should refactor a bit the Coin if you want to use it as a constructor function:

```<code>function Coin(id){
    this.id = id;
}
</code>```

Doing this change you can use it as below:

```<code>CoinArray.push(new Coin('123'));
</code>```

function Coin(id){
    this.id = id;
}

var CoinArray = [];
CoinArray.push(new Coin('123'));
CoinArray.push(new Coin('456'));
CoinArray.push(new Coin('789'));

console.log(CoinArray);```
</div>
</div>
</p>

<p><strong>Update</strong></p>

<blockquote>
  <p>At the end I want to have array with object and for example I will
  take first el of array, and execute other method from Coin class.</p>
</blockquote>

<p>For this purpose If I were you I would have gone with the creation of an object with keys the ids and values references to <code>Coin</code> objects:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function Coin(id){
    this.id = id;
}

Coin.prototype.start = function(){
    console.log("game with id "+this.id+" started.");
}

Coins = {}
Coins['123'] = new Coin('123');
Coins['456'] = new Coin('456');
Coins['789'] = new Coin('789');

Coins['456'].start();</code>```

Body:
My Class look like this:

var Coin = {
    _id: null,
    createGame: function(id) {
     this._id = id;
    },
    start: function() {

    }
};

I'm trying to create an array of objects, but I can create only one.
Could someone tell what i'm doing wrong?

I create array like this:

CoinArray = [];
CoinArray['123'] = new Coin.createGame(123);
CoinArray['333'] = new Coin.createGame(333);
CoinArray['333'].start

At the end I want to have array with object and for example I will take first el of array, and execute other method from Coin class.

Body:
You need to push a newly created item to your array like below:

CoinArray.push(new Coin.Create('123));

On the other hand if you want to create an object with keys ids and values corresponding Coin objects, you should try this:

CoinDictionary = {};
CoinDictionary['123'] = new Coin.Create('123');

Note:

I think that you should refactor a bit the Coin if you want to use it as a constructor function:

function Coin(id){
    this.id = id;
}

Doing this change you can use it as below:

CoinArray.push(new Coin('123'));

function Coin(id){
    this.id = id;
}

var CoinArray = [];
CoinArray.push(new Coin('123'));
CoinArray.push(new Coin('456'));
CoinArray.push(new Coin('789'));

console.log(CoinArray);

Update

At the end I want to have array with object and for example I will
  take first el of array, and execute other method from Coin class.

For this purpose If I were you I would have gone with the creation of an object with keys the ids and values references to Coin objects:

function Coin(id){
    this.id = id;
}

Coin.prototype.start = function(){
    console.log("game with id "+this.id+" started.");
}

Coins = {}
Coins['123'] = new Coin('123');
Coins['456'] = new Coin('456');
Coins['789'] = new Coin('789');

Coins['456'].start();


问:
How to integrate Ant with Checkstyle and PMD plug-ins in Jenkins
I want to integrate Checkstyle and PMD plug-ins in Jenkins for checking quality code automatically.
I followed the instructions from: http://www.treselle.com/blog/static-code-analysis-jenkins/

My build.xml in workspace was appended those codes:

```<code><taskdef name="checkstyle" classpath="WEB-INF/libs/checkstyle-5.6.jar" classname="com.puppycrawl.tools.checkstyle.CheckStyleTask" />
<target name="checkstyle" description="Generates a report of code convention violations.">
    <checkstyle config="sun_checks.xml" failOnViolation="false">
        <formatter type="xml" tofile="checkstyle_report.xml" />
        <fileset dir="WEB-INF/src" includes="**/*.java" />
    </checkstyle>
</target>
<taskdef name="pmd" classpath="WEB-INF/libs/pmd.jar" classname="net.sourceforge.pmd.ant.PMDTask" />
<target name="pmd" depends="compress">
    <pmd rulesetfiles="java-imports">
        <formatter type="xml" toFile="pmd_report.x.ml" />
        <fileset dir="WEB-INF/src">
            <include name="**/*.java" />
        </fileset>
    </pmd>
</target>
</code>```

I also added enough library, but when I builded Jobs, I got a exception:

```<code>taskdef class com.puppycrawl.tools.checkstyle.CheckStyleTask cannot be found using the classloader AntClassLoader[]
</code>```

Why is there such error? And How do I integrate them correctly?

Thanks a lot!

答:
classname="com.puppycrawl.tools.checkstyle.CheckStyleTask" />
  taskdef class com.puppycrawl.tools.checkstyle.CheckStyleTask cannot be found

The class is named CheckstyleAntTask.

See https://github.com/checkstyle/checkstyle/blob/master/config/ant-phase-verify.xml on an example on how to use CheckstyleAntTask.

checkstyle-5.6.jar

I recommend upgrading to a newer version. Checkstyle is currently on version 8.

Body:
I want to integrate Checkstyle and PMD plug-ins in Jenkins for checking quality code automatically.
I followed the instructions from: http://www.treselle.com/blog/static-code-analysis-jenkins/

My build.xml in workspace was appended those codes:

<taskdef name="checkstyle" classpath="WEB-INF/libs/checkstyle-5.6.jar" classname="com.puppycrawl.tools.checkstyle.CheckStyleTask" />
<target name="checkstyle" description="Generates a report of code convention violations.">
    <checkstyle config="sun_checks.xml" failOnViolation="false">
        <formatter type="xml" tofile="checkstyle_report.xml" />
        <fileset dir="WEB-INF/src" includes="**/*.java" />
    </checkstyle>
</target>
<taskdef name="pmd" classpath="WEB-INF/libs/pmd.jar" classname="net.sourceforge.pmd.ant.PMDTask" />
<target name="pmd" depends="compress">
    <pmd rulesetfiles="java-imports">
        <formatter type="xml" toFile="pmd_report.x.ml" />
        <fileset dir="WEB-INF/src">
            <include name="**/*.java" />
        </fileset>
    </pmd>
</target>

I also added enough library, but when I builded Jobs, I got a exception:

taskdef class com.puppycrawl.tools.checkstyle.CheckStyleTask cannot be found using the classloader AntClassLoader[]

Why is there such error? And How do I integrate them correctly?

Thanks a lot!


问:
how to obtain index of dataframe by comparing values of a column to a string without iterrows
I have a dataframe(df) with a large number of rows :

```<code>0   A     B     C     D     E
1   ax    92    47    32    89
2   av    12    41    26    87
3   bn    54    87    98    09
</code>```

string='av'
I need to find the index of df with A=av
it need to return 2

I tried using df.iterrows(), but there are a huge number of rows which takes a lot of time or crashes

Is it possible to do this without iterrows ?

答:
```<code>index=df.loc[df['A'] == 'av', '0'].iloc[0]
</code>```

This technique is called Boolean Masking.index will have value 2
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html
Refer to Pandas Documentation. Pandas is well documented !

Body:
I have a dataframe(df) with a large number of rows :

0   A     B     C     D     E
1   ax    92    47    32    89
2   av    12    41    26    87
3   bn    54    87    98    09

string='av'
I need to find the index of df with A=av
it need to return 2

I tried using df.iterrows(), but there are a huge number of rows which takes a lot of time or crashes

Is it possible to do this without iterrows ?

Body:
index=df.loc[df['A'] == 'av', '0'].iloc[0]

This technique is called Boolean Masking.index will have value 2
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html
Refer to Pandas Documentation. Pandas is well documented !


答:
Use boolean filtering and .loc.

Three ways to access value 2 from column '0'

```<code>In [377]: df.loc[df['A'] == 'av', '0']
Out[377]:
1    2
Name: 0, dtype: int64

In [378]: df.loc[df['A'] == 'av', '0'].item()
Out[378]: 2L

In [379]: df.loc[df['A'] == 'av', '0'].iloc[0]
Out[379]: 2
</code>```

Title: how to obtain index of dataframe by comparing values of a column to a string without iterrows

Body:
Use boolean filtering and .loc.

Three ways to access value 2 from column '0'

In [377]: df.loc[df['A'] == 'av', '0']
Out[377]:
1    2
Name: 0, dtype: int64

In [378]: df.loc[df['A'] == 'av', '0'].item()
Out[378]: 2L

In [379]: df.loc[df['A'] == 'av', '0'].iloc[0]
Out[379]: 2


问:
Check if received more or less than one message
I need to make simple chat application using QTcpSocket and QTcpServer. I understand I should put message size in the beginning of the message to check message bounds. But how should I handle the cases when application receives only part of the message or more than one message?

Or there could be the case when application at first receives incomplete message and after that receives another message. In that situation both messages would be combined in one and only part of second message would be recognized.

答:
You are right. Data from single reading could be incomplete. Read this entry.
You can make up your own protocol for correct data transfer.
Let`s imagine that you have to send text message. You could do it in the next way:
First 4 bytes - message size, next bytes - message.
When you receive first piece of data you can analyze it and understand hove many bytes you are waiting for. When you read all data from the first message, beginning of the next message will contain full message size in the firs 4 bytes.</p>