问:
Remove current filter
I have a list of items wrapped in div that can either be filtered using drop down or input box.
How do you remove the filter from input box before filtering using the drop down? It only affect when filtered via input first then drop-down. It works the other way around.

I have an input box that filters the div with the following:

```<code>$("#dirSearchKey").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#searchBlock div[class^=filterDiv]").each(function() {
    $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
</code>```

The filter is cleared when user manually deletes the input box value. I found out I can't trigger a delete or backspace key. I tried removing the last character as suggested on this post but it didn't work.

I'm using below code from w3school to filter the elements via a drop down.

```<code>function filterSelection(c, d) {
var x, i;
    x = document.getElementsByClassName("filterDiv");

if (c == "all") c = "";
for (i = 0; i < x.length; i++) {
    w3RemoveClass(x[i], "show");
    if (x[i].className.indexOf(c) > -1) w3AddClass(x[i], "show");
}
document.getElementById('formheader').innerHTML = d + ' Form(s)';
}

function w3AddClass(element, name) {
var i, arr1, arr2;
    arr1 = element.className.split(" ");
    arr2 = name.split(" ");
for (i = 0; i < arr2.length; i++) {
    if (arr1.indexOf(arr2[i]) == -1) {element.className += " " + arr2[i];}
}
}

function w3RemoveClass(element, name) {
var i, arr1, arr2;
    arr1 = element.className.split(" ");
    arr2 = name.split(" ");
for (i = 0; i < arr2.length; i++) {
    while (arr1.indexOf(arr2[i]) > -1) {
        arr1.splice(arr1.indexOf(arr2[i]), 1);
    }
}
element.className = arr1.join(" ");
}
</code>```

I added below in filterSelection() but it seems to only work once. Subsequent filters between drop-down and input don't work.

```<code>        var srcVal = document.getElementById('dirSearchKey').value;
    if (srcVal !== '') {
        document.getElementById('dirSearchKey').value = '';
        $("#searchBlock div[class^=filterDiv]").filter(function() {
            var value = '';
            $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
        });
    }
</code>```

答:
I replaced filter() with .each() and removed all the code I got from w3school (i.e. add/remove classes) and just used below

```<code>function filterSelection(d) {

if (d == "All") d = "";

$("#searchBlock div[class^=filterDiv]").each(function() {
    $(this).removeAttr("style");
    $(this).toggle($(this).text().indexOf(d) > -1);
});

document.getElementById('formheader').innerHTML = d;
</code>```

}

When I was looking into .each() I looked into .toggle() as well and above is the result. Seems to work well after few tests.

Title: Remove current filter

Body:
I have a list of items wrapped in div that can either be filtered using drop down or input box.
How do you remove the filter from input box before filtering using the drop down? It only affect when filtered via input first then drop-down. It works the other way around.

I have an input box that filters the div with the following:

$("#dirSearchKey").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#searchBlock div[class^=filterDiv]").each(function() {
    $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});

The filter is cleared when user manually deletes the input box value. I found out I can't trigger a delete or backspace key. I tried removing the last character as suggested on this post but it didn't work.

I'm using below code from w3school to filter the elements via a drop down.

function filterSelection(c, d) {
var x, i;
    x = document.getElementsByClassName("filterDiv");

if (c == "all") c = "";
for (i = 0; i < x.length; i++) {
    w3RemoveClass(x[i], "show");
    if (x[i].className.indexOf(c) > -1) w3AddClass(x[i], "show");
}
document.getElementById('formheader').innerHTML = d + ' Form(s)';
}

function w3AddClass(element, name) {
var i, arr1, arr2;
    arr1 = element.className.split(" ");
    arr2 = name.split(" ");
for (i = 0; i < arr2.length; i++) {
    if (arr1.indexOf(arr2[i]) == -1) {element.className += " " + arr2[i];}
}
}

function w3RemoveClass(element, name) {
var i, arr1, arr2;
    arr1 = element.className.split(" ");
    arr2 = name.split(" ");
for (i = 0; i < arr2.length; i++) {
    while (arr1.indexOf(arr2[i]) > -1) {
        arr1.splice(arr1.indexOf(arr2[i]), 1);
    }
}
element.className = arr1.join(" ");
}

I added below in filterSelection() but it seems to only work once. Subsequent filters between drop-down and input don't work.

        var srcVal = document.getElementById('dirSearchKey').value;
    if (srcVal !== '') {
        document.getElementById('dirSearchKey').value = '';
        $("#searchBlock div[class^=filterDiv]").filter(function() {
            var value = '';
            $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
        });
    }

Body:
I replaced filter() with .each() and removed all the code I got from w3school (i.e. add/remove classes) and just used below

function filterSelection(d) {

if (d == "All") d = "";

$("#searchBlock div[class^=filterDiv]").each(function() {
    $(this).removeAttr("style");
    $(this).toggle($(this).text().indexOf(d) > -1);
});

document.getElementById('formheader').innerHTML = d;

}

When I was looking into .each() I looked into .toggle() as well and above is the result. Seems to work well after few tests.


来源: stackexchange

问:
How to find the invalid controls in Angular(v2 onwards) reactive form
I have a reactive form in Angular like below:

this.AddCustomerForm = this.formBuilder.group({
    Firstname: ['', Validators.required],
    Lastname: ['', Validators.required],
    Email: ['', Validators.required, Validators.pattern(this.EMAIL_REGEX)],
    Picture: [''],
    Username: ['', Validators.required],
    Password: ['', Validators.required],
    Address: ['', Validators.required],
    Postcode: ['', Validators.required],
    City: ['', Validators.required],
    Country: ['', Validators.required]
});

createCustomer(currentCustomer: Customer)
{
    if (!this.AddCustomerForm.valid)
    {
        //some app logic
    }
}
```

this.AddCustomerForm.valid returns false, but everything looks good.

I have tried to find with checking the status property in the controls collection. But I wonder if there is a way to find the invalid ones and display to the user?

答:
try this

```<code> findInvalidControls(f: FormGroup) {
    const invalid = [];
    const controls = f.controls;
    for (const name in controls) {
      if (controls[name].invalid) {
        invalid.push(name);
      }
    }
    return invalid;
  }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a reactive form in Angular like below:

this.AddCustomerForm = this.formBuilder.group({
    Firstname: ['', Validators.required],
    Lastname: ['', Validators.required],
    Email: ['', Validators.required, Validators.pattern(this.EMAIL_REGEX)],
    Picture: [''],
    Username: ['', Validators.required],
    Password: ['', Validators.required],
    Address: ['', Validators.required],
    Postcode: ['', Validators.required],
    City: ['', Validators.required],
    Country: ['', Validators.required]
});

createCustomer(currentCustomer: Customer)
{
    if (!this.AddCustomerForm.valid)
    {
        //some app logic
    }
}

this.AddCustomerForm.valid returns false, but everything looks good.

I have tried to find with checking the status property in the controls collection. But I wonder if there is a way to find the invalid ones and display to the user?

Body:
try this

 findInvalidControls(f: FormGroup) {
    const invalid = [];
    const controls = f.controls;
    for (const name in controls) {
      if (controls[name].invalid) {
        invalid.push(name);
      }
    }
    return invalid;
  }


问:
Aggregation on aggregate
We have a collection as follows - Batches(0,1,2 etc) running jobs in chunks.

Each batch would have multiple chunks/documents having jobs.

We need to aggregate jobs for each batch.

Thereafter,job count of each batch needs to be subtracted from that of batch '0'.

The result would be an array/collection of the difference of job counts of each batch with batch 0 respectively.

If there are 'x' batches,the size of the array would be x-1 obviously.

Can this be done in a single aggregation operation?

```<code>{
    "_id": ObjectId("xxxxxx"),
    "batch": ["0"],
    "jobs":2500
},
{
    "_id": ObjectId("xxxxxx"),
    "batch": ["1"],
    "jobs":1500
},
{
    "_id": ObjectId("xxxxxx"),
    "batch": ["0"],
    "jobs":1500
},
{
    "_id": ObjectId("xxxxxx"),
    "batch": ["2"],
    "jobs":3500
},
{
    "_id": ObjectId("xxxxxx"),
    "batch": ["1"],
    "jobs":500
},
{
    "_id": ObjectId("xxxxxx"),
    "batch": ["0"],
    "jobs":1500
},
{
    "_id": ObjectId("xxxxxx"),
    "batch": ["3"],
    "jobs":2500
},
</code>```

Expected output:

```<code>[ 3500,2000,3000]
</code>```

答:
You can try this :

```<code>db.collection.aggregate([
    { $unwind: '$batch' },
    { $group: { _id: '$batch', count: { $sum: '$jobs' } } },
    { $group: { _id: '', data: { $push: '$$ROOT' } } },
    {
        $addFields: {
            value: { $filter: { input: '$data', as: 'e', cond: { $eq: ['$$e._id', '0'] } } }
        }
    },
    {
        $project: {
            _id: 0,
            data: { $filter: { input: { $map: { input: '$data', as: 'e', in: { $subtract: [{ $arrayElemAt: ['$value.count', 0] }, '$$e.count'] } } }, as: 'e', cond: { $ne: ['$$e', 0] } } }
        }
    }])
</code>```

Test : MongoDB-Playground

Title: Aggregation on aggregate

Body:
We have a collection as follows - Batches(0,1,2 etc) running jobs in chunks.

Each batch would have multiple chunks/documents having jobs.

We need to aggregate jobs for each batch.

Thereafter,job count of each batch needs to be subtracted from that of batch '0'.

The result would be an array/collection of the difference of job counts of each batch with batch 0 respectively.

If there are 'x' batches,the size of the array would be x-1 obviously.

Can this be done in a single aggregation operation?

{
    "_id": ObjectId("xxxxxx"),
    "batch": ["0"],
    "jobs":2500
},
{
    "_id": ObjectId("xxxxxx"),
    "batch": ["1"],
    "jobs":1500
},
{
    "_id": ObjectId("xxxxxx"),
    "batch": ["0"],
    "jobs":1500
},
{
    "_id": ObjectId("xxxxxx"),
    "batch": ["2"],
    "jobs":3500
},
{
    "_id": ObjectId("xxxxxx"),
    "batch": ["1"],
    "jobs":500
},
{
    "_id": ObjectId("xxxxxx"),
    "batch": ["0"],
    "jobs":1500
},
{
    "_id": ObjectId("xxxxxx"),
    "batch": ["3"],
    "jobs":2500
},

Expected output:

[ 3500,2000,3000]

Body:
You can try this :

db.collection.aggregate([
    { $unwind: '$batch' },
    { $group: { _id: '$batch', count: { $sum: '$jobs' } } },
    { $group: { _id: '', data: { $push: '$$ROOT' } } },
    {
        $addFields: {
            value: { $filter: { input: '$data', as: 'e', cond: { $eq: ['$$e._id', '0'] } } }
        }
    },
    {
        $project: {
            _id: 0,
            data: { $filter: { input: { $map: { input: '$data', as: 'e', in: { $subtract: [{ $arrayElemAt: ['$value.count', 0] }, '$$e.count'] } } }, as: 'e', cond: { $ne: ['$$e', 0] } } }
        }
    }])

Test : MongoDB-Playground


