问:
How to fill a map from a shapefile using its own attributes table in R?
I see some people using R to fill maps from shapefiles, e.g. here. With my R knowledge, I only read the shapefile and plot it.

With QGIS I added an extra column to the attribute table called "OCCURENCE". This column is a year when a specific event occurred. I'd like to fill each country according to the year of occurence using a color scale, leaving the countries with no data without fill. The folder with the shapefiles is here. As example, I added some years to a few countries, and I like to obtain something like:

 and a legend .

```<code>library(rgdal)
library(ggplot2)

World <- readOGR(dsn = "mundo", layer = "mundo")
class(World)

World2 <- fortify(World)
class(World2)

ggplot() +
  geom_polygon(data = World2, aes(x = long, y = lat, group = group),
               colour = "black", size = 0.5, fill = "white")
</code>```

Any help??

答:
The simple way, as @jazzurro said, is to work with sf package. But, you can achieve this with the method proposed by you adding a couple of steps.

You need to add an id field in SpatialPolygonsDataFrame and join these attributes with fortify() product. With this, you can fill polygons with any field:

```<code>library(rgdal)
library(ggplot2)

World <- readOGR(dsn = "mundo", layer = "mundo")
class(World)

World2 <- fortify(World)
class(World2)

World@data$id <- 0:(dim(World@data)[1]-1) # add id field

World2_join = plyr::join(x = World2,y = World@data, by="id") # join by id

ggplot() +
  geom_polygon(data = World2_join, aes(x = long, y = lat, group = group, fill = OCCURENCE), # fill by OCCURENCE
               colour = "black", size = 0.5)
</code>```

Body:
I see some people using R to fill maps from shapefiles, e.g. here. With my R knowledge, I only read the shapefile and plot it.

With QGIS I added an extra column to the attribute table called "OCCURENCE". This column is a year when a specific event occurred. I'd like to fill each country according to the year of occurence using a color scale, leaving the countries with no data without fill. The folder with the shapefiles is here. As example, I added some years to a few countries, and I like to obtain something like:

 and a legend .

library(rgdal)
library(ggplot2)

World <- readOGR(dsn = "mundo", layer = "mundo")
class(World)

World2 <- fortify(World)
class(World2)

ggplot() +
  geom_polygon(data = World2, aes(x = long, y = lat, group = group),
               colour = "black", size = 0.5, fill = "white")

Any help??

Body:
The simple way, as @jazzurro said, is to work with sf package. But, you can achieve this with the method proposed by you adding a couple of steps.

You need to add an id field in SpatialPolygonsDataFrame and join these attributes with fortify() product. With this, you can fill polygons with any field:

library(rgdal)
library(ggplot2)

World <- readOGR(dsn = "mundo", layer = "mundo")
class(World)

World2 <- fortify(World)
class(World2)

World@data$id <- 0:(dim(World@data)[1]-1) # add id field

World2_join = plyr::join(x = World2,y = World@data, by="id") # join by id

ggplot() +
  geom_polygon(data = World2_join, aes(x = long, y = lat, group = group, fill = OCCURENCE), # fill by OCCURENCE
               colour = "black", size = 0.5)


来源: stackexchange

问:
Alamofire No Such Module (CocoaPods)
Using Xcode 7

I am trying to install Alamofire in a sample project. Have used the instructions from Ray Wenderlich's page

Only change from above link is the podfile -- which is from GitHub page here because the version has been updated. I have also used the Swift 2.0 branch.

Below is the snapshop of the error, my pod file and my terminal post installing the pod

PODFILE

TERMINAL

P.S: I want to use cocoapods to install Alamofire. I don't want to download it from github page

答:
I am using swift 3, I fixed this problem by deleting Derived Data for this project.
Cheers...!!!

ContentLicense: CC BY-SA 3.0

Title: Alamofire No Such Module (CocoaPods)


问:
How do you set the text in an NSTextField?
I'm trying to set the text in an NSTextField, but the -setStringValue: and -setTitleWithMnemonic: methods are not working. Any ideas?

答:
Swift 4

```<code>self.yourTextField.stringValue = "Your_Value"
</code>```

Note: Fetching value from self.yourTextField.stringValue at that will get warning message i.e.

To avoid this kind of warning you can use like this (suggested way)

```<code>DispatchQueue.main.async {
 your code ...
}
</code>```

OR also refer to this.

Body:
Swift 4

self.yourTextField.stringValue = "Your_Value"

Note: Fetching value from self.yourTextField.stringValue at that will get warning message i.e.

To avoid this kind of warning you can use like this (suggested way)

DispatchQueue.main.async {
 your code ...
}

OR also refer to this.


问:
Datastore query returns no data when ordering result
I have a simple test object Foo with the string property Bar. When I do a .GetAll("Foo") query I get all objects returned, however, when I add .Order("Bar") then nothing is returned. I have tried both with and without index.yaml specifying the object and property, with and without sort order. What am I missing? I'm not using "noindex" on the Bar property.</p>

```<code>type Foo struct {
   Bar string
}

.NewQuery("Foo").Order("Bar").GetAll(c, &foo)  <-- nothing returned

.NewQuery("Foo").GetAll(c, &foo)  <-- objects returned
</code>```

答:
Entities are indexed at the moment of inserting.

Make sure your struct field does not have noindex annotation for datastore.

