问:
How to manually create multipart/form-data
We can use .formData() of Body mixin to return a FormData representation of data at Chromium (Chrome) 60+ and Firefox 39+

Relevant specifications:

7.2 The Multipart Content-Type

Returning Values from Forms:  multipart/form-data

Errata

Clarification of Body package data algorithm with bytes, FormData and multipart/form-data MIME type #392

Documenting de-facto handling of multipart/form-data form field file uploads #3040

Related

Multipart HTTP response

How to upload files in Web Workers when FormData is not defined

How to manually create multipart/form-data using JavaScript at client and at server to serve the multipart/form-data as a response?

答:
You can write you own FormData polyfill, or just google it "FormData polyfill"))) And also you can use normal FormData at browsers Chrome, FireFox, Opera, Safari, IE(10+), Edge.
FormData polyfill is only useful for old IE, and for workers, but for workers you better should use this - https://gist.github.com/Rob--W/8b5adedd84c0d36aba64

wikipedia

standart formdata not of body

What you need to do? You want send formdata or recieve it at js?

You can try to use my polyfill, but I have not tested it.

sample:

```<code>var data = new RawFormData();
data.append("key","value")
data.append("key", new Blob("test"), "my file.txt");
data.getOutputDeferred().then(function(formData){
    var xml = new XMLHttpRequest();
    xml.setRequestHeader("Content-Type", "multipart/form-data; boundary=" + data.getBoundry());
    xml.setRequestHeader("Content-Length", formData.length);
    xml.open(method, url);
    xml.send(formData);
});
</code>```

code:

```<code>/**
* @constructor
*/
RawFormData = function () {
    this._promises = [];
    this._boundry = this.makeBoundary();
};

/**
* @return {string}
*/
RawFormData.prototype.getBoundary = function () {
    return this._boundry;
}

/**
* @return {string}
*/
RawFormData.prototype.makeBoundary = function () {
    return 'MyBoundary' + window.btoa(Math.random().toString()).substr(0, 12);
};

/**
* @param {string} name
* @param {string|number|File|Blob|boolean|null|undefined} val
* @param {string=} filename
*/
RawFormData.prototype.append = function (name, val, filename) {
    var prom = null;

    if(val instanceof File || val instanceof Blob){
        prom = this.readAsBinaryString(val).then(function(base64){
            var contentType = val.type || 'application/octet-stream';
            var result = '--' + this._boundry + '\r\n' +
                'Content-Disposition: form-data; ' +
                'name="' + name + '"; filename="' + this.encode_utf8(filename || "blob") + '"\r\n' +
                'Content-Type: ' + contentType + '\r\n\r\n' +
                base64 + '\r\n';
            return result;
        }.bind(this))
    }else{
        prom = new Promise(function(resolve){
            return '--' + this._boundry + '\r\n' +
                'Content-Disposition: form-data; ' +
                'name="' + this.encode_utf8(name) + '"\r\n\r\n' +
                this.encode_utf8(val) + '\r\n'
        }.bind(this));
    }

    this._promises.push(prom);

    return prom;
};
/**
* @return {File|Blob} blob
* @return {Promise<string>}
*/
RawFormData.prototype.readAsBinaryString = function (blob) {
        var reader = new FileReader();
        return new Promise(function(resolve,reject){
            var binStringCallback = function (e) {
                resolve(e.target.result);
            };

            var arrBufferCallback = function (e) {
                var binary = "";
                var bytes = new Uint8Array(e.target.result);
                var length = bytes.byteLength;
                for (var i = 0; i < length; i++) {
                    binary += String.fromCharCode(bytes[i]);
                }
                resolve(binary);
            };

            reader.onerror = reader.onabort = function () {
                resolve(null);
            };

            if (typeof reader.readAsBinaryString != "undefined") {
                reader.onload = binStringCallback;
                reader.readAsBinaryString(blob);
            } else {
                reader.onload = arrBufferCallback;
                reader.readAsArrayBuffer(blob);
            }
        });
};

RawFormData.prototype.encode_utf8 = function( s ){
   return unescape( encodeURIComponent( s ) );
}

RawFormData.prototype.getOutputDeferred = function () {
    return Promise.all(this._promises).then(function (rows) {
        var output = '--' + this._boundry + '\r\n';
        rows.forEach(function(row) {
            output += row;
        });
        output += '--' + this._boundry + '\r\n';
        return output;
    }.bind(this));
};
</code>```

Body:
You can write you own FormData polyfill, or just google it "FormData polyfill"))) And also you can use normal FormData at browsers Chrome, FireFox, Opera, Safari, IE(10+), Edge.
FormData polyfill is only useful for old IE, and for workers, but for workers you better should use this - https://gist.github.com/Rob--W/8b5adedd84c0d36aba64

wikipedia

standart formdata not of body

What you need to do? You want send formdata or recieve it at js?

You can try to use my polyfill, but I have not tested it.

sample:

var data = new RawFormData();
data.append("key","value")
data.append("key", new Blob("test"), "my file.txt");
data.getOutputDeferred().then(function(formData){
    var xml = new XMLHttpRequest();
    xml.setRequestHeader("Content-Type", "multipart/form-data; boundary=" + data.getBoundry());
    xml.setRequestHeader("Content-Length", formData.length);
    xml.open(method, url);
    xml.send(formData);
});

code:

/**
* @constructor
*/
RawFormData = function () {
    this._promises = [];
    this._boundry = this.makeBoundary();
};

/**
* @return {string}
*/
RawFormData.prototype.getBoundary = function () {
    return this._boundry;
}

/**
* @return {string}
*/
RawFormData.prototype.makeBoundary = function () {
    return 'MyBoundary' + window.btoa(Math.random().toString()).substr(0, 12);
};

/**
* @param {string} name
* @param {string|number|File|Blob|boolean|null|undefined} val
* @param {string=} filename
*/
RawFormData.prototype.append = function (name, val, filename) {
    var prom = null;

    if(val instanceof File || val instanceof Blob){
        prom = this.readAsBinaryString(val).then(function(base64){
            var contentType = val.type || 'application/octet-stream';
            var result = '--' + this._boundry + '\r\n' +
                'Content-Disposition: form-data; ' +
                'name="' + name + '"; filename="' + this.encode_utf8(filename || "blob") + '"\r\n' +
                'Content-Type: ' + contentType + '\r\n\r\n' +
                base64 + '\r\n';
            return result;
        }.bind(this))
    }else{
        prom = new Promise(function(resolve){
            return '--' + this._boundry + '\r\n' +
                'Content-Disposition: form-data; ' +
                'name="' + this.encode_utf8(name) + '"\r\n\r\n' +
                this.encode_utf8(val) + '\r\n'
        }.bind(this));
    }

    this._promises.push(prom);

    return prom;
};
/**
* @return {File|Blob} blob
* @return {Promise<string>}
*/
RawFormData.prototype.readAsBinaryString = function (blob) {
        var reader = new FileReader();
        return new Promise(function(resolve,reject){
            var binStringCallback = function (e) {
                resolve(e.target.result);
            };

            var arrBufferCallback = function (e) {
                var binary = "";
                var bytes = new Uint8Array(e.target.result);
                var length = bytes.byteLength;
                for (var i = 0; i < length; i++) {
                    binary += String.fromCharCode(bytes[i]);
                }
                resolve(binary);
            };

            reader.onerror = reader.onabort = function () {
                resolve(null);
            };

            if (typeof reader.readAsBinaryString != "undefined") {
                reader.onload = binStringCallback;
                reader.readAsBinaryString(blob);
            } else {
                reader.onload = arrBufferCallback;
                reader.readAsArrayBuffer(blob);
            }
        });
};

RawFormData.prototype.encode_utf8 = function( s ){
   return unescape( encodeURIComponent( s ) );
}

RawFormData.prototype.getOutputDeferred = function () {
    return Promise.all(this._promises).then(function (rows) {
        var output = '--' + this._boundry + '\r\n';
        rows.forEach(function(row) {
            output += row;
        });
        output += '--' + this._boundry + '\r\n';
        return output;
    }.bind(this));
};


来源: stackexchange

问:
Python: how to find the first nonzero in a multi-series dataframe?
I have a dataframe with 5 columns indexed to date.  the data is consisted of 0's and 1's.  I would like to find the first nonzeros in each series and multiple it (and only it) by 100.

Date   A   B   C   D   E
3/1/16  0   0   0   0   0
3/2/16  0   0   1   0   0
3/3/16  1   0   0   0   0
3/4/16  0   1   0   0   0
3/7/16  0   0   1   0   1
3/8/16  0   0   0   0   1
3/9/16  0   0   0   1   1

I tried the following code, but it didn't work.

```<code>for col in df.columns:
    idx = df[col].first_valid_index()
    df[col][idx] = df[col][idx]*100.
</code>```

答:
Use set_index first for all numeric columns and then create boolean mask with eq (same as ==) with chain by cumsum and compare too.

Then select by mask and multiple, last reset_index:

```<code>df = df.set_index('Date')

m = df.eq(1) & df.cumsum().eq(1)
df[m] *= 100

df = df.reset_index()
print (df)
     Date    A    B    C    D    E
0  3/1/16    0    0    0    0    0
1  3/2/16    0    0  100    0    0
2  3/3/16  100    0    0    0    0
3  3/4/16    0  100    0    0    0
4  3/7/16    0    0    1    0  100
5  3/8/16    0    0    0    0    1
6  3/9/16    0    0    0  100    1
</code>```

Details:

```<code>print (df.cumsum())
        A  B  C  D  E
Date
3/1/16  0  0  0  0  0
3/2/16  0  0  1  0  0
3/3/16  1  0  1  0  0
3/4/16  1  1  1  0  0
3/7/16  1  1  2  0  1
3/8/16  1  1  2  0  2
3/9/16  1  1  2  1  3

print (df.cumsum().eq(1))
            A      B      C      D      E
Date
3/1/16  False  False  False  False  False
3/2/16  False  False   True  False  False
3/3/16   True  False   True  False  False
3/4/16   True   True   True  False  False
3/7/16   True   True  False  False   True
3/8/16   True   True  False  False  False
3/9/16   True   True  False   True  False

print (df.eq(1))
            A      B      C      D      E
Date
3/1/16  False  False  False  False  False
3/2/16  False  False   True  False  False
3/3/16   True  False  False  False  False
3/4/16  False   True  False  False  False
3/7/16  False  False   True  False   True
3/8/16  False  False  False  False   True
3/9/16  False  False  False   True   True
</code>```

```<code>m = df.eq(1) & df.cumsum(axis=1).eq(1)
print (m)
            A      B      C      D      E
Date
3/1/16  False  False  False  False  False
3/2/16  False  False   True  False  False
3/3/16   True  False  False  False  False
3/4/16  False   True  False  False  False
3/7/16  False  False   True  False  False
3/8/16  False  False  False  False   True
3/9/16  False  False  False   True  False
</code>```

Setup:

```<code>from pandas.compat import StringIO

temp=u"""Date   A   B   C   D   E
3/1/16  0   0   0   0   0
3/2/16  0   0   1   0   0
3/3/16  1   0   0   0   0
3/4/16  0   1   0   0   0
3/7/16  0   0   1   0   1
3/8/16  0   0   0   0   1
3/9/16  0   0   0   1   1"""
df = pd.read_csv(StringIO(temp), sep="\s+")
print (df)

     Date  A  B  C  D  E
0  3/1/16  0  0  0  0  0
1  3/2/16  0  0  1  0  0
2  3/3/16  1  0  0  0  0
3  3/4/16  0  1  0  0  0
4  3/7/16  0  0  1  0  1
5  3/8/16  0  0  0  0  1
6  3/9/16  0  0  0  1  1
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a dataframe with 5 columns indexed to date.  the data is consisted of 0's and 1's.  I would like to find the first nonzeros in each series and multiple it (and only it) by 100.

Date   A   B   C   D   E
3/1/16  0   0   0   0   0
3/2/16  0   0   1   0   0
3/3/16  1   0   0   0   0
3/4/16  0   1   0   0   0
3/7/16  0   0   1   0   1
3/8/16  0   0   0   0   1
3/9/16  0   0   0   1   1

I tried the following code, but it didn't work.

for col in df.columns:
    idx = df[col].first_valid_index()
    df[col][idx] = df[col][idx]*100.

Body:
Use set_index first for all numeric columns and then create boolean mask with eq (same as ==) with chain by cumsum and compare too.

Then select by mask and multiple, last reset_index:

df = df.set_index('Date')

m = df.eq(1) & df.cumsum().eq(1)
df[m] *= 100

df = df.reset_index()
print (df)
     Date    A    B    C    D    E
0  3/1/16    0    0    0    0    0
1  3/2/16    0    0  100    0    0
2  3/3/16  100    0    0    0    0
3  3/4/16    0  100    0    0    0
4  3/7/16    0    0    1    0  100
5  3/8/16    0    0    0    0    1
6  3/9/16    0    0    0  100    1

Details:

print (df.cumsum())
        A  B  C  D  E
Date
3/1/16  0  0  0  0  0
3/2/16  0  0  1  0  0
3/3/16  1  0  1  0  0
3/4/16  1  1  1  0  0
3/7/16  1  1  2  0  1
3/8/16  1  1  2  0  2
3/9/16  1  1  2  1  3

print (df.cumsum().eq(1))
            A      B      C      D      E
Date
3/1/16  False  False  False  False  False
3/2/16  False  False   True  False  False
3/3/16   True  False   True  False  False
3/4/16   True   True   True  False  False
3/7/16   True   True  False  False   True
3/8/16   True   True  False  False  False
3/9/16   True   True  False   True  False

print (df.eq(1))
            A      B      C      D      E
Date
3/1/16  False  False  False  False  False
3/2/16  False  False   True  False  False
3/3/16   True  False  False  False  False
3/4/16  False   True  False  False  False
3/7/16  False  False   True  False   True
3/8/16  False  False  False  False   True
3/9/16  False  False  False   True   True

m = df.eq(1) & df.cumsum(axis=1).eq(1)
print (m)
            A      B      C      D      E
Date
3/1/16  False  False  False  False  False
3/2/16  False  False   True  False  False
3/3/16   True  False  False  False  False
3/4/16  False   True  False  False  False
3/7/16  False  False   True  False  False
3/8/16  False  False  False  False   True
3/9/16  False  False  False   True  False

Setup:

from pandas.compat import StringIO

temp=u"""Date   A   B   C   D   E
3/1/16  0   0   0   0   0
3/2/16  0   0   1   0   0
3/3/16  1   0   0   0   0
3/4/16  0   1   0   0   0
3/7/16  0   0   1   0   1
3/8/16  0   0   0   0   1
3/9/16  0   0   0   1   1"""
df = pd.read_csv(StringIO(temp), sep="\s+")
print (df)

     Date  A  B  C  D  E
0  3/1/16  0  0  0  0  0
1  3/2/16  0  0  1  0  0
2  3/3/16  1  0  0  0  0
3  3/4/16  0  1  0  0  0
4  3/7/16  0  0  1  0  1
5  3/8/16  0  0  0  0  1
6  3/9/16  0  0  0  1  1


问:
Detect Android orientation: landscape-Left v. landscape-Right
How can I detect which one of 4 sides of the phone is up.

I can detect portrait/landscape mode, but how do I tell landscape-turned-on-left-side from landscape-turned-on-right-side?

Basically I want to make a nice transition animation when user turns phone. You know, like in iPhone's Safari: a swift 400ms rotation from the previous layout to the new.

答: It seems like you should be able to tell from the screenOrientation, gotten via getRequestedOrientation</p>

ContentLicense: CC BY-SA 2.5


问:
when I created border on css and I put the link into that border but it's over border
I created class border for a link and put the link into that border. Then when I see by responsive device link is over length form that border while I try to keep sentence into border it has no problem.
How can I resolve it?

My CSS:

```<code>.border {
    border: 1px solid #cc0000;
    border-radius: 8px;
    width: 100%;
    padding: 5px;
}
</code>```

答:
You probably used an element with display: block as a host of your .border class:

.border {
  border: 1px solid #cc0000;
  border-radius: 8px;
  width: 100%;
  padding: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="border">
  Google
</div></code>```

's default display value is block, hence full width.

What you need is using an element with display: inline:

.border {
  border: 1px solid #cc0000;
  border-radius: 8px;
  width: 100%;
  padding: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span class="border">
  Google
</span></code>```

Or, simply add display: inline to your .border styles:

.border {
  border: 1px solid #cc0000;
  border-radius: 8px;
  width: 100%;
  padding: 5px;
  display: inline; /* <---- */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="border">
  Google
</div></code>```

Body:
I created class border for a link and put the link into that border. Then when I see by responsive device link is over length form that border while I try to keep sentence into border it has no problem.
How can I resolve it?

My CSS:

.border {
    border: 1px solid #cc0000;
    border-radius: 8px;
    width: 100%;
    padding: 5px;
}

Body:
You probably used an element with display: block as a host of your .border class:

.border {
  border: 1px solid #cc0000;
  border-radius: 8px;
  width: 100%;
  padding: 5px;
}

<div class="border">
  <a href="https://google.com">Google</a>
</div>

<div>'s default display value is block, hence full width.

What you need is using an element with display: inline:

.border {
  border: 1px solid #cc0000;
  border-radius: 8px;
  width: 100%;
  padding: 5px;
}

<span class="border">
  <a href="https://google.com">Google</a>
</span>

Or, simply add display: inline to your .border styles:

.border {
  border: 1px solid #cc0000;
  border-radius: 8px;
  width: 100%;
  padding: 5px;
  display: inline; /* <---- */
}

<div class="border">
  <a href="https://google.com">Google</a>
</div>


问:
How to make search bar shrinking effect like default mailbox
How make animation like ios  default mail. I need the same effect like search bar is hide at initial and when i drag table view download the it shows the search bar.

like in the screenshot

update to the question.- Right now i am using a searchBar above tableview in the view controller.

```<code>var resultSearchController = UISearchController()
self.resultSearchController = ({
        let controller = UISearchController(searchResultsController: nil)
        controller.searchResultsUpdater = self
        controller.dimsBackgroundDuringPresentation = false
        controller.searchBar.sizeToFit()

        workActivityTableView.tableHeaderView = controller.searchBar
        workActivityTableView.contentOffset = CGPoint(x: 0, y: controller.searchBar.frame.height)
        navigationController?.extendedLayoutIncludesOpaqueBars = true

        return controller
    })()
</code>```

答:
I'd suggest you add the search bar as a tableHeaderView to your tableView, and in your viewDidLoad, add the following lines:

```<code>tableView.tableHeaderView = your_searchbar
tableView.contentOffset = CGPoint(x: 0, y: your_searchar.frame.height)
navigationController?.extendedLayoutIncludesOpaqueBars = true
</code>```

UPDATE:

This can be easily achieved by adding the search controller as a part of navigationItem. Something like this:
self.navigationItem.searchController = searchController

This is available from iOS 11.

Body:
How make animation like ios  default mail. I need the same effect like search bar is hide at initial and when i drag table view download the it shows the search bar.

like in the screenshot

update to the question.- Right now i am using a searchBar above tableview in the view controller.

var resultSearchController = UISearchController()
self.resultSearchController = ({
        let controller = UISearchController(searchResultsController: nil)
        controller.searchResultsUpdater = self
        controller.dimsBackgroundDuringPresentation = false
        controller.searchBar.sizeToFit()

        workActivityTableView.tableHeaderView = controller.searchBar
        workActivityTableView.contentOffset = CGPoint(x: 0, y: controller.searchBar.frame.height)
        navigationController?.extendedLayoutIncludesOpaqueBars = true

        return controller
    })()

Body:
I'd suggest you add the search bar as a tableHeaderView to your tableView, and in your viewDidLoad, add the following lines:

tableView.tableHeaderView = your_searchbar
tableView.contentOffset = CGPoint(x: 0, y: your_searchar.frame.height)
navigationController?.extendedLayoutIncludesOpaqueBars = true

UPDATE:

This can be easily achieved by adding the search controller as a part of navigationItem. Something like this:
self.navigationItem.searchController = searchController

This is available from iOS 11.


问:
How to access the ajax submitted data in PHP from javascript FormData
I have the following code to upload a file along with a user_id and a token via ajax post:

HTML Form:

```<code><?php foreach($model['all_documents'] as $doc=>$val){ ?>
<form enctype="multipart/form-data" class="form">
  <input type="hidden" name="_csrf" value="<?=Yii::$app->request->getCsrfToken()?>" />
  <input type="hidden" name="user_id" value="<?=$model['user_id']?>" />
  <button type="button" class="col-md-7 btn btn-default documentUpload form-control">
    <i class="fa fa-file-image-o"></i> انتخاب اسکن
  </button>
  <input type="file" name="<?=$doc?>" class="documentUpload" style="display: none;" />
  <button class="col-md-4 btn btn-primary form-control submit pull-left">
    <i class="fa fa-upload"></i> آپلود
  </button>
</form>
<?php } ?>
</code>```

Javascript:

```<code>$(".form").submit(function(){
  var formData = new FormData(this);
  console.info(formData); // Shows FormData(), but can't find my stuff in it

  $.ajax({
    url: '<?=Yii::$app->homeUrl?>courier/upload-document',
    type: 'POST',
    data: formData,
    async: false,
    processData: false,
    // beforeSend: function(){
    // },
    success: function(data){
      console.log(data);
    }
  });
  return false;
});
</code>```

I tried to access the user_id and file like:

```<code>// $user_id = $_POST['user_id']; // Nothing
// $docs = $_FILES['image_url']; // Nothing
print_r($_POST);exit;
</code>```

What I get in my chrome's network response is as follows:

```<code>Array
(
    [------WebKitFormBoundaryk0378isAjf4Png8L
Content-Disposition:_form-data;_name] => "_csrf"

dy5nWlJFb1U6dwg.FwshCjZ5NANmd1tkFFcdFh8sLgcnQQQxZzwoOA==
------WebKitFormBoundaryk0378isAjf4Png8L
Content-Disposition: form-data; name="user_id"

456
------WebKitFormBoundaryk0378isAjf4Png8L
Content-Disposition: form-data; name="image_url"; filename="avatar3.png"
Content-Type: image/png

�PNG

IHDR����4�PLTE�ɦ!!!�e<"""���r=-�Y<����cB   �����`@��^?����G2�ȥ�R8u>-�K4�aA�[=�D0����Z<�\=�W;�Ƥ�S9�P6�N6����ma�ġ��������Ÿ_>���UF<�Y<��������U:����ͭޏh纥�y@.|B/���ի��I3�~V�jA��ϻ�������Ѵ�m[����oG�L5Ɵ����쩅.,
</code>```

答:
Setting processData to false lets you prevent jQuery from
automatically transforming the data into a query string.

Setting the contentType to false is imperative, since otherwise
    jQuery will set it incorrectly.

Body:
I have the following code to upload a file along with a user_id and a token via ajax post:

HTML Form:

<?php foreach($model['all_documents'] as $doc=>$val){ ?>
<form enctype="multipart/form-data" class="form">
  <input type="hidden" name="_csrf" value="<?=Yii::$app->request->getCsrfToken()?>" />
  <input type="hidden" name="user_id" value="<?=$model['user_id']?>" />
  <button type="button" class="col-md-7 btn btn-default documentUpload form-control">
     انتخاب اسکن
  </button>
  <input type="file" name="<?=$doc?>" class="documentUpload" style="display: none;" />
  <button class="col-md-4 btn btn-primary form-control submit pull-left">
     آپلود
  </button>
</form>
<?php } ?>

Javascript:

$(".form").submit(function(){
  var formData = new FormData(this);
  console.info(formData); // Shows FormData(), but can't find my stuff in it

  $.ajax({
    url: '<?=Yii::$app->homeUrl?>courier/upload-document',
    type: 'POST',
    data: formData,
    async: false,
    processData: false,
    // beforeSend: function(){
    // },
    success: function(data){
      console.log(data);
    }
  });
  return false;
});

I tried to access the user_id and file like:

// $user_id = $_POST['user_id']; // Nothing
// $docs = $_FILES['image_url']; // Nothing
print_r($_POST);exit;

What I get in my chrome's network response is as follows:

Array
(
    [------WebKitFormBoundaryk0378isAjf4Png8L
Content-Disposition:_form-data;_name] => "_csrf"

dy5nWlJFb1U6dwg.FwshCjZ5NANmd1tkFFcdFh8sLgcnQQQxZzwoOA==
------WebKitFormBoundaryk0378isAjf4Png8L
Content-Disposition: form-data; name="user_id"

456
------WebKitFormBoundaryk0378isAjf4Png8L
Content-Disposition: form-data; name="image_url"; filename="avatar3.png"
Content-Type: image/png

�PNG

IHDR����4�PLTE�ɦ!!!�e<"""���r=-�Y<����cB   �����`@��^?����G2�ȥ�R8u>-�K4�aA�[=�D0����Z<�\=�W;�Ƥ�S9�P6�N6����ma�ġ��������Ÿ_>���UF<�Y<��������U:����ͭޏh纥�y@.|B/���ի��I3�~V�jA��ϻ�������Ѵ�m[����oG�L5Ɵ����쩅.,


问:
Task and plugin conflict in Gradle (Failed to apply plugin [class 'org.gradle.langu...)
I tried to run a task from build.gradle using the following command:

```<code>gradle footype
</code>```

However the build failed and displayed these two error messages that I want to fix:

```<code>> Configure project :
The Task.leftShift(Closure) method has been deprecated and is scheduled to
be removed in Gradle 5.0. Please use Task.doLast(Action) instead.
</code>```

And this message as well:

```<code>* What went wrong:
An exception occurred applying plugin request [id: 'java']
> Failed to apply plugin [class
'org.gradle.language.base.plugins.LifecycleBasePlugin']
   > Declaring custom 'assemble' task when using the standard Gradle
lifecycle plugins is not allowed.
</code>```

Here is the code of the build.gradle file:

```<code>plugins{
  id "com.gradle.build-scan" version "1.10.2"
  id "org.arquillian.spacelift" version "1.0.0-alpha-17"
  id "java"
}

group 'k'
version '1.0-SNAPSHOT'

sourceCompatibility = 1.8

repositories {
  mavenCentral()
}

task fooType {
  doLast {
    def foo = "bar"
    println "$foo + foo = ${foo + "foo"}"
  }
}
</code>```

I searched on other posts and they all seem to mention a task called clean() which doesn't appear in my code, so I'd like to know what's the problem.

Thank you muchly for reading this post.

答:
When it comes to this message:

Configure project :
  The Task.leftShift(Closure) method has been deprecated and is scheduled to
  be removed in Gradle 5.0. Please use Task.doLast(Action) instead.

it is just a warning. It states that one (possibly more) plugin you applied uses << which will be removed in version 5.0 of gradle in favour of doLast. You are not using << directly in your script and that's ok. To eliminate this warning first of all you need to know which plugin uses it, then raise an issue on plugin's site asking for deprecated code elimination.

When it comes to the second message it's an error and in single build script nothing can be done about it. Two plugins java and org.arquillian.spacelift have declared a task with the same name (it's assemble) - this is a conflict. Maybe you can split you project into a multimodule?

Body:
I tried to run a task from build.gradle using the following command:

gradle footype

However the build failed and displayed these two error messages that I want to fix:

> Configure project :
The Task.leftShift(Closure) method has been deprecated and is scheduled to
be removed in Gradle 5.0. Please use Task.doLast(Action) instead.

And this message as well:

* What went wrong:
An exception occurred applying plugin request [id: 'java']
> Failed to apply plugin [class
'org.gradle.language.base.plugins.LifecycleBasePlugin']
   > Declaring custom 'assemble' task when using the standard Gradle
lifecycle plugins is not allowed.

Here is the code of the build.gradle file:

plugins{
  id "com.gradle.build-scan" version "1.10.2"
  id "org.arquillian.spacelift" version "1.0.0-alpha-17"
  id "java"
}

group 'k'
version '1.0-SNAPSHOT'

sourceCompatibility = 1.8

repositories {
  mavenCentral()
}

task fooType {
  doLast {
    def foo = "bar"
    println "$foo + foo = ${foo + "foo"}"
  }
}

I searched on other posts and they all seem to mention a task called clean() which doesn't appear in my code, so I'd like to know what's the problem.

Thank you muchly for reading this post.


问:
Parsing mixed data with Java
Kind of a Java noob, and have flipped between about 6 different streams+scanner and still haven't found a way to do everything I need to.  Am trying to implement an algorithm to parse a file that follows a certain syntax.  There are several places where I need to peek at the next character to see if it is a parenthesis or comma, and also need to be able to read strings and decimal values.  I had it working with a stream up to the point that I tried to read the double.  The double is NOT in a binary format, so DataInputStream is not what I want.

I could use the scanner for its getNextFloat, but the problem with using a scanner is there are no real delimiters in the file: (test:1.234,rightTest:5.6789)

If I specify ( , : ) as delimeters with the Scanner, then I lose the ability to test for their existence of the delimiter(I thionk, because the way it seems is it eats the delimiter).  These blocks can be nested in each other in various ways, so I often need to test the next char to see if it's a opening parenthesis and then branch to different pieces of logic. I.e. it forms a tree(but please don't right code to parse a tree because that is my homework assignment).

I could do away with the scanner and just go back to my original solution with a stream if I could only figure out how to parse the decimal value.  I need something that does a "read until you find one of these characters" so that I can say stream.ReadUntil(",)").  The decimals are always followed by a comma or closing paren.  As a hack I will probably just read one char at a time.  This is the same thing I did to grab the string like "test" and "rightTest", and it felt really awful.

The only other option I know if is something with a string tokenizer, but my feeling from examples is that I'd have to read the entire file into a string to tokenize it, essentially defeating the purpose of using a stream.  These files can be really big and just as an exersize for myself I like to try and code such that I don't bring it all into memory if it is unnecessary, even though for this assignment it doesn't really matter.

So essentially what I'm looking for is some help on the mechanics of the file IO to be able to peek at the next char so I can check for  ( , : ) when necesary, and also have the ability to read a string up to a : and read a decimal value up to a : or )

答:
Have you looked at the PushbackReader from java.io? Peeking is one of its usecases. Below is a sample.

```<code>PushbackReader pusher = new PushbackReader(reader);
char c = (char)pusher .read();
// code to work with the peeked character
pusher .unread((int)c); //push character back into the buffer
</code>```

Title: Parsing mixed data with Java

Body:
Have you looked at the PushbackReader from java.io? Peeking is one of its usecases. Below is a sample.

PushbackReader pusher = new PushbackReader(reader);
char c = (char)pusher .read();
// code to work with the peeked character
pusher .unread((int)c); //push character back into the buffer


问:
URISyntaxException Illegal character in query
I am trying to open a link in default browser. I have used the following code.

```<code>String myUrl = "http://www.example.com/engine/myProcessor.jsp?Type=A Type&Name=1100110&Char=!";

        try {
            Desktop.getDesktop().browse(new URI(myUrl));
        } catch (IOException err) {
            setTxtOutput("Error: "+err.getMessage());
        } catch (URISyntaxException err) {
            setTxtOutput("Error: "+err.getMessage());
        } catch (Exception err) {
            setTxtOutput("Error: "+err.getMessage());
        }
</code>```

I am getting URISyntaxException Illegal character in query at index

I think this is because of characters such as ?, & and ! in my URL. I tried using:

```<code>URLEncoder.encode(myUrl, "UTF-8");
</code>```

But this gives me another error.

```<code>Failed to open http%3A%2F%2Fwww.example.com%2F...........
The system cannot find the file specified.
</code>```

Please can you tell me how to correct the URISyntaxException Illegal character error.

答: Replace spaces in URL with + like If url contains category=Adult Care then replace it with category=Adult+Care.</p>

Body:
I am trying to open a link in default browser. I have used the following code.

String myUrl = "http://www.example.com/engine/myProcessor.jsp?Type=A Type&Name=1100110&Char=!";

        try {
            Desktop.getDesktop().browse(new URI(myUrl));
        } catch (IOException err) {
            setTxtOutput("Error: "+err.getMessage());
        } catch (URISyntaxException err) {
            setTxtOutput("Error: "+err.getMessage());
        } catch (Exception err) {
            setTxtOutput("Error: "+err.getMessage());
        }

I am getting URISyntaxException Illegal character in query at index

I think this is because of characters such as ?, & and ! in my URL. I tried using:

URLEncoder.encode(myUrl, "UTF-8");

But this gives me another error.

Failed to open http%3A%2F%2Fwww.example.com%2F...........
The system cannot find the file specified.

Please can you tell me how to correct the URISyntaxException Illegal character error.


问:
Operator new and delete on Inherited class. Operator delete not executing
I was messing around operator overloading and I've noticed that on inherited object, the overloaded operator delete doesn't seem to execute when the inherited object has an operator new overloaded:

```<code>#include <iostream>
#include <string>

class TestAbs {
public:
  TestAbs (void) {
  }
  virtual ~TestAbs (void) noexcept {
  }
};

class Test : public TestAbs {
public:
  Test (void)
      : TestAbs () {
  }
  ~Test (void) noexcept override {
  }
  void* operator new (size_t) throw () {
    std::cout << "Overloaded operator new!\n";
    return nullptr;
  }
  void operator delete (void*) noexcept {
    std::cout << "Overloaded operator delete in class: Test!\n";
  }
};

int main() {
    TestAbs* tp = new Test ();
    delete tp;

    return 0;
}
</code>```

The code above has the following output:

```<code>Overloaded operator new!
</code>```

What happened to the overloaded operator delete?
Thank you all in advance!

Update:
Thank you guys for all the help. It seems like the problem was indeed the nullptr return on the overloaded new.

答:
Deleting a nullptr is always a no-op in C++14 and later. Nothing gets called. To make your example work, you'd need to return a pointer that is not null. For example:

```<code>void* operator new(size_t) throw()
{
    std::cout << "Overloaded operator new!\n";
    return ::new Test;
}
</code>```

From cppreference:

If expression evaluates to a null pointer value, no destructors are called, and the deallocation function is not called.

The above is for C++14 and later. Up to C++11, the deallocation function might get called. It's implementation-defined:

If expression evaluates to a null pointer value, no destructors are called, and the deallocation function may or may not be called (it's implementation-defined), but the default deallocation functions are guaranteed to do nothing when handed a null pointer.

Body:
I was messing around operator overloading and I've noticed that on inherited object, the overloaded operator delete doesn't seem to execute when the inherited object has an operator new overloaded:

#include <iostream>
#include <string>

class TestAbs {
public:
  TestAbs (void) {
  }
  virtual ~TestAbs (void) noexcept {
  }
};

class Test : public TestAbs {
public:
  Test (void)
      : TestAbs () {
  }
  ~Test (void) noexcept override {
  }
  void* operator new (size_t) throw () {
    std::cout << "Overloaded operator new!\n";
    return nullptr;
  }
  void operator delete (void*) noexcept {
    std::cout << "Overloaded operator delete in class: Test!\n";
  }
};

int main() {
    TestAbs* tp = new Test ();
    delete tp;

    return 0;
}

The code above has the following output:

Overloaded operator new!

What happened to the overloaded operator delete?
Thank you all in advance!

Update:
Thank you guys for all the help. It seems like the problem was indeed the nullptr return on the overloaded new.

Body:
Deleting a nullptr is always a no-op in C++14 and later. Nothing gets called. To make your example work, you'd need to return a pointer that is not null. For example:

void* operator new(size_t) throw()
{
    std::cout << "Overloaded operator new!\n";
    return ::new Test;
}

From cppreference:

If expression evaluates to a null pointer value, no destructors are called, and the deallocation function is not called.

The above is for C++14 and later. Up to C++11, the deallocation function might get called. It's implementation-defined:

If expression evaluates to a null pointer value, no destructors are called, and the deallocation function may or may not be called (it's implementation-defined), but the default deallocation functions are guaranteed to do nothing when handed a null pointer.


问:
ExtJS classic - insert chart into tooltip
I'm new with ExtJS, so I don't know, if it even possible. Google answers only how to make tooltips to charts, so...

I need to make a grid with a tooltips, which will be shown when user set mouse on the cell. In that tooltip it need to be a custom information, based on the store of this grid (this part I've made) and a PolarChart, based on the same store.

It needs to be like

```<code>Name:          first
Date start:    10-02-2017
Date end:      12-02-2017
*It is the PolarChart*
</code>```

I've tried to create a PolarChart inside tip.update() in the beforeshow function, but it only returns Object(Object) instead of rendered chart.

I've tried to render chart with defining it as variable and then render it like tip.update(var.render()), but it throw an Uncaught TypeError: Cannot read property 'dom' of undefined error.

And even if I try to put property renderTo as variable tip or Ext.getCmp('tipID'), it throws that error.

So, I think, it cannot reach DOM node of the tooltip because it creates dynamically.

Is it some ways to resolve my problem?

答:
You can use dynamic tooltip creation on grid itemmouseenter and itemmouseleave.

I have created a small sencha fiddle demo.

```<code>function createToolTip(target, data) {
     return Ext.create('Ext.tip.ToolTip', {
         // target: target.id,
         title: 'Company Overview using pie chart',
         width: 200,
         height: 200,
         items: [{
             xtype: 'polar',
             width: 180,
             height: 180,
             theme: 'green',
             interactions: ['rotate', 'itemhighlight'],
             store: {
                 fields: ['name', 'value'],
                 data: data
             },
             series: {
                 type: 'pie',
                 highlight: true,
                 angleField: 'value',
                 label: {
                     field: 'name',
                     display: 'inside'
                 },
                 donut: 30
             }
         }]
     }).showBy(target);
 }

 Ext.create('Ext.grid.Panel', {
     renderTo: Ext.getBody(),
     store: store,
     title: 'Company Data',
     width: '100%',
     columns: [{
         text: 'Company',
         flex: 1,
         sortable: true,
         dataIndex: 'company'
     }, {
         text: 'Price',
         width: 90,
         sortable: true,
         dataIndex: 'price',
         align: 'right',
         renderer: function (v) {
             return Ext.util.Format.usMoney(v)
         }
     }, {
         text: 'Revenue',
         width: 110,
         sortable: true,
         align: 'right',
         dataIndex: 'revenue %',
         renderer: perc
     }, {
         text: 'Growth',
         width: 100,
         sortable: true,
         align: 'right',
         dataIndex: 'growth %',
         renderer: perc
     }, {
         text: 'Product',
         width: 110,
         sortable: true,
         align: 'right',
         dataIndex: 'product %',
         renderer: perc
     }, {
         text: 'Market',
         width: 100,
         sortable: true,
         align: 'right',
         dataIndex: 'market %',
         renderer: perc
     }],

     listeners: {
         itemmouseenter: function (grid, record, item, index, e, eOpts) {
             //If tooltip is already created then first destroy then create new.
             if (grid.customToolTip) {
                 Ext.destroy(grid.customToolTip);
             }
             grid.customToolTip = createToolTip(item, [{
                 name: 'Revenue',
                 value: record.get('revenue %')
             }, {
                 name: 'Growth',
                 value: record.get('growth %')
             }, {
                 name: 'Product',
                 value: record.get('product %')
             }, {
                 name: 'Market',
                 value: record.get('market %')
             }]);
         },
         itemmouseleave: function (grid, record, item, index, e, eOpts) {
             //destory toolTip on mouse out
             if (grid.customToolTip) {
                 Ext.destroy(grid.customToolTip);
             }
         }
     }
 })
</code>```

Body:
I'm new with ExtJS, so I don't know, if it even possible. Google answers only how to make tooltips to charts, so...

I need to make a grid with a tooltips, which will be shown when user set mouse on the cell. In that tooltip it need to be a custom information, based on the store of this grid (this part I've made) and a PolarChart, based on the same store.

It needs to be like

Name:          first
Date start:    10-02-2017
Date end:      12-02-2017
*It is the PolarChart*

I've tried to create a PolarChart inside tip.update() in the beforeshow function, but it only returns Object(Object) instead of rendered chart.

I've tried to render chart with defining it as variable and then render it like tip.update(var.render()), but it throw an Uncaught TypeError: Cannot read property 'dom' of undefined error.

And even if I try to put property renderTo as variable tip or Ext.getCmp('tipID'), it throws that error.

So, I think, it cannot reach DOM node of the tooltip because it creates dynamically.

Is it some ways to resolve my problem?

Body:
You can use dynamic tooltip creation on grid itemmouseenter and itemmouseleave.

I have created a small sencha fiddle demo.

function createToolTip(target, data) {
     return Ext.create('Ext.tip.ToolTip', {
         // target: target.id,
         title: 'Company Overview using pie chart',
         width: 200,
         height: 200,
         items: [{
             xtype: 'polar',
             width: 180,
             height: 180,
             theme: 'green',
             interactions: ['rotate', 'itemhighlight'],
             store: {
                 fields: ['name', 'value'],
                 data: data
             },
             series: {
                 type: 'pie',
                 highlight: true,
                 angleField: 'value',
                 label: {
                     field: 'name',
                     display: 'inside'
                 },
                 donut: 30
             }
         }]
     }).showBy(target);
 }

 Ext.create('Ext.grid.Panel', {
     renderTo: Ext.getBody(),
     store: store,
     title: 'Company Data',
     width: '100%',
     columns: [{
         text: 'Company',
         flex: 1,
         sortable: true,
         dataIndex: 'company'
     }, {
         text: 'Price',
         width: 90,
         sortable: true,
         dataIndex: 'price',
         align: 'right',
         renderer: function (v) {
             return Ext.util.Format.usMoney(v)
         }
     }, {
         text: 'Revenue',
         width: 110,
         sortable: true,
         align: 'right',
         dataIndex: 'revenue %',
         renderer: perc
     }, {
         text: 'Growth',
         width: 100,
         sortable: true,
         align: 'right',
         dataIndex: 'growth %',
         renderer: perc
     }, {
         text: 'Product',
         width: 110,
         sortable: true,
         align: 'right',
         dataIndex: 'product %',
         renderer: perc
     }, {
         text: 'Market',
         width: 100,
         sortable: true,
         align: 'right',
         dataIndex: 'market %',
         renderer: perc
     }],

     listeners: {
         itemmouseenter: function (grid, record, item, index, e, eOpts) {
             //If tooltip is already created then first destroy then create new.
             if (grid.customToolTip) {
                 Ext.destroy(grid.customToolTip);
             }
             grid.customToolTip = createToolTip(item, [{
                 name: 'Revenue',
                 value: record.get('revenue %')
             }, {
                 name: 'Growth',
                 value: record.get('growth %')
             }, {
                 name: 'Product',
                 value: record.get('product %')
             }, {
                 name: 'Market',
                 value: record.get('market %')
             }]);
         },
         itemmouseleave: function (grid, record, item, index, e, eOpts) {
             //destory toolTip on mouse out
             if (grid.customToolTip) {
                 Ext.destroy(grid.customToolTip);
             }
         }
     }
 })


问:
Importing sharedModule in App and in every Module angular 2
I am a little confused with how a shared module is imported is used in angular 2 and looking for some clarification.

So when i create  a SharedModule class with imported components and modules which i also export to reuse. I imported the SharedModule into my app.module so: 1. it will be there on app load. 2. so i don't have to import it in other feature modules.

I noticed that even though i imported in my app.module but when i would run my application i get the error message that either i am missing a component or reference to a module. So i end up importing the shared module in all my feature modules. I thought by placing it in the app.module that i wouldn't have to import it in my other modules?

答:
If the shared component has Components, Pipes and Directives, you need to import Shared module into each feature module that needs it. As an exception to the above point, you have to import Shared Module in your App module in the below scenario:

Used Lazy loading, and have a service shared between different feature modules, and there is a need to have a single instance of the service created and shared between the feature modules.

```<code>import { ModuleWithProviders } from '@angular/core';
import { SampleService } from './services/sample';

@NgModule({
  declarations: [],
  imports: [],
  exports: []
})

export class SharedComponentsModule {
  static forRoot(): ModuleWithProviders {
    return {
        ngModule: SharedComponentsModule,
        providers: [SampleService]
    };
}}
//Import the module with Provider in AppModule :
Imports: [
SharedComponentsModule.forRoot()
]
</code>```

Body:
If the shared component has Components, Pipes and Directives, you need to import Shared module into each feature module that needs it. As an exception to the above point, you have to import Shared Module in your App module in the below scenario:

Used Lazy loading, and have a service shared between different feature modules, and there is a need to have a single instance of the service created and shared between the feature modules.

import { ModuleWithProviders } from '@angular/core';
import { SampleService } from './services/sample';

@NgModule({
  declarations: [],
  imports: [],
  exports: []
})

export class SharedComponentsModule {
  static forRoot(): ModuleWithProviders {
    return {
        ngModule: SharedComponentsModule,
        providers: [SampleService]
    };
}}
//Import the module with Provider in AppModule :
Imports: [
SharedComponentsModule.forRoot()
]


问:
sails.controllers.booking.approve(...) is not a function
I am trying to unit-test the controllers of a Sails.js project with mocha.
Since I have a different security policies I cannot use suptertest or similar testing frameworks to test the controllers, by actually calling the url. I would have to make sure the parameters of the call would pass all policies.

Instead I am trying to call the methods of the controllers directly with sails.controllers.[controller].[methods](req, res) like suggested here, and spy on the res object with sinon.

But whenever I call a controller method e.g. sails.controllers.booking.approve(req, res) I get the error message TypeError: sails.controllers.booking.approve(...) is not a function. How can I call the controller method instead?

答:
NPM to install Mocha, Grunt Mocha Test, Sinon and the Assert library

I modified the Gruntfile.js at the root of the project to use Grunt Mocha Tests,

```<code>grunt.initConfig({

mochaTest: {
  test: {
    options: {
      reporter: 'spec'
    },
    src: ['tests/**/*.spec.js']
  }
},

...
});
</code>```

Then add and register the task to run the test:

```<code>grunt.loadNpmTasks('grunt-mocha-test');
grunt.registerTask('test', ['mochaTest']);
</code>```

Example: AboutController.js

```<code>module.exports = {

  index: function (req, res) {
    return res.view();
  },

  _config: {}
};
</code>```

test inside tests/controllers and name it about.spec.js

```<code>var AboutController = require('../../api/controllers/AboutController'),
sinon = require('sinon'),
assert = require('assert');
describe('The About Controller', function () {
  describe('when we load the about page', function () {
    it ('should render the view', function () {
        var view = sinon.spy();
        AboutController.index(null, {
            view: view
        });
        assert.ok(view.called);
       });
  });
});
</code>```

Body:
NPM to install Mocha, Grunt Mocha Test, Sinon and the Assert library

I modified the Gruntfile.js at the root of the project to use Grunt Mocha Tests,

grunt.initConfig({

mochaTest: {
  test: {
    options: {
      reporter: 'spec'
    },
    src: ['tests/**/*.spec.js']
  }
},

...
});

Then add and register the task to run the test:

grunt.loadNpmTasks('grunt-mocha-test');
grunt.registerTask('test', ['mochaTest']);

Example: AboutController.js

module.exports = {

  index: function (req, res) {
    return res.view();
  },

  _config: {}
};

test inside tests/controllers and name it about.spec.js

var AboutController = require('../../api/controllers/AboutController'),
sinon = require('sinon'),
assert = require('assert');
describe('The About Controller', function () {
  describe('when we load the about page', function () {
    it ('should render the view', function () {
        var view = sinon.spy();
        AboutController.index(null, {
            view: view
        });
        assert.ok(view.called);
       });
  });
});


问:
Android Studio version control keeps adding build dir to commits
So when I go to make a commit, I have to uncheck the app/build directory from the commit. I want to remove these files from being tracked.

Does my .gitignore file look correct?

```<code>build/
app/build/
.idea
.gradle
</code>```

I've tried

```<code>git rm -r --cached .
git add .
</code>```

Which appears to work, git status shows all build files have been deleted. So then I do a commit, and the files are deleted. But after building and the files changing, they show up on my next commit. Why is this, and why can't I untrack these files?

答:
Looks like build directory already in index.
Use

```<code>git rm -r --cached .
git add .
</code>```

to remove untracked files then commit changes.

But even better to remove files from the history:

```<code>git filter-branch --index-filter 'git rm -r --cached --ignore-unmatch <path-to-build-dir>' --prune-empty -f -- --all
</code>```

But in this case you have to use force push to update server history also.

Body:
So when I go to make a commit, I have to uncheck the app/build directory from the commit. I want to remove these files from being tracked.

Does my .gitignore file look correct?

build/
app/build/
.idea
.gradle

I've tried

git rm -r --cached .
git add .

Which appears to work, git status shows all build files have been deleted. So then I do a commit, and the files are deleted. But after building and the files changing, they show up on my next commit. Why is this, and why can't I untrack these files?

Body:
Looks like build directory already in index.
Use

git rm -r --cached .
git add .

to remove untracked files then commit changes.

But even better to remove files from the history:

git filter-branch --index-filter 'git rm -r --cached --ignore-unmatch <path-to-build-dir>' --prune-empty -f -- --all

But in this case you have to use force push to update server history also.


问:
Execution part of an infinite list in Haskell?
I'm a little confused about how exactly Haskell execution works on infinite lists. for example, consider below sum function :

```<code>sum (takeWhile (<10000) (filter odd (map (^2) [1..])))
</code>```

here the code for finding Sum of all odd squares that are smaller than 10000  and I know how these takewhile, filter, map functions work. my doubt is, here the map function is taking one element from the infinite list and squaring it and returning the list of squared elements to the filter function right? in that case it would run infinitely for squaring that infinite list of elements isn't it? or is it taking just one element squaring it and then returning to the filter?

答: takeWhile (<10000) puts a limit on how many elements to process for the sum. Haskell is lazy-evaluated and will only do as much work as needed.  For this reason it's a common pattern to create an infinite list and limit it with a take operation.  This means that only elements from a list that are used are generated and processed. Once takeWhiles condition is false, no other elements from the list are used, so they aren't generated.

ContentLicense: CC BY-SA 4.0

Body:
I'm a little confused about how exactly Haskell execution works on infinite lists. for example, consider below sum function :

sum (takeWhile (<10000) (filter odd (map (^2) [1..])))

here the code for finding Sum of all odd squares that are smaller than 10000  and I know how these takewhile, filter, map functions work. my doubt is, here the map function is taking one element from the infinite list and squaring it and returning the list of squared elements to the filter function right? in that case it would run infinitely for squaring that infinite list of elements isn't it? or is it taking just one element squaring it and then returning to the filter?


问:
NodeJS Change variable from within a function
Long story short, im newish to NodeJS and im trying to change a variable after a function has been executed, however I cant return a result like I thought I could.

```<code>app.get('/:steamid', function(req, res) {

    var steamID;
    var steamAvatarUrl;
    var steamRegisterDate;

    steamAPI.ResolveVanityURL(req.params.steamid, function(err, res) {
        console.log('Steam64: ' + res); // <- this prints out my result
        steamID = res;
    });

    steamAPI.getAvatarUrl(req.params.steamid, function(err, res) {
        console.log('Avatar URL: ' + res); // <- this prints out my result
        steamAvatarUrl = res;
    });

    steamAPI.memberSince(req.params.steamid, function(err, res) {
        console.log('Registered: ' + res); // <- this prints out my result
        steamRegisterDate = res;
    });

    console.log(steamID); //<--- This returns undefined

    res.render('steamid.hbs', {
        "title": steamID,
        "avatarURL": steamAvatarUrl,
        "registerDate": steamRegisterDate
    });
});
</code>```

An help with an example/resolution of how I accomplish this would be amazing. I am a visual learner so please dont say "use this or do that" without giving some sort of example to it or I honestly wont get it lol.

Thanks ahead of time.

答:
Javascript is asynchronous by default. You can't return a value inside of a callback function neither can you assign to a variable outside as it is returned immediately.

```<code>app.get('/:steamid', function(req, res) {

    steamAPI.ResolveVanityURL(req.params.steamid, function(err, res) {
        console.log('Steam64: ' + res); // <- this prints out my result
        var steamID = res;
        console.log(steamID); // <-- defined
    });
});
</code>```

You could learn about Promises and how they work as they are preferred to using callbacks.

Body:
Long story short, im newish to NodeJS and im trying to change a variable after a function has been executed, however I cant return a result like I thought I could.

app.get('/:steamid', function(req, res) {

    var steamID;
    var steamAvatarUrl;
    var steamRegisterDate;

    steamAPI.ResolveVanityURL(req.params.steamid, function(err, res) {
        console.log('Steam64: ' + res); // <- this prints out my result
        steamID = res;
    });

    steamAPI.getAvatarUrl(req.params.steamid, function(err, res) {
        console.log('Avatar URL: ' + res); // <- this prints out my result
        steamAvatarUrl = res;
    });

    steamAPI.memberSince(req.params.steamid, function(err, res) {
        console.log('Registered: ' + res); // <- this prints out my result
        steamRegisterDate = res;
    });

    console.log(steamID); //<--- This returns undefined

    res.render('steamid.hbs', {
        "title": steamID,
        "avatarURL": steamAvatarUrl,
        "registerDate": steamRegisterDate
    });
});

An help with an example/resolution of how I accomplish this would be amazing. I am a visual learner so please dont say "use this or do that" without giving some sort of example to it or I honestly wont get it lol.

Thanks ahead of time.

Body:
Javascript is asynchronous by default. You can't return a value inside of a callback function neither can you assign to a variable outside as it is returned immediately.

app.get('/:steamid', function(req, res) {

    steamAPI.ResolveVanityURL(req.params.steamid, function(err, res) {
        console.log('Steam64: ' + res); // <- this prints out my result
        var steamID = res;
        console.log(steamID); // <-- defined
    });
});

You could learn about Promises and how they work as they are preferred to using callbacks.


问:
In .NET, when do I have to reference a DLL that an external library also references?
I'm trying to understand when it's necessary for my .NET project to reference a DLL that an external library references.

A practical example: Microsoft.Bot.Builder depends on Chronic.Signed.dll

If I reference Microsoft.Bot.Builder.dll, do I always have to also add a reference to Chronic.Signed.dll in my own project, even if I'm not using it directly? Or do I only have to only under certain circumstances?

答:
If I reference Microsoft.Bot.Builder.dll, do I always have to also add
  a reference to Chronic.Signed.dll in my own project, even if I'm not
  using it directly? Or do I only have to only under certain
  circumstances?

When you add packages using NuGet, dependent packages are also installed with them. So when you will add Microsoft.Bot.Builder.dll it will automatically install the Chronic.Signed.dll as well.

Now comes the part, Why? Some lib packages are dependent on other packages. Like a function in Microsoft.Bot.Builder.dll might be using some helper or main function from Chronic.Signed.dll. So if you will remove the reference of Chronic.Signed.dll you will will get error of missing dependency or reference.

do I always have to also add
       a reference to Chronic.Signed.dll in my own project, even if I'm not
       using it directly?

Yes, Because Microsoft.bot is using it internally.

Not all packages depends on others. Some are independent and never install any other dlls but some do.


问:
Optional parameters in ABAP CDS views?
I'm trying to create a CDS view for consumption with optional parameters. But at the moment, optional parameters are not supported.

Is there a workaround available to somehow choose which where clauses are to be executed/used based on input parameters ?

答:
Did you check the Consumption.defaultValue annotation
Please have a look at reference document

Title: Optional parameters in ABAP CDS views?


问:
Regex for my custom URL
Good Day,

I cant create the regex exact for my url:

any-any.test.test2.com or ALL CAPS

http://any-any.test.test2.com or ALL CAPS

https://any-any.test.test2.com or ALL CAPS

can someone please help me how can I make a regex that can accept this url's.

Useful Link:
https://regex101.com/

Note: any means user can input any characters and after first any should have "-" , then all must contain :

.test.test2.com  or

.TEST.TEST2.COM

at the end.

答:
a simple regex pattern in vim
...-....test.test2.com\c

This will match
"any-any.test.test2.com";
"ANY-ANY.TEST.TEST2.COM"

Title: Regex for my custom URL


问:
Ionic - Error: Cannot find module 'android-versions'
When a try to run

```<code>ionic run android --device
</code>```

I'm getting an error of module:

```<code>Error: Cannot find module 'android-versions'
</code>```

Versions:

```<code>java -version
  java version "1.8.0_144"
Android studio Version 2.3.3
ionic -v
2.2.1
cordova -v
6.5.0
</code>```

答:
Not sure if this will help some other Ionic developers, but I was getting the same Error: Cannot find module 'android-versions' and I fixed it by removing and adding the Android platform again:

```<code>ionic cordova platform remove android --save
</code>```

And then

```<code>ionic cordova platform add android --save
</code>```

Body:
When a try to run

ionic run android --device

I'm getting an error of module:

Error: Cannot find module 'android-versions'

Versions:

java -version
  java version "1.8.0_144"
Android studio Version 2.3.3
ionic -v
2.2.1
cordova -v
6.5.0

Body:
Not sure if this will help some other Ionic developers, but I was getting the same Error: Cannot find module 'android-versions' and I fixed it by removing and adding the Android platform again:

ionic cordova platform remove android --save

And then

ionic cordova platform add android --save


问:
Center aligning a switch in Horizontal Stack View
Note: I'm completely new to iOS development.

In storyboard, I've got a Vertical Stack View with a Horizontal Stack View inside.

In the Horizontal Stack View, I've got a label and a switch. I changed the Distribution of both stack views to "Fill Equally".

Currently, this is what the view looks like:

The label is aligned perfectly both horizontally and vertically, but the switch is in the wrong position. I also want the switch to be aligned like the label, so that it appears on the right of the label and on the same vertical level.

I've tried various options with storyboard but nothing seems to work.

答:
It's simple.

your horizontal stackView will contain UILabel and UIView(let's call it vSwitchContainer).

Now place your switch inside vSwitchContainer. assign constraints for horizontally and vertically centre for UISwitch


问:
Passing JSON objects to jq arguments
Data sample - sample.json (full sample: https://pastebin.com/KFkVmc2M)

```<code>    {
      "ip": 3301234701,
      "_shodan": {
        "options": {
          "referrer": "7ae15507-f5cc-4353-b72e-5cc0b1c34c5e"
        },
      },
      "hash": -1056085507,
      "os": null,
      "title": "WHM Login",
      "opts": {
        "vulns": ["!CVE-2014-0160"],
        "heartbleed": "2017/08/29 09:57:30 196.196.216.13:2087 - SAFE\
        }
      },
      "isp": "Fiber Grid Inc",
      "http": {
        "redirects": [],
        "title": "WHM Login",
        "robots": null,
        "favicon": null,
        "host": "196.196.216.13",
        "html":
}
</code>```

Script using jq which I hoped would work and haven't found a another solution yet.

```<code>   cat sample.json | jq \
   --arg key0   'Host' \
   --arg value0 '.host' \
   --arg key1   'Vulnerability' \
   --arg value1 '.opts.vulns[0]' \
   --arg key2   'ISP' \
   --arg value2 '.isp' \
   '. | .[$key0]= $value0 | .[$key1]=$value1 | .[$key2]=$value2' \
   <<<'{}'
</code>```

The end result I hoped, but not getting:

```<code>{
  "Host": "196.196.216.13",
  "Vulnerability": "!CVE-2014-0160",
  "ISP": "Fiber Grid Inc"
}
</code>```

Right now it just returns the object as a string and I've tried a lot of different ways to approach the problem. I am quite new to working with JSON and jq but based on what I've read so far, the solution might not be as simple as I'm wishing?

Simply put, why isn't the object being returned as a value of the sample.json object and what do I have to do, to make it work?

Thanks!

to: chepner

```<code>{
  "196.196.216.13":[
  "AS63119",
  "Fiber Grid Inc",
  "2017-08-29T06:57:22.546423",
  "!CVE-2014-0160"
],
"196.196.216.14":[
  "AS63119",
  "Fiber Grid Inc",
  "2017-08-29T06:57:22.546423",
  "!CVE-2014-0160"
]
}
</code>```

答:
Here's a variant solution using the approach suggested by @CharlesDuffy:

```<code>$ config='{"Host": ["http", "host"],
           "Vulnerability": ["opts", "vulns", 0],
           "ISP": ["isp"]}'
$ jq --argjson config "$config" '
   . as $in
   | $config
   | map_values( . as $p | $in | getpath($p) )' pastebin.json
</code>```

Output:

```<code>{
  "Host": "196.196.216.13",
  "Vulnerability": "!CVE-2014-0160",
  "ISP": "Fiber Grid Inc"
}
</code>```

This incidentally highlights @chepner's point: the care and maintenance required for $config is no less than the care and maintenance required for the corresponding jq query, whereas the jq query language -- by design -- offers far more flexibility.

Title: Passing JSON objects to jq arguments

Body:
Data sample - sample.json (full sample: https://pastebin.com/KFkVmc2M)

    {
      "ip": 3301234701,
      "_shodan": {
        "options": {
          "referrer": "7ae15507-f5cc-4353-b72e-5cc0b1c34c5e"
        },
      },
      "hash": -1056085507,
      "os": null,
      "title": "WHM Login",
      "opts": {
        "vulns": ["!CVE-2014-0160"],
        "heartbleed": "2017/08/29 09:57:30 196.196.216.13:2087 - SAFE\
        }
      },
      "isp": "Fiber Grid Inc",
      "http": {
        "redirects": [],
        "title": "WHM Login",
        "robots": null,
        "favicon": null,
        "host": "196.196.216.13",
        "html":
}

Script using jq which I hoped would work and haven't found a another solution yet.

   cat sample.json | jq \
   --arg key0   'Host' \
   --arg value0 '.host' \
   --arg key1   'Vulnerability' \
   --arg value1 '.opts.vulns[0]' \
   --arg key2   'ISP' \
   --arg value2 '.isp' \
   '. | .[$key0]= $value0 | .[$key1]=$value1 | .[$key2]=$value2' \
   <<<'{}'

The end result I hoped, but not getting:

{
  "Host": "196.196.216.13",
  "Vulnerability": "!CVE-2014-0160",
  "ISP": "Fiber Grid Inc"
}

Right now it just returns the object as a string and I've tried a lot of different ways to approach the problem. I am quite new to working with JSON and jq but based on what I've read so far, the solution might not be as simple as I'm wishing?

Simply put, why isn't the object being returned as a value of the sample.json object and what do I have to do, to make it work?

Thanks!

to: chepner

{
  "196.196.216.13":[
  "AS63119",
  "Fiber Grid Inc",
  "2017-08-29T06:57:22.546423",
  "!CVE-2014-0160"
],
"196.196.216.14":[
  "AS63119",
  "Fiber Grid Inc",
  "2017-08-29T06:57:22.546423",
  "!CVE-2014-0160"
]
}

Body:
Here's a variant solution using the approach suggested by @CharlesDuffy:

$ config='{"Host": ["http", "host"],
           "Vulnerability": ["opts", "vulns", 0],
           "ISP": ["isp"]}'
$ jq --argjson config "$config" '
   . as $in
   | $config
   | map_values( . as $p | $in | getpath($p) )' pastebin.json

Output:

{
  "Host": "196.196.216.13",
  "Vulnerability": "!CVE-2014-0160",
  "ISP": "Fiber Grid Inc"
}

This incidentally highlights @chepner's point: the care and maintenance required for $config is no less than the care and maintenance required for the corresponding jq query, whereas the jq query language -- by design -- offers far more flexibility.


问:
How to deal with the URISyntaxException
I got this error message :

```<code>java.net.URISyntaxException: Illegal character in query at index 31: http://finance.yahoo.com/q/h?s=^IXIC
</code>```

My_Url = http://finance.yahoo.com/q/h?s=^IXIC

When I copied it into a browser address field, it showed the correct page, it's a valid URL, but I can't parse it with this: new URI(My_Url)

I tried : My_Url=My_Url.replace("^","\\^"), but

It won't be the url I need

It doesn't work either

How to handle this ?

Frank

答: Replace spaces in URL with + like If url contains dimension1=Incontinence Liners then replace it with dimension1=Incontinence+Liners.</p>

Title: How to deal with the URISyntaxException

Body:
I got this error message :

java.net.URISyntaxException: Illegal character in query at index 31: http://finance.yahoo.com/q/h?s=^IXIC

My_Url = http://finance.yahoo.com/q/h?s=^IXIC

When I copied it into a browser address field, it showed the correct page, it's a valid URL, but I can't parse it with this: new URI(My_Url)

I tried : My_Url=My_Url.replace("^","\\^"), but

It won't be the url I need

It doesn't work either

How to handle this ?

Frank


问:
Convert python dict to a structure using ctypes
I have a structure like this:

struct Person {
  std::string name;
  int age;
  std::string title;
  float income;
};
```

<p>In the python side, I have a dict like this:</p>

<pre class="lang-py prettyprint-override"><code>person = { 'name':'Alex',
           'age':36,
           'title':'programmer',
           'income':13435.40
          }
</code>```

Now I want to convert the Python dict to the C++ program by using ctypes. There is a stupid way to do this task is that we can write 4 c-style functions to set these four elements independently. How can we do this task in a single function, which can solve different data type (string, int, float)?

答:
ctypes can't handle C++ on its own.

SWIG can though this is equivalent to writing a C wrapper for the C++ code. It requires building native code.

Body:
I have a structure like this:

struct Person {
  std::string name;
  int age;
  std::string title;
  float income;
};

In the python side, I have a dict like this:

person = { 'name':'Alex',
           'age':36,
           'title':'programmer',
           'income':13435.40
          }

Now I want to convert the Python dict to the C++ program by using ctypes. There is a stupid way to do this task is that we can write 4 c-style functions to set these four elements independently. How can we do this task in a single function, which can solve different data type (string, int, float)?


问:
Unable to set href in angular 4 on nginx server
Please bear with me as it's a long question but I am stuck badly.

Objective

I want to ran my ssl configured build on my linux based server on Nginx and I want to access it on my domain https://dev.server.nl with resources /ggmd/webconsole i.e https://dev.server.nl/ggmd/webconsole

Steps I followed

I have deployed my angular 4 build on my linux server machine in webconsole folder. Path is something like  /opt/web/dev/ggmd/webconsole and all my build files are inside it.

I have ran build on nginx server by doing configuration in default file.

```<code>server {
    listen 4200 default_server;
    root /opt/web/dev/ggmd/webconsole;
    index index.html index.htm;
    server_name localhost;
    location / {
        try_files $uri $uri/ /index.html;
    }
}
</code>```

And my base href is set to <base href="/ggmd/webconsole/">

```<code><!doctype html>
<html lang="en">
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
      <meta charset="utf-8">
    <title>GGMD Console</title>
    <base href="/ggmd/webconsole/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-root></app-root>
<script type="text/javascript" src="inline.bundle.js"></script><script type="text/javascript" src="polyfills.bundle.js"></script><script type="text/javascript" src="scripts.bundle.js"></script><script type="text/javascript" src="styles.bundle.js"></script><script type="text/javascript" src="vendor.bundle.js"></script><script type="text/javascript" src="main.bundle.js"></script></body>
</html>
</code>```

My mapping configurations to access URl on domain is following:

```<code>location /ggmd/webconsole {
        proxy_pass http://13.26.100.155:4200;
        proxy_redirect http://13.26.100.155:4200 https://dev.w-integrate.nl/ggmd/webconsole;

        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Server $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

}
</code>```

Problem Statement

I am unable to access it via IP on https but when I try to access via HTTP http://13.26.100.155:4200/ggmd/webconsole/

I redirected to 404 page of my angular application that I defined and made in my angular router code.

When I tried to access with redirect proxy then I am unable to access it on http but When I try https on https://dev.w-integrate.nl/ggmd/web/console

I get following error in browser console.

Refused to execute script from inline.bundle.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.

When I remove "/ggmd/webconsole/" from my base href and redirect configuration like following

<base href="/"> and my redirect configurations to following

```<code>location / {
            proxy_pass http://13.26.100.155:4200;
            proxy_redirect http://13.26.100.155:4200 https://dev.w-integrate.nl/;

            proxy_set_header X-Forwarded-Host $host;
            proxy_set_header X-Forwarded-Server $host;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

    }
</code>```

Then I am able to access my project on following

https://dev.server.nl/

http://13.26.100.155:4200 (NOT on HTTPS)

But I want to ran it on https and with /ggmd/webconsole resource https://dev.server.nl/ggmd/webconsole

How can I do this? Please forgive in case of any typing mistake.

EDIT : SOLUTION

port 443 was already in use with some other certificates under server tag server { //configurations }

I added my configurations in server tag below the server tag where port is 443 and Base href is "/"

My configurations are below:

```<code>server {
    listen 4200 ssl;

        ssl_certificate /opt/web/dev/ggmd/webconsole/devcom.crt;
        ssl_certificate_key /opt/web/dev/ggmd/webconsole/devcom.key;

    root /opt/web/dev/ggmd/webconsole;
    index index.html index.htm;
    server_name dev.w-integrate.nl;

        location /ggmd/webconsole(.*)$ {
        proxy_pass https://83.96.205.55:4200;
        proxy_redirect https://83.96.205.55:4200 https://dev.w-integrate.nl/ggmd/webconsole;

        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Server $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

        }
    location / {
        try_files $uri $uri/ /index.html;
    }
}
</code>```

Now I am able to access https but following is happening:

Via IP https://13.26.100.155:4200/ggmd/webconsole

I am routed to 404 page of my angular application via angular route and

Via reverse proxy https://dev.server.nl/ggmd/webconsole/

I am routed to 404 page of nginx

What is wrong now?

答:
Can you see if this file works</p>

```<code>server {
        listen 443 ssl;

        server_name <YOUR_DOMAIN_NAME eg www.example.com>;

        ssl_certificate /path/to/rapid_ssl.crt;
        ssl_certificate_key /path/tp/cert/rapid_ssl.key;

        location /ggmd/webconsole(.*)$ {
        proxy_pass http://13.26.100.155:4200;
        proxy_redirect http://13.26.100.155:4200 https://dev.w-integrate.nl/ggmd/webconsole;

        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Server $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

        }

        location / {
                try_files $uri $uri/ /index.html;
        }
}
</code>```

Body:
Please bear with me as it's a long question but I am stuck badly.

Objective

I want to ran my ssl configured build on my linux based server on Nginx and I want to access it on my domain https://dev.server.nl with resources /ggmd/webconsole i.e https://dev.server.nl/ggmd/webconsole

Steps I followed

I have deployed my angular 4 build on my linux server machine in webconsole folder. Path is something like  /opt/web/dev/ggmd/webconsole and all my build files are inside it.

I have ran build on nginx server by doing configuration in default file.

server {
    listen 4200 default_server;
    root /opt/web/dev/ggmd/webconsole;
    index index.html index.htm;
    server_name localhost;
    location / {
        try_files $uri $uri/ /index.html;
    }
}

And my base href is set to <base href="/ggmd/webconsole/">

<!doctype html>

      <meta charset="utf-8">
    <title>GGMD Console</title>
    <base href="/ggmd/webconsole/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

  <app-root></app-root>

My mapping configurations to access URl on domain is following:

location /ggmd/webconsole {
        proxy_pass http://13.26.100.155:4200;
        proxy_redirect http://13.26.100.155:4200 https://dev.w-integrate.nl/ggmd/webconsole;

        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Server $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

}

Problem Statement

I am unable to access it via IP on https but when I try to access via HTTP http://13.26.100.155:4200/ggmd/webconsole/

I redirected to 404 page of my angular application that I defined and made in my angular router code.

When I tried to access with redirect proxy then I am unable to access it on http but When I try https on https://dev.w-integrate.nl/ggmd/web/console

I get following error in browser console.

Refused to execute script from inline.bundle.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.

When I remove "/ggmd/webconsole/" from my base href and redirect configuration like following

<base href="/"> and my redirect configurations to following

location / {
            proxy_pass http://13.26.100.155:4200;
            proxy_redirect http://13.26.100.155:4200 https://dev.w-integrate.nl/;

            proxy_set_header X-Forwarded-Host $host;
            proxy_set_header X-Forwarded-Server $host;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

    }

Then I am able to access my project on following

https://dev.server.nl/

http://13.26.100.155:4200 (NOT on HTTPS)

But I want to ran it on https and with /ggmd/webconsole resource https://dev.server.nl/ggmd/webconsole

How can I do this? Please forgive in case of any typing mistake.

EDIT : SOLUTION

port 443 was already in use with some other certificates under server tag server { //configurations }

I added my configurations in server tag below the server tag where port is 443 and Base href is "/"

My configurations are below:

server {
    listen 4200 ssl;

        ssl_certificate /opt/web/dev/ggmd/webconsole/devcom.crt;
        ssl_certificate_key /opt/web/dev/ggmd/webconsole/devcom.key;

    root /opt/web/dev/ggmd/webconsole;
    index index.html index.htm;
    server_name dev.w-integrate.nl;

        location /ggmd/webconsole(.*)$ {
        proxy_pass https://83.96.205.55:4200;
        proxy_redirect https://83.96.205.55:4200 https://dev.w-integrate.nl/ggmd/webconsole;

        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Server $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

        }
    location / {
        try_files $uri $uri/ /index.html;
    }
}

Now I am able to access https but following is happening:

Via IP https://13.26.100.155:4200/ggmd/webconsole

I am routed to 404 page of my angular application via angular route and

Via reverse proxy https://dev.server.nl/ggmd/webconsole/

I am routed to 404 page of nginx

What is wrong now?

Body:
Can you see if this file works

server {
        listen 443 ssl;

        server_name <YOUR_DOMAIN_NAME eg www.example.com>;

        ssl_certificate /path/to/rapid_ssl.crt;
        ssl_certificate_key /path/tp/cert/rapid_ssl.key;

        location /ggmd/webconsole(.*)$ {
        proxy_pass http://13.26.100.155:4200;
        proxy_redirect http://13.26.100.155:4200 https://dev.w-integrate.nl/ggmd/webconsole;

        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Server $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

        }

        location / {
                try_files $uri $uri/ /index.html;
        }
}


问:
Android google map marker/label similar to latest traffic map
I am quite new to using google map on android. So far I found the following code snippet.

```<code>public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }
</code>```

This does a simple labelling of the marker. What I am looking is something like the picture below.What I want to do is how to show the label or inforwindow like its shows the traffic jam how minutes +8 min etc. I am not too sure is it to be done a label, custom info window or how?

答:
1. Make sure your current location is detected in Google Map

2.Make sure your Google Map has traffic data available for your current location.

2.Make sure your Internet Connection is available for your Devices.

```<code>@Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        mMap.setTrafficEnabled(true);// Traffic line is on in mapview

    }
</code>```

Body:
I am quite new to using google map on android. So far I found the following code snippet.

public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }

This does a simple labelling of the marker. What I am looking is something like the picture below.What I want to do is how to show the label or inforwindow like its shows the traffic jam how minutes +8 min etc. I am not too sure is it to be done a label, custom info window or how?

Body:
1. Make sure your current location is detected in Google Map

2.Make sure your Google Map has traffic data available for your current location.

2.Make sure your Internet Connection is available for your Devices.

@Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        mMap.setTrafficEnabled(true);// Traffic line is on in mapview

    }


问:
Create a global variable in TypeScript
In JavaScript I can just do this:

```<code> something = 'testing';
</code>```

And then in another file:

```<code> if (something === 'testing')
</code>```

and it will have something be defined (as long as they were called in the correct order).

I can't seem to figure out how to do that in TypeScript.

This is what I have tried.

In a .d.ts file:

```<code>interface Window { something: string; }
</code>```

Then in my main.ts file:

```<code> window.something = 'testing';
</code>```

then in another file:

```<code> if (window.something  === 'testing')
</code>```

And this works.  But I want to be able to lose the window. part of it and just have my something be global. Is there a way to do that in TypeScript?

(In case someone is interested, I am really trying to setup my logging for my application.  I want to be able to call log.Debug from any file without having to import and create objects.)

答:
im using only this</p>

```<code>import {globalVar} from "./globals";
declare let window:any;
window.globalVar = globalVar;
</code>```

Title: Create a global variable in TypeScript

Body:
In JavaScript I can just do this:

 something = 'testing';

And then in another file:

 if (something === 'testing')

and it will have something be defined (as long as they were called in the correct order).

I can't seem to figure out how to do that in TypeScript.

This is what I have tried.

In a .d.ts file:

interface Window { something: string; }

Then in my main.ts file:

 window.something = 'testing';

then in another file:

 if (window.something  === 'testing')

And this works.  But I want to be able to lose the window. part of it and just have my something be global. Is there a way to do that in TypeScript?

(In case someone is interested, I am really trying to setup my logging for my application.  I want to be able to call log.Debug from any file without having to import and create objects.)

Body:
im using only this

import {globalVar} from "./globals";
declare let window:any;
window.globalVar = globalVar;


问:
Remove trailing whitespace recursively only at end of file using grep/sed?
Basically, I've got about 1,500 files and the last character of any of these files should not be any type of white space.

How do I check a bunch of files to make sure that they don't end in some form of whitespace?(newline, space, carriage return, tab, etc.)?

答:
Might be easier reading the file from the bottom to the top:</p>

```<code>tac filename |
awk '
    /^[[:space:]]*$/ && !seen {next}
    /[^[:space:]]/   && !seen {gsub(/[[:space:]]+$/,""); seen=1}
    seen
' |
tac
</code>```

Body:
Might be easier reading the file from the bottom to the top:

tac filename |
awk '
    /^[[:space:]]*$/ && !seen {next}
    /[^[:space:]]/   && !seen {gsub(/[[:space:]]+$/,""); seen=1}
    seen
' |
tac


问:
Angular - close modal window with event
I would like to fire an event when the close button is clicked within the modal window.
The button has the attribute data-dismiss="modal" and doesn't call the click event. Is it possible to have data-dismiss and click event or only click event and close modal from class?

```<code><div class="modal-dialog">
 <div class="modal-content">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" (click)="close()">×</button>
    <h4 class="modal-title">{{modalHeader}}</h4>
  </div>
 </div>
</div>

close() {
    //Can I close modal window manually?
    this.onClose.emit();
  }
</code>```

Method close dont call because button has data-dismiss attribute.

Thank you

答:
In angular, use [hidden] attribute to show/hide the model popup,  and remove data-dismiss="modal" in your close button

try this

```<code><div [hidden]="IsmodelShow" class="modal-dialog">
     <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" (click)="close()">×</button>
        <h4 class="modal-title">{{modalHeader}}</h4>
      </div>
     </div>
    </div

close() {
    this.IsmodelShow=true;// set false while you need open your model popup
   // do your more code
}
</code>```

Update

just add data-target="#modal" in your div and it will be works

```<code><div class="modal-dialog" data-target="#modal">
 <div class="modal-content">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" (click)="close()">×</button>
    <h4 class="modal-title">{{modalHeader}}</h4>
  </div>
 </div>
</div>

close() {
//write your code
}
</code>```

Update 2

You need to set data-target as target id of your modal and data-toggle = "modal" to the button on which you want to activate the modal

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

<button type="button" data-target="#myupdate" data-toggle="modal" class="btn btn-info btn-lg">Update</button>

          <button type="button" class="close" data-dismiss="modal">×</button>

New Update

This is a small modal.

          <button type="button" class="btn btn-default" data-dismiss="modal" (click)="close()">Close</button>

```

Title: Angular - close modal window with event

Body:
I would like to fire an event when the close button is clicked within the modal window.
The button has the attribute data-dismiss="modal" and doesn't call the click event. Is it possible to have data-dismiss and click event or only click event and close modal from class?

    <button type="button" class="close" data-dismiss="modal" (click)="close()">×</button>

{{modalHeader}}

close() {
    //Can I close modal window manually?
    this.onClose.emit();
  }

Method close dont call because button has data-dismiss attribute.

Thank you

Body:
In angular, use [hidden] attribute to show/hide the model popup,  and remove data-dismiss="modal" in your close button

try this

<div [hidden]="IsmodelShow" class="modal-dialog">
     <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" (click)="close()">&times;</button>
        <h4 class="modal-title">{{modalHeader}}</h4>
      </div>
     </div>
    </div

close() {
    this.IsmodelShow=true;// set false while you need open your model popup
   // do your more code
}

Update

just add data-target="#modal" in your div and it will be works

<div class="modal-dialog" data-target="#modal">
 <div class="modal-content">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" (click)="close()">&times;</button>
    <h4 class="modal-title">{{modalHeader}}</h4>
  </div>
 </div>
</div>

close() {
//write your code
}

Update 2

You need to set data-target as target id of your modal and data-toggle = "modal" to the button on which you want to activate the modal

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<button type="button" data-target="#myupdate" data-toggle="modal" class="btn btn-info btn-lg">Update</button>

  <!-- Modal -->
  <div class="modal fade" id="myupdate" role="dialog">
    <div class="modal-dialog modal-sm">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">New Update </h4>
        </div>
        <div class="modal-body">
          <p>This is a small modal.</p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal" (click)="close()">Close</button>
        </div>
      </div>
    </div>
  </div>


问:
What is a callback function and how do I use it with OOP
I want to use the php simple HTML DOM parser to grab the image, title, date, and description from each article on a page full of articles. When looking at the API I notice it has a set_callback which Sets a callback function. However im not sure what this does or how I would use it? In one of the examples its used to call a function which strips out some stuff, im wondering if you have to use this to call all functions?

I guess im wondering why I use this, and what does it do as I have never come across a callback function before!

答:
With PHP 5.3, you can now do this:

```<code>function doIt($callback) { $callback(); }

doIt(function() {
    // this will be done
});
</code>```

Finally, a nice way to do it. A great addition to PHP, because callbacks are awesome.

OwnerDisplayName: Paul M

Body:
With PHP 5.3, you can now do this:

function doIt($callback) { $callback(); }

doIt(function() {
    // this will be done
});

Finally, a nice way to do it. A great addition to PHP, because callbacks are awesome.


问:
Python: how to find the first nonzero in a multi-series dataframe?
I have a dataframe with 5 columns indexed to date.  the data is consisted of 0's and 1's.  I would like to find the first nonzeros in each series and multiple it (and only it) by 100.

Date   A   B   C   D   E
3/1/16  0   0   0   0   0
3/2/16  0   0   1   0   0
3/3/16  1   0   0   0   0
3/4/16  0   1   0   0   0
3/7/16  0   0   1   0   1
3/8/16  0   0   0   0   1
3/9/16  0   0   0   1   1

I tried the following code, but it didn't work.

```<code>for col in df.columns:
    idx = df[col].first_valid_index()
    df[col][idx] = df[col][idx]*100.
</code>```

答:
With the for loop, we can do

```<code>cols = df.columns[df.columns != 'Date']
for col in cols:
    idx = df[col][df[col] != 0].index[0]
    df[col][idx] = df[col][idx]*100
</code>```

Body:
I have a dataframe with 5 columns indexed to date.  the data is consisted of 0's and 1's.  I would like to find the first nonzeros in each series and multiple it (and only it) by 100.

Date   A   B   C   D   E
3/1/16  0   0   0   0   0
3/2/16  0   0   1   0   0
3/3/16  1   0   0   0   0
3/4/16  0   1   0   0   0
3/7/16  0   0   1   0   1
3/8/16  0   0   0   0   1
3/9/16  0   0   0   1   1

I tried the following code, but it didn't work.

for col in df.columns:
    idx = df[col].first_valid_index()
    df[col][idx] = df[col][idx]*100.

Body:
With the for loop, we can do

cols = df.columns[df.columns != 'Date']
for col in cols:
    idx = df[col][df[col] != 0].index[0]
    df[col][idx] = df[col][idx]*100


问:
Operator new and delete on Inherited class. Operator delete not executing
I was messing around operator overloading and I've noticed that on inherited object, the overloaded operator delete doesn't seem to execute when the inherited object has an operator new overloaded:

```<code>#include <iostream>
#include <string>

class TestAbs {
public:
  TestAbs (void) {
  }
  virtual ~TestAbs (void) noexcept {
  }
};

class Test : public TestAbs {
public:
  Test (void)
      : TestAbs () {
  }
  ~Test (void) noexcept override {
  }
  void* operator new (size_t) throw () {
    std::cout << "Overloaded operator new!\n";
    return nullptr;
  }
  void operator delete (void*) noexcept {
    std::cout << "Overloaded operator delete in class: Test!\n";
  }
};

int main() {
    TestAbs* tp = new Test ();
    delete tp;

    return 0;
}
</code>```

The code above has the following output:

```<code>Overloaded operator new!
</code>```

What happened to the overloaded operator delete?
Thank you all in advance!

Update:
Thank you guys for all the help. It seems like the problem was indeed the nullptr return on the overloaded new.

答:
Your code should work, if you just return an address that isn't null pointer value. To quote the C++ standard:

[class.free]/4

Class-specific deallocation function lookup is a part of general
  deallocation function lookup ([expr.delete]) and occurs as follows. If
  the delete-expression is used to deallocate a class object whose
  static type has a virtual destructor, the deallocation function is the
  one selected at the point of definition of the dynamic type's virtual
  destructor ([class.dtor]).

[class.dtor]/13

At the point of definition of a virtual destructor (including an
  implicit definition), the non-array deallocation function is
  determined as if for the expression delete this appearing in a
  non-virtual destructor of the destructor's class (see [expr.delete]).
  If the lookup fails or if the deallocation function has a deleted
  definition, the program is ill-formed. [ Note: This assures that a
  deallocation function corresponding to the dynamic type of an object
  is available for the delete-expression ([class.free]).  — end note ]

[expr.delete]/6

If the value of the operand of the delete-expression is not a null
  pointer value, the delete-expression will invoke the destructor (if
  any) for the object or the elements of the array being deleted.

You just set it up in a way that won't invoke anything at the delete expression. I fixed it up to forward onto the global operators new and delete, and everything works as expected. The code is on Coliru Viewer.

Body:
I was messing around operator overloading and I've noticed that on inherited object, the overloaded operator delete doesn't seem to execute when the inherited object has an operator new overloaded:

#include <iostream>
#include <string>

class TestAbs {
public:
  TestAbs (void) {
  }
  virtual ~TestAbs (void) noexcept {
  }
};

class Test : public TestAbs {
public:
  Test (void)
      : TestAbs () {
  }
  ~Test (void) noexcept override {
  }
  void* operator new (size_t) throw () {
    std::cout << "Overloaded operator new!\n";
    return nullptr;
  }
  void operator delete (void*) noexcept {
    std::cout << "Overloaded operator delete in class: Test!\n";
  }
};

int main() {
    TestAbs* tp = new Test ();
    delete tp;

    return 0;
}

The code above has the following output:

Overloaded operator new!

What happened to the overloaded operator delete?
Thank you all in advance!

Update:
Thank you guys for all the help. It seems like the problem was indeed the nullptr return on the overloaded new.