问:
Anyone have experience integrating datadog monitoring with Snowflake?
Does anyone know if Datadog agent works on snowflake? We want to use Datadog to collect snowflake metrics, traces and logs and create dashboards, graphs, and monitors.</p>

答:
No, you cannot install the Datadog agent on a Snowflake host.

We use our separate job scheduling system to monitor Snowflake by running queries (e.g. checks on SYSTEM$CLUSTERING_DEPTH, aggregate queries against the QUERY_HISTORY for timing, etc) via the JDBC connector then relaying the results to our monitoring stack (similar to how Datadog agent would work.)


问:
Get ZXing to work
I followed every instructions, wiki, getting started, guides, help,
etc. I could find about ZXing project.
After many many debugging, I finally manged to compile using ant
core.jar, javame.jar, and javese.jar.
I would like to integrate ZXing into my code, i.e., I wish to scan
\read a barcode and handle its data.

I've imported as external jar each of the files mentioned above. Then
I turned to https://code.google.com/p/zxing/wiki/DeveloperNotes to use
the MultiFormatReader().
The BufferedImage class cannot be resolved. I tried whatever I know
and I even tried android's Bitmap for a workaround, but it didn't help
me either.

I know I can use an intent to read\scan the barcode, but I wish to
handle it myself and not to install a "3rd party" application.

Can anyone please help me understand how can I do so?
Few lines of code will be appreciated.

And again, I only want to scan\read a barcode and analyze its data.

答:
The shortest answer is that you should not use javase.jar in an Android app. It is code intended for JavaSE. Not all JavaSE classes are in Android. In particular Android does not have AWT classes like BufferedImage.

You only want to include core.jar in your project. Then write your Android app using it.

ContentLicense: CC BY-SA 3.0

Title: Get ZXing to work


问:
How to construct a person class that allows tracking of property values over time
I'd like to construct a person class that has a property which the value may change over time but I want to keep the history of values. A person grows taller over time and their weight may change.  You may imagine a "HockeyPlayer: Person" that plays over many seasons.  Each season their height/weight may be different.  I would then use EntityFramework to create tables.  I think the main question I have is where do I put those properties? In their own class? In HockeyPlayer?  In Person?  Thank you in advance

pseudocode example:

```<code>public class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public System.DateTime DateOfBirth { get; set; }
}

public class Season
{
    public int Id { get; set; }
    public string season { get; set; }
}

public class HockeyPlayer : Person
{
    public int PersonId {get; set; }
    public int SeasonId { get; set; }
    public int JerseyNumber { get; set; }
    public int HeightInches { get; set; }
    public int WeightPounds { get; set; }
}
</code>```

答:
I would recommend doing some research into database normalization.

I would create another entity called PersonMetrics with SeasonId, PersonId and Date attributes. You would then add whatever values you want to measure in that. Technically SeasonId and PersonId could form the composite primary key (in which case you would be better off putting Date on the Season entity), but for ease of use with EntityFramework, or if there will be multiple measurements per season you may choose to give it its own Id.

Body:
I'd like to construct a person class that has a property which the value may change over time but I want to keep the history of values. A person grows taller over time and their weight may change.  You may imagine a "HockeyPlayer: Person" that plays over many seasons.  Each season their height/weight may be different.  I would then use EntityFramework to create tables.  I think the main question I have is where do I put those properties? In their own class? In HockeyPlayer?  In Person?  Thank you in advance

pseudocode example:

public class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public System.DateTime DateOfBirth { get; set; }
}

public class Season
{
    public int Id { get; set; }
    public string season { get; set; }
}

public class HockeyPlayer : Person
{
    public int PersonId {get; set; }
    public int SeasonId { get; set; }
    public int JerseyNumber { get; set; }
    public int HeightInches { get; set; }
    public int WeightPounds { get; set; }
}


问:
Function as parameter (DART)
I'm trying to understand how dart uses a function as parameter. I wrote this code...

```<code>typedef Future<String> myFunction();

void main() {
  A a = A();
  a.f1(a._f1);
}

class A {
  f1(myFunction func) async {
    String x = await _f1;
    print(x);
  }

  Future<String> _f1() {
    Future.delayed(Duration(seconds: 3)).then((f) {
      return "test";
    });
  }
}
</code>```

I need the function f1 returns "test", but I have this error : A value of type 'Future Function()' can't be assigned to a variable of type 'String'

If I change  String x = await _f1 by Future x = await _f1 I have another error.. I tried a lot of
combinations, all of them fail.

Can someone fix my code? Thank you.

答:
To execute a function you need to add brackets ( arguments ) after its name. It doesn't matter function is a variable or predefined one (constant).

Please check out this examples:

Example 1.

Future<int> add(int a, int b) async {
  return Future.delayed(Duration(seconds: 2)).then((f) {
    return a + b;
  });
}

Future<int> test(Future<int> Function(int a, int b) func) async {
  return await func(3, 2);
}

void main() {
  test(add)
    .then(print); /// will return result of 3+2 after 2 seconds
}
```

<p>Run this code</p>

<h2>Example 2.</h2>

<pre class="lang-dart prettyprint-override"><code>String Function(String, String) mergeFunction = (String a, String b) {
  return a + b;
};

void main() {
  print(mergeFunction('Hello ', 'world'));
}
</code>```

Run this code

Title: Function as parameter (DART)

Body:
I'm trying to understand how dart uses a function as parameter. I wrote this code...

typedef Future<String> myFunction();

void main() {
  A a = A();
  a.f1(a._f1);
}

class A {
  f1(myFunction func) async {
    String x = await _f1;
    print(x);
  }

  Future<String> _f1() {
    Future.delayed(Duration(seconds: 3)).then((f) {
      return "test";
    });
  }
}

I need the function f1 returns "test", but I have this error : A value of type 'Future Function()' can't be assigned to a variable of type 'String'

If I change  String x = await _f1 by Future x = await _f1 I have another error.. I tried a lot of
combinations, all of them fail.

Can someone fix my code? Thank you.

Body:
To execute a function you need to add brackets ( arguments ) after its name. It doesn't matter function is a variable or predefined one (constant).

Please check out this examples:

Example 1.

Future<int> add(int a, int b) async {
  return Future.delayed(Duration(seconds: 2)).then((f) {
    return a + b;
  });
}

Future<int> test(Future<int> Function(int a, int b) func) async {
  return await func(3, 2);
}

void main() {
  test(add)
    .then(print); /// will return result of 3+2 after 2 seconds
}

Run this code

Example 2.

String Function(String, String) mergeFunction = (String a, String b) {
  return a + b;
};

void main() {
  print(mergeFunction('Hello ', 'world'));
}

Run this code


问:
"ImportError: file_cache is unavailable" when using Python client for Google service account file_cache
I'm using a service account for G Suite with full domain delegation. I have a script with readonly access to Google Calendar. The script works just fine, but throws an error (on a background thread?) when I "build" the service. Here's the code:

```<code>from oauth2client.service_account import ServiceAccountCredentials
from httplib2 import Http
import urllib
import requests
from apiclient.discovery import build

cal_id = "my_calendar_id@group.calendar.google.com"

scopes                = ['https://www.googleapis.com/auth/calendar.readonly']
credentials           = ServiceAccountCredentials.from_json_keyfile_name('my_cal_key.json', scopes=scopes)
delegated_credentials = credentials.create_delegated('me@mydomain.com')
http_auth             = delegated_credentials.authorize(Http())

# This is the line that throws the error
cal_service  = build('calendar','v3',http=http_auth)

#Then everything continues to work normally
request = cal_service.events().list(calendarId=cal_id)
response = request.execute()

# etc...
</code>```

The error thrown is:

```<code>WARNING:googleapiclient.discovery_cache:file_cache is unavailable when using oauth2client >= 4.0.0
Traceback (most recent call last):
  File "/Users/myuseraccount/anaconda3/lib/python3.5/site-packages/googleapiclient/discovery_cache/__init__.py", line 36, in autodetect
    from google.appengine.api import memcache
ImportError: No module named 'google'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/myuseraccount/anaconda3/lib/python3.5/site-packages/googleapiclient/discovery_cache/file_cache.py", line 33, in <module>
    from oauth2client.contrib.locked_file import LockedFile
ImportError: No module named 'oauth2client.contrib.locked_file'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/myuseraccount/anaconda3/lib/python3.5/site-packages/googleapiclient/discovery_cache/file_cache.py", line 37, in <module>
    from oauth2client.locked_file import LockedFile
ImportError: No module named 'oauth2client.locked_file'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/myuseraccount/anaconda3/lib/python3.5/site-packages/googleapiclient/discovery_cache/__init__.py", line 41, in autodetect
    from . import file_cache
  File "/Users/myuseraccount/anaconda3/lib/python3.5/site-packages/googleapiclient/discovery_cache/file_cache.py", line 41, in <module>
    'file_cache is unavailable when using oauth2client >= 4.0.0')
ImportError: file_cache is unavailable when using oauth2client >= 4.0.0
</code>```

What's going on here and is this something that I can fix? I've tried reinstalling and/or upgrading the google package.

答:
I did not want to downgrade my oauth2client. You can use oauth2client 4.1.2 when you set cache_discovery=False for apiclient.discovery.build. This simple solution silenced the error:

```<code>service = discovery.build(api_name,
                          api_version,
                          credentials=credentials,
                          cache_discovery=False)
</code>```

Source

Body:
I'm using a service account for G Suite with full domain delegation. I have a script with readonly access to Google Calendar. The script works just fine, but throws an error (on a background thread?) when I "build" the service. Here's the code:

from oauth2client.service_account import ServiceAccountCredentials
from httplib2 import Http
import urllib
import requests
from apiclient.discovery import build

cal_id = "my_calendar_id@group.calendar.google.com"

scopes                = ['https://www.googleapis.com/auth/calendar.readonly']
credentials           = ServiceAccountCredentials.from_json_keyfile_name('my_cal_key.json', scopes=scopes)
delegated_credentials = credentials.create_delegated('me@mydomain.com')
http_auth             = delegated_credentials.authorize(Http())

# This is the line that throws the error
cal_service  = build('calendar','v3',http=http_auth)

#Then everything continues to work normally
request = cal_service.events().list(calendarId=cal_id)
response = request.execute()

# etc...

The error thrown is:

WARNING:googleapiclient.discovery_cache:file_cache is unavailable when using oauth2client >= 4.0.0
Traceback (most recent call last):
  File "/Users/myuseraccount/anaconda3/lib/python3.5/site-packages/googleapiclient/discovery_cache/__init__.py", line 36, in autodetect
    from google.appengine.api import memcache
ImportError: No module named 'google'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/myuseraccount/anaconda3/lib/python3.5/site-packages/googleapiclient/discovery_cache/file_cache.py", line 33, in <module>
    from oauth2client.contrib.locked_file import LockedFile
ImportError: No module named 'oauth2client.contrib.locked_file'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/myuseraccount/anaconda3/lib/python3.5/site-packages/googleapiclient/discovery_cache/file_cache.py", line 37, in <module>
    from oauth2client.locked_file import LockedFile
ImportError: No module named 'oauth2client.locked_file'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/myuseraccount/anaconda3/lib/python3.5/site-packages/googleapiclient/discovery_cache/__init__.py", line 41, in autodetect
    from . import file_cache
  File "/Users/myuseraccount/anaconda3/lib/python3.5/site-packages/googleapiclient/discovery_cache/file_cache.py", line 41, in <module>
    'file_cache is unavailable when using oauth2client >= 4.0.0')