Make sure your struct field does not change property name in the annotation (comment. e.g.:

Bar string // datastore:bar

Make sure you did not override PropertyLoadSaver and do not make the property unindexable and do not change name.

Check in datastore viewer you can order on the property so it's not problem with your Put() code and probably problem with your query.

Body:
I have a simple test object Foo with the string property Bar. When I do a .GetAll("Foo") query I get all objects returned, however, when I add .Order("Bar") then nothing is returned. I have tried both with and without index.yaml specifying the object and property, with and without sort order. What am I missing? I'm not using "noindex" on the Bar property.

type Foo struct {
   Bar string
}

.NewQuery("Foo").Order("Bar").GetAll(c, &foo)  <-- nothing returned

.NewQuery("Foo").GetAll(c, &foo)  <-- objects returned


问:
how to use Alamofire with custom headers
I am just starting to take a look at Mattt's wonderful new Alamofire swift networking library and am not quite sure how one would use it with custom headers.

The code i am trying to convert from AFNetworking to Alamofire is this:

```<code>let request = NSMutableURLRequest(URL: url)
request.setValue(authorizationToken, forHTTPHeaderField:"Authorization")
</code>```

答:
Alamofire 4.x, XCode 9.1, Swift 4.x

When Headers cause problem while sending it in the request, then we need to encode parameter, for this we do JSONEncoding.prettyPrinted or JSONEncoding.default like :

```<code>let url = "http:\your.url.string\"
let parameter = ["Username":"name", "Password":"123"]
let headers = ["Content-Type" : "application/json"]

Alamofire.request(url, method : .post, parameters : parameter, encoding : JSONEncoding.default , headers : headers).responseData { dataResponse in

     print(dataResponse.request as Any) // your request
     print(dataResponse.response as Any) // your response
 }
</code>```

Body:
I am just starting to take a look at Mattt's wonderful new Alamofire swift networking library and am not quite sure how one would use it with custom headers.

The code i am trying to convert from AFNetworking to Alamofire is this:

let request = NSMutableURLRequest(URL: url)
request.setValue(authorizationToken, forHTTPHeaderField:"Authorization")

Body:
Alamofire 4.x, XCode 9.1, Swift 4.x

When Headers cause problem while sending it in the request, then we need to encode parameter, for this we do JSONEncoding.prettyPrinted or JSONEncoding.default like :

let url = "http:\your.url.string\"
let parameter = ["Username":"name", "Password":"123"]
let headers = ["Content-Type" : "application/json"]

Alamofire.request(url, method : .post, parameters : parameter, encoding : JSONEncoding.default , headers : headers).responseData { dataResponse in

     print(dataResponse.request as Any) // your request
     print(dataResponse.response as Any) // your response
 }


问:
Is it a smell to accumulate things in a parameter returned by reference in C++?
I have the following mapper class:

```<code>class ObjectMapper {
public:
   std::map<uint32_t, uint32_t>& getMappingForObject(
          Object* object);

private:
    std::unordered_map<Object*, std::map<uint32_t, uint32_t>> m_objMapping;
};
</code>```

Whose implementation is something like this:

```<code>std::map<uint32_t, uint32_t>& ObjectMapper::getMappingForObject(
      Object* object) {
    const auto mappingTableIterator = m_objMapping.find(object);
    if (mappingTableIterator == m_objMapping.end()) {
        auto it = m_objMapping.emplace(object,
                                          std::map<uint32_t, uint32_t>());
        return it.first->second;
    }
    return mappingTableIterator->second;
}
</code>```

So then the caller can do this:

```<code>std::map<uint32_t, uint32_t>& mappingTable =
          objMapper.getMappingForObject(object);
</code>```

And go on and add/remove things in mappingTable.

Is this a good pattern in C++? I feel this is using a reference output parameter to pass ownership, which is a smell, but I'm not sure. Is there any alternative that is nicer?

答:
Rewriting your function in simpler terms show that it is correct, as long as the caller does not store the result for later use and knows that changing the map will invalidate the reference.  Let's get back to that...

Your original function can be rewritten as:

```<code>std::map<uint32_t, uint32_t>& ObjectMapper::getMappingForObject(Object* object)
{
    if (m_objMapping.count(object) == 0)
    {
        // a new object, remove test if nothing special needs to be done.
    }
    return m_objMapping[object];
}
</code>```

As a general rule, you should assume that the ObjectMapper object will outlive the scope of the caller. The reference returned is from our own object data, so there should be no lifetime issues, as long as the caller follows the rules.

If you intend to use the returned map for a lengthy amount of time (more than a couple milliseconds :) or are in a multi-threaded application, you will want to work with a copy of the map instead, to minimize the time your data structure is under lock, and to 'transactionalize' any changes to your map data.

Body:
I have the following mapper class:

class ObjectMapper {
public:
   std::map<uint32_t, uint32_t>& getMappingForObject(
          Object* object);

private:
    std::unordered_map<Object*, std::map<uint32_t, uint32_t>> m_objMapping;
};

Whose implementation is something like this:

std::map<uint32_t, uint32_t>& ObjectMapper::getMappingForObject(
      Object* object) {
    const auto mappingTableIterator = m_objMapping.find(object);
    if (mappingTableIterator == m_objMapping.end()) {
        auto it = m_objMapping.emplace(object,
                                          std::map<uint32_t, uint32_t>());
        return it.first->second;
    }
    return mappingTableIterator->second;
}

So then the caller can do this:

std::map<uint32_t, uint32_t>& mappingTable =
          objMapper.getMappingForObject(object);

And go on and add/remove things in mappingTable.

Is this a good pattern in C++? I feel this is using a reference output parameter to pass ownership, which is a smell, but I'm not sure. Is there any alternative that is nicer?

Body:
Rewriting your function in simpler terms show that it is correct, as long as the caller does not store the result for later use and knows that changing the map will invalidate the reference.  Let's get back to that...

Your original function can be rewritten as:

std::map<uint32_t, uint32_t>& ObjectMapper::getMappingForObject(Object* object)
{
    if (m_objMapping.count(object) == 0)
    {
        // a new object, remove test if nothing special needs to be done.
    }
    return m_objMapping[object];
}

As a general rule, you should assume that the ObjectMapper object will outlive the scope of the caller. The reference returned is from our own object data, so there should be no lifetime issues, as long as the caller follows the rules.

If you intend to use the returned map for a lengthy amount of time (more than a couple milliseconds :) or are in a multi-threaded application, you will want to work with a copy of the map instead, to minimize the time your data structure is under lock, and to 'transactionalize' any changes to your map data.


问:
call linkbutton event on page load in asp.net
I am calling the link button event on page load which is not working as there is no sender for the click.
but when I tried to create a new object it gives an error.</p>

```<code> lnkFirst_Click(new object(),new CommandEventArgs());
</code>```

答:
Try it like this</p>

```<code>lnkFirst_Click(sender,e)
</code>```

Body:
I am calling the link button event on page load which is not working as there is no sender for the click.
but when I tried to create a new object it gives an error.

 lnkFirst_Click(new object(),new CommandEventArgs());

Body:
Try it like this

lnkFirst_Click(sender,e)


问:
What data mining application to use?
The last I used was weka
. The last I heard java was coming up with an API (JDM) for it. Can anyone share their experiences with the tools. I am mostly interested in using the tools for classification/clustering (weka does a decent job here) and the tool should have good API support. </p>

答: I am using RapidMiner (formerly YALE from Univ. of Dortmund). Its a Java-based open source tool and implements most of the popular classifier/clustering methods. And it also ships with algorithms implemented for the Weka toolkit, so there are more options there. Comes with a GUI which is quite easy to use, and a Java-based API.</p>

ContentLicense: CC BY-SA 2.5

Title: What data mining application to use?

OwnerDisplayName: Bohana


问:
How to make webpack less verbose?
This is Wes Craven's New Nightmare!

Why do I even need this horror on every little bit of change? How can I turn off these notifications?!

答:
You can use Webpack CLI's --display option to set the verbosity of the stats output. Here are the available values.

E.g.

```<code>--display=minimal
</code>```

Title: How to make webpack less verbose?

Body:
You can use Webpack CLI's --display option to set the verbosity of the stats output. Here are the available values.

E.g.

--display=minimal


问:
MethodNotAllowedHttpException when POST method (Laravel 5.5)
In my /reoutes/api.php i have the following route

```<code>Route::middleware('api')->group(function(){

    Route::post('/prepare/', 'CompgenApiController@prepareDefault');

});
</code>```

and when i try open page https://mydomen/api/prepare/ with postman i get an exception "Method Not Allowed Http Exception". Also i added in my VerifyCsrfToken.php

```<code>protected $except = [
    '/api/prepare/',
];
</code>```

If i replace post on get - all ok!

答:
The issue is that the page can only be loaded using a POST request. This error is not to do with CSRF Token verification.

Update Postman to make a POST request to https://mydomen/api/prepare/ instead of GET. Or you can cheat and enable both POST and GET:

```<code>Route::get('/prepare/', 'CompgenApiController@prepareDefault');
Route::post('/prepare/', 'CompgenApiController@prepareDefault');
</code>```

Body:
In my /reoutes/api.php i have the following route

Route::middleware('api')->group(function(){

    Route::post('/prepare/', 'CompgenApiController@prepareDefault');

});

and when i try open page https://mydomen/api/prepare/ with postman i get an exception "Method Not Allowed Http Exception". Also i added in my VerifyCsrfToken.php

protected $except = [
    '/api/prepare/',
];

If i replace post on get - all ok!

Body:
The issue is that the page can only be loaded using a POST request. This error is not to do with CSRF Token verification.

Update Postman to make a POST request to https://mydomen/api/prepare/ instead of GET. Or you can cheat and enable both POST and GET:

Route::get('/prepare/', 'CompgenApiController@prepareDefault');
Route::post('/prepare/', 'CompgenApiController@prepareDefault');


问:
Google Vision failes to create an instance of TextRecognizer
I have a project which used to work with Android Studio 2; now after the update to Android studio 3 my app crashes when it reaches:
 TextRecognizer textRecognizer = new TextRecognizer.Builder(context).build();

Do you have any idea why this is happening?

```<code>  @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    try
    {
        //here it fails
        textRecognizer = new TextRecognizer.Builder(this).build();
    }
    catch (Exception e) {
        Toast.makeText(this, e.getMessage() + " Unable to write to external storage.",
                Toast.LENGTH_LONG).show();
    }
</code>```

Logs:

```<code>11-25 18:21:58.042 20384-20384/? I/art: Late-enabling -Xcheck:jni
11-25 18:21:58.045 20384-20384/? I/art: Reinit property: dalvik.vm.checkjni= false
11-25 18:21:58.136 20384-20384/com.mary.pocket I/MultiDex: VM with version 2.1.0 has multidex support
11-25 18:21:58.136 20384-20384/com.mary.pocket I/MultiDex: Installing application
11-25 18:21:58.137 20384-20384/com.mary.pocket I/MultiDex: VM has multidex support, MultiDex support library is disabled.
11-25 18:21:58.209 20384-20384/com.mary.pocket I/HwCust: Constructor found for class android.app.HwCustActivityImpl
11-25 18:21:58.217 20384-20384/com.mary.pocket I/MultiDex: Installing application
11-25 18:21:58.217 20384-20384/com.mary.pocket I/MultiDex: VM has multidex support, MultiDex support library is disabled.
11-25 18:21:58.227 20384-20384/com.mary.pocket I/HwCust: Constructor found for class android.app.HwCustHwWallpaperManagerImpl
11-25 18:21:58.251 20384-20384/com.mary.pocket W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
11-25 18:21:58.262 20384-20384/com.mary.pocket W/DynamiteModule: Local module descriptor class for com.google.android.gms.vision.dynamite not found.
11-25 18:21:58.423 20384-20384/com.mary.pocket I/DynamiteModule: Considering local module com.google.android.gms.vision.dynamite:0 and remote module com.google.android.gms.vision.dynamite:1402
11-25 18:21:58.423 20384-20384/com.mary.pocket I/DynamiteModule: Selected remote version of com.google.android.gms.vision.dynamite, version >= 1402
11-25 18:21:58.484 20384-20384/com.mary.pocket W/System: ClassLoader referenced unknown path:
11-25 18:21:58.522 20384-20384/com.mary.pocket W/System: ClassLoader referenced unknown path: /data/user_de/0/com.google.android.gms/app_chimera/m/00000014/n/arm64-v8a
11-25 18:21:58.595 20384-20384/com.mary.pocket I/Vision: Loading library libocr.so
11-25 18:21:58.672 20384-20384/com.mary.pocket I/Vision: libocr.so library load status: true
11-25 18:21:58.672 20384-20384/com.mary.pocket I/Vision: Reading ocr models from /data/user/0/com.google.android.gms/app_vision/ocr/data/models
11-25 18:21:58.675 20384-20384/com.mary.pocket I/native: jni_helper.cc:166 Loading model config /data/user/0/com.google.android.gms/app_vision/ocr/data/models/semanticlift_engine_0.2.bincfg
11-25 18:21:58.675 20384-20384/com.mary.pocket E/native: jni_helper.cc:170 GetContents failed: /data/user/0/com.google.android.gms/app_vision/ocr/data/models/semanticlift_engine_0.2.bincfg
11-25 18:21:58.675 20384-20384/com.mary.pocket I/native: jni_helper.cc:166 Loading model config /data/user/0/com.google.android.gms/app_vision/ocr/data/models/tfmini_lstm_engine_latin_0.2.bincfg
11-25 18:21:58.678 20384-20384/com.mary.pocket A/native: timer.cc:38 Check failed: x >= 1 (0 vs. 1)
11-25 18:21:58.678 20384-20384/com.mary.pocket A/native: terminating.
11-25 18:21:58.684 20384-20384/com.mary.pocket A/libc: Fatal signal 6 (SIGABRT), code -6 in tid 20384 (com.mary.pocket)

                                                       [ 11-25 18:21:58.686   387:  387 W/         ]
                                                       debuggerd: handling request: pid=20384 uid=10209 gid=10209 tid=20384
</code>```

答: Check the following issue from Google Samples github</p>

ContentLicense: CC BY-SA 4.0

Body:
I have a project which used to work with Android Studio 2; now after the update to Android studio 3 my app crashes when it reaches:
 TextRecognizer textRecognizer = new TextRecognizer.Builder(context).build();

Do you have any idea why this is happening?

  @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    try
    {
        //here it fails
        textRecognizer = new TextRecognizer.Builder(this).build();
    }
    catch (Exception e) {
        Toast.makeText(this, e.getMessage() + " Unable to write to external storage.",
                Toast.LENGTH_LONG).show();
    }

Logs:

11-25 18:21:58.042 20384-20384/? I/art: Late-enabling -Xcheck:jni
11-25 18:21:58.045 20384-20384/? I/art: Reinit property: dalvik.vm.checkjni= false
11-25 18:21:58.136 20384-20384/com.mary.pocket I/MultiDex: VM with version 2.1.0 has multidex support
11-25 18:21:58.136 20384-20384/com.mary.pocket I/MultiDex: Installing application
11-25 18:21:58.137 20384-20384/com.mary.pocket I/MultiDex: VM has multidex support, MultiDex support library is disabled.
11-25 18:21:58.209 20384-20384/com.mary.pocket I/HwCust: Constructor found for class android.app.HwCustActivityImpl
11-25 18:21:58.217 20384-20384/com.mary.pocket I/MultiDex: Installing application
11-25 18:21:58.217 20384-20384/com.mary.pocket I/MultiDex: VM has multidex support, MultiDex support library is disabled.
11-25 18:21:58.227 20384-20384/com.mary.pocket I/HwCust: Constructor found for class android.app.HwCustHwWallpaperManagerImpl
11-25 18:21:58.251 20384-20384/com.mary.pocket W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
11-25 18:21:58.262 20384-20384/com.mary.pocket W/DynamiteModule: Local module descriptor class for com.google.android.gms.vision.dynamite not found.
11-25 18:21:58.423 20384-20384/com.mary.pocket I/DynamiteModule: Considering local module com.google.android.gms.vision.dynamite:0 and remote module com.google.android.gms.vision.dynamite:1402
11-25 18:21:58.423 20384-20384/com.mary.pocket I/DynamiteModule: Selected remote version of com.google.android.gms.vision.dynamite, version >= 1402
11-25 18:21:58.484 20384-20384/com.mary.pocket W/System: ClassLoader referenced unknown path:
11-25 18:21:58.522 20384-20384/com.mary.pocket W/System: ClassLoader referenced unknown path: /data/user_de/0/com.google.android.gms/app_chimera/m/00000014/n/arm64-v8a
11-25 18:21:58.595 20384-20384/com.mary.pocket I/Vision: Loading library libocr.so
11-25 18:21:58.672 20384-20384/com.mary.pocket I/Vision: libocr.so library load status: true
11-25 18:21:58.672 20384-20384/com.mary.pocket I/Vision: Reading ocr models from /data/user/0/com.google.android.gms/app_vision/ocr/data/models
11-25 18:21:58.675 20384-20384/com.mary.pocket I/native: jni_helper.cc:166 Loading model config /data/user/0/com.google.android.gms/app_vision/ocr/data/models/semanticlift_engine_0.2.bincfg
11-25 18:21:58.675 20384-20384/com.mary.pocket E/native: jni_helper.cc:170 GetContents failed: /data/user/0/com.google.android.gms/app_vision/ocr/data/models/semanticlift_engine_0.2.bincfg
11-25 18:21:58.675 20384-20384/com.mary.pocket I/native: jni_helper.cc:166 Loading model config /data/user/0/com.google.android.gms/app_vision/ocr/data/models/tfmini_lstm_engine_latin_0.2.bincfg
11-25 18:21:58.678 20384-20384/com.mary.pocket A/native: timer.cc:38 Check failed: x >= 1 (0 vs. 1)
11-25 18:21:58.678 20384-20384/com.mary.pocket A/native: terminating.
11-25 18:21:58.684 20384-20384/com.mary.pocket A/libc: Fatal signal 6 (SIGABRT), code -6 in tid 20384 (com.mary.pocket)

                                                       [ 11-25 18:21:58.686   387:  387 W/         ]
                                                       debuggerd: handling request: pid=20384 uid=10209 gid=10209 tid=20384


问:
preg match only one line in each match
I have this pattern.. The matches must not cross multiple lines (there must not be any newline char in the matches) so I added the m modifier..

But sometimes there is a \n in the matches.. How to prevent this?

```<code>preg_match_all('/(?<!\d|\d\D)(?:dk)?([\d\PL]{8,})/m', $input, $matches, PREG_PATTERN_ORDER);
</code>```

答:
The \PL pattern matches any char but a Unicode letter and also matches digits and whitespace chars. So, [\d\PL] can be shortened to \PL and since you need to subtract line breaks from it, replace it with the reverse shorthand character class (\pL) and use it inside a negated bracket expression, [^\pL], and add \r and \n there:

```<code>'/(?<!\d|\d\D)(?:dk)?([^\pL\r\n]{8,})/u'
</code>```

The m modifier is redundant since it only redefines the behavior of ^ and $ anchors. You might need the u modifier though, for the Unicode property class to work safely with Unicode strings in PHP/PCRE. Change \d to [0-9] and \D to [^0-9] if you only want to match ASCII digits.

Title: preg match only one line in each match

Body:
I have this pattern.. The matches must not cross multiple lines (there must not be any newline char in the matches) so I added the m modifier..

But sometimes there is a \n in the matches.. How to prevent this?

preg_match_all('/(?<!\d|\d\D)(?:dk)?([\d\PL]{8,})/m', $input, $matches, PREG_PATTERN_ORDER);

Body:
The \PL pattern matches any char but a Unicode letter and also matches digits and whitespace chars. So, [\d\PL] can be shortened to \PL and since you need to subtract line breaks from it, replace it with the reverse shorthand character class (\pL) and use it inside a negated bracket expression, [^\pL], and add \r and \n there:

'/(?<!\d|\d\D)(?:dk)?([^\pL\r\n]{8,})/u'

The m modifier is redundant since it only redefines the behavior of ^ and $ anchors. You might need the u modifier though, for the Unicode property class to work safely with Unicode strings in PHP/PCRE. Change \d to [0-9] and \D to [^0-9] if you only want to match ASCII digits.


问:
Can not decode json string in command line
I have a json that is an array of objects.

The following code works just fine:

```<code>use JSON qw( decode_json );
# the contents of json are from the file jsonfile.json
my $data='[{...}]'; # omitted for clarity
@decoded = @{decode_json($data)};
print Dumper \@decoded;
</code>```

But when I try to run it from the command line as an one-liner it breaks

None of the following work:

```<code>cat jsonfile.json | perl -MData::Dumper -MJSON=decode_json -ne'my $data=q{$_}; print decode_json($data)'

cat jsonfile.json | perl -MData::Dumper -MJSON=decode_json -ne"print decode_json('$_')"
</code>```

I think the issue is the quoting. I had the same issue in the script until I replaced qw with ’ otherwise it would complaint e.g. if an @ was in the fields or it was confused with the double quotes of the json fields.

What am I doing wrong here?

Another example:

This breaks:

```<code>$ echo [{"a":"b"}] |perl -MData::Dumper -MJSON=decode_json -ne'print decode_json($_)'
unexpected end of string while parsing JSON string, at character offset 3 (before ":b}]\n") at -e line 1.
</code>```

But this works:

```<code>$ echo '[{"a":"b"}]'| perl -MData::Dumper -MJSON=decode_json -ne'print decode_json($_)'
ARRAY(0x7fd8d400b2b8)
</code>```

答:
Perl's -n option "causes Perl to assume the following loop around your program, which makes it iterate over filename arguments somewhat like sed -n or awk:

```<code>  LINE:
    while (<>) {
    ...     # your program goes here
    }
</code>```

" (source: https://perldoc.perl.org/perlrun.html)

<> is perl's input operator, in this case called without a filehandle, so it reads from STDIN. Perl automatically splits the input, the default is to split on line breaks (\n). This means, that your expression is executed once per input line. Unless your JSON file contains everything in one line, your code will not work!

Perl's special variable $/ (aka $INPUT_RECORD_SEPARATOR) controls how perl splits multi-line input when reading with <>. The default value is \n, so that every line is read separately. By setting it to undef, perl reads the whole input in one go (regardless if it is single-line or multi-line), giving you the complete content of your file in $data.

You also need to remove -n from perl's parameters and read manually from STDIN.

```<code>cat jsonfile.json | perl -MData::Dumper -MJSON=decode_json -e '$/=undef; my $data=<>; print decode_json($data)'
</code>```

$/=undef; tells perl not to split the input in separate lines.

my $data=<>; reads from STDIN. And as we told perl to not split the input, the whole input (your file's complete content) is stored in $data.

As a side node: your code my $data=q{$_}; does not do what you seem to expect: q{} is the equivalent of a single quote ('), so $data contains the literal string $_ (a dollar sign followed by an underscore), not the content of the variable $_.

Body:
I have a json that is an array of objects.

The following code works just fine:

use JSON qw( decode_json );
# the contents of json are from the file jsonfile.json
my $data='[{...}]'; # omitted for clarity
@decoded = @{decode_json($data)};
print Dumper \@decoded;

But when I try to run it from the command line as an one-liner it breaks

None of the following work:

cat jsonfile.json | perl -MData::Dumper -MJSON=decode_json -ne'my $data=q{$_}; print decode_json($data)'

cat jsonfile.json | perl -MData::Dumper -MJSON=decode_json -ne"print decode_json('$_')"

I think the issue is the quoting. I had the same issue in the script until I replaced qw with ’ otherwise it would complaint e.g. if an @ was in the fields or it was confused with the double quotes of the json fields.

What am I doing wrong here?

Another example:

This breaks:

$ echo [{"a":"b"}] |perl -MData::Dumper -MJSON=decode_json -ne'print decode_json($_)'
unexpected end of string while parsing JSON string, at character offset 3 (before ":b}]\n") at -e line 1.

But this works:

$ echo '[{"a":"b"}]'| perl -MData::Dumper -MJSON=decode_json -ne'print decode_json($_)'
ARRAY(0x7fd8d400b2b8)

Body:
Perl's -n option "causes Perl to assume the following loop around your program, which makes it iterate over filename arguments somewhat like sed -n or awk:

  LINE:
    while (<>) {
    ...     # your program goes here
    }

" (source: https://perldoc.perl.org/perlrun.html)

<> is perl's input operator, in this case called without a filehandle, so it reads from STDIN. Perl automatically splits the input, the default is to split on line breaks (\n). This means, that your expression is executed once per input line. Unless your JSON file contains everything in one line, your code will not work!

Perl's special variable $/ (aka $INPUT_RECORD_SEPARATOR) controls how perl splits multi-line input when reading with <>. The default value is \n, so that every line is read separately. By setting it to undef, perl reads the whole input in one go (regardless if it is single-line or multi-line), giving you the complete content of your file in $data.

You also need to remove -n from perl's parameters and read manually from STDIN.

cat jsonfile.json | perl -MData::Dumper -MJSON=decode_json -e '$/=undef; my $data=<>; print decode_json($data)'

$/=undef; tells perl not to split the input in separate lines.

my $data=<>; reads from STDIN. And as we told perl to not split the input, the whole input (your file's complete content) is stored in $data.

As a side node: your code my $data=q{$_}; does not do what you seem to expect: q{} is the equivalent of a single quote ('), so $data contains the literal string $_ (a dollar sign followed by an underscore), not the content of the variable $_.


问:
Convert for loop to recursive function in python3
Is it possible to convert the following loop:

```<code>c = 0
for a in find:
    c += 1
return c
</code>```

Where find is a list like [a,b,c,d] to a function that uses recursion without using external libraries?

答:
Something as simple as this would work:

```<code>def to_rec(lst):
    # base case, when list is empty
    if not lst:
        return 0

    # recursive case
    return 1 + to_rec(lst[1:])
</code>```

Base case: If the list has no elements, return 0.

Recursive case: Otherwise return 1 + the length of the list, minus one element, which is why we use [1:] here, to disregard the head of the list.

You could also explicitly set an accumulator with a helper function. If you've ever used a functional programming language, such as Haskell or Prolog, this technique is quite popular. Here is what it could look like:

```<code># main function
def to_rec(lst):

    # calls helper function with starting accumulator of 0
    return accum(lst, 0)

def accum(lst, acc):

    # returns accumulator instead
    if not lst:
        return acc

    # increments accumulator, and looks at the tail of the list
    return accum(lst[1:], acc + 1)
</code>```

Both work as follows:

```<code>>>> print(to_rec(['a', 'b', 'c', 'd']))
4
>>> print(to_rec([]))
0
>>> print(to_rec(['a']))
1
</code>```

Body:
Is it possible to convert the following loop:

c = 0
for a in find:
    c += 1
return c

Where find is a list like [a,b,c,d] to a function that uses recursion without using external libraries?

Body:
Something as simple as this would work:

def to_rec(lst):
    # base case, when list is empty
    if not lst:
        return 0

    # recursive case
    return 1 + to_rec(lst[1:])

Base case: If the list has no elements, return 0.

Recursive case: Otherwise return 1 + the length of the list, minus one element, which is why we use [1:] here, to disregard the head of the list.

You could also explicitly set an accumulator with a helper function. If you've ever used a functional programming language, such as Haskell or Prolog, this technique is quite popular. Here is what it could look like:

# main function
def to_rec(lst):

    # calls helper function with starting accumulator of 0
    return accum(lst, 0)

def accum(lst, acc):

    # returns accumulator instead
    if not lst:
        return acc

    # increments accumulator, and looks at the tail of the list
    return accum(lst[1:], acc + 1)

Both work as follows:

>>> print(to_rec(['a', 'b', 'c', 'd']))
4
>>> print(to_rec([]))
0
>>> print(to_rec(['a']))
1


问:
Can I wrap windows dll to use it in Python under Linux?
Is it possible to wrap Windows DLL (driver for specific hardware) to use it from Python under Linux.

If yes, what would be the best approach?

答:
Disclaimer: Depending on the context, the following is certainly NOT the best approach. It is just ONE possible approach that kind of fits the description.

I wrote a small Python module for calling into Windows DLLs from Python on Linux. It is based on IPC between a regular Linux/Unix Python process and a Wine-based Python process. Because I have needed it in too many different use-cases / scenarios myself, I designed it as a "generic" ctypes module drop-in replacement, which does most of the required plumbing automatically in the background.

Example: Assume you're in Python on Linux, you have Wine installed, and you want to call into msvcrt.dll (the Microsoft C runtime library). You can do the following:

from zugbruecke import ctypes
dll_pow = ctypes.cdll.msvcrt.pow
dll_pow.argtypes = (ctypes.c_double, ctypes.c_double)
dll_pow.restype = ctypes.c_double
print('You should expect "1024.0" to show up here: "%.1f".' % dll_pow(2.0, 10.0))
```

Source code (LGPL), PyPI package & documentation.

It's still a bit rough around the edges (i.e. alpha and insecure), but it does handle most types of parameters (including pointers).

I'd be really interested to see how it behaves and performs when used with a hardware driver. Feedback is highly welcomed!

Body:
Disclaimer: Depending on the context, the following is certainly NOT the best approach. It is just ONE possible approach that kind of fits the description.

I wrote a small Python module for calling into Windows DLLs from Python on Linux. It is based on IPC between a regular Linux/Unix Python process and a Wine-based Python process. Because I have needed it in too many different use-cases / scenarios myself, I designed it as a "generic" ctypes module drop-in replacement, which does most of the required plumbing automatically in the background.

Example: Assume you're in Python on Linux, you have Wine installed, and you want to call into msvcrt.dll (the Microsoft C runtime library). You can do the following:

from zugbruecke import ctypes
dll_pow = ctypes.cdll.msvcrt.pow
dll_pow.argtypes = (ctypes.c_double, ctypes.c_double)
dll_pow.restype = ctypes.c_double
print('You should expect "1024.0" to show up here: "%.1f".' % dll_pow(2.0, 10.0))

Source code (LGPL), PyPI package & documentation.

It's still a bit rough around the edges (i.e. alpha and insecure), but it does handle most types of parameters (including pointers).

I'd be really interested to see how it behaves and performs when used with a hardware driver. Feedback is highly welcomed!


问:
Sleuth not sending trace information to Zipkin
Sleuth is not sending the trace information to Zipkin, even though Zipkin is running fine.
I am using Spring 1.5.8.RELEASE, spring cloud Dalston.SR4 and I have added the below dependencies in my microservices:

```<code><dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-sleuth</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-zipkin</artifactId>
</dependency>
</code>```

My Logs are always coming false:
[FOOMS,2e740f33c26e286d,2e740f33c26e286d,false]

My Zipkin dependencies are:

```<code><dependency>
    <groupId>io.zipkin.java</groupId>
    <artifactId>zipkin-server</artifactId>
</dependency>
<dependency>
    <groupId>io.zipkin.java</groupId>
    <artifactId>zipkin-autoconfigure-ui</artifactId>
    <scope>runtime</scope>
</dependency>
</code>```

Why am I getting false instead of true in my slueth statements? The traceId and SpanId are properly generated for all the calls though. My Zipkin is running in port 9411

答: I found that I need to add a sampler percentage. By default zero percentage of the samples are sent and that is why the sleuth was not sending anything to zipkin. when I added spring.sleuth.sampler.percentage=1.0 in the properties files, it started working.

Body:
Sleuth is not sending the trace information to Zipkin, even though Zipkin is running fine.
I am using Spring 1.5.8.RELEASE, spring cloud Dalston.SR4 and I have added the below dependencies in my microservices:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-sleuth</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-zipkin</artifactId>
</dependency>

My Logs are always coming false:
[FOOMS,2e740f33c26e286d,2e740f33c26e286d,false]

My Zipkin dependencies are:

<dependency>
    <groupId>io.zipkin.java</groupId>
    <artifactId>zipkin-server</artifactId>
</dependency>
<dependency>
    <groupId>io.zipkin.java</groupId>
    <artifactId>zipkin-autoconfigure-ui</artifactId>
    <scope>runtime</scope>
</dependency>

Why am I getting false instead of true in my slueth statements? The traceId and SpanId are properly generated for all the calls though. My Zipkin is running in port 9411


问:
Get all numbers starting with 104* including the next line associated with some texts or spaces
I am trying to get all the possible order numbers for example on a given chunk of text. Order number usually starts with 104* and character limit 0f 10. However I was not able to get my desired outcome.

Here is the sample chunk of text.

05.12.17 PRZELEW PRZYCHODZACY 05.12.17 1,408.10
 Referencje : PL0INE117339IZFN
 Nr Ref: 4339429172
 Tytuł Płatnosci: 400481
  1048432317, 400470 104843231
 6
 Kontr. : GDANSKDIS SP. Z O.O.
  UL. OBRONCÓW
 WYBRZEZA 1 80-398 GDANSK POLAND
 Nr Banku:
  18400007 SG Centrala
 Nr Rachunku: 31184000072413423008101119

  Data Stempla 171205
 Kwota Przekazu: 1,408.10 PLN Info Code;
  0002794237

Some input are like these:

05.12.17 PRZELEW PRZYCHODZACY 05.12.17 316,082.18
 Referencje : PL0INE117339BHBU
 Nr Ref: 4339079115
 Tytuł Płatnosci: ID
  0001817374 ZA1048418311 1
 0484240771048423894 10484238
 95AWIZO
  Z DNIA 05.12.17
 Kontr. : ZABKA POLSKA SPÓŁKA AKCYJNA
 PL
  ANDERSA 7
 61-894 POZNAN
 Nr Banku: 12402076 PEKAO Centrum
  Rozliczeniow
 Nr Rachunku: 94124017471111001003042253
 Data
  Stempla 171205
 Kwota Przekazu: 316,082.18 PLN

Also like this:

05.12.17 PRZELEW PRZYCHODZACY 05.12.17 999,429.47
 Referencje : PL0INE117339LJBU
 Nr Ref: 4339548267
 Tytuł Płatnosci:
  PY01832649 1048432358 1048432351 10
 48432466 1048432560 1048432594
  1048
 432267 1048432353 1048432450 104843
 2360 1048432577
  1048432391/KOR
 Kontr. : EUROCASH S.A.
 UL. WISNIOWA 11

  62-052 KOMORNIKI
 Nr Banku: 10500028 ING Bank Slaski S.A.
 Nr
  Rachunku: 73105000861000002334209315
 Data Stempla 171205
 Kwota
  Przekazu: 999,429.47 PLN
 Info Code; 0000193176

The code I used is simple as this: \b104\d*

My result from the first input was:

1048432317

and

104843231

The last result was lacking in number as you can see, the last digit was in the next line.

My expected result is a regex that will able to extract all those order numbers without getting cut because the next digit was on the next line or sometimes order number getting cut.

答:
It seems, you are looking for something like this:</p>

```<code>string source =
@"05.12.17 PRZELEW PRZYCHODZACY 05.12.17 999,429.47
Referencje : PL0INE117339LJBU
Nr Ref: 4339548267
Tytuł Płatnosci: PY01832649 1048432358 1048432351 10
48432466 1048432560 1048432594 1048
432267 1048432353 1048432450 104843
2360 1048432577 1048432391/KOR
Kontr. : EUROCASH S.A.
UL. WISNIOWA 11
62-052 KOMORNIKI
Nr Banku: 10500028 ING Bank Slaski S.A.
Nr Rachunku: 73105000861000002334209315
Data Stempla 171205
Kwota Przekazu: 999,429.47 PLN
Info Code; 0000193176";

// We have to get rid of new lines and curret returns
var text = source
  .Replace("\r", "")
  .Replace("\n", "");

// pattern: we want 10 digits in total (3 for "104" and 7 for the rest part)
var result = Regex.Matches(text, @"\b104[0-9]{7}")
  .OfType<Match>()
  .Select(match => match.Value)
  .ToArray();
</code>```

Body:
It seems, you are looking for something like this:

string source =
@"05.12.17 PRZELEW PRZYCHODZACY 05.12.17 999,429.47
Referencje : PL0INE117339LJBU
Nr Ref: 4339548267
Tytuł Płatnosci: PY01832649 1048432358 1048432351 10
48432466 1048432560 1048432594 1048
432267 1048432353 1048432450 104843
2360 1048432577 1048432391/KOR
Kontr. : EUROCASH S.A.
UL. WISNIOWA 11
62-052 KOMORNIKI
Nr Banku: 10500028 ING Bank Slaski S.A.
Nr Rachunku: 73105000861000002334209315
Data Stempla 171205
Kwota Przekazu: 999,429.47 PLN
Info Code; 0000193176";

// We have to get rid of new lines and curret returns
var text = source
  .Replace("\r", "")
  .Replace("\n", "");

// pattern: we want 10 digits in total (3 for "104" and 7 for the rest part)
var result = Regex.Matches(text, @"\b104[0-9]{7}")
  .OfType<Match>()
  .Select(match => match.Value)
  .ToArray();


问:
Access a local method variable inside an anonymous inner class that has a variable with the same name
I have two variables with the same name one in a method and the other one is in an anonymous inner class inside that method. How can I access the method one inside the anonymous class without the need to rename any of them?

```<code>public void doSomething() {
   final String s = "method string";
   new Runnable() {
      public void run() {
         String s = "anonymous inner class string";
         // how can I access the method string here without the need to rename any of the variables
      }
   };
}
</code>```

I know this can be solved by renaming any of the variables, but I'd like to know if there is a smarter way.

答:
If you don't want to rename any variable then you can create another method to access the method string variable. Like this:

```<code>final String s = "method string";
Runnable runnable = new Runnable() {
    public void run() {
        String s = "anonymous inner class string";
        String outerS = getS();
        System.out.println(outerS);
        System.out.println(s);
        // how can I access the method string here without the need to rename any of the variables
    }

    public String getS() {
        return s;
    }
};
</code>```

A method getS() is created here to access the method string variable.

Body:
I have two variables with the same name one in a method and the other one is in an anonymous inner class inside that method. How can I access the method one inside the anonymous class without the need to rename any of them?

public void doSomething() {
   final String s = "method string";
   new Runnable() {
      public void run() {
         String s = "anonymous inner class string";
         // how can I access the method string here without the need to rename any of the variables
      }
   };
}

I know this can be solved by renaming any of the variables, but I'd like to know if there is a smarter way.

Body:
If you don't want to rename any variable then you can create another method to access the method string variable. Like this:

final String s = "method string";
Runnable runnable = new Runnable() {
    public void run() {
        String s = "anonymous inner class string";
        String outerS = getS();
        System.out.println(outerS);
        System.out.println(s);
        // how can I access the method string here without the need to rename any of the variables
    }

    public String getS() {
        return s;
    }
};

A method getS() is created here to access the method string variable.


问:
How to stretch live type

I'd like to stretch type to fill an entire area of a div, but am having trouble, as the scale() feature in CSS is kind of limiting (and also does some weird things to the div itself)

I know it is possible to turn the text into an svg and scale it that way, but I'd like to keep the text live as I've made a countdown feature.

Essentially I'd like the type to completely fill the box, stretching itself even as the type alters in width as the characters alternate.

Is this possible? Or am I better off using something like bodymovin?

var count = 505;

var counter = setInterval(timer, 10); //10 will  run it every 100th of a second

function timer() {
  if (count <= 0) {
    clearInterval(counter);
    return;
  }
  count--;
  document.getElementById("timer").innerHTML = count / 100;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  display: flex;
  justify-content: center;
  align-items: center;
}

#timercontainer {
  width: 750px;
  height: 500px;
  display: flex;
  align-items: center;
}

#timer {
  font-size: 250px;
  transform: scale(1, 2);
  display: flex;
  align-items: center;
  text-align: left;
}</code>```

```

答:
Why is SVG ruled out?  An SVG can be live also.

var count = 505;

var counter = setInterval(timer, 10); //10 will  run it every 100th of a second

function timer() {
  if (count <= 0) {
    clearInterval(counter);
    return;
  }
  count--;
  document.getElementById("timer").textContent = count / 100;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#timercontainer {
  width: 750px;
  height: 500px;
}

svg { background-color: yellow; }</code>```

  <svg width="100%" height="100%" viewBox="-1 6 36 15" preserveAspectRatio="none">
    <text id="timer" x="0" y="20" font-size="20"></text>
  </svg>

```

Title: How to stretch live type

Body:
I'd like to stretch type to fill an entire area of a div, but am having trouble, as the scale() feature in CSS is kind of limiting (and also does some weird things to the div itself)

I know it is possible to turn the text into an svg and scale it that way, but I'd like to keep the text live as I've made a countdown feature.

Essentially I'd like the type to completely fill the box, stretching itself even as the type alters in width as the characters alternate.

Is this possible? Or am I better off using something like bodymovin?

var count = 505;

var counter = setInterval(timer, 10); //10 will  run it every 100th of a second

function timer() {
  if (count <= 0) {
    clearInterval(counter);
    return;
  }
  count--;
  document.getElementById("timer").innerHTML = count / 100;
}

body {
  display: flex;
  justify-content: center;
  align-items: center;
}

#timercontainer {
  width: 750px;
  height: 500px;
  display: flex;
  align-items: center;
}

#timer {
  font-size: 250px;
  transform: scale(1, 2);
  display: flex;
  align-items: center;
  text-align: left;
}

Body:
Why is SVG ruled out?  An SVG can be live also.

var count = 505;

var counter = setInterval(timer, 10); //10 will  run it every 100th of a second

function timer() {
  if (count <= 0) {
    clearInterval(counter);
    return;
  }
  count--;
  document.getElementById("timer").textContent = count / 100;
}

#timercontainer {
  width: 750px;
  height: 500px;
}

svg { background-color: yellow; }

<div id="timercontainer">
  <svg width="100%" height="100%" viewBox="-1 6 36 15" preserveAspectRatio="none">
    <text id="timer" x="0" y="20" font-size="20"></text>
  </svg>
</div>


问:
Datepicker - Using a default function with a custom function
Currently, I have this custom function:

```<code>var $myBadDates = new Array(<?php foreach($aryDates as $disabledate) { echo ' "$disabledate",'; } echo " 1"; ?>);
// Creates the array (The echo " 1"; is merely to close the array and will not affect the outcome
</code>```

function checkAvailability(mydate) {
    var $return = true;
    var $returnclass = "available";
    $checkdate = $.datepicker.formatDate('yy-mm-dd', mydate);
    for (var i = 0; i < $myBadDates.length; i++) {
        if ($myBadDates[i] == $checkdate) {
            $return = false;
            $returnclass = "unavailable";
        }
    }
    return [$return, $returnclass];
}
```

<p>The datepicker section goes as such:</p>

```$(function () {
    //To enable End Date picker only when Start Date has been chosen (And to disable all dates prior of said date)
    var end = $('#enddate').datepicker({
        numberOfMonths: 3,
        stepMonths: 3,
        beforeShowDay: checkAvailability
    });
    // Defining a function, because we're binding this to two different events
    function enableEnd() {
        end.attr('disabled', !this.value.length) // Enable the end input element if the first one has anything in it
        .datepicker('option', 'minDate', this.value); // Set the minimum date to the date in the first input
    }
    //End of function
    // Datepicker
    $('#startdate').datepicker({
        numberOfMonths: 3,
        stepMonths: 3,
        beforeShowDay: checkAvailability,
        minDate: +1,
        onSelect: enableEnd // Call enableEnd when a date is selected in the first datepicker
    }).bind('input', enableEnd); // Do the same when something is inputted by the user
    //hover states on the static widgets
    $('#dialog_link, ul#icons li').hover(

    function () {
        $(this).toggleClass('ui-state-hover');
    });
});
//End of Function
```

What I do is from my SQL DB, i use a custom function that changes a start date and an end date to an array of dates, which is then pushed into a single array and used to disable the said dates.

The second datepicker is only enabled when a valid date from the first is returned as TRUE.

The problem now is this:

I can block out all the dates that I have to. Great. But now, how do I block out weekends on top of this?

beforeShowDay: $.datepicker.noWeekends can't work because I'm already using a custom function. So, I have to customize my custom function even further. I can't use getDate() and show those > than 0 and < 7, so how can I tackle this?

Any help, answer of even a tip would help. I've been trying this out for sometime and I haven't gotten anywhere. Thanks.

答:
Seems rather simple but I fail to understand why can't you use getDay() function:

```<code>function checkAvailability(d) {
    if (
        d.getDay() == 6 /* saturday */ ||
        d.getDay() == 0 /* sunday */
    ) {
        return [false,'unavailable unavailable-cuz-its-weekend'];
    }
    $checkdate = $.datepicker.formatDate('yy-mm-dd', d);
    for (var i = 0; i < $myBadDates.length; i++) {
        if($myBadDates[i] == $checkdate)
        {
            return [false, "unavailable"];
        }
    }
    return [true, "available"];
}
</code>```

Body:
Currently, I have this custom function:

var $myBadDates = new Array(<?php foreach($aryDates as $disabledate) { echo ' "$disabledate",'; } echo " 1"; ?>);
// Creates the array (The echo " 1"; is merely to close the array and will not affect the outcome

function checkAvailability(mydate) {
    var $return = true;
    var $returnclass = "available";
    $checkdate = $.datepicker.formatDate('yy-mm-dd', mydate);
    for (var i = 0; i < $myBadDates.length; i++) {
        if ($myBadDates[i] == $checkdate) {
            $return = false;
            $returnclass = "unavailable";
        }
    }
    return [$return, $returnclass];
}

The datepicker section goes as such:

$(function () {
    //To enable End Date picker only when Start Date has been chosen (And to disable all dates prior of said date)
    var end = $('#enddate').datepicker({
        numberOfMonths: 3,
        stepMonths: 3,
        beforeShowDay: checkAvailability
    });
    // Defining a function, because we're binding this to two different events
    function enableEnd() {
        end.attr('disabled', !this.value.length) // Enable the end input element if the first one has anything in it
        .datepicker('option', 'minDate', this.value); // Set the minimum date to the date in the first input
    }
    //End of function
    // Datepicker
    $('#startdate').datepicker({
        numberOfMonths: 3,
        stepMonths: 3,
        beforeShowDay: checkAvailability,
        minDate: +1,
        onSelect: enableEnd // Call enableEnd when a date is selected in the first datepicker
    }).bind('input', enableEnd); // Do the same when something is inputted by the user
    //hover states on the static widgets
    $('#dialog_link, ul#icons li').hover(

    function () {
        $(this).toggleClass('ui-state-hover');
    });
});
//End of Function

What I do is from my SQL DB, i use a custom function that changes a start date and an end date to an array of dates, which is then pushed into a single array and used to disable the said dates.

The second datepicker is only enabled when a valid date from the first is returned as TRUE.

The problem now is this:

I can block out all the dates that I have to. Great. But now, how do I block out weekends on top of this?

beforeShowDay: $.datepicker.noWeekends can't work because I'm already using a custom function. So, I have to customize my custom function even further. I can't use getDate() and show those > than 0 and < 7, so how can I tackle this?

Any help, answer of even a tip would help. I've been trying this out for sometime and I haven't gotten anywhere. Thanks.

Body:
Seems rather simple but I fail to understand why can't you use getDay() function:

function checkAvailability(d) {
    if (
        d.getDay() == 6 /* saturday */ ||
        d.getDay() == 0 /* sunday */
    ) {
        return [false,'unavailable unavailable-cuz-its-weekend'];
    }
    $checkdate = $.datepicker.formatDate('yy-mm-dd', d);
    for (var i = 0; i < $myBadDates.length; i++) {
        if($myBadDates[i] == $checkdate)
        {
            return [false, "unavailable"];
        }
    }
    return [true, "available"];
}


问:
Mongoose virtual populate and aggregates
I'm trying to do aggregations on Mongoose schemas that use the newer virtual populate functionality (using Mongoose 4.13, Mongo 3.6).

Lets say I have the following (simplified for illustration purposes) schemas:

```<code>const ProjectSchema = new mongoose.Schema({
  projectId: Number,
  description: String
});

ProjectSchema.virtual('tasks', {
  ref: 'Task',
  localField: 'projectId',
  foreignField: 'projectId'
  justOne: false
]);

const TaskSchema = new mongoose.Schema({
  taskId: Number,
  projectId: Number
  hours: Number
});

const Project = mongoose.model('Project', ProjectSchema);
const Task = mongoose.model('Task', TaskSchema);
</code>```

Querying on Project and populating relating tasks is working fine using  .populate() like:

```<code>Project.find({projectId: <id>}).populate('tasks');
</code>```

But now I would like to sum the hours on tasks by project (left the $sum part out below btw..). I'm only getting empty arrays back no matter what. Isn't it possible to aggregate with virtual populate or?

```<code>const result = await Project.aggregate([
   { $match : { projectId: <id> } },
   { $lookup: {
       from: 'tasks',
       localField: 'projectId',
       foreignField: 'projectId',
       as: 'tasks'
     },
     {
        $unwind: '$tasks'
     }
   }
 ]);
</code>```

答: Virtual populate won't work with aggregate, because "The documents returned are plain javascript objects, not mongoose documents (since any shape of document can be returned)."(c), more information in the docs - Mongoose aggregate</p>

Body:
I'm trying to do aggregations on Mongoose schemas that use the newer virtual populate functionality (using Mongoose 4.13, Mongo 3.6).

Lets say I have the following (simplified for illustration purposes) schemas:

const ProjectSchema = new mongoose.Schema({
  projectId: Number,
  description: String
});

ProjectSchema.virtual('tasks', {
  ref: 'Task',
  localField: 'projectId',
  foreignField: 'projectId'
  justOne: false
]);

const TaskSchema = new mongoose.Schema({
  taskId: Number,
  projectId: Number
  hours: Number
});

const Project = mongoose.model('Project', ProjectSchema);
const Task = mongoose.model('Task', TaskSchema);

Querying on Project and populating relating tasks is working fine using  .populate() like:

Project.find({projectId: <id>}).populate('tasks');

But now I would like to sum the hours on tasks by project (left the $sum part out below btw..). I'm only getting empty arrays back no matter what. Isn't it possible to aggregate with virtual populate or?

const result = await Project.aggregate([
   { $match : { projectId: <id> } },
   { $lookup: {
       from: 'tasks',
       localField: 'projectId',
       foreignField: 'projectId',
       as: 'tasks'
     },
     {
        $unwind: '$tasks'
     }
   }
 ]);


问:
boost spirit wide char rule create null char´s
With this rule

```<code>name_valid %= (lexeme[+(boost::spirit::standard_wide::alpha | lit('_'))]);
</code>```

of type

```<code>typedef qi::rule<Iterator, std::wstring()> name_valid;
</code>```

Running in debug mode all is fine. name_valid contains the correct string. When going to release mode in VC2017 I got a NUL char on such inputs

```<code>Input  : a_b
Output : a(NULL)b
</code>```

I found out that I have to rewrite the rule like this. Can´t see a lit as wide char operation. Do I miss something here?

```<code> name_valid %= +(boost::spirit::standard_wide::alpha | wide::char_(L'_'));
</code>```

答:
i found out that i have to rewrite the rule like this

Well, if the goal was to match '_' as part of a name, then you NEED to write that anyway. Because +(alpha | '_') exposes an attribute which is the character sequence of all alpha characters, but not '_' since literals do not expose an attribute.

Can´t see a lit as wide char operation.

That's qi::lit(L'_')

Do i miss something here

What I think is happening is that alpha|'_' synthesizes an optional<char>. Apparently, the propagation rules are so relaxed that optional<char> can be assigned to char through its conversion-to-bool operation (resulting in a NUL characater). Wide characters have nothing to do with it:

Live On Coliru

```<code>#include <boost/spirit/include/qi.hpp>
namespace qi = boost::spirit::qi;
namespace enc = boost::spirit::standard;

int main() {
    std::string const input = "A.B";
    auto f = input.begin(), l = input.end();

    std::string output;
    if (qi::parse(f, l, +(enc::alpha | '.'), output)) {
        std::cout << "Parsed: '" << output << "'\n";
    } else {
        std::cout << "Failed\n";
    }

    if (f!=l)
        std::cout << "Remaining unparsed: '" << std::string(f,l) << "'\n";
}
</code>```

Prints

```<code>00000000: 5061 7273 6564 3a20 2741 0042 270a       Parsed: 'A.B'.
</code>```

Testing The Hypothesis:

Splitting it up in separate rules makes it visible: Live On Coliru

```<code>qi::rule<It, char()> c = enc::alpha | '.';
qi::rule<It, std::string()> s = +c;
BOOST_SPIRIT_DEBUG_NODES((s)(c))
</code>```

Prints

```<code><s>
  <try>A.B</try>
  <c>
    <try>A.B</try>
    <success>.B</success>
    <attributes>[A]</attributes>
  </c>
  <c>
    <try>.B</try>
    <success>B</success>
    <attributes>[NUL]</attributes>
  </c>
  <c>
    <try>B</try>
    <success></success>
    <attributes>[B]</attributes>
  </c>
  <c>
    <try></try>
    <fail/>
  </c>
  <success></success>
  <attributes>[[A, NUL, B]]</attributes>
</s>
</code>```

This highlights that the char exposed by c indeed becomes the NUL char. The following, however, makes clear that wasn't completely intentional:  Live On Coliru

```<code>qi::rule<It, boost::optional<char>()> c = enc::alpha | '.';
qi::rule<It, std::string()> s = +c;
BOOST_SPIRIT_DEBUG_NODES((s)(c))
</code>```

which will abort with an assertion:

```<code>sotest: /home/sehe/custom/boost_1_65_0/boost/optional/optional.hpp:1106: boost::optional::reference_const_type boost::optional<char>::get() const [T = char]: Assertion `this->is_initialized()' failed.
</code>```

Out of curiosity: this fixes it: Live On Coliru

```<code>qi::rule<It, std::string()> c = enc::alpha | '.';
qi::rule<It, std::string()> s = +c;
</code>```

Prints

```<code>Parsed: 'AB'
</code>```

fully as expected

Summary

Automatic attribute propagation rules are powerful, but can be surprising.

Don't play fast and loose with attribute compatibility: say what you mean. In your case alpha | char_('_') is conceptually the only thing that SHOULD do what you expect.

Body:
With this rule

name_valid %= (lexeme[+(boost::spirit::standard_wide::alpha | lit('_'))]);

of type

typedef qi::rule<Iterator, std::wstring()> name_valid;

Running in debug mode all is fine. name_valid contains the correct string. When going to release mode in VC2017 I got a NUL char on such inputs

Input  : a_b
Output : a(NULL)b

I found out that I have to rewrite the rule like this. Can´t see a lit as wide char operation. Do I miss something here?

 name_valid %= +(boost::spirit::standard_wide::alpha | wide::char_(L'_'));

Body:
i found out that i have to rewrite the rule like this

Well, if the goal was to match '_' as part of a name, then you NEED to write that anyway. Because +(alpha | '_') exposes an attribute which is the character sequence of all alpha characters, but not '_' since literals do not expose an attribute.

Can´t see a lit as wide char operation.

That's qi::lit(L'_')

Do i miss something here

What I think is happening is that alpha|'_' synthesizes an optional<char>. Apparently, the propagation rules are so relaxed that optional<char> can be assigned to char through its conversion-to-bool operation (resulting in a NUL characater). Wide characters have nothing to do with it:

Live On Coliru

#include <boost/spirit/include/qi.hpp>
namespace qi = boost::spirit::qi;
namespace enc = boost::spirit::standard;

int main() {
    std::string const input = "A.B";
    auto f = input.begin(), l = input.end();

    std::string output;
    if (qi::parse(f, l, +(enc::alpha | '.'), output)) {
        std::cout << "Parsed: '" << output << "'\n";
    } else {
        std::cout << "Failed\n";
    }

    if (f!=l)
        std::cout << "Remaining unparsed: '" << std::string(f,l) << "'\n";
}

Prints

00000000: 5061 7273 6564 3a20 2741 0042 270a       Parsed: 'A.B'.

Testing The Hypothesis:

Splitting it up in separate rules makes it visible: Live On Coliru

qi::rule<It, char()> c = enc::alpha | '.';
qi::rule<It, std::string()> s = +c;
BOOST_SPIRIT_DEBUG_NODES((s)(c))

Prints

<s>
  <try>A.B</try>
  <c>
    <try>A.B</try>
    <success>.B</success>
    <attributes>[A]</attributes>
  </c>
  <c>
    <try>.B</try>
    <success>B</success>
    <attributes>[NUL]</attributes>
  </c>
  <c>
    <try>B</try>
    <success></success>
    <attributes>[B]</attributes>
  </c>
  <c>
    <try></try>
    <fail/>
  </c>
  <success></success>
  <attributes>[[A, NUL, B]]</attributes>
</s>

This highlights that the char exposed by c indeed becomes the NUL char. The following, however, makes clear that wasn't completely intentional:  Live On Coliru

qi::rule<It, boost::optional<char>()> c = enc::alpha | '.';
qi::rule<It, std::string()> s = +c;
BOOST_SPIRIT_DEBUG_NODES((s)(c))

which will abort with an assertion:

sotest: /home/sehe/custom/boost_1_65_0/boost/optional/optional.hpp:1106: boost::optional::reference_const_type boost::optional<char>::get() const [T = char]: Assertion `this->is_initialized()' failed.

Out of curiosity: this fixes it: Live On Coliru

qi::rule<It, std::string()> c = enc::alpha | '.';
qi::rule<It, std::string()> s = +c;

Prints

Parsed: 'AB'

fully as expected

Summary

Automatic attribute propagation rules are powerful, but can be surprising.

Don't play fast and loose with attribute compatibility: say what you mean. In your case alpha | char_('_') is conceptually the only thing that SHOULD do what you expect.


问:
React Select - How to show / iterate through data from api call in option instead of hardcoding options?
I am using react-select and I don't want to hard code the options which should be displayed, but options is data I am fetching from an api. I can't really find anything and what I was trying to do doesn't work as nothing gets displayed. Anyone knows? Thanks!!!

api.js:

```<code>export function availableCities() {
   return axios.get('/cities').then(function (response) {
      return response.data;
   })
}
</code>```

Component:

```<code>import Select from 'react-select';
import {availableCities} from '../utils/api.js';

class App extends React.Component {
    constructor(props) {
    super(props);
    this.state = {
        selectedOption: '',
        clearable: true,
        cities: [],
     }
   }
   componentDidMount() {
    availableCities()
        .then(res => {
            this.setState({
                cities: res.Cities.name
            })
            console.log("hello", this.state.cities)
        })
   }

   handleChange(selectedOption) {
    this.setState({selectedOption});
   }
 render(){
    let options = this.state.cities.map(function (city) {
            return city.name;
    })
 return (
      <div>
           <Select
                name="form-field-name"
                value={this.state.value}
                onChange={this.handleChange}
                clearable={this.state.clearable}
                searchable={this.state.searchable}
                options={options}
            />
      </div>
  )
 }
}
</code>```

Data( this.state.cities is an array of objects and looks like:

```<code>{code: "LTS", name: "Altus", countryCode: "US", countryName: "United States", regionName: "North America", …}

...
</code>```

答:
The issue here comes from the objects in your array. react-select needs an array of objects with following keys in order to understand it: value and label.

So, in render, you could replace

```<code>let options = this.state.cities.map(function (city) {
  return city.name;
})
</code>```

by, for example,

```<code>let options = this.state.cities.map(function (city) {
  return { value: city.countryCode, label: city.name };
})
</code>```

or, like pritesh pointed out, simply tell react-select what keys to use like

```<code>render () {
  return (
    <div>
      <Select
        name="form-field-name"
        value={this.state.value}
        onChange={this.handleChange}
        clearable={this.state.clearable}
        searchable={this.state.searchable}
        labelKey='name'
        valueKey='countryCode'
        options={this.state.cities}
      />
    </div>
  )
}
</code>```

Hope this helps you out!

Body:
I am using react-select and I don't want to hard code the options which should be displayed, but options is data I am fetching from an api. I can't really find anything and what I was trying to do doesn't work as nothing gets displayed. Anyone knows? Thanks!!!

api.js:

export function availableCities() {
   return axios.get('/cities').then(function (response) {
      return response.data;
   })
}

Component:

import Select from 'react-select';
import {availableCities} from '../utils/api.js';

class App extends React.Component {
    constructor(props) {
    super(props);
    this.state = {
        selectedOption: '',
        clearable: true,
        cities: [],
     }
   }
   componentDidMount() {
    availableCities()
        .then(res => {
            this.setState({
                cities: res.Cities.name
            })
            console.log("hello", this.state.cities)
        })
   }

   handleChange(selectedOption) {
    this.setState({selectedOption});
   }
 render(){
    let options = this.state.cities.map(function (city) {
            return city.name;
    })
 return (

           <Select
                name="form-field-name"
                value={this.state.value}
                onChange={this.handleChange}
                clearable={this.state.clearable}
                searchable={this.state.searchable}
                options={options}
            />

  )
 }
}

Data( this.state.cities is an array of objects and looks like:

{code: "LTS", name: "Altus", countryCode: "US", countryName: "United States", regionName: "North America", …}

...

Body:
The issue here comes from the objects in your array. react-select needs an array of objects with following keys in order to understand it: value and label.

So, in render, you could replace

let options = this.state.cities.map(function (city) {
  return city.name;
})

by, for example,

let options = this.state.cities.map(function (city) {
  return { value: city.countryCode, label: city.name };
})

or, like pritesh pointed out, simply tell react-select what keys to use like

render () {
  return (
    <div>
      <Select
        name="form-field-name"
        value={this.state.value}
        onChange={this.handleChange}
        clearable={this.state.clearable}
        searchable={this.state.searchable}
        labelKey='name'
        valueKey='countryCode'
        options={this.state.cities}
      />
    </div>
  )
}

Hope this helps you out!


问:
Only permit one instance of a row with a particular column value in a multidimensional array
In my input array, I have multiple rows with a userTag of All, but I only want a maximum of one.  Other rows my have duplicated userTag values (such as Seeker), but extra All rows must be removed.

```<code>$input = [
    0 => ['userTag' => 'All', 'fbId' => 10210118553469338, 'price' => 70],
    1 => ['userTag' => 'All', 'fbId' => 10210118553469338, 'price' => 14],
    2 => ['userTag' => 'All', 'fbId' => 10210118553469338, 'price' => null],
    3 => ['userTag' => 'Seeker', 'fbId' => 10207897577195936, 'price' => 65],
    6 => ['userTag' => 'Seeker', 'fbId' => 709288842611719, 'price' => 75],
    17 => ['userTag' => 'Trader', 'fbId' => 2145752308783752, 'price' => null]
];
</code>```

My current code:

```<code>$dat = array();
$dat2 = array();
foreach ($input as $key => $value)
{
    $i = 0;
    $j = 0;
    if (count($dat) == 0) {
        $dat = $input[$key];
        $i++;
    } else {
        if ($input[$key]['userTag'] == "All") {
            if ($this->check($input[$key]['fbId'], $dat) == false) {
                $dat[$i] = $input[$key];
                $i++;
            }
        } else {
            $dat2[$j] = $input[$key];
            $j++;
        }
    }
}
$data =  array_merge($dat, $dat2);
return $data;
</code>```

The check() function:

```<code>public function check($val, $array) {
    foreach ($array as $vl) {
        if ($val == $array[$vl]['fbId']) {
             return true;
             break;
        }
    }
    return false;
}
</code>```

答:
Check this code. Perfectly working.</p>

```<code>$n_array = array();$i=0;
foreach($array as $row){
    if($row['userTag']=="All"){
       if($i==0){
          $n_array[]=$row;
          $i=1;
       }
    }
    else $n_array[]=$row;
}
echo "```";print_r($n_array);
</code>```

<p><strong>Result</strong></p>

```<code>    Array
    (
        [0] => Array
            (
                [userTag] => All
                [fbId] => 10210118553469338
                [fName] => Danish
                [lName] => Aftab
                [imageUrl] => https://scontent.xx.fbcdn.net/v/t1.0-1/p50x50/22491765_10210410024475931_8589925114603818114_n.jpg?oh=7fa6266e7948ef2d218076857972f7e0
                [subsType] => gold
                [user_visible] => 0
                [distance] => 0.01
                [advising] => 0
                [avgRate] => 4
                [totalReview] => 2
                [us_seeker_type] => new
                [price] => 70
            )

        [1] => Array
            (
                [userTag] => Seeker
                [fbId] => 10207897577195936
                [fName] => Saq
                [lName] => Khan
                [imageUrl] => https://scontent.xx.fbcdn.net/v/t1.0-1/p50x50/21151741_10207631130774942_8962953748374982841_n.jpg?oh=f5e5b9dff52b1ba90ca47ade3d703b01
                [subsType] => gold
                [user_visible] => 0
                [background] =>
                [topic] =>
                [distance] => 0.01
                [advising] => 0
                [avgRate] => 0
                [totalReview] => 0
                [us_seeker_type] => new
                [price] => 65
            )

        [2] => Array
            (
                [userTag] => Seeker
                [fbId] => 709288842611719
                [fName] => Muhammad
                [lName] => Hasan
                [imageUrl] => https://scontent.xx.fbcdn.net/v/t1.0-1/p50x50/20264704_681395725401031_2098768310549259034_n.jpg?oh=36db5b6ed60214088750794d4e3aa3e6
                [subsType] => gold
                [user_visible] => 0
                [distance] => 0.02
                [advising] => 0
                [avgRate] => 0
                [totalReview] => 0
                [us_seeker_type] => new
                [price] => 75
            )

        [3] => Array
            (
                [userTag] => Trader
                [fbId] => 2145752308783752
                [fName] => Jawaid
                [lName] => Ahmed
                [imageUrl] => https://scontent.xx.fbcdn.net/v/t1.0-1/p50x50/20992899_2068273703198280_4249128502952085310_n.jpg?oh=6df0be6ced405dd66ee50de238156183
                [subsType] => basic
                [user_visible] => 0
                [advising] => 0
                [distance] => 0
                [avgRate] => 0
                [totalReview] => 0
                [utr_trader_type] => new
                [price] =>
            )

    )
</code>```

Body:
In my input array, I have multiple rows with a userTag of All, but I only want a maximum of one.  Other rows my have duplicated userTag values (such as Seeker), but extra All rows must be removed.

$input = [
    0 => ['userTag' => 'All', 'fbId' => 10210118553469338, 'price' => 70],
    1 => ['userTag' => 'All', 'fbId' => 10210118553469338, 'price' => 14],
    2 => ['userTag' => 'All', 'fbId' => 10210118553469338, 'price' => null],
    3 => ['userTag' => 'Seeker', 'fbId' => 10207897577195936, 'price' => 65],
    6 => ['userTag' => 'Seeker', 'fbId' => 709288842611719, 'price' => 75],
    17 => ['userTag' => 'Trader', 'fbId' => 2145752308783752, 'price' => null]
];

My current code:

$dat = array();
$dat2 = array();
foreach ($input as $key => $value)
{
    $i = 0;
    $j = 0;
    if (count($dat) == 0) {
        $dat = $input[$key];
        $i++;
    } else {
        if ($input[$key]['userTag'] == "All") {
            if ($this->check($input[$key]['fbId'], $dat) == false) {
                $dat[$i] = $input[$key];
                $i++;
            }
        } else {
            $dat2[$j] = $input[$key];
            $j++;
        }
    }
}
$data =  array_merge($dat, $dat2);
return $data;

The check() function:

public function check($val, $array) {
    foreach ($array as $vl) {
        if ($val == $array[$vl]['fbId']) {
             return true;
             break;
        }
    }
    return false;
}

Body:
Check this code. Perfectly working.

$n_array = array();$i=0;
foreach($array as $row){
    if($row['userTag']=="All"){
       if($i==0){
          $n_array[]=$row;
          $i=1;
       }
    }
    else $n_array[]=$row;
}
echo "<pre>";print_r($n_array);

Result

    Array
    (
        [0] => Array
            (
                [userTag] => All
                [fbId] => 10210118553469338
                [fName] => Danish
                [lName] => Aftab
                [imageUrl] => https://scontent.xx.fbcdn.net/v/t1.0-1/p50x50/22491765_10210410024475931_8589925114603818114_n.jpg?oh=7fa6266e7948ef2d218076857972f7e0
                [subsType] => gold
                [user_visible] => 0
                [distance] => 0.01
                [advising] => 0
                [avgRate] => 4
                [totalReview] => 2
                [us_seeker_type] => new
                [price] => 70
            )

        [1] => Array
            (
                [userTag] => Seeker
                [fbId] => 10207897577195936
                [fName] => Saq
                [lName] => Khan
                [imageUrl] => https://scontent.xx.fbcdn.net/v/t1.0-1/p50x50/21151741_10207631130774942_8962953748374982841_n.jpg?oh=f5e5b9dff52b1ba90ca47ade3d703b01
                [subsType] => gold
                [user_visible] => 0
                [background] =>
                [topic] =>
                [distance] => 0.01
                [advising] => 0
                [avgRate] => 0
                [totalReview] => 0
                [us_seeker_type] => new
                [price] => 65
            )

        [2] => Array
            (
                [userTag] => Seeker
                [fbId] => 709288842611719
                [fName] => Muhammad
                [lName] => Hasan
                [imageUrl] => https://scontent.xx.fbcdn.net/v/t1.0-1/p50x50/20264704_681395725401031_2098768310549259034_n.jpg?oh=36db5b6ed60214088750794d4e3aa3e6
                [subsType] => gold
                [user_visible] => 0
                [distance] => 0.02
                [advising] => 0
                [avgRate] => 0
                [totalReview] => 0
                [us_seeker_type] => new
                [price] => 75
            )

        [3] => Array
            (
                [userTag] => Trader
                [fbId] => 2145752308783752
                [fName] => Jawaid
                [lName] => Ahmed
                [imageUrl] => https://scontent.xx.fbcdn.net/v/t1.0-1/p50x50/20992899_2068273703198280_4249128502952085310_n.jpg?oh=6df0be6ced405dd66ee50de238156183
                [subsType] => basic
                [user_visible] => 0
                [advising] => 0
                [distance] => 0
                [avgRate] => 0
                [totalReview] => 0
                [utr_trader_type] => new
                [price] =>
            )

    )


问:
How do I make a 'submit' option on a form that has an unlimited number of inputs?
I am trying to create a 'calculator' where you can add the amount of inputs as well, so you can enter as many as you wish. On submit, it should display the added value of all inputs - however, I can only get it to show the value of the last input. Also I wish to times the value of x input by the amount of x input, written into the number input - how do I go about doing that?

var prices= new Array();
prices["none"]=0;
prices["burger"]=10;
prices["fish"]=20;
prices["steak"]=30;

var i = 0;

function createInput() {
    i++;

    var container = document.getElementById("newInputs");

    var select = document.createElement("select");
    select.setAttribute("id", "select" + i);
    container.appendChild(select);

    var none = document.createElement("option");
    none.setAttribute("value", "none");
    none.text = "";
    select.add(none);

    var one = document.createElement("option");
    one.setAttribute("value", "burger");
    one.text = "Burger";
    select.add(one);

    var two = document.createElement("option");
    two.setAttribute("value", "fish");
    two.text = "Fish";
    select.add(two);

    var three = document.createElement("option");
    three.setAttribute("value", "steak");
    three.text = "Steak";
    select.add(three);

    var amount = document.createElement("input");
    amount.setAttribute("id", "amount" + i);
    amount.setAttribute("type", "number")
    container.appendChild(amount);

    return i;
}

function getPrice() {
    var price = 0;
    var theForm = document.forms["form"];
    var items = theForm.elements["select" + i];
    price = prices[items.value];
    return price;
}

function getTotal() {
    var totalPrice = getPrice();
    document.getElementById('total').innerHTML = "£" + totalPrice;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="form">
        <select id="select0">
            <option value="none"></option>
            <option value="burger">Burger</option>
            <option value="fish">Fish</option>
            <option value="steak">Steak</option>
        </select>
        <input type="number" id="amount1">
        <div id="newInputs">

        </div>
        <input type="button" onclick="createInput()" value="More Inputs!">
        <input type="button" onclick="getTotal()" value="Submit!">
    </form>
    <p id="total">You haven't got a total yet</p></code>```

It's probably a really silly mistake I'm making but thanks for helping anyway!

答:
Check this out ~

var prices= new Array();
prices["none"]=0;
prices["burger"]=10;
prices["fish"]=20;
prices["steak"]=30;

var i = 0;

function createInput() {
    i++;

    var container = document.getElementById("newInputs");

    var select = document.createElement("select");
    select.setAttribute("id", "select" + i);
    container.appendChild(select);

    var none = document.createElement("option");
    none.setAttribute("value", "none");
    none.text = "";
    select.add(none);

    var one = document.createElement("option");
    one.setAttribute("value", "burger");
    one.text = "Burger";
    select.add(one);

    var two = document.createElement("option");
    two.setAttribute("value", "fish");
    two.text = "Fish";
    select.add(two);

    var three = document.createElement("option");
    three.setAttribute("value", "steak");
    three.text = "Steak";
    select.add(three);

    var amount = document.createElement("input");
    amount.setAttribute("id", "amount" + i);
    amount.setAttribute("type", "number")
    container.appendChild(amount);

    return i;
}

function getPrice() {
    var price = 0, ix, ixLen, value, type;
    var newInputs = document.getElementById('newInputs');

    price += (prices[document.getElementById('select0').value || 'none']) *
             (document.getElementById('amount0').value || 0);
    for(ix = 0, ixLen = newInputs.children.length; ix < ixLen; ix += 2){
        type = newInputs.children[ix].value || 'none';
        value = newInputs.children[ix+1].value || 0;
        price += prices[type] * +value;
    }

    return price;
}

function getTotal() {
    var totalPrice = getPrice();
    document.getElementById('total').innerHTML = "£" + totalPrice;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="form">
 <select id="select0">
  <option value="none"></option>
  <option value="burger">Burger</option>
  <option value="fish">Fish</option>
  <option value="steak">Steak</option>
 </select>
 <input type="number" id="amount0">
 <div id="newInputs">

 </div>
 <input type="button" onclick="createInput()" value="More Inputs!">
 <input type="button" onclick="getTotal()" value="Submit!">
</form>
<p id="total">You haven't got a total yet</p></code>```

Body:
I am trying to create a 'calculator' where you can add the amount of inputs as well, so you can enter as many as you wish. On submit, it should display the added value of all inputs - however, I can only get it to show the value of the last input. Also I wish to times the value of x input by the amount of x input, written into the number input - how do I go about doing that?

var prices= new Array();
prices["none"]=0;
prices["burger"]=10;
prices["fish"]=20;
prices["steak"]=30;

var i = 0;

function createInput() {
    i++;

    var container = document.getElementById("newInputs");

    var select = document.createElement("select");
    select.setAttribute("id", "select" + i);
    container.appendChild(select);

    var none = document.createElement("option");
    none.setAttribute("value", "none");
    none.text = "";
    select.add(none);

    var one = document.createElement("option");
    one.setAttribute("value", "burger");
    one.text = "Burger";
    select.add(one);

    var two = document.createElement("option");
    two.setAttribute("value", "fish");
    two.text = "Fish";
    select.add(two);

    var three = document.createElement("option");
    three.setAttribute("value", "steak");
    three.text = "Steak";
    select.add(three);

    var amount = document.createElement("input");
    amount.setAttribute("id", "amount" + i);
    amount.setAttribute("type", "number")
    container.appendChild(amount);

    return i;
}

function getPrice() {
    var price = 0;
    var theForm = document.forms["form"];
    var items = theForm.elements["select" + i];
    price = prices[items.value];
    return price;
}

function getTotal() {
    var totalPrice = getPrice();
    document.getElementById('total').innerHTML = "£" + totalPrice;
}

<form id="form">
        <select id="select0">
            <option value="none"></option>
            <option value="burger">Burger</option>
            <option value="fish">Fish</option>
            <option value="steak">Steak</option>
        </select>
        <input type="number" id="amount1">

        <input type="button" onclick="createInput()" value="More Inputs!">
        <input type="button" onclick="getTotal()" value="Submit!">
    </form>

You haven't got a total yet

It's probably a really silly mistake I'm making but thanks for helping anyway!

Body:
Check this out ~

var prices= new Array();
prices["none"]=0;
prices["burger"]=10;
prices["fish"]=20;
prices["steak"]=30;

var i = 0;

function createInput() {
    i++;

    var container = document.getElementById("newInputs");

    var select = document.createElement("select");
    select.setAttribute("id", "select" + i);
    container.appendChild(select);

    var none = document.createElement("option");
    none.setAttribute("value", "none");
    none.text = "";
    select.add(none);

    var one = document.createElement("option");
    one.setAttribute("value", "burger");
    one.text = "Burger";
    select.add(one);

    var two = document.createElement("option");
    two.setAttribute("value", "fish");
    two.text = "Fish";
    select.add(two);

    var three = document.createElement("option");
    three.setAttribute("value", "steak");
    three.text = "Steak";
    select.add(three);

    var amount = document.createElement("input");
    amount.setAttribute("id", "amount" + i);
    amount.setAttribute("type", "number")
    container.appendChild(amount);

    return i;
}

function getPrice() {
    var price = 0, ix, ixLen, value, type;
    var newInputs = document.getElementById('newInputs');

    price += (prices[document.getElementById('select0').value || 'none']) *
             (document.getElementById('amount0').value || 0);
    for(ix = 0, ixLen = newInputs.children.length; ix < ixLen; ix += 2){
        type = newInputs.children[ix].value || 'none';
        value = newInputs.children[ix+1].value || 0;
        price += prices[type] * +value;
    }

    return price;
}

function getTotal() {
    var totalPrice = getPrice();
    document.getElementById('total').innerHTML = "£" + totalPrice;
}

<form id="form">
 <select id="select0">
  <option value="none"></option>
  <option value="burger">Burger</option>
  <option value="fish">Fish</option>
  <option value="steak">Steak</option>
 </select>
 <input type="number" id="amount0">
 <div id="newInputs">

 </div>
 <input type="button" onclick="createInput()" value="More Inputs!">
 <input type="button" onclick="getTotal()" value="Submit!">
</form>
<p id="total">You haven't got a total yet</p>


问:
How to set the Image property of a PictureBox Control by using OpenFileDialog? C# winforms
How to set the Image property of a PictureBox Control by using OpenFileDialog?</p>

答:
Set PictureBox.Image using Image.FromFile

```<code>OpenFileDialog _openFileDialog = new OpenFileDialog();
_openFileDialog.FileOk += OpenFileDialogFileOk;
_openFileDialog.CheckFileExists = true;
_openFileDialog.CheckPathExists = true;
_openFileDialog.ShowDialog();

void OpenFileDialogFileOk(object sender, CancelEventArgs e)
{
    var imageInformation = new FileInfo(_openFileDialog.FileName);
    var sizeInBytes = imageInformation.Length;

    myPictureBox.Image = Image.FromFile(_openFileDialog.FileName);
}
</code>```

Body:
Set PictureBox.Image using Image.FromFile

OpenFileDialog _openFileDialog = new OpenFileDialog();
_openFileDialog.FileOk += OpenFileDialogFileOk;
_openFileDialog.CheckFileExists = true;
_openFileDialog.CheckPathExists = true;
_openFileDialog.ShowDialog();

void OpenFileDialogFileOk(object sender, CancelEventArgs e)
{
    var imageInformation = new FileInfo(_openFileDialog.FileName);
    var sizeInBytes = imageInformation.Length;

    myPictureBox.Image = Image.FromFile(_openFileDialog.FileName);
}


问:
Excel functions do not work properly after getting csv output from Pandas
Recently, I confronted a very strange thing in Microsoft Excel. I made a dataframe in Python 3.6 and  filled it with some integer numbers, then I used "to_csv" function to get csv output. I opened the file with Microsoft Excel for doing basic statistical analysis and drawing some charts, however; Microsoft Excel doesn't recognize the numbers in the cells as number. For example, when I add two cell, the result will be zero, no matter what are the numbers.
This is a screenshot from my my Excel environment:

In the yellow cell (C101) I tried to get the sum of cells in column C, but as I explained the sum function (and all the other functions like Count or Max) doesn't work properly. I also, have to say, all the cells have "Number" data type. I'm quite confused, any suggestion would help.

答:
I would have written the answer as a comment, but my reputation is too low.

By default, the decimal seperator is set to a dot ('.'). You have to switch it to a comma (',') like this:

```<code>df.to_csv(file, decimal=',')
</code>```

EDIT:

I forgot that you also have to set the seperator, since its default value is comma:

```<code>df.to_csv(file, sep=';', decimal=',')
</code>```

Body:
I would have written the answer as a comment, but my reputation is too low.

By default, the decimal seperator is set to a dot ('.'). You have to switch it to a comma (',') like this:

df.to_csv(file, decimal=',')

EDIT:

I forgot that you also have to set the seperator, since its default value is comma:

df.to_csv(file, sep=';', decimal=',')


问:
Xamarin.Forms HybridWebView zoom (Android)

I created a WebViewPage class that inherits from HybridWebView
Now I need to implement the zoom but I can not find the string that allows to do

code:

```<code>public class WebViewPage : HybridWebView
    {
           ...code
    }
     protected override void OnStart()
            {
                var webView = Container.GetInstance<WebViewPage>();
                webView.LoadFromContent("index.html");
    ...code
    }
</code>```

how I enable pinch to zoom?

答:
You will need to modify the source and set the appropriate WebKit zoom settings.

re: setBuiltInZoomControls

In the HybridWebViewRenderer.cs you need to turn on BuiltInZoomControls
 and turn the visual zoom controls (DisplayZoomControls) off (if not desired).

```<code>webView.Settings.BuiltInZoomControls = true;
webView.Settings.DisplayZoomControls = false;
</code>```

Body:
I created a WebViewPage class that inherits from HybridWebView
Now I need to implement the zoom but I can not find the string that allows to do

code:

public class WebViewPage : HybridWebView
    {
           ...code
    }
     protected override void OnStart()
            {
                var webView = Container.GetInstance<WebViewPage>();
                webView.LoadFromContent("index.html");
    ...code
    }

how I enable pinch to zoom?

Body:
You will need to modify the source and set the appropriate WebKit zoom settings.

re: setBuiltInZoomControls

In the HybridWebViewRenderer.cs you need to turn on BuiltInZoomControls
 and turn the visual zoom controls (DisplayZoomControls) off (if not desired).

webView.Settings.BuiltInZoomControls = true;
webView.Settings.DisplayZoomControls = false;


问:
Stratified sampling with pyspark
I have a Spark DataFrame that has one column that has lots of zeros and very few ones (only 0.01% of ones).

I'd like to take a random subsample but a stratified one - so that it keeps the ratio of 1s to 0s in that column.

Is it possible to do in pyspark ?

I am looking for a non-scala solution and on based on DataFrames and not RDD-based.

Title: Stratified sampling with pyspark

Body:
The solution I suggested in Stratified sampling in Spark
 is pretty straightforward to convert from Scala to Python (or even to Java - What's the easiest way to stratify a Spark Dataset ?).

Nevertheless, I'll rewrite it python. Let's start first by creating a toy DataFrame :

from pyspark.sql.functions import lit
list = [(2147481832,23355149,1),(2147481832,973010692,1),(2147481832,2134870842,1),(2147481832,541023347,1),(2147481832,1682206630,1),(2147481832,1138211459,1),(2147481832,852202566,1),(2147481832,201375938,1),(2147481832,486538879,1),(2147481832,919187908,1),(214748183,919187908,1),(214748183,91187908,1)]
df = spark.createDataFrame(list, ["x1","x2","x3"])
df.show()
# +----------+----------+---+
# |        x1|        x2| x3|
# +----------+----------+---+
# |2147481832|  23355149|  1|
# |2147481832| 973010692|  1|
# |2147481832|2134870842|  1|
# |2147481832| 541023347|  1|
# |2147481832|1682206630|  1|
# |2147481832|1138211459|  1|
# |2147481832| 852202566|  1|
# |2147481832| 201375938|  1|
# |2147481832| 486538879|  1|
# |2147481832| 919187908|  1|
# | 214748183| 919187908|  1|
# | 214748183|  91187908|  1|
# +----------+----------+---+

This DataFrame has 12 elements as you can see :

df.count()
# 12

Distributed as followed :

df.groupBy("x1").count().show()
# +----------+-----+
# |        x1|count|
# +----------+-----+
# |2147481832|   10|
# | 214748183|    2|
# +----------+-----+

Now let's sample :

First we'll set the seed :

seed = 12

The find the keys to fraction on and sample :

fractions = df.select("x1").distinct().withColumn("fraction", lit(0.8)).rdd.collectAsMap()
print(fractions)
# {2147481832: 0.8, 214748183: 0.8}
sampled_df = df.stat.sampleBy("x1", fractions, seed)
sampled_df.show()
# +----------+---------+---+
# |        x1|       x2| x3|
# +----------+---------+---+
# |2147481832| 23355149|  1|
# |2147481832|973010692|  1|
# |2147481832|541023347|  1|
# |2147481832|852202566|  1|
# |2147481832|201375938|  1|
# |2147481832|486538879|  1|
# |2147481832|919187908|  1|
# | 214748183|919187908|  1|
# | 214748183| 91187908|  1|
# +----------+---------+---+

We can now check the content of our sample :

sampled_df.count()
# 9

sampled_df.groupBy("x1").count().show()
# +----------+-----+
# |        x1|count|
# +----------+-----+
# |2147481832|    7|
# | 214748183|    2|
# +----------+-----+


问:
How to Generate accurate thumbnails with FFMPEG
I am using FFmpeg for generating thumbnails map.

I need to generate a thumbnail for every second. Here is code i use on Windows:

-i "C:\temp\MyVideo.mp4" -vf "drawtext=fontfile=../Fonts/calibri.ttf: text=%%
{n}: r=25: x=(w-tw)/2: y=h-lh-122: fontsize=295: fontcolor=Red:   box=0: boxcolor=Black,fps=1/1" -s 400x300 -vcodec ppm -f image2pipe - | montage -  -
    tile 10x -geometry 200x+0+0 C:\temp\Thumbnailer.jpg

Code Work's Fine , generate a thumbnails map with piping FFMPEG+Imagemagick (montage).
In ffmpeg i burn the frame number to check accuracy.

Only problem is FFMPEG start generating at frames 12, 37, 62, 87...(video is 25 fps).

How to start generating thumbnails at first frame #1 accurate?

In FFMPEG i try options like -ss 00:00:00.0 but FFMPEG start always at frame 12.
Only solution i found is to generate all frames (25fps) and post process to keep  frames number 1,25,50... but very slow post process...

My FFMPEG version : ffmpeg version N-88153-ga4743d2574-Reino

答:
The fps filter will select based on the timestamp rounding method used.

For your purposes, use fps=1/1:round=up

See all available methods at https://ffmpeg.org/ffmpeg-filters.html#fps-1