ImportError: file_cache is unavailable when using oauth2client >= 4.0.0

What's going on here and is this something that I can fix? I've tried reinstalling and/or upgrading the google package.

Body:
I did not want to downgrade my oauth2client. You can use oauth2client 4.1.2 when you set cache_discovery=False for apiclient.discovery.build. This simple solution silenced the error:

service = discovery.build(api_name,
                          api_version,
                          credentials=credentials,
                          cache_discovery=False)

Source


问:
CSS Animating an underline when hover, stay when active
I am learning to use React, and SASS together.

I have the follow SASS code

```<code>.option{
  color: white;
  margin: 10px;
  padding: 7px 5px;
  cursor: pointer;
  text-decoration: none;
  position: relative;
  animation: perspective(1px) translateZ(0);
  transform: perspective(1px) translateZ(0);
  box-shadow: 0 0 1px rgba(0, 0, 0, 0);
  overflow: hidden;

  &:before {
    content: "";
    position: absolute;
    z-index: -1;
    left: 51%;
    right: 51%;
    bottom: 0;
    background: white;
    height: 2px;
    animation: left, right;
    transition-property: left, right;
    animation: 0.3s;
    transition-duration: 0.3s;
    animation: ease-out;
    transition-timing-function: ease-out;
  }

  &:hover:before, &:hover:focus:before, &hover:active:before{
    left: 0;
    right: 0;
  }
}
</code>```

}

What I am trying to do is when the text is hovered over it underlines it with the animation, Then when you select the option, the underline stays instead of transitioning out.

I cant seem to figure it out.

Im just doing this on a basic React page.

```<code><div className="options">
      <Link className="option" to="/">
        Home
      </Link>
      <Link className="option" to="/test1">
        Test1
      </Link>
      <Link className="option" to="/test2">
        Test2
      </Link>
    </div>
</code>```

答:
Thank you @Temani-Afif it was just eluding me.

separating worked

```<code>&:active:before{
        left:0;
        right:0;
      }

      &:focus:before{
        left:0;
        right:0;
      }

      &:hover:before{
        left: 0;
        right: 0;
      }
</code>```

Body:
I am learning to use React, and SASS together.

I have the follow SASS code

.option{
  color: white;
  margin: 10px;
  padding: 7px 5px;
  cursor: pointer;
  text-decoration: none;
  position: relative;
  animation: perspective(1px) translateZ(0);
  transform: perspective(1px) translateZ(0);
  box-shadow: 0 0 1px rgba(0, 0, 0, 0);
  overflow: hidden;

  &:before {
    content: "";
    position: absolute;
    z-index: -1;
    left: 51%;
    right: 51%;
    bottom: 0;
    background: white;
    height: 2px;
    animation: left, right;
    transition-property: left, right;
    animation: 0.3s;
    transition-duration: 0.3s;
    animation: ease-out;
    transition-timing-function: ease-out;
  }

  &:hover:before, &:hover:focus:before, &hover:active:before{
    left: 0;
    right: 0;
  }
}

}

What I am trying to do is when the text is hovered over it underlines it with the animation, Then when you select the option, the underline stays instead of transitioning out.

I cant seem to figure it out.

Im just doing this on a basic React page.

      <Link className="option" to="/">
        Home
      </Link>
      <Link className="option" to="/test1">
        Test1
      </Link>
      <Link className="option" to="/test2">
        Test2
      </Link>

Body:
Thank you @Temani-Afif it was just eluding me.

separating worked

&:active:before{
        left:0;
        right:0;
      }

      &:focus:before{
        left:0;
        right:0;
      }

      &:hover:before{
        left: 0;
        right: 0;
      }


问:
How to show data already on the database in a update form in Django?
I currently have a form that successfully updates both the model Userand Client.

The only thing I want it also to do is, when accessing the update page, that the form already have the current information (like we can do with placeholders, but actually editable data) so that the client can edit what he needs.

I also wonder if there is a way of updating only the changed fields or if it must update everything, even if it is the same.

This is my form:

```<code>class UpdateClient(ModelForm):
    address = forms.CharField(max_length=200, label="Morada", widget=forms.TextInput(attrs={'class': 'form-control'}))
    nif = forms.CharField(max_length=9, label="NIF", validators=[RegexValidator(r'^\d{1,10}$')], widget=forms.TextInput(attrs={'class': 'form-control'}))
    mobile = forms.CharField(max_length=9, label="Telemóvel", validators=[RegexValidator(r'^\d{1,10}$')], widget=forms.TextInput(attrs={'class': 'form-control'}))

    def clean_nif(self):
        nif = self.cleaned_data['nif'];
        if Clients.objects.filter(nif=nif).exists(): raise forms.ValidationError("NIF já existente.")
        return nif

    def __init__(self, *args, **kwargs):
        super(UpdateClient, self).__init__(*args, **kwargs)
        self.fields['first_name'].widget = TextInput(attrs={'class': 'form-control'})
        self.fields['last_name'].widget = TextInput(attrs={'class': 'form-control'})
        self.fields['email'].widget = EmailInput(attrs={'class': 'form-control'})

    class Meta:
        model = User
        fields = ('email','first_name','last_name', 'address', 'nif', 'mobile')
</code>```

And this is my views.py:

```<code>def client_det(request, nif):
    ls= Clients.objects.get(nif=nif)
    if request.method == 'POST':
        form = UpdateClient(request.POST, instance=ls.user)
        if form.is_valid():
            user = form.save()
            user.refresh_from_db()
            user.clients.address = form.cleaned_data.get('address')
            user.clients.nif = form.cleaned_data.get('nif')
            user.clients.mobile = form.cleaned_data.get('mobile')
            user.clients.save()
            return redirect('clients')
    else:
        form = UpdateClient()
    return render(request, 'backend/client_detail.html', {'form': form, 'ls': ls})
</code>```

And my client_detail.html

```<code>    <form method="post">
                            {% csrf_token %}
                     <!-- Address -->
                            <h6 class="heading-small text-muted mb-4">Dados Cliente</h6>
                            <div class="pl-lg-4">
                            <div class="row">
                                    <div class="col-lg-4">
                                        <div class="form-group">
                                            <label class="form-control-label" for="input-first-name">Primeiro Nome</label>
                                            {{form.first_name}}
                                        </div>

(...)
</code>```

答:
When instantiating the form, supply the instance for the GET branch, the same as you do in the POST branch.

```<code>def client_det(request, nif):
    ls= Clients.objects.get(nif=nif)
    if request.method == 'POST':
        form = UpdateClient(request.POST, instance=ls.user)
        ...
    else:
        form = UpdateClient(instance=ls.user)
    return render(request, 'backend/client_detail.html', {'form': form, 'ls': ls})
</code>```

Edit:
I missed the part of your question where you also need the client information set.

I think for that you could either do it in the __init__ function on the form or pass the values through the initial parameter.

Example 1:

```<code>def __init__(*args, **kwargs):
     super().__init__(*args, **kwargs)
     if self.instance:
         self.fields['nif'] = self.instance.clients.nif
         ...
</code>```

Example 2:

```<code> form = UpdateClient(instance=ls.user, initial={"nif": ls.user.clients.nif, ...})
</code>```

Body:
I currently have a form that successfully updates both the model Userand Client.

The only thing I want it also to do is, when accessing the update page, that the form already have the current information (like we can do with placeholders, but actually editable data) so that the client can edit what he needs.

I also wonder if there is a way of updating only the changed fields or if it must update everything, even if it is the same.

This is my form:

class UpdateClient(ModelForm):
    address = forms.CharField(max_length=200, label="Morada", widget=forms.TextInput(attrs={'class': 'form-control'}))
    nif = forms.CharField(max_length=9, label="NIF", validators=[RegexValidator(r'^\d{1,10}$')], widget=forms.TextInput(attrs={'class': 'form-control'}))
    mobile = forms.CharField(max_length=9, label="Telemóvel", validators=[RegexValidator(r'^\d{1,10}$')], widget=forms.TextInput(attrs={'class': 'form-control'}))

    def clean_nif(self):
        nif = self.cleaned_data['nif'];
        if Clients.objects.filter(nif=nif).exists(): raise forms.ValidationError("NIF já existente.")
        return nif

    def __init__(self, *args, **kwargs):
        super(UpdateClient, self).__init__(*args, **kwargs)
        self.fields['first_name'].widget = TextInput(attrs={'class': 'form-control'})
        self.fields['last_name'].widget = TextInput(attrs={'class': 'form-control'})
        self.fields['email'].widget = EmailInput(attrs={'class': 'form-control'})

    class Meta:
        model = User
        fields = ('email','first_name','last_name', 'address', 'nif', 'mobile')

And this is my views.py:

def client_det(request, nif):
    ls= Clients.objects.get(nif=nif)
    if request.method == 'POST':
        form = UpdateClient(request.POST, instance=ls.user)
        if form.is_valid():
            user = form.save()
            user.refresh_from_db()
            user.clients.address = form.cleaned_data.get('address')
            user.clients.nif = form.cleaned_data.get('nif')
            user.clients.mobile = form.cleaned_data.get('mobile')
            user.clients.save()
            return redirect('clients')
    else:
        form = UpdateClient()
    return render(request, 'backend/client_detail.html', {'form': form, 'ls': ls})

And my client_detail.html

    <form method="post">
                            {% csrf_token %}

Dados Cliente

                                            Primeiro Nome
                                            {{form.first_name}}

(...)

Body:
When instantiating the form, supply the instance for the GET branch, the same as you do in the POST branch.

def client_det(request, nif):
    ls= Clients.objects.get(nif=nif)
    if request.method == 'POST':
        form = UpdateClient(request.POST, instance=ls.user)
        ...
    else:
        form = UpdateClient(instance=ls.user)
    return render(request, 'backend/client_detail.html', {'form': form, 'ls': ls})

Edit:
I missed the part of your question where you also need the client information set.

I think for that you could either do it in the __init__ function on the form or pass the values through the initial parameter.

Example 1:

def __init__(*args, **kwargs):
     super().__init__(*args, **kwargs)
     if self.instance:
         self.fields['nif'] = self.instance.clients.nif
         ...

Example 2:

 form = UpdateClient(instance=ls.user, initial={"nif": ls.user.clients.nif, ...})


问:
ESLint SyntaxError: Invalid regular expression flags, Regex
I tried to install Eslint extension plugin on my React App project, it appears that the EsLint Server stopped because I have an issue on the no-octal-escape.js file

const match = node.raw.match(/^(?:[^\\]|\\.)*?\\([0-3][0-7]{1,2}|[4-7][0-7]|0(?=[89])|[1-7])/su)

Node version : 12.13.1
Eslint version : 6.5.1

Can't figure it out

Console output

答:
The fix for me came by using nvm in order to make sure I was actually using the last version by using the following command:

```<code>$ nvm install stable
</code>```

I just ran into the exact same problem with my VueJS App project.

Even though I had an up to date node version, it turned out that I was not, in fact, using it. Which seems to be quite common: https://github.com/eslint/eslint/issues/12538

Body:
The fix for me came by using nvm in order to make sure I was actually using the last version by using the following command:

$ nvm install stable

I just ran into the exact same problem with my VueJS App project.

Even though I had an up to date node version, it turned out that I was not, in fact, using it. Which seems to be quite common: https://github.com/eslint/eslint/issues/12538


问:
How to add a new row to Excel file using unmanaged C++?
How can I add a new row (with contents) to an existing Excel .xls file using unmanaged C++ running on Windows?

I don't mind using OLE, COM, or any external free library, whatever is the easiest way.

答:
I've used SQL to do this.  I don't have sample code handy, but a quick google search brought this up:  Link

Hope its helpful.


问:
Forward function calls to underlying data in a wrapper template
I'm writing a template wrapper, something like this

```<code>template<class T>
class Wrapper{
public:
    Wrapper(T data);
    ~Wrapper();

    void doSomeWrapperWork();

private:
    T data;
};
</code>```

If I want to access the wrapped data, I can obviously add a getter function that returns a reference to the data. I was wondering however if there is anyway, with some template magic, to call directly on the wrapper functions of the underlying wrapped data. In other words, if I have a class TestObject with a public function void foo(), I would like to be able to call it in this way:

```<code>Wrapper<TestObject> myWrapper;
myWrapper.foo();
</code>```

instead of:

```<code>myWrapper.getData().foo();
</code>```

without knowing a priori that such a function exists. Is this possible?

答:
Yes, try something like

```<code>#include <iostream>
struct TestObject{
    void foo() { std::cout << "TestObject" << std::endl;}
};

template <class T>
struct Wrapper : public T{
    Wrapper() {}
    void doSomeWrapperWork() {}
};

int main() {
    Wrapper<TestObject> wrapper;
    wrapper.foo();
}
</code>```

This allows you to add more functionality as need while still allowing the wrapper to be used as a class T.

This is inspired by the decorator design pattern.

Body:
I'm writing a template wrapper, something like this

template<class T>
class Wrapper{
public:
    Wrapper(T data);
    ~Wrapper();

    void doSomeWrapperWork();

private:
    T data;
};

If I want to access the wrapped data, I can obviously add a getter function that returns a reference to the data. I was wondering however if there is anyway, with some template magic, to call directly on the wrapper functions of the underlying wrapped data. In other words, if I have a class TestObject with a public function void foo(), I would like to be able to call it in this way:

Wrapper<TestObject> myWrapper;
myWrapper.foo();

instead of:

myWrapper.getData().foo();

without knowing a priori that such a function exists. Is this possible?

Body:
Yes, try something like

#include <iostream>
struct TestObject{
    void foo() { std::cout << "TestObject" << std::endl;}
};

template <class T>
struct Wrapper : public T{
    Wrapper() {}
    void doSomeWrapperWork() {}
};

int main() {
    Wrapper<TestObject> wrapper;
    wrapper.foo();
}

This allows you to add more functionality as need while still allowing the wrapper to be used as a class T.

This is inspired by the decorator design pattern.


问:
Leaflet getBounds() returning longitudes greater than 180
I suggested an issue and the author closed it on Github, but I am still left with no conclusion. Longitudes range from -180 to 180. But sometimes, Leaflet returns longitudes like 474.2578215 from getBounds(), which then of course nothing gets returned in my database.

I was told: It's intended behavior. That happens when you zoom too far out and/or drag the map to another copies of the world, and getBounds longitudes are not wrapped by default. You can use LatLng wrap method to get what you want though — e.g. bounds.getSouthWest().wrap().

Ok. So I added the wrap method in there, and the correct data is returned, but now no markers will show up on the map. This is probably due to the marker locations not being within that high number range (what leaflet thinks is the coordinates of the boundaries...)

I'm not sure that zooming or dragging is the cause of the issue. The problem persists when refreshing the page, where the user does no zooming or dragging events have occurred. I have the zoom limited in the init with: minZoom: 6, maxZoom: 13.

I should also note, that this code (unchanged) used to work just fine. Here is my code:

```<code>    $(document).ready(function(){ initmap(); });

var map;
var plotlist;
var plotlayers=[];

function initmap(){
    // set up the map
    map = new L.Map('map');

    //get our map
    var osmUrl='http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
    var osmAttrib='© <a href = "http://www.openstreetmap.org/copyright">  OpenStreetMap </a> contributors';
    var osm = new L.TileLayer(osmUrl, {minZoom: 6, maxZoom: 13,
             attribution: osmAttrib});

    map.setView(new L.LatLng(<?=$slat;?>, <?=$slng;?>),9);
    map.attributionControl.setPrefix('');
    map.addLayer(osm);
    getGameMarkers();
    map.on('moveend', onMapMove);
}

   function onMapMove(e){
      getGameMarkers();
   }

 function getGameMarkers(){
     var center = map.getCenter();
     var zoo = map.getZoom();
     var bounds = map.getBounds();
     console.log(bounds);

       var min = bounds.getSouthWest().wrap();
   var max = bounds.getNorthEast().wrap();

   $.ajax({type: "GET", url: "./ajax/markers.php", dataType: "json", data: "clat="+center.lat+"&clng="+center.lng+"&zoom="+zoo+"&minlat="+min.lat+"&minlng="+min.lng+"&maxlat="+max.lat+"&maxlng="+max.lng+cookiestr,
    success: function(data){
         if (data.showmap == 1) {
           plotlist = data.map_data;
           removeMarkers();
           for (i=0;i<plotlist.length;i++) {
                var iconic = String(plotlist[i].icon);
                var plotmark = new  L.marker([plotlist[i].lat,plotlist[i].lng], {icon: L.icon({iconUrl: iconic, iconSize: [32, 32]}) }).bindPopup(plotlist[i].html);
                map.addLayer(plotmark);
                plotlayers.push(plotmark);
            }

           $("#content").html(data.html);
        }else {
          $("#map_content").show();
          $("#map_content").html(data.main_content);
          $("#content").html(data.side_content);
        }
        }
      });
  }
</code>```

The wrap() functions give the correct coordinates, and the DB returns the correct plots. But for some reason, they don't display. Here are the plots returned (the map_data portion):

```<code>map_data: [{lat:36.672825, lng:-76.541748, icon:./img/avicon3.png,…},…]
           0: {lat:36.672825, lng:-76.541748, icon:./img/avicon3.png,…}
           1: {lat:36.901314, lng:-76.041870, icon:./img/avicon2.png,…}
           2: {lat:37.101192, lng:-76.264343, icon:./img/avicon3.png,…}
           3: {lat:37.300274, lng:-75.673828, icon:./img/avicon3.png,…}
           4: {lat:37.348328, lng:-76.830139, icon:./img/avicon3.png,…}
           5: {lat:37.2481003, lng:-76.1194000, icon:./img/bicon3.png,…}
           6: {lat:37.0298691, lng:-76.3452225, icon:./img/ricon.png,…}
           7: {lat:37.6087608, lng:-77.3733063, icon:./img/ricon.png,…}
           8: {lat:37.7440300, lng:-77.1316376, icon:./img/ricon.png,…}
           9: {lat:37.5917015, lng:-77.4207993, icon:./img/bicon2.png,…}
          10: {lat:37.5206985, lng:-77.3783112, icon:./img/ricon.png,…}
          11: {lat:37.3306999, lng:-77.3227615, icon:./img/ricon.png,…}
          12: {lat:37.1228981, lng:-75.9063034, icon:./img/bicon2.png,…}
</code>```

No errors in console, and as I said, sometimes it all works (when getBounds doesn't return a crazy big LON). So what in the heck am I doing wrong, and more importantly, how do I solve it?

答:
'worldCopyJump': true   work for me.

Can see this link.

<!DOCTYPE html>

Lat:

Lng:

    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.0.1/dist/leaflet.css" />
 <meta name="referrer" content="never">

```

Body:
I suggested an issue and the author closed it on Github, but I am still left with no conclusion. Longitudes range from -180 to 180. But sometimes, Leaflet returns longitudes like 474.2578215 from getBounds(), which then of course nothing gets returned in my database.

I was told: It's intended behavior. That happens when you zoom too far out and/or drag the map to another copies of the world, and getBounds longitudes are not wrapped by default. You can use LatLng wrap method to get what you want though — e.g. bounds.getSouthWest().wrap().

Ok. So I added the wrap method in there, and the correct data is returned, but now no markers will show up on the map. This is probably due to the marker locations not being within that high number range (what leaflet thinks is the coordinates of the boundaries...)

I'm not sure that zooming or dragging is the cause of the issue. The problem persists when refreshing the page, where the user does no zooming or dragging events have occurred. I have the zoom limited in the init with: minZoom: 6, maxZoom: 13.

I should also note, that this code (unchanged) used to work just fine. Here is my code:

    $(document).ready(function(){ initmap(); });

var map;
var plotlist;
var plotlayers=[];

function initmap(){
    // set up the map
    map = new L.Map('map');

    //get our map
    var osmUrl='http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
    var osmAttrib='©   OpenStreetMap  contributors';
    var osm = new L.TileLayer(osmUrl, {minZoom: 6, maxZoom: 13,
             attribution: osmAttrib});

    map.setView(new L.LatLng(<?=$slat;?>, <?=$slng;?>),9);
    map.attributionControl.setPrefix('');
    map.addLayer(osm);
    getGameMarkers();
    map.on('moveend', onMapMove);
}

   function onMapMove(e){
      getGameMarkers();
   }

 function getGameMarkers(){
     var center = map.getCenter();
     var zoo = map.getZoom();
     var bounds = map.getBounds();
     console.log(bounds);

       var min = bounds.getSouthWest().wrap();
   var max = bounds.getNorthEast().wrap();

   $.ajax({type: "GET", url: "./ajax/markers.php", dataType: "json", data: "clat="+center.lat+"&clng="+center.lng+"&zoom="+zoo+"&minlat="+min.lat+"&minlng="+min.lng+"&maxlat="+max.lat+"&maxlng="+max.lng+cookiestr,
    success: function(data){
         if (data.showmap == 1) {
           plotlist = data.map_data;
           removeMarkers();
           for (i=0;i<plotlist.length;i++) {
                var iconic = String(plotlist[i].icon);
                var plotmark = new  L.marker([plotlist[i].lat,plotlist[i].lng], {icon: L.icon({iconUrl: iconic, iconSize: [32, 32]}) }).bindPopup(plotlist[i].html);
                map.addLayer(plotmark);
                plotlayers.push(plotmark);
            }

           $("#content").html(data.html);
        }else {
          $("#map_content").show();
          $("#map_content").html(data.main_content);
          $("#content").html(data.side_content);
        }
        }
      });
  }

The wrap() functions give the correct coordinates, and the DB returns the correct plots. But for some reason, they don't display. Here are the plots returned (the map_data portion):

map_data: [{lat:36.672825, lng:-76.541748, icon:./img/avicon3.png,…},…]
           0: {lat:36.672825, lng:-76.541748, icon:./img/avicon3.png,…}
           1: {lat:36.901314, lng:-76.041870, icon:./img/avicon2.png,…}
           2: {lat:37.101192, lng:-76.264343, icon:./img/avicon3.png,…}
           3: {lat:37.300274, lng:-75.673828, icon:./img/avicon3.png,…}
           4: {lat:37.348328, lng:-76.830139, icon:./img/avicon3.png,…}
           5: {lat:37.2481003, lng:-76.1194000, icon:./img/bicon3.png,…}
           6: {lat:37.0298691, lng:-76.3452225, icon:./img/ricon.png,…}
           7: {lat:37.6087608, lng:-77.3733063, icon:./img/ricon.png,…}
           8: {lat:37.7440300, lng:-77.1316376, icon:./img/ricon.png,…}
           9: {lat:37.5917015, lng:-77.4207993, icon:./img/bicon2.png,…}
          10: {lat:37.5206985, lng:-77.3783112, icon:./img/ricon.png,…}
          11: {lat:37.3306999, lng:-77.3227615, icon:./img/ricon.png,…}
          12: {lat:37.1228981, lng:-75.9063034, icon:./img/bicon2.png,…}

No errors in console, and as I said, sometimes it all works (when getBounds doesn't return a crazy big LON). So what in the heck am I doing wrong, and more importantly, how do I solve it?

Body:
'worldCopyJump': true   work for me.

Can see this link.

<!DOCTYPE html>
<html lang="en">
Lat: <p  id="LatClick"> </p><br>
Lng: <p id="LOnClick" > </p><br>
<head>
    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.0.1/dist/leaflet.css" />
 <meta name="referrer" content="never">
    <style>
        body {
            padding: 0;
            margin: 0;
        }
        html, body, #map {
            height: 80%;
         }
        .lorem {
            font-style: italic;
            color: #AAA;
        }
    </style>
</head>
<body>

    <div id="map"  ></div>
    <script src="https://unpkg.com/leaflet@1.0.1/dist/leaflet.js"></script>
    <script>
        var map = L.map('map',{'worldCopyJump': true});
        map.setView([31.623116,84.497856], 8); L.tileLayer( 'http://{s}.tile.thunderforest.com/cycle/{z}/{x}/{y}.png', { maxZoom: 18}).addTo(map);
//var marker = L.marker([31.2, 97]).addTo(map);
var theMarker={};
map.on('click', function(e){
  var coord = e.latlng;
  var lat = coord.lat;
   map.removeLayer(theMarker);
  var lng = coord.lng;
  theMarker=L.marker([lat,lng]).addTo(map);
document.getElementById("LatClick").innerHTML = lat;
document.getElementById("LOnClick").innerHTML = lng;
});
     </script>
</body>
</html>


问:
How to skip NA values in for loop
I'm applying a for loop to generate multiple API requests from the RePEc database. Unfortunately, the data is not reproducible because my access code the administrator gave me only works on my IP address but I'm hoping someone can help me figure out what I've done wrong in my for loop (I'm not great at writing for loops).

Basically, I have a column of 80,000 cells df$author_reg_2with a whole lot of NA values. I want to skip the NA values and only generate API requests for cells with an actual value in them.

```<code>url <- "https://api.repec.org/call.cgi?code=USERCODE&getauthorrecordraw="

affiliation_2 <-vector(length=length(df$author_reg_2))
for(i in 1:length(df$author_reg_2))
    try({
        Sys.sleep(1)
        if(is.na(df$author_reg_2)) next
        affiliation_fun <- paste0(url,df$author_reg_2[i])
        affiliation_run <- fromJSON(txt=affiliation_fun) %>% select("affiliation")
        affiliation_2[i] <- paste(unlist(affiliation_run), collapse =" ")
        print(i)
    })
</code>```

Each time I try to run this script, it still generates errors telling me that it's running the NA values.

Any help appreciated! Thank you in advance!

答:
As we are looping over each element and passing the logic on if(takes a length of  1 and output 1), need the single element

```<code>url <- "https://api.repec.org/call.cgi?code=USERCODE&getauthorrecordraw="

affiliation_2 <-vector("list", length=length(df$author_reg_2))
for(i in seq_along(df$author_reg_2))
try({
    Sys.sleep(1)
    if(is.na(df$author_reg_2[i])) next
    affiliation_fun <- paste0(url,df$author_reg_2[i])
    affiliation_run <- fromJSON(txt=affiliation_fun) %>% select("affiliation")
    affiliation_2[[i]] <- paste(unlist(affiliation_run), collapse =" ")
    print(i)
})
</code>```

The list would also hold vector of different length and there is no need to paste and  collapse at the end (if that is the case)

If we need to change next to have a NA value in `affliation_2

```<code>for(i in seq_along(df$author_reg_2))
    try({
        Sys.sleep(1)
        if(is.na(df$author_reg_2[i])) {
            affiliation_2[[i]] <-  NA_character_
           }  else{
            affiliation_fun <- paste0(url,df$author_reg_2[i])
            affiliation_run <- fromJSON(txt=affiliation_fun) %>% select("affiliation")
            affiliation_2[[i]] <- paste(unlist(affiliation_run), collapse =" ")
         }
        print(i)
    })
</code>```

Title: How to skip NA values in for loop

Body:
I'm applying a for loop to generate multiple API requests from the RePEc database. Unfortunately, the data is not reproducible because my access code the administrator gave me only works on my IP address but I'm hoping someone can help me figure out what I've done wrong in my for loop (I'm not great at writing for loops).

Basically, I have a column of 80,000 cells df$author_reg_2with a whole lot of NA values. I want to skip the NA values and only generate API requests for cells with an actual value in them.

url <- "https://api.repec.org/call.cgi?code=USERCODE&getauthorrecordraw="

affiliation_2 <-vector(length=length(df$author_reg_2))
for(i in 1:length(df$author_reg_2))
    try({
        Sys.sleep(1)
        if(is.na(df$author_reg_2)) next
        affiliation_fun <- paste0(url,df$author_reg_2[i])
        affiliation_run <- fromJSON(txt=affiliation_fun) %>% select("affiliation")
        affiliation_2[i] <- paste(unlist(affiliation_run), collapse =" ")
        print(i)
    })

Each time I try to run this script, it still generates errors telling me that it's running the NA values.

Any help appreciated! Thank you in advance!

Body:
As we are looping over each element and passing the logic on if(takes a length of  1 and output 1), need the single element

url <- "https://api.repec.org/call.cgi?code=USERCODE&getauthorrecordraw="

affiliation_2 <-vector("list", length=length(df$author_reg_2))
for(i in seq_along(df$author_reg_2))
try({
    Sys.sleep(1)
    if(is.na(df$author_reg_2[i])) next
    affiliation_fun <- paste0(url,df$author_reg_2[i])
    affiliation_run <- fromJSON(txt=affiliation_fun) %>% select("affiliation")
    affiliation_2[[i]] <- paste(unlist(affiliation_run), collapse =" ")
    print(i)
})

The list would also hold vector of different length and there is no need to paste and  collapse at the end (if that is the case)

If we need to change next to have a NA value in `affliation_2

for(i in seq_along(df$author_reg_2))
    try({
        Sys.sleep(1)
        if(is.na(df$author_reg_2[i])) {
            affiliation_2[[i]] <-  NA_character_
           }  else{
            affiliation_fun <- paste0(url,df$author_reg_2[i])
            affiliation_run <- fromJSON(txt=affiliation_fun) %>% select("affiliation")
            affiliation_2[[i]] <- paste(unlist(affiliation_run), collapse =" ")
         }
        print(i)
    })


问:
Count same values on array using each Ruby Rails
I execute the query in the bank by the controller and I receive the data in the var when executing each on top of the var returns me an array, I wanted to count how many times the same parameter is repeated to create a counter could help me follow my code.

Rails 3.2, ruby 2.3

results os my query.. from postgresql

```<code>#<tickets title: "any text any first register ", updated_at: "2018-01-30 18:38:58", company: 89869>

#<tickets title: "any text any second register ", updated_at: "2018-06-25 20:18:20", company: 99991>
</code>```

I want to count how many times the same date is repeated regardless of the time to count the number of times that displays the same date.

答:
For a specific value you can use count method:

```<code>date = Date.today # Put your date here
tickets.count { |ticket| ticket.updated_at.to_date == date }
</code>```

UPD

Group tickets by date and take the result from the hash. I am not sure if it works in Rails 3.2

```<code>date = Date.today # Put your date here
Ticket.group('date(updated_at)').size[date]
</code>```

Body:
I execute the query in the bank by the controller and I receive the data in the var when executing each on top of the var returns me an array, I wanted to count how many times the same parameter is repeated to create a counter could help me follow my code.

Rails 3.2, ruby 2.3

results os my query.. from postgresql

#<tickets title: "any text any first register ", updated_at: "2018-01-30 18:38:58", company: 89869>

#<tickets title: "any text any second register ", updated_at: "2018-06-25 20:18:20", company: 99991>

I want to count how many times the same date is repeated regardless of the time to count the number of times that displays the same date.

Body:
For a specific value you can use count method:

date = Date.today # Put your date here
tickets.count { |ticket| ticket.updated_at.to_date == date }

UPD

Group tickets by date and take the result from the hash. I am not sure if it works in Rails 3.2

date = Date.today # Put your date here
Ticket.group('date(updated_at)').size[date]


答:
If you have no restrictions to use managed libraries you can check NPOI, a managed library to handle Excel file format.

Since it is managed it should be possible to register it as a COM server. If, for any reason, it proves hard/impossible to register it as a COM server you can write a thin COM server (either in C++ or C# or whatever you prefer) to expose just the functionality you need to your unmanaged C++ code.

Title: How to add a new row to Excel file using unmanaged C++?

Body:
How can I add a new row (with contents) to an existing Excel .xls file using unmanaged C++ running on Windows?

I don't mind using OLE, COM, or any external free library, whatever is the easiest way.


问:
Uploaded an Application to the play store but it won't open
So I recently uploaded my Android application to the Google Play store and it published successfully. This is the application here: https://play.google.com/store/apps/details?id=com.kyoudai.sudioku

The problem is, when anyone installs thiis application, they cannot open it i.e. the open option does not appear on the playstore, only the uninstall option. This application also cannot be found in the application drawer on any device, or in the list of installed applications. I've tried editing my manifest and included everything necessary but I have no idea why this happens. I generally believe if there was an issue with my code that should not be possible for an android application, the play store would flag it. When I was developing this, it showed up on the emulator application drawer so I assumed it was fine. I'm not sure why this happens, and I'm not even sure where to contact google regarding this. Any help is appreciated.

Given people are gonna jump on the manifest configuration, here it is: https://github.com/BerserkerLan/Sudoku-Android/blob/master/app/src/main/AndroidManifest.xml

答: So basically, the issue was that I just had too many category elements in my intent-filter and thus somehow that was interfering with the MAIN, VIEW and LAUNCHER elements, so now I only have those three in it and it launches fine. </p>


问:
List comprehension where the condition depends on the list being generated
I am new to Python programming. I want to rewrite the following code as a list comprehension:

lx = [1, 2, 3, 4, 5, 1, 2]
ly = [2, 5, 4]

lz = []
for x in lx:
    if x in ly and x not in lz:
        lz.append(x)
```

This will create a new list with common elements of lx and ly; but the condition x not in lz depends on the list that is being built. How can this code be rewritten as a list comprehension?

答:
If you don't want to use set, this can be another approach using list comprehension.</p>

```<code>lx = [1, 2, 3, 4, 5, 1, 2]
ly = [2, 5, 4]

lz=[]
[lz.append(x) for x in lx if (x in ly and x not in lz)]
print(lz)
</code>```

Body:
I am new to Python programming. I want to rewrite the following code as a list comprehension:

lx = [1, 2, 3, 4, 5, 1, 2]
ly = [2, 5, 4]

lz = []
for x in lx:
    if x in ly and x not in lz:
        lz.append(x)

This will create a new list with common elements of lx and ly; but the condition x not in lz depends on the list that is being built. How can this code be rewritten as a list comprehension?

Body:
If you don't want to use set, this can be another approach using list comprehension.

lx = [1, 2, 3, 4, 5, 1, 2]
ly = [2, 5, 4]

lz=[]
[lz.append(x) for x in lx if (x in ly and x not in lz)]
print(lz)


问:
Ansible environment variable or default
How do I get a value from an environment variable, but use a default if the environment variable is unset?

This is an example that does not work

```<code>---
- name: a playbook
  hosts: all
  vars:
    build_dir: "{{ lookup('env','BUILD_DIR') | default('builds/1.0.0/LATEST') }}"
  tasks:
    - debug: msg="{{ build_dir }}"
</code>```

Running this playbook returns an empty string instead of the default.

```<code>$ ansible-playbook build.yml

TASK [debug] ********************
ok: [amber] => {
    "msg": ""
}
</code>```

However, it works as expected to obtain the environment variable.

```<code>$ BUILD_DIR=LOL ansible-playbook build.yml

TASK [debug] ****************
ok: [amber] => {
    "msg": "LOL"
}
</code>```

答:
Discovered this that is more concise and easier to read than some other options I have seen </p>

```<code>"{{ lookup('env','BUILD_DIR') or 'builds/1.0.0/LATEST' }}"
</code>```

Title: Ansible environment variable or default

Body:
How do I get a value from an environment variable, but use a default if the environment variable is unset?

This is an example that does not work

---
- name: a playbook
  hosts: all
  vars:
    build_dir: "{{ lookup('env','BUILD_DIR') | default('builds/1.0.0/LATEST') }}"
  tasks:
    - debug: msg="{{ build_dir }}"

Running this playbook returns an empty string instead of the default.

$ ansible-playbook build.yml

TASK [debug] ********************
ok: [amber] => {
    "msg": ""
}

However, it works as expected to obtain the environment variable.

$ BUILD_DIR=LOL ansible-playbook build.yml

TASK [debug] ****************
ok: [amber] => {
    "msg": "LOL"
}

Body:
Discovered this that is more concise and easier to read than some other options I have seen

"{{ lookup('env','BUILD_DIR') or 'builds/1.0.0/LATEST' }}"


问:
How can I make an image have a box-shadow on 3 sides (top, right, and left) and also have a fade to white on the bottom using CSS?
I am trying to use CSS linear-gradient and box-shadow to make an image have a box-shadow on 3 sides (top, right, and left) while also having a "fade-to-white" on the bottom edge of the image.
I don't want the image url in the CSS, I want to use the img tag in the html.
This is what I have so far: https://codepen.io/adelelanders/pen/rNVMxZw however the bottom edge is still showing the box-shadow (dark line). I want the bottom edge to fade to white.

img {
  max-width: 100%;
}

.image-container {
  max-width: 100%;
  width: 600px;
}

.white-fade::after {
  display: block;
  position: relative;
  background-image: linear-gradient(to bottom, rgba(255, 255, 255, 0) 0, #fff 100%);
  margin-top: -150px;
  height: 150px;
  width: 100%;
  content: '';
}

.box-shadow {
  border-radius: 5px;
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.19), 0 6px 6px rgba(0, 0, 0, 0.23);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="image-container white-fade">
  <img class="box-shadow" src="https://cdn.pixabay.com/photo/2019/03/18/06/46/cyber-4062449__340.jpg" />
</div></code>```

答:
consider mask instead of gradient

img {
  max-width: 100%;
}

.image-container {
  max-width: 100%;
  width: 600px;
  padding:20px; /* Some padding for the shadow */
  -webkit-mask:
    linear-gradient(#fff,#fff)        top/100% calc(100% - 149px) no-repeat,
    linear-gradient(#fff,transparent) bottom/100% 150px           no-repeat;
  mask:
    linear-gradient(#fff,#fff)        top/100% calc(100% - 149px) no-repeat,
    linear-gradient(#fff,transparent) bottom/100% 150px           no-repeat;
}

.box-shadow {
  border-radius: 5px;
  display:block;
  box-shadow: 0 10px 20px rgba(0, 0, 0, 1), 0 6px 6px rgba(0, 0, 0, 1);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="image-container white-fade">
  <img class="box-shadow" src="https://cdn.pixabay.com/photo/2019/03/18/06/46/cyber-4062449__340.jpg" />
</div></code>```

Body:
consider mask instead of gradient

img {
  max-width: 100%;
}

.image-container {
  max-width: 100%;
  width: 600px;
  padding:20px; /* Some padding for the shadow */
  -webkit-mask:
    linear-gradient(#fff,#fff)        top/100% calc(100% - 149px) no-repeat,
    linear-gradient(#fff,transparent) bottom/100% 150px           no-repeat;
  mask:
    linear-gradient(#fff,#fff)        top/100% calc(100% - 149px) no-repeat,
    linear-gradient(#fff,transparent) bottom/100% 150px           no-repeat;
}

.box-shadow {
  border-radius: 5px;
  display:block;
  box-shadow: 0 10px 20px rgba(0, 0, 0, 1), 0 6px 6px rgba(0, 0, 0, 1);
}

<div class="image-container white-fade">
  <img class="box-shadow" src="https://cdn.pixabay.com/photo/2019/03/18/06/46/cyber-4062449__340.jpg" />
</div>


问:
problem with oracle connection in c#
I have a Windows XP  machine used to create .Net applications with VS 2008.

I want to connect to a remote network server (using Windows xp) that is running an Oracle 10g database.

I am using the code below (with the first connection string) to connect directly to a version of 10g that is running on the same machine with no problems, however when I try to connect to the network machine, it actually crashes my application.

I have tried several variations of connection strings as I feel that I must be making a syntax error somewhere.

What concerns me is that I have dual try/catch statements in the application and I do not understand why it simply does not refuse the connection and report the error.

I suppose the real question is 'what is the correct syntax for the connection string'....or WHATEVER the hell I am doing wrong.

Any help or suggestions are greatly appreciated. Thank you in advance.

```<code>//Class Variables
string CONNSTR = "Server=192.168.0.1:1521;User ID=zahid;Password=abc123;";

public Oracle()
{
  InitializeComponent();
}

//Methods
private void TestMyOracleConnection()
{
  OracleConnection Conn = new OracleConnection(CONNSTR);
  try
  {
    Conn.Open();
    MessageBox.Show("Oracle Connection Established", "Success");
  }
  catch (OracleException ex)
  {
    MessageBox.Show(ex.Message, "Oracle Connection Failed!");
  }
  catch (Exception ex)
  {
    MessageBox.Show(ex.Message, "Oracle Connection Failed!");
  }
  finally
  {
    Conn.Close();
    MessageBox.Show("Oracle Connection Closed", "Success");
  }
}

private void buttonTestConnection_Click(object sender, EventArgs e)
{
  TestMyOracleConnection();
}
</code>```

答:
Assuming you are using ODP.Net, you can try a connection string such as the following (taken from a web.config):

```<code><add name="OdpConnection" connectionString="Data Source=xe;User Id=some_user;Password=some_password; Promotable Transaction=local"
     providerName="Oracle.DataAccess.Client" />
</code>```

You can read this connection string from the web.config in your code using something like this:

```<code>string connectionString = ConfigurationManager.ConnectionStrings["OdpConnection"].ConnectionString;
</code>```

It's a good practice to avoid putting connection strings directly in code, since to change them requires a re-compile. By putting them in a config file, such as web.config or app.config, you can change them without having to re-compile your library or exe.

Title: problem with oracle connection in c#

Body:
I have a Windows XP  machine used to create .Net applications with VS 2008.

I want to connect to a remote network server (using Windows xp) that is running an Oracle 10g database.

I am using the code below (with the first connection string) to connect directly to a version of 10g that is running on the same machine with no problems, however when I try to connect to the network machine, it actually crashes my application.

I have tried several variations of connection strings as I feel that I must be making a syntax error somewhere.

What concerns me is that I have dual try/catch statements in the application and I do not understand why it simply does not refuse the connection and report the error.

I suppose the real question is 'what is the correct syntax for the connection string'....or WHATEVER the hell I am doing wrong.

Any help or suggestions are greatly appreciated. Thank you in advance.

//Class Variables
string CONNSTR = "Server=192.168.0.1:1521;User ID=zahid;Password=abc123;";

public Oracle()
{
  InitializeComponent();
}

//Methods
private void TestMyOracleConnection()
{
  OracleConnection Conn = new OracleConnection(CONNSTR);
  try
  {
    Conn.Open();
    MessageBox.Show("Oracle Connection Established", "Success");
  }
  catch (OracleException ex)
  {
    MessageBox.Show(ex.Message, "Oracle Connection Failed!");
  }
  catch (Exception ex)
  {
    MessageBox.Show(ex.Message, "Oracle Connection Failed!");
  }
  finally
  {
    Conn.Close();
    MessageBox.Show("Oracle Connection Closed", "Success");
  }
}

private void buttonTestConnection_Click(object sender, EventArgs e)
{
  TestMyOracleConnection();
}

Body:
Assuming you are using ODP.Net, you can try a connection string such as the following (taken from a web.config):

<add name="OdpConnection" connectionString="Data Source=xe;User Id=some_user;Password=some_password; Promotable Transaction=local"
     providerName="Oracle.DataAccess.Client" />

You can read this connection string from the web.config in your code using something like this:

string connectionString = ConfigurationManager.ConnectionStrings["OdpConnection"].ConnectionString;

It's a good practice to avoid putting connection strings directly in code, since to change them requires a re-compile. By putting them in a config file, such as web.config or app.config, you can change them without having to re-compile your library or exe.


问:
How to create a dynamic object with an array inside so that it does not overwrite?
How to create a dynamic object with an array inside so that it does not overwrite?</p>

```<code>    let id;
    let obj = {};
    obj[id] = []; // if I declare  here inside the function it is undefined

    function ex(event) {
       id = event.id;
       obj[id] = [];// if I declare obj[id]=[]  here its overwrite
       obj[id].push(event.data);
    }

    //what needs to be done to get global obj like this

     {
         31dsa: ['sdf32da', '3fsdffs'],
         1dfga: ['hfs32da'],
         ....
    }
</code>```

答:
You can validate if the array exist.</p>

```<code> function ex(event) {
   id = event.id;
   if (!obj[id]){ // if undefined its falsy
      obj[id]= [];
   }
   obj[id].push(event.data);
}
</code>```

Body:
How to create a dynamic object with an array inside so that it does not overwrite?

    let id;
    let obj = {};
    obj[id] = []; // if I declare  here inside the function it is undefined

    function ex(event) {
       id = event.id;
       obj[id] = [];// if I declare obj[id]=[]  here its overwrite
       obj[id].push(event.data);
    }

    //what needs to be done to get global obj like this

     {
         31dsa: ['sdf32da', '3fsdffs'],
         1dfga: ['hfs32da'],
         ....
    }

Body:
You can validate if the array exist.

 function ex(event) {
   id = event.id;
   if (!obj[id]){ // if undefined its falsy
      obj[id]= [];
   }
   obj[id].push(event.data);
}


问:
issue passing json2html containing function thru ajax
I am trying to assign the responseText of an XHR request to an object variable that I can then pass thru json2html in order to create a form.  The problem I am having is the json I'm passing has a function assigned to the onclick event of an item on the form. This keeps me from being able to convert the responseText string using JSON.parse() as it errors out on the function call. I know that the json will work if I'm able to call it as an object but it wont let me create the object; I know that I can use the ready() function but would prefer to pass the function thru the json2html call. I imagine it's something simple I'm overlooking but need some help figuring out how I can get the string into a usable format. As an example:</p>

```<code>//works fine
var x= {
    "<>":"div",
    "class":"",
    "text":"test",
    "onclick": function(
        {
            console.log("click")
        }
    };
    $('#content').json2html({},x);

    //does not work
    x=$.ajax({url:u});

    x.complete(function(){
    //responseText:
        {
            "<>":"div",
            "class":"btn p-3 bg-white test",
            "text":"test",
            "onclick": function(){console.log("click")}
        }
//.responseText
        $('#content').json2html({},x["responseText"]);
 });
//.does not work
</code>```

答:
Firstly your responseText is just that text, make sure you jsonParse the text first into a json object before you send it to json2html. </p>

<p>Secondly you won't be able to transfer the onclick function via ajax, that's something that will need to be added client side. </p>

Body:
I am trying to assign the responseText of an XHR request to an object variable that I can then pass thru json2html in order to create a form.  The problem I am having is the json I'm passing has a function assigned to the onclick event of an item on the form. This keeps me from being able to convert the responseText string using JSON.parse() as it errors out on the function call. I know that the json will work if I'm able to call it as an object but it wont let me create the object; I know that I can use the ready() function but would prefer to pass the function thru the json2html call. I imagine it's something simple I'm overlooking but need some help figuring out how I can get the string into a usable format. As an example:

//works fine
var x= {
    "<>":"div",
    "class":"",
    "text":"test",
    "onclick": function(
        {
            console.log("click")
        }
    };
    $('#content').json2html({},x);

    //does not work
    x=$.ajax({url:u});

    x.complete(function(){
    //responseText:
        {
            "<>":"div",
            "class":"btn p-3 bg-white test",
            "text":"test",
            "onclick": function(){console.log("click")}
        }
//.responseText
        $('#content').json2html({},x["responseText"]);
 });
//.does not work

Body:
Firstly your responseText is just that text, make sure you jsonParse the text first into a json object before you send it to json2html.

Secondly you won't be able to transfer the onclick function via ajax, that's something that will need to be added client side.


问:
Check whether the date time is in between two date time in database Laravel 6
I'm newbie in php laravel. I'm currently working in my appointment system. I have two date, the start and end. I want to check if the date and time is in between of these two. Is there a Validation in between two date?</p>

答:
Request Validation

```<code>$validation = $this->validate($request, [
    'date' => 'required|date_format:Y-m-d H:i:s|after_or_equal:startDateColumn|before_or_equal: endDateColumn',
    //...
]);
</code>```

Elequent Query Check

```<code>$date = date('Y-m-d H:i:s');

$count = Model::where('startDateColumn', '>=', $date)
              ->where('endDateColumn', '<=', $date)->count();
</code>```

Then

```<code>if($count > 0) {
  // ...
} else {
 // ...
}
</code>```

Body:
Request Validation

$validation = $this->validate($request, [
    'date' => 'required|date_format:Y-m-d H:i:s|after_or_equal:startDateColumn|before_or_equal: endDateColumn',
    //...
]);

Elequent Query Check

$date = date('Y-m-d H:i:s');

$count = Model::where('startDateColumn', '>=', $date)
              ->where('endDateColumn', '<=', $date)->count();

Then

if($count > 0) {
  // ...
} else {
 // ...
}


问:
recursively traverse multidimensional dictionary, dimension unknown
I want to create a function to recursively traverse a multidimensional dictionary, where the dimensions are unknown.

Here is what I have come up with so far, but it doesn't seem to be working correctly.  This will print out some key / values twice and they are not in order.

```<code>def walk_dict(d):
    for k,v in d.items():
        if isinstance(v, dict):
            walk_dict(v)
        else:
            print "%s %s" % (k, v)
</code>```

Here's a sample array:

```<code>d = {
        'plan_code': 'b',
        'quantity': '1',
        'account': {
            'account_code': 'b',
            'username': 'jdoe',
            'email': 'jdoe@domain.com',
            'first_name': 'b',
            'last_name': 'b',
            'company_name': 'Company, LLC.',
            'billing_info': {
                'first_name': 'b',
                'last_name': 'b',
                'address1': '123 Test St',
                'city': 'San Francisco',
                'state': 'CA',
                'country': 'US',
                'zip': '94105',
                'credit_card': {
                    'number': '1',
                    'year': '2018',
                    'month': '12',
                    'verification_value': '123',
                },
            },
        },
    }
</code>```

答:
The solutions mentioned so far didn't do what I wanted but working from Justin Peel's spelled out version, I was able to make something that printed in a way I wanted:

```<code>def dict_parser(data, depth=0):
    if isinstance(data, dict):
        for key in data:
            value = data[key]
            print('  ') * depth + '"' + key + '":'
            dict_parser(value, depth + 1)
    elif isinstance(data, list):
        for item in data:
            if isinstance(item, list):
                dict_parser(item, depth + 1)
            else:
                print('  ') * depth + '"' + item + '"'
    elif isinstance(data, bool):
        print('  ') * depth + str(data)
    else:
        print('  ') * depth + '"' + data + '"'
</code>```

Which printed something like:

```<code>"saved_skels":
  "E:\Child_Skeleton_6ft.fbx"
  "E:\Female_Skeleton_6ft.fbx"
  "E:\HeroFemale_Skeleton.fbx"
  "E:\HeroMale_Skeleton.fbx"
"saved_roots":
  "E:\users\Characters"
  "E:\content\characters"
"saved_tabs":
  "Characters":
    "ProxyFemale":
      "HeroFemale_Skeleton.fbx"
    "animation":
      "HeroFemale_Skeleton.fbx"
    "ProxyMale":
      "HeroMale_Skeleton.fbx"
  "Game":
    ""
  "Proto":
    "Female":
      "Female_Skeleton_NewBP.fbx"
  "Assets":
    ""
  "characters":
    "player":
      "player_Skeleton.fbx"
    "actor":
      "Hero_Skeleton.fbx"
"edit_common_checkbox_state":
  False
"get_latest_checkbox_state":
  True
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I want to create a function to recursively traverse a multidimensional dictionary, where the dimensions are unknown.

Here is what I have come up with so far, but it doesn't seem to be working correctly.  This will print out some key / values twice and they are not in order.

def walk_dict(d):
    for k,v in d.items():
        if isinstance(v, dict):
            walk_dict(v)
        else:
            print "%s %s" % (k, v)

Here's a sample array:

d = {
        'plan_code': 'b',
        'quantity': '1',
        'account': {
            'account_code': 'b',
            'username': 'jdoe',
            'email': 'jdoe@domain.com',
            'first_name': 'b',
            'last_name': 'b',
            'company_name': 'Company, LLC.',
            'billing_info': {
                'first_name': 'b',
                'last_name': 'b',
                'address1': '123 Test St',
                'city': 'San Francisco',
                'state': 'CA',
                'country': 'US',
                'zip': '94105',
                'credit_card': {
                    'number': '1',
                    'year': '2018',
                    'month': '12',
                    'verification_value': '123',
                },
            },
        },
    }

Body:
The solutions mentioned so far didn't do what I wanted but working from Justin Peel's spelled out version, I was able to make something that printed in a way I wanted:

def dict_parser(data, depth=0):
    if isinstance(data, dict):
        for key in data:
            value = data[key]
            print('  ') * depth + '"' + key + '":'
            dict_parser(value, depth + 1)
    elif isinstance(data, list):
        for item in data:
            if isinstance(item, list):
                dict_parser(item, depth + 1)
            else:
                print('  ') * depth + '"' + item + '"'
    elif isinstance(data, bool):
        print('  ') * depth + str(data)
    else:
        print('  ') * depth + '"' + data + '"'

Which printed something like:

"saved_skels":
  "E:\Child_Skeleton_6ft.fbx"
  "E:\Female_Skeleton_6ft.fbx"
  "E:\HeroFemale_Skeleton.fbx"
  "E:\HeroMale_Skeleton.fbx"
"saved_roots":
  "E:\users\Characters"
  "E:\content\characters"
"saved_tabs":
  "Characters":
    "ProxyFemale":
      "HeroFemale_Skeleton.fbx"
    "animation":
      "HeroFemale_Skeleton.fbx"
    "ProxyMale":
      "HeroMale_Skeleton.fbx"
  "Game":
    ""
  "Proto":
    "Female":
      "Female_Skeleton_NewBP.fbx"
  "Assets":
    ""
  "characters":
    "player":
      "player_Skeleton.fbx"
    "actor":
      "Hero_Skeleton.fbx"
"edit_common_checkbox_state":
  False
"get_latest_checkbox_state":
  True


问:
Input Validation onblur focus
Having trouble getting this to work

```<code>  <script type="text/javascript">
  //<![CDATA[
  <!--
   function checkPrice(form) {
     var input=0;
     input=document.stickerPrice.value;
        if (input<100000) {
            alert("Sticker price must be more than $100,000");
            document.getElementsByName("stickerPrice").focus();
    }
 }

       // -->
       //]]>
     </script>
</code>```

and heres the label part.

```<code>   <form action=''>

    <p>Sticker Price on the Car (in dollars):
    <input type="text" name="stickerPrice" size="15" onblur="checkPrice(this.formData)" /></p>
    </form>
</code>```

I want an alert box to come up if its less than 10,000 with the onblur event and then place focus back onto that text box.

答:
I suggest you work-around and remove focus() with onblur.

function checkPrice(form) {
     var input=0;
     input=form.value;
        if (input<100000) {
            alert("Sticker price must be more than $100,000");
            form.value='';
    }
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <form action=''>
    <p>Sticker Price on the Car (in dollars):
    <input type="text" name="stickerPrice" size="15" onblur="checkPrice(this);" /></p>
    </form></code>```

Title: Input Validation onblur focus

Body:
Having trouble getting this to work

and heres the label part.

   <form action=''>

Sticker Price on the Car (in dollars):
    <input type="text" name="stickerPrice" size="15" onblur="checkPrice(this.formData)" />

    </form>

I want an alert box to come up if its less than 10,000 with the onblur event and then place focus back onto that text box.

Body:
I suggest you work-around and remove focus() with onblur.

function checkPrice(form) {
     var input=0;
     input=form.value;
        if (input<100000) {
            alert("Sticker price must be more than $100,000");
            form.value='';
    }
 }

 <form action=''>
    <p>Sticker Price on the Car (in dollars):
    <input type="text" name="stickerPrice" size="15" onblur="checkPrice(this);" /></p>
    </form>


问:
Error not catch on Try Catch on Route level
I am using async await in my functions. My Controller level is able the catch the error, but when returning to route level. Error is not catch, and only return data:{}. What am i doing wrong here?</p>

```<code>//route
router.get('/user', auth, async function(req,res){
try{
const userId = req.body.userId
const user = await UserController.getUser(userId)
res.status(200).send({data:user})
}catch(err){
res.status(400).send({message:err})
}
}
</code>```

```<code>//Controller
exports.getUser = async function(userId ){
try{
const user = await User.findOne({_id:userId })
return user
}catch(err){
return err
}
}
</code>```

答:
If you are already catching the error in the controller level, you won't be able to catch it anymore in the route catch block unless you throw it again after catching it in the controller catch block i.e:

```<code>exports.getUser = async function (userId) {
  try {
    const user = await User.findOne({ _id: userId })
    return user
  } catch (err) {
    // throw the error again
    throw(err);
  }
}
</code>```

However, this approach is wasteful, if you intend to handle the error in the route call back function, then there is no need catching it in the controller. The right thing to do would be to just write the controller function without any try/catch block:

```<code>exports.getUser = async function (userId) {
    return await User.findOne({ _id: userId })
}
</code>```

Then handle the error in the route call back like you are already doing.

Body:
I am using async await in my functions. My Controller level is able the catch the error, but when returning to route level. Error is not catch, and only return data:{}. What am i doing wrong here?

//route
router.get('/user', auth, async function(req,res){
try{
const userId = req.body.userId
const user = await UserController.getUser(userId)
res.status(200).send({data:user})
}catch(err){
res.status(400).send({message:err})
}
}

//Controller
exports.getUser = async function(userId ){
try{
const user = await User.findOne({_id:userId })
return user
}catch(err){
return err
}
}

Body:
If you are already catching the error in the controller level, you won't be able to catch it anymore in the route catch block unless you throw it again after catching it in the controller catch block i.e:

exports.getUser = async function (userId) {
  try {
    const user = await User.findOne({ _id: userId })
    return user
  } catch (err) {
    // throw the error again
    throw(err);
  }
}

However, this approach is wasteful, if you intend to handle the error in the route call back function, then there is no need catching it in the controller. The right thing to do would be to just write the controller function without any try/catch block:

exports.getUser = async function (userId) {
    return await User.findOne({ _id: userId })
}

Then handle the error in the route call back like you are already doing.


问:
JQuery async .each returns empty promises
Problem

Hi friends,

I am having the problem that the object promises is returning me as empty []. While the console.log I have documented shows me the data.

If there is a way to solve the problem, I will appreciate it.

const getALLMovies = async(page: number = 1): Promise<IMovies[]> =>{
  const res = await axios.get(`${BASE_URL}peliculas/${page}`);
  const body = await res.data;
  const $ = load(body);
  const promises: IMovies[] = [];

$('body div div div div div div div div div div div div#default-tab-1 div.Posters a').each(async(index , element) =>{
    const $element = $(element);
    const id = $element.attr('href').replace(BASE_URL , '').trim();
    const title = $element.find('div.listing-content p').text().trim();
    const poster = $element.find('img').attr('src');
    const extra = await contentHandler(id);
    promises.push({
      //id: id || null,
      title: title || null,
      poster: poster || null,
      year:   extra[0].year || null,
      genres: extra[0].genres || null,
      rating: extra[0].rating || null,
      synopsis: extra[0].synopsis || null,
      authors:  extra[0].authors || null,
      director: extra[0].director || null,
      writers:  extra[0].writers || null,
      country:  extra[0].country || null,
      releaseDate: extra[0].releaseDate || null,
    })
    //console.log(JSON.stringify(promises , null , 2)) --> The data is shown here.

  });

  return Promise.all(promises);
};

getALLMovies()
  .then(res =>{
    console.log(res.map(x => x)) --> empty object
  })

```

答:
The issue you are having is a race condition.  Your .each handler schedules some asynchronous code, namely it has to await the results of contentHandler.  As such, when getALLMovies is called promises is still an empty array, and that array won't be fully populated until all calls to contentHandler complete.  I.e. for each element, the result of contentHandler is queued up (4 times in the example below).

var promises = [];

function timeout(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function go() {
  $("div").each(async() => {
    await timeout(1500);
    console.log("now");
    promises.push("example");
  })
  console.log(promises);
}

go();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div></div>
<div></div>
<div></div>
<div></div></code>```

This is how I would alter your code to achieve your desired result:

var promises = [];

function timeout(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function go() {
  console.log("go");

  promises = $("div").map(async () => {
    await timeout(1500);
    console.log ("now");
    return "value";
  });

  return Promise.all(promises);
}

go().then(() => console.log(promises.length));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div></div>
<div></div>
<div></div>
<div></div></code>```

Also a side note... body div div div div div div div div div div div div in your selector is likely irrelevant due to the inclusion of #default-tab-1 which is a higher order or specificity.

Body:
The issue you are having is a race condition.  Your .each handler schedules some asynchronous code, namely it has to await the results of contentHandler.  As such, when getALLMovies is called promises is still an empty array, and that array won't be fully populated until all calls to contentHandler complete.  I.e. for each element, the result of contentHandler is queued up (4 times in the example below).

var promises = [];

function timeout(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function go() {
  $("div").each(async() => {
    await timeout(1500);
    console.log("now");
    promises.push("example");
  })
  console.log(promises);
}

go();

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div></div>
<div></div>
<div></div>
<div></div>

This is how I would alter your code to achieve your desired result:

var promises = [];

function timeout(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function go() {
  console.log("go");

  promises = $("div").map(async () => {
    await timeout(1500);
    console.log ("now");
    return "value";
  });

  return Promise.all(promises);
}

go().then(() => console.log(promises.length));

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div></div>
<div></div>
<div></div>
<div></div>

Also a side note... body div div div div div div div div div div div div in your selector is likely irrelevant due to the inclusion of #default-tab-1 which is a higher order or specificity.


问:
Keras LSTM input and output variable ranges
I am fairly new to machine learning but I have put together a LSTM network for educational purposes that seems to be working fairly well.

I have not been able to fully understand the numerical ranges for input and output variables. I normalized my input and training data so all variables are centered at 0 with a standard deviation of 1. When I test the network, all of my predictions are positive between 0 and 1, there are never any negative values even though the training data contained negative values.

I have worked around this by creating one output for positive numbers and another for negative in my training data. For example:

Original training data:

```<code>data
-1.0
-0.5
0.0
0.5
1.0
</code>```

becomes:

```<code>pos_data   neg_data
0.0        1.0
0.0        0.5
0.0        0.0
0.5        0.0
1.0        0.0
</code>```

After I run the model, I convert the pos_data and neg_data back to a single column with positive and negative values. This seems to work, but feels like it should be unnecessary.

Does Keras allow negative values in the input or training data? If so, does anyone have any ideas why I would only be getting positive predictions when the model was trained with both positive and negative values?

Thank you!

答:
Does Keras allow negative values in the input or training data?

Yes, a good example would be BERT word embeddings while doing natural language processing. Some data scalers are on the interval -1 to 1

If so, does anyone have any ideas why I would only be getting positive predictions when the model was trained with both positive and negative values?

If your model is a single LSTM cell then your output is run through softmax before you are given your output.

Image Provided by Rosand Liu

The range of the softmax function is between 0 and 1. Which would explain why you are getting only positive values!

Body:
I am fairly new to machine learning but I have put together a LSTM network for educational purposes that seems to be working fairly well.

I have not been able to fully understand the numerical ranges for input and output variables. I normalized my input and training data so all variables are centered at 0 with a standard deviation of 1. When I test the network, all of my predictions are positive between 0 and 1, there are never any negative values even though the training data contained negative values.

I have worked around this by creating one output for positive numbers and another for negative in my training data. For example:

Original training data:

data
-1.0
-0.5
0.0
0.5
1.0

becomes:

pos_data   neg_data
0.0        1.0
0.0        0.5
0.0        0.0
0.5        0.0
1.0        0.0

After I run the model, I convert the pos_data and neg_data back to a single column with positive and negative values. This seems to work, but feels like it should be unnecessary.

Does Keras allow negative values in the input or training data? If so, does anyone have any ideas why I would only be getting positive predictions when the model was trained with both positive and negative values?

Thank you!


问:
Associate user to a post in Django
hi everyone i'm trying to make a blog and i want to associate a user to post .. and to comment , it's a multi-user blog and i don't know how to do it , any help guys ? !

here is the model file :

```<code>from django.db import models
from django.utils import timezone
from django.conf import settings
from django.utils.text import slugify

# Create your models here.
#this is for categories
class Category(models.Model):
    title=models.CharField(max_length=100,default='')
    def __str__(self):
        return self.title
        #this is where a user can create his own gigs
class Gigposter(models.Model):

    title=models.CharField(default='',max_length=100,blank=False)
    user=models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=False)
    categories=models.OneToOneField(Category,on_delete=models.PROTECT,default='',null=False)
    published_at=models.DateTimeField(auto_now_add=True)
    description=models.TextField(default='',max_length=None,blank=False)
    mainphoto=models.ImageField(default='')
    photo=models.ImageField()
    def __str__(self):
        return self.title

#this is where a user can comment and say what he thinks about others work
class Comment_area(models.Model):

    user=models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,blank=False)
    comment=models.TextField(max_length=None,default='')
    commented_at=models.DateTimeField(auto_now_add=True)
</code>```

and the views file is empty as you can see :

```<code>from django.shortcuts import render

# Create your views here.
</code>```

答:
Wouldn't recommend using a OneToOneField here, as it tells Django the user is tied to exactly one comment/post (when, a user is likely to post more than once).

You could use models.ForeignKey:

```<code>from django.contrib.auth.models import User

class Gigposter(models.Model):
   # Other properties...
   user = models.ForeignKey(
                    'User'
                     on_delete=models.CASCADE
                 )
</code>```

Title: Associate user to a post in Django

Body:
hi everyone i'm trying to make a blog and i want to associate a user to post .. and to comment , it's a multi-user blog and i don't know how to do it , any help guys ? !

here is the model file :

from django.db import models
from django.utils import timezone
from django.conf import settings
from django.utils.text import slugify

# Create your models here.
#this is for categories
class Category(models.Model):
    title=models.CharField(max_length=100,default='')
    def __str__(self):
        return self.title
        #this is where a user can create his own gigs
class Gigposter(models.Model):

    title=models.CharField(default='',max_length=100,blank=False)
    user=models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=False)
    categories=models.OneToOneField(Category,on_delete=models.PROTECT,default='',null=False)
    published_at=models.DateTimeField(auto_now_add=True)
    description=models.TextField(default='',max_length=None,blank=False)
    mainphoto=models.ImageField(default='')
    photo=models.ImageField()
    def __str__(self):
        return self.title

#this is where a user can comment and say what he thinks about others work
class Comment_area(models.Model):

    user=models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,blank=False)
    comment=models.TextField(max_length=None,default='')
    commented_at=models.DateTimeField(auto_now_add=True)

and the views file is empty as you can see :

from django.shortcuts import render

# Create your views here.

Body:
Wouldn't recommend using a OneToOneField here, as it tells Django the user is tied to exactly one comment/post (when, a user is likely to post more than once).

You could use models.ForeignKey:

from django.contrib.auth.models import User

class Gigposter(models.Model):
   # Other properties...
   user = models.ForeignKey(
                    'User'
                     on_delete=models.CASCADE
                 )