问:
SQL to return all records 18 months ahead of another date (to end of month)
I have a table with two DATETIME fields, OpeningDate and FinishingDate.

I am trying to write a query that returns all records that have a FinishingDate that is exactly 16 months ahead of the OpeningDate.

I have tried:

```<code>SELECT * FROM Sales
WHERE FinishingDate = DATEADD(MONTH, 16, OpeningDate)
</code>```

But it appears to give me all records that fall between those dates (only up to the day in the month), I need it to get all records up until the end of the month.

So lets say I have an OpeningDate of 2017-10-6 (year, month, day) 18 months ahead would be 2019-04-06. This will only include records up to the 6th of April, I need it to include records up until the end of April.

What modifications can I make to the query to achieve this?

Any help would be great.

Thanks!

答:
You can simply try this

```<code>SELECT * FROM Sales
WHERE FinishingDate = DATEADD(MONTH, 16, Convert(datetime,OpeningDate))
</code>```

I tried it on my SQL server and it works fine with me.

Body:
I have a table with two DATETIME fields, OpeningDate and FinishingDate.

I am trying to write a query that returns all records that have a FinishingDate that is exactly 16 months ahead of the OpeningDate.

I have tried:

SELECT * FROM Sales
WHERE FinishingDate = DATEADD(MONTH, 16, OpeningDate)

But it appears to give me all records that fall between those dates (only up to the day in the month), I need it to get all records up until the end of the month.

So lets say I have an OpeningDate of 2017-10-6 (year, month, day) 18 months ahead would be 2019-04-06. This will only include records up to the 6th of April, I need it to include records up until the end of April.

What modifications can I make to the query to achieve this?

Any help would be great.

Thanks!

Body:
You can simply try this

SELECT * FROM Sales
WHERE FinishingDate = DATEADD(MONTH, 16, Convert(datetime,OpeningDate))

I tried it on my SQL server and it works fine with me.


来源: stackexchange

问:
Didn't find class "com.google.firebase.provider.FirebaseInitProvider"?
I am getting the below exception on app launch.

```<code>java.lang.RuntimeException: Unable to get provider com.google.firebase.provider.FirebaseInitProvider: java.lang.ClassNotFoundException: Didn't find class "com.google.firebase.provider.FirebaseInitProvider" on path: DexPathList[[zip file "/data/app/com.vfirst.ifbagro-1.apk"],nativeLibraryDirectories=[/data/app-lib/com.vfirst.ifbagro-1, /vendor/lib, /system/lib]]
at android.app.ActivityThread.installProvider(ActivityThread.java:4993)
at android.app.ActivityThread.installContentProviders(ActivityThread.java:4596)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4536)
at android.app.ActivityThread.access$1300(ActivityThread.java:149)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1353)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5214)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:555)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.firebase.provider.FirebaseInitProvider" on path: DexPathList[[zip file "/data/app/com.vfirst.ifbagro-1.apk"],nativeLibraryDirectories=[/data/app-lib/com.vfirst.ifbagro-1, /vendor/lib, /system/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:53)
at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
at android.app.ActivityThread.installProvider(ActivityThread.java:4978)
at android.app.ActivityThread.installContentProviders(ActivityThread.java:4596)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4536)
at android.app.ActivityThread.access$1300(ActivityThread.java:149)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1353)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5214)
at java.lang.reflect.Method.invokeNative(Native Method)
</code>```

Here is the the app level build.gradle

```<code>apply plugin: 'com.android.application'
apply plugin: 'android-apt'

android {
compileSdkVersion 24
buildToolsVersion "24.0.1"

defaultConfig {
    applicationId "com.vfirst.ifbagro"
    minSdkVersion 17
    targetSdkVersion 24
    versionCode 1
    versionName "1.0"
    multiDexEnabled true
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])

compile 'com.android.support:appcompat-v7:24.2.1'
compile 'com.android.support:design:24.2.1'
compile 'com.android.support:support-v4:24.2.1'
compile 'com.google.android.gms:play-services-gcm:9.4.0'
compile 'com.google.android.gms:play-services-location:9.4.0'
compile 'com.android.support:multidex:1.0.1'
compile 'com.google.firebase:firebase-messaging:9.4.0'
compile 'com.google.android.gms:play-services:9.4.0'
testCompile 'junit:junit:4.12'
}

apply plugin: 'com.google.gms.google-services'
</code>```

This is my application level build.gradle

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
repositories {
    jcenter()
    mavenCentral()
}
dependencies {
    classpath 'com.android.tools.build:gradle:2.2.0'
    classpath 'com.google.gms:google-services:3.0.0'
    classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
    classpath 'com.google.gms:google-services:3.0.0'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}

allprojects {
repositories {
    jcenter()
}
}

task clean(type: Delete) {
     delete rootProject.buildDir
}
</code>```

How to solve the issue?

答:
I had the same issue and solved just add a piece of code, If you are getting this issue means you had already completed all the steps that need to use Firebase. You just need to create a class that extends the Application (public class Application_CrashReport extends Application ) and add this class in mainifest file and In that class just override the  below method

```<code>  @Override
protected void attachBaseContext(Context base) {
    super.attachBaseContext(base);
}
</code>```

and add  MultiDex.install(this); in that method means

```<code>  @Override
protected void attachBaseContext(Context base) {
    super.attachBaseContext(base);
    MultiDex.install(this);
}
</code>```

Note :- Don't forget to follow above steps

ContentLicense: CC BY-SA 3.0

Body:
I am getting the below exception on app launch.

java.lang.RuntimeException: Unable to get provider com.google.firebase.provider.FirebaseInitProvider: java.lang.ClassNotFoundException: Didn't find class "com.google.firebase.provider.FirebaseInitProvider" on path: DexPathList[[zip file "/data/app/com.vfirst.ifbagro-1.apk"],nativeLibraryDirectories=[/data/app-lib/com.vfirst.ifbagro-1, /vendor/lib, /system/lib]]
at android.app.ActivityThread.installProvider(ActivityThread.java:4993)
at android.app.ActivityThread.installContentProviders(ActivityThread.java:4596)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4536)
at android.app.ActivityThread.access$1300(ActivityThread.java:149)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1353)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5214)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:555)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.firebase.provider.FirebaseInitProvider" on path: DexPathList[[zip file "/data/app/com.vfirst.ifbagro-1.apk"],nativeLibraryDirectories=[/data/app-lib/com.vfirst.ifbagro-1, /vendor/lib, /system/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:53)
at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
at android.app.ActivityThread.installProvider(ActivityThread.java:4978)
at android.app.ActivityThread.installContentProviders(ActivityThread.java:4596)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4536)
at android.app.ActivityThread.access$1300(ActivityThread.java:149)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1353)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5214)
at java.lang.reflect.Method.invokeNative(Native Method)

Here is the the app level build.gradle

apply plugin: 'com.android.application'
apply plugin: 'android-apt'

android {
compileSdkVersion 24
buildToolsVersion "24.0.1"

defaultConfig {
    applicationId "com.vfirst.ifbagro"
    minSdkVersion 17
    targetSdkVersion 24
    versionCode 1
    versionName "1.0"
    multiDexEnabled true
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])

compile 'com.android.support:appcompat-v7:24.2.1'
compile 'com.android.support:design:24.2.1'
compile 'com.android.support:support-v4:24.2.1'
compile 'com.google.android.gms:play-services-gcm:9.4.0'
compile 'com.google.android.gms:play-services-location:9.4.0'
compile 'com.android.support:multidex:1.0.1'
compile 'com.google.firebase:firebase-messaging:9.4.0'
compile 'com.google.android.gms:play-services:9.4.0'
testCompile 'junit:junit:4.12'
}

apply plugin: 'com.google.gms.google-services'

This is my application level build.gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
repositories {
    jcenter()
    mavenCentral()
}
dependencies {
    classpath 'com.android.tools.build:gradle:2.2.0'
    classpath 'com.google.gms:google-services:3.0.0'
    classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
    classpath 'com.google.gms:google-services:3.0.0'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}

allprojects {
repositories {
    jcenter()
}
}

task clean(type: Delete) {
     delete rootProject.buildDir
}

How to solve the issue?

Body:
I had the same issue and solved just add a piece of code, If you are getting this issue means you had already completed all the steps that need to use Firebase. You just need to create a class that extends the Application (public class Application_CrashReport extends Application ) and add this class in mainifest file and In that class just override the  below method

  @Override
protected void attachBaseContext(Context base) {
    super.attachBaseContext(base);
}

and add  MultiDex.install(this); in that method means

  @Override
protected void attachBaseContext(Context base) {
    super.attachBaseContext(base);
    MultiDex.install(this);
}

Note :- Don't forget to follow above steps


问:
Java expand FilenameFilter
I have a method where upon calling a FilenameFilter is passed to (as anonymous inner class). Now, if a variable is set, I want to extend the FilenameFilter. Example:

```<code>new FilenameFilter() {

    @Override
    public boolean accept(File dir, String name) {
        return name.toLowerCase().endsWith(".txt");
    }
}
</code>```

Should become:

```<code>new FilenameFilter() {

    @Override
    public boolean accept(File dir, String name) {
        return name.toLowerCase().endsWith(".txt") || new File(dir, name).isDirectory();
    }
}
</code>```

How can I get the filtering from the first filter and add the directory check? (I don't want to implement the FilenameFilter with directories upon calling the method, because it might not be needed at all)

Solution based upon accepted answer. filenameFilter is the instance passed to the method:

```<code>new FilenameFilter() {

    @Override
    public boolean accept(File dir, String name) {
        return filenameFilter.accept(dir, name) || new File(dir, name).isDirectory();
    }
};
</code>```

答:
You should extends the first filter:</p>

```<code>class FilenameFilter1 implements FilenameFilter {
    @Override
    public boolean accept(File dir, String name) {
        return name.toLowerCase().endsWith(".txt");
    }
}

class FilenameFilter2 extends FilenameFilter1 {
    @Override
    public boolean accept(File dir, String name) {
        return super.accept(dir, name) && new File(dir, name).isDirectory();
    }
}
</code>```

Title: Java expand FilenameFilter

Body:
I have a method where upon calling a FilenameFilter is passed to (as anonymous inner class). Now, if a variable is set, I want to extend the FilenameFilter. Example:

new FilenameFilter() {

    @Override
    public boolean accept(File dir, String name) {
        return name.toLowerCase().endsWith(".txt");
    }
}

Should become:

new FilenameFilter() {

    @Override
    public boolean accept(File dir, String name) {
        return name.toLowerCase().endsWith(".txt") || new File(dir, name).isDirectory();
    }
}

How can I get the filtering from the first filter and add the directory check? (I don't want to implement the FilenameFilter with directories upon calling the method, because it might not be needed at all)

Solution based upon accepted answer. filenameFilter is the instance passed to the method:

new FilenameFilter() {

    @Override
    public boolean accept(File dir, String name) {
        return filenameFilter.accept(dir, name) || new File(dir, name).isDirectory();
    }
};

Body:
You should extends the first filter:

class FilenameFilter1 implements FilenameFilter {
    @Override
    public boolean accept(File dir, String name) {
        return name.toLowerCase().endsWith(".txt");
    }
}

class FilenameFilter2 extends FilenameFilter1 {
    @Override
    public boolean accept(File dir, String name) {
        return super.accept(dir, name) && new File(dir, name).isDirectory();
    }
}


问:
How to find maximum value in a list of arrays
I have a very large list of arrays that looks something like this:

```<code>'apples': array([1,2,3,4]), 'pears': array([1,2,10,11]),'oranges': array([1,10,10,3])
</code>```

I want to find the maximum value out of all the arrays. In my short example above it would be 11.

I am struggling to write something that would give me the maximum value for all arrays in the list. Any thoughts would be welcome.

答:
From your example given it looks like that's a dictionary rather than a list, anyways for simplicity let's assume that it is a list in the form of:

```<code>[[2,3,55],[23,5,63],[2,3,6],[4,6,78], ...]
</code>```

So what you can do is iterate over the main list and keep the current max value in a variable, and just compare to max of each array and update if greater.

Example

```<code>max_value = 0
for l in yourList:
    curr = max(l)
    if curr > max_value:
        max_value = curr
print max_value
</code>```

This can be easily converted to use dictionary instead of a list, just iterate over each of the items within the dictionary and the logic would be the same (would have to get max() from the value).

Hope this helps!

Body:
I have a very large list of arrays that looks something like this:

'apples': array([1,2,3,4]), 'pears': array([1,2,10,11]),'oranges': array([1,10,10,3])

I want to find the maximum value out of all the arrays. In my short example above it would be 11.

I am struggling to write something that would give me the maximum value for all arrays in the list. Any thoughts would be welcome.

Body:
From your example given it looks like that's a dictionary rather than a list, anyways for simplicity let's assume that it is a list in the form of:

[[2,3,55],[23,5,63],[2,3,6],[4,6,78], ...]

So what you can do is iterate over the main list and keep the current max value in a variable, and just compare to max of each array and update if greater.

Example

max_value = 0
for l in yourList:
    curr = max(l)
    if curr > max_value:
        max_value = curr
print max_value

This can be easily converted to use dictionary instead of a list, just iterate over each of the items within the dictionary and the logic would be the same (would have to get max() from the value).

Hope this helps!


问:
PHPStorm auto-complete not working with Laravel 5
I'm using PHP Storm v8.0.3 with the latest version of Laravel.

I'm having trouble making the autocomplete work.

As you can see in the image above.

I have installed barryvdh ide-helper, following the readme he provides on git. I haven't received any errors during its installation.

I have included it in the providers array as either

'Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider'

or

Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider:class

It didn't make any difference(as far as I can tell).

I have also installed the Laravel plugin.

Again, no difference, still no auto-complete.

I tried dumping the config file which resulted in:

```<code>array:27 [▼
 ...
  22 => "Illuminate\View\ViewServiceProvider"
  23 => "Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider"
  24 => "App\Providers\AppServiceProvider"
 ...
]
</code>```

I'm really stuck on this one. I have no idea what could be wrong. Any nudging in the right direction is greatly appreciated.

答:
i tried all the Answers, but after i include doctrine/dbal for automatic phpDocs for models, the code autocomplete start to work because the automatic phpDocs for models added the @mixin \Eloquent and this do the trick and more ;)

steps:

```<code>https://github.com/barryvdh/laravel-ide-helper

Require this package with composer using the following command:
composer require --dev barryvdh/laravel-ide-helper

After updating composer, add the service provider to the providers array in config/app.php
Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class,

php artisan clear-compiled
php artisan ide-helper:generate
php artisan optimize

You can configure your composer.json to do this after each commit:

"scripts":{
    "post-update-cmd": [
        "Illuminate\\Foundation\\ComposerScripts::postUpdate",
        "php artisan ide-helper:generate",
        "php artisan ide-helper:meta",
        "php artisan optimize"
    ]
},

composer require doctrine/dbal

php artisan ide-helper:models
</code>```

Body:
I'm using PHP Storm v8.0.3 with the latest version of Laravel.

I'm having trouble making the autocomplete work.

As you can see in the image above.

I have installed barryvdh ide-helper, following the readme he provides on git. I haven't received any errors during its installation.

I have included it in the providers array as either

'Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider'

or

Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider:class

It didn't make any difference(as far as I can tell).

I have also installed the Laravel plugin.

Again, no difference, still no auto-complete.

I tried dumping the config file which resulted in:

array:27 [▼
 ...
  22 => "Illuminate\View\ViewServiceProvider"
  23 => "Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider"
  24 => "App\Providers\AppServiceProvider"
 ...
]

I'm really stuck on this one. I have no idea what could be wrong. Any nudging in the right direction is greatly appreciated.

Body:
i tried all the Answers, but after i include doctrine/dbal for automatic phpDocs for models, the code autocomplete start to work because the automatic phpDocs for models added the @mixin \Eloquent and this do the trick and more ;)

steps:

https://github.com/barryvdh/laravel-ide-helper

Require this package with composer using the following command:
composer require --dev barryvdh/laravel-ide-helper

After updating composer, add the service provider to the providers array in config/app.php
Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class,

php artisan clear-compiled
php artisan ide-helper:generate
php artisan optimize

You can configure your composer.json to do this after each commit:

"scripts":{
    "post-update-cmd": [
        "Illuminate\\Foundation\\ComposerScripts::postUpdate",
        "php artisan ide-helper:generate",
        "php artisan ide-helper:meta",
        "php artisan optimize"
    ]
},

composer require doctrine/dbal

php artisan ide-helper:models

ContentLicense: CC BY-SA 4.0


问:
fail astype method to grouped dataframe in pandas
I get following error when I try to apply astype(float) method to grouped dataframe in pandas.

```<code>ValueError: could not convert string to float:
</code>```

Do you know what is the reason why I cannot convert string to float by astype method? and how I can solve this?
Below is the code I get error and example data.

```<code>def group(self,agg_method):
    df=self.df

    grouped=df.groupby(['Tilt [deg]', 'Azimuth [deg]'],as_index=False)
    groupdf=grouped.agg(agg_method)
    print(groupdf['Azimuth [deg]'][0],len(groupdf['Azimuth [deg]'][0]))
    groupdf['Azimuth [deg]']=groupdf['Azimuth [deg]'].astype(float)  <- I get error here
</code>```

Example data

```<code>   Tilt [deg] Azimuth [deg]  Glass SHGC  Area of Multiplied Openings [m2]  \
0        90.0        124.48        0.57                           1450.24
1        90.0         207.3        0.57                            115.66
2        90.0        207.47        0.57                            115.62
3        90.0        208.25        0.57                             23.18
4        90.0        208.26        0.57                            113.12
5        90.0        214.48        0.57                            451.94
6        90.0        218.57        0.57                            230.08
7        90.0        304.46        0.57                             72.66
8        90.0        304.48        0.57                           1827.53
9        90.0         34.48        0.57                            917.29
</code>```

答:
I believe you need to_numeric with parameter errors='coerce' for convert non numeric to NaNs:

```<code>groupdf['Azimuth [deg]']= pd.to_numeric(groupdf['Azimuth [deg]'], errors='coerce')
</code>```

If need remove all columns which are not parseable and no NaNs values in data is possible use boolean indexing and filter by notnull:

```<code>groupdf = groupdf[pd.to_numeric(groupdf['Azimuth [deg]'], errors='coerce').notnull()]
</code>```

In last version of pandas, 0.21.0 is possible use Series.notna:

```<code>groupdf = groupdf[pd.to_numeric(groupdf['Azimuth [deg]'], errors='coerce').notna()]
</code>```

Body:
I get following error when I try to apply astype(float) method to grouped dataframe in pandas.

ValueError: could not convert string to float:

Do you know what is the reason why I cannot convert string to float by astype method? and how I can solve this?
Below is the code I get error and example data.

def group(self,agg_method):
    df=self.df

    grouped=df.groupby(['Tilt [deg]', 'Azimuth [deg]'],as_index=False)
    groupdf=grouped.agg(agg_method)
    print(groupdf['Azimuth [deg]'][0],len(groupdf['Azimuth [deg]'][0]))
    groupdf['Azimuth [deg]']=groupdf['Azimuth [deg]'].astype(float)  <- I get error here

Example data

   Tilt [deg] Azimuth [deg]  Glass SHGC  Area of Multiplied Openings [m2]  \
0        90.0        124.48        0.57                           1450.24
1        90.0         207.3        0.57                            115.66
2        90.0        207.47        0.57                            115.62
3        90.0        208.25        0.57                             23.18
4        90.0        208.26        0.57                            113.12
5        90.0        214.48        0.57                            451.94
6        90.0        218.57        0.57                            230.08
7        90.0        304.46        0.57                             72.66
8        90.0        304.48        0.57                           1827.53
9        90.0         34.48        0.57                            917.29

Body:
I believe you need to_numeric with parameter errors='coerce' for convert non numeric to NaNs:

groupdf['Azimuth [deg]']= pd.to_numeric(groupdf['Azimuth [deg]'], errors='coerce')

If need remove all columns which are not parseable and no NaNs values in data is possible use boolean indexing and filter by notnull:

groupdf = groupdf[pd.to_numeric(groupdf['Azimuth [deg]'], errors='coerce').notnull()]

In last version of pandas, 0.21.0 is possible use Series.notna:

groupdf = groupdf[pd.to_numeric(groupdf['Azimuth [deg]'], errors='coerce').notna()]


问:
Installing hyperledger indy node code fails on python3 not being default on Mac
I am installing Hyperledger Indy (sovrin) self-identity software per these instructions.

I have Python2.7 installed via Anaconda 3. I also have Python3.6.3 installed that I downloaded and installed from here.

I'm trying to install some other software that has a dependency for Python > 3.5.

I've tried several methods to change my default Python:

Per this SO I set it manual in current terminal window:

alias python='python3'

Per same SO I vi .bash_profile and added:

alias python='python3'

then source ~/.bash_profile

Set a link to Python3:

bc-computer:~ momi$ unlink /usr/local/bin/python2
bc-computer:~ momi$ ln -s /usr/local/bin/python3 /usr/local/bin/python

but still continue to get the same error:

```<code>bc-computer:~ momi$ pip install indy-node-dev
Collecting indy-node-dev
  Using cached indy-node-dev-1.2.227.tar.gz
    Complete output from command python setup.py egg_info:
    FAIL: Requires Python 3.5 or later, but setup.py was run using 2.7.14
    NOTE: Installation failed. Run setup.py using python3

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/3f/sh6dr8wx6w720b1_w38f_fh00000gq/T/pip-build-ecZnYY/indy-node-dev/
</code>```

I also tried setting up a python3 test environment per this:

```<code>python3 setup.py test
</code>```

And got this error:

```<code>> /usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/Resources/Python.app/Contents/MacOS/Python:
> can't open file 'setup.py': [Errno 2] No such file or directory
</code>```

Please note that I tried this suggestion which seems to be the non-duplicate answer but didn't work for me:

The safest way is to set an alias in ~/.bashrc:

alias python=python3

My environment:

```<code>uname -msra
Darwin bc-computer.local 17.2.0 Darwin Kernel Version 17.2.0: Fri Sep 29 18:27:05 PDT 2017; root:xnu-4570.20.62~3/RELEASE_X86_64 x86_64
</code>```

My OS:
High Sierra 10.13.1

```<code>which -a python
/Users/momi/anaconda2/bin/python
/usr/local/bin/python
/usr/bin/python
</code>```

Thank you

答:
Ok the solution was to use pip3 rather than pip for my install command per Mike Mueller's answer here:

```<code>pip3 install indy-node-dev
</code>```

I assume that pip3 points to python3x rather than 2x.

Body:
I am installing Hyperledger Indy (sovrin) self-identity software per these instructions.

I have Python2.7 installed via Anaconda 3. I also have Python3.6.3 installed that I downloaded and installed from here.

I'm trying to install some other software that has a dependency for Python > 3.5.

I've tried several methods to change my default Python:

Per this SO I set it manual in current terminal window:

alias python='python3'

Per same SO I vi .bash_profile and added:

alias python='python3'

then source ~/.bash_profile

Set a link to Python3:

bc-computer:~ momi$ unlink /usr/local/bin/python2
bc-computer:~ momi$ ln -s /usr/local/bin/python3 /usr/local/bin/python

but still continue to get the same error:

bc-computer:~ momi$ pip install indy-node-dev
Collecting indy-node-dev
  Using cached indy-node-dev-1.2.227.tar.gz
    Complete output from command python setup.py egg_info:
    FAIL: Requires Python 3.5 or later, but setup.py was run using 2.7.14
    NOTE: Installation failed. Run setup.py using python3

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/3f/sh6dr8wx6w720b1_w38f_fh00000gq/T/pip-build-ecZnYY/indy-node-dev/

I also tried setting up a python3 test environment per this:

python3 setup.py test

And got this error:

> /usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/Resources/Python.app/Contents/MacOS/Python:
> can't open file 'setup.py': [Errno 2] No such file or directory

Please note that I tried this suggestion which seems to be the non-duplicate answer but didn't work for me:

The safest way is to set an alias in ~/.bashrc:

alias python=python3

My environment:

uname -msra
Darwin bc-computer.local 17.2.0 Darwin Kernel Version 17.2.0: Fri Sep 29 18:27:05 PDT 2017; root:xnu-4570.20.62~3/RELEASE_X86_64 x86_64

My OS:
High Sierra 10.13.1

which -a python
/Users/momi/anaconda2/bin/python
/usr/local/bin/python
/usr/bin/python

Thank you

Body:
Ok the solution was to use pip3 rather than pip for my install command per Mike Mueller's answer here:

pip3 install indy-node-dev

I assume that pip3 points to python3x rather than 2x.


问:
How to avoid external call in JUnit Groovy
Finally I am able to get Groovy class in my Java file and able to perform JUnit on my groovy classes. Now my problem is I want to test my method which triggers RPC calls.but I want to avoid that call in unit test. How should I do that? Below is my sample code for logout how I am proceeding</p>

```<code>@Test
public void logoutTest() {
    GroovyObject loginOject =new Login();
    GroovyObject logoutObject =new Logout();
    XMLRPCServerProxy serverProxy = (XMLRPCServerProxy) loginOject.invokeMethod(
        "getServerProxy",
        "https://urlproxy"
    );
    String sessionId = (String) loginOject.invokeMethod(
        "getSession",
        new Object[]{"username","password",serverProxy}
    );
    logoutObject.invokeMethod("logout",new Object[]{sessionId,serverProxy});
}
</code>```

答:
You can do so by using mocks. I assume you are testing logoutObject.invokeMethod("logout",new Object[]{sessionId,serverProxy}); method which calls a method on your XMLRPCServerProxy serverProxy. If you a have an option to introduce a dependency on mocking framework such as Mockito you can then create a mock instead of

```<code>XMLRPCServerProxy serverProxy = (XMLRPCServerProxy) oginOject.invokeMethod("getServerProxy", "https://urlproxy");
</code>```

You can mock it

```<code>XMLRPCServerProxy serverProxy = mock(XMLRPCServerProxy.class);
when(serverProxy.sendRequest("payload")).thenReturn("result");
</code>```

If you cannot use a mock library you can extend XMLRPCServerProxy in the test and override a method that does rpc call to do whatever you want (this is effectively what Mockito would do for you)

```<code>XMLRPCServerProxy proxyServer = new XMLRPCServerProxy() {
        public String request(String payload) {
            // your mock code
            return "result";
        }
    };
</code>```

Body:
Finally I am able to get Groovy class in my Java file and able to perform JUnit on my groovy classes. Now my problem is I want to test my method which triggers RPC calls.but I want to avoid that call in unit test. How should I do that? Below is my sample code for logout how I am proceeding

@Test
public void logoutTest() {
    GroovyObject loginOject =new Login();
    GroovyObject logoutObject =new Logout();
    XMLRPCServerProxy serverProxy = (XMLRPCServerProxy) loginOject.invokeMethod(
        "getServerProxy",
        "https://urlproxy"
    );
    String sessionId = (String) loginOject.invokeMethod(
        "getSession",
        new Object[]{"username","password",serverProxy}
    );
    logoutObject.invokeMethod("logout",new Object[]{sessionId,serverProxy});
}

Body:
You can do so by using mocks. I assume you are testing logoutObject.invokeMethod("logout",new Object[]{sessionId,serverProxy}); method which calls a method on your XMLRPCServerProxy serverProxy. If you a have an option to introduce a dependency on mocking framework such as Mockito you can then create a mock instead of

XMLRPCServerProxy serverProxy = (XMLRPCServerProxy) oginOject.invokeMethod("getServerProxy", "https://urlproxy");

You can mock it

XMLRPCServerProxy serverProxy = mock(XMLRPCServerProxy.class);
when(serverProxy.sendRequest("payload")).thenReturn("result");

If you cannot use a mock library you can extend XMLRPCServerProxy in the test and override a method that does rpc call to do whatever you want (this is effectively what Mockito would do for you)

XMLRPCServerProxy proxyServer = new XMLRPCServerProxy() {
        public String request(String payload) {
            // your mock code
            return "result";
        }
    };


问:
checking net connection to catch error while mailing in python/flask
I am using python/flask (importing MAIL from flask_mail). Here is a small module of my code.

```<code>token = s.dumps(email, salt='email-confirm')
t = url_for('confirm_email', token=token, _external=True)
msg = Message('Confirm Email', sender='origrosh@gmail.com', recipients=[email], html=render_template('mail.html', text=t))
link = url_for('confirm_email', token=token, _external=True)
msg.body = 'Your link is {}'.format(link)
mail.send(msg)
</code>```

If I run the code when the Internet connection is off, I get a 'socket.gaierror: [Errno -3] Temporary failure in name resolution' error. Can  you please tell me how to catch this exception and display something like "Make sure you are connected to the Internet" or something instead?

```<code>except urllib2.URLError as err:
    return False
</code>```

Some way to catch the exception like the above (where an attempt is made to access a particular URL) would also be helpful. So, what is the alternative to that when you are using MAIL in FLASK instead.

Also, I would be very thankful if you can also provide a more general solution as I may end up having to tackle similar problems (when the Internet is not connected) later.

Thanking you in advance.

答:
I do know how to catch exceptions but not this particular one

Well, just like with any exception actually:

```<code>>>> import socket
>>> try:
...     raise socket.gaierror(3, "wtf")
... except socket.gaierror as e:
...     print "got gaiesocket error %s" % e
...
got gaiesocket error [Errno 3] wtf
</code>```

If you want to special-case errno 3, just test e.errno:

```<code>>>> e
gaierror(3, 'wtf')
>>> e.errno
3
</code>```

Body:
I am using python/flask (importing MAIL from flask_mail). Here is a small module of my code.

token = s.dumps(email, salt='email-confirm')
t = url_for('confirm_email', token=token, _external=True)
msg = Message('Confirm Email', sender='origrosh@gmail.com', recipients=[email], html=render_template('mail.html', text=t))
link = url_for('confirm_email', token=token, _external=True)
msg.body = 'Your link is {}'.format(link)
mail.send(msg)

If I run the code when the Internet connection is off, I get a 'socket.gaierror: [Errno -3] Temporary failure in name resolution' error. Can  you please tell me how to catch this exception and display something like "Make sure you are connected to the Internet" or something instead?

except urllib2.URLError as err:
    return False

Some way to catch the exception like the above (where an attempt is made to access a particular URL) would also be helpful. So, what is the alternative to that when you are using MAIL in FLASK instead.

Also, I would be very thankful if you can also provide a more general solution as I may end up having to tackle similar problems (when the Internet is not connected) later.

Thanking you in advance.

Body:
I do know how to catch exceptions but not this particular one

Well, just like with any exception actually:

>>> import socket
>>> try:
...     raise socket.gaierror(3, "wtf")
... except socket.gaierror as e:
...     print "got gaiesocket error %s" % e
...
got gaiesocket error [Errno 3] wtf

If you want to special-case errno 3, just test e.errno:

>>> e
gaierror(3, 'wtf')
>>> e.errno
3


问:
Combining $("#myId").val() with $(this).val()
I would like to combine

```<code>$("#myId").val()
</code>```

and

```<code>$(this).val()
</code>```

so that I can use the same id and a name value connected to an array -- characters[x].name -- to store and display different names.

http://jsfiddle.net/ren1999/Fae95/

答:
Assuming the layout of input elements is somewhat similar, you could just find the sibling of the input box, and assign the text to it.

```<code>$("#getName1, #getName2").blur(function() {
    var name = $(this).val();
    $(this).siblings('b').text(name);
}).blur();
</code>```

http://jsfiddle.net/Fae95/1/

ContentLicense: CC BY-SA 2.5

Body:
I would like to combine

$("#myId").val()

and

$(this).val()

so that I can use the same id and a name value connected to an array -- characters[x].name -- to store and display different names.

http://jsfiddle.net/ren1999/Fae95/

Body:
Assuming the layout of input elements is somewhat similar, you could just find the sibling of the input box, and assign the text to it.

$("#getName1, #getName2").blur(function() {
    var name = $(this).val();
    $(this).siblings('b').text(name);
}).blur();

http://jsfiddle.net/Fae95/1/


问:
jquery ui: css scaled elements do not work with draggable()

I'm trying to make CSS scaled objects work correct when using the draggable() method in jquery ui.

CSS:

```<code>#container{
  zoom: 2;
  -moz-transform: scale(2);
  width: 200px;
  height: 200px;
  background-color: #888;
}

#box{
  width: 100px;
  height: 100px;
  background-color: blue;
}
</code>```

JS:

```<code>$('#box').draggable();
</code>```

See the example here: https://jsfiddle.net/9zm486xu/1/

In the example above you'll notice that the scale factor affects the dragging behaviour, resulting in e.g. twice the mouse distance when scaling is set to 2.

Is there a way to make CSS scaled objects draggable as the user might expect it (to be always under the mouse)? I can use an approach where I calculate each object to be scaled and then apply it to the DOM, but scaling just the container (see example) would be so much easier.

答:
```<code>$( ".selector" ).draggable({
  drag: function( event, ui ) {

    ui.position.left = ui.position.left / scale
    ui.position.top = ui.position.top / scale
  }
});
</code>```

You can do something like this if you https://jsfiddle.net/9zm486xu/2/

Body:
I'm trying to make CSS scaled objects work correct when using the draggable() method in jquery ui.

CSS:

#container{
  zoom: 2;
  -moz-transform: scale(2);
  width: 200px;
  height: 200px;
  background-color: #888;
}

#box{
  width: 100px;
  height: 100px;
  background-color: blue;
}

JS:

$('#box').draggable();

See the example here: https://jsfiddle.net/9zm486xu/1/

In the example above you'll notice that the scale factor affects the dragging behaviour, resulting in e.g. twice the mouse distance when scaling is set to 2.

Is there a way to make CSS scaled objects draggable as the user might expect it (to be always under the mouse)? I can use an approach where I calculate each object to be scaled and then apply it to the DOM, but scaling just the container (see example) would be so much easier.

Body:
$( ".selector" ).draggable({
  drag: function( event, ui ) {

    ui.position.left = ui.position.left / scale
    ui.position.top = ui.position.top / scale
  }
});

You can do something like this if you https://jsfiddle.net/9zm486xu/2/


问:
How to create CoreData database swift4
Plese share some sample code snippet for database save details and fetch saved details in swift 4</p>

答:
This is my answer

Step 1 : Create Coredata Stack Class see below

var coreDataStack: CoreDataStack = CoreDataStack() // add this line on appDelegate

```<code>    class Stack
    {
    lazy var managedObjectModel: NSManagedObjectModel = {
    let modelUrl = Bundle.main.url(forResource: "Model", withExtension: "momd")!
    return NSManagedObjectModel(contentsOf: modelUrl)!
}()

lazy var peristentStoreCoordinator: NSPersistentStoreCoordinator = {
    let coordinator: NSPersistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
    let applicationDocumentsDirectory: URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last!
    let persistentStoreUrl: URL = applicationDocumentsDirectory.appendingPathComponent("Model.sqlite")

    do {
        try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: persistentStoreUrl, options: nil)
    }
    catch {
        fatalError("Persistent store error! \(error)")
    }

    return coordinator
}()

lazy var managedObjectContext: NSManagedObjectContext = {
    let managedObjectContext: NSManagedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
    managedObjectContext.persistentStoreCoordinator = self.peristentStoreCoordinator

    return managedObjectContext
}()

func saveContext() {
    if self.managedObjectContext.hasChanges {
        do {
            try self.managedObjectContext.save()
            }
            catch {
                fatalError("There was an error saving the managed object context \(error)")
            }
        }
    }
}
</code>```

Step 2 : Create entity
Step 3 : Create ManagedObjectModelSubclass -- Editor -> ManagedObjectModelSubclass
Step 4 : import core data on class and add below code

```<code>    var person = [Person]() //[Person] here denote subclassclass name
    var  appDelegate = UIApplication.shared.delegate as! AppDelegate

    let personEntity: NSEntityDescription? = NSEntityDescription.entity(forEntityName: "EntityName", in: self.appDelegate.coreDataStack.managedObjectContext)

    if personEntity != nil {

        let person1: Person = Person(entity: personEntity!, insertInto: self.appDelegate.coreDataStack.managedObjectContext)
        person1.name = "name"
        person1.country = "US"
        person1.age = "26"
        person1.place = "NewYork"
     }
</code>```

Step 5 : For fetch data use below code

```<code>  var persons: [Person] = [] // subclass name

  var appDelegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate

var listdata = [ModelClass]() // create a modelclass object

  func fetchDemoData() {
    let fetchRequest: NSFetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "EntityName")
    do {
        if let results = try self.appDelegate.coreDataStack.managedObjectContext.fetch(fetchRequest) as? [NSManagedObject] {
            let personList: [Person]? = results as? [Person]
            if personList != nil {
                self.persons = personList!

                for eachData in persons {

                    let name = eachData.name as String!
                    let username = eachData.age as String!
                    let email = eachData.country as String!
                    let address = eachData.place as! [String : Any]

                    self.listdata.append(ModelClass(name: name!, username: username!,email : email!,address : address))
                }

                 //self.tableview.reloadData()

            }

        }
    }
    catch {
        fatalError("There was an error fetching the items")
    }
}
</code>```

Title: How to create CoreData database swift4

Body:
This is my answer

Step 1 : Create Coredata Stack Class see below

var coreDataStack: CoreDataStack = CoreDataStack() // add this line on appDelegate

    class Stack
    {
    lazy var managedObjectModel: NSManagedObjectModel = {
    let modelUrl = Bundle.main.url(forResource: "Model", withExtension: "momd")!
    return NSManagedObjectModel(contentsOf: modelUrl)!
}()

lazy var peristentStoreCoordinator: NSPersistentStoreCoordinator = {
    let coordinator: NSPersistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
    let applicationDocumentsDirectory: URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last!
    let persistentStoreUrl: URL = applicationDocumentsDirectory.appendingPathComponent("Model.sqlite")

    do {
        try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: persistentStoreUrl, options: nil)
    }
    catch {
        fatalError("Persistent store error! \(error)")
    }

    return coordinator
}()

lazy var managedObjectContext: NSManagedObjectContext = {
    let managedObjectContext: NSManagedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
    managedObjectContext.persistentStoreCoordinator = self.peristentStoreCoordinator

    return managedObjectContext
}()

func saveContext() {
    if self.managedObjectContext.hasChanges {
        do {
            try self.managedObjectContext.save()
            }
            catch {
                fatalError("There was an error saving the managed object context \(error)")
            }
        }
    }
}

Step 2 : Create entity
Step 3 : Create ManagedObjectModelSubclass -- Editor -> ManagedObjectModelSubclass
Step 4 : import core data on class and add below code

    var person = [Person]() //[Person] here denote subclassclass name
    var  appDelegate = UIApplication.shared.delegate as! AppDelegate

    let personEntity: NSEntityDescription? = NSEntityDescription.entity(forEntityName: "EntityName", in: self.appDelegate.coreDataStack.managedObjectContext)

    if personEntity != nil {

        let person1: Person = Person(entity: personEntity!, insertInto: self.appDelegate.coreDataStack.managedObjectContext)
        person1.name = "name"
        person1.country = "US"
        person1.age = "26"
        person1.place = "NewYork"
     }

Step 5 : For fetch data use below code

  var persons: [Person] = [] // subclass name

  var appDelegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate

var listdata = [ModelClass]() // create a modelclass object

  func fetchDemoData() {
    let fetchRequest: NSFetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "EntityName")
    do {
        if let results = try self.appDelegate.coreDataStack.managedObjectContext.fetch(fetchRequest) as? [NSManagedObject] {
            let personList: [Person]? = results as? [Person]
            if personList != nil {
                self.persons = personList!

                for eachData in persons {

                    let name = eachData.name as String!
                    let username = eachData.age as String!
                    let email = eachData.country as String!
                    let address = eachData.place as! [String : Any]

                    self.listdata.append(ModelClass(name: name!, username: username!,email : email!,address : address))
                }

                 //self.tableview.reloadData()

            }

        }
    }
    catch {
        fatalError("There was an error fetching the items")
    }
}


问:
Multiple GridLayouts, each one contains TextView with same ID, retrieve only this inside specific GridLayout
I got 16 GridLayouts and inside them I got one TextView with same ID for each GridLayout. I want to find only this TextView which is inside of gridLayout1 or gridLayout2 etc. Is that possible?

```<code>switch (view.getId()) {
            case R.id.gridLayout1:
findViewById(R.id.textView)
case R.id.gridLayout2:
findViewById(R.id.textView)
....
case R.id.gridLayout16:
findViewById(R.id.textView)
</code>```

答:
If you perform findViewById on the specific GridLayout, you should be able to find that specific TextView.
Try this code:

```<code>switch (view.getId()) {
    case R.id.gridLayout1:
      view.findViewById(R.id.textView);
      break;
   case R.id.gridLayout2:
      view.findViewById(R.id.textView);
      break;
   ....
   case R.id.gridLayout16:
      view.findViewById(R.id.textView);
      break;
</code>```

But notice that actually you don't need this switch statement.

Body:
I got 16 GridLayouts and inside them I got one TextView with same ID for each GridLayout. I want to find only this TextView which is inside of gridLayout1 or gridLayout2 etc. Is that possible?

switch (view.getId()) {
            case R.id.gridLayout1:
findViewById(R.id.textView)
case R.id.gridLayout2:
findViewById(R.id.textView)
....
case R.id.gridLayout16:
findViewById(R.id.textView)

Body:
If you perform findViewById on the specific GridLayout, you should be able to find that specific TextView.
Try this code:

switch (view.getId()) {
    case R.id.gridLayout1:
      view.findViewById(R.id.textView);
      break;
   case R.id.gridLayout2:
      view.findViewById(R.id.textView);
      break;
   ....
   case R.id.gridLayout16:
      view.findViewById(R.id.textView);
      break;

But notice that actually you don't need this switch statement.


问:
Java url parsing
Okay so I'm trying to parse the url and extract partial data.. However it doesn't seem to be extracting the exact data I want.. I assume it's extracting ID and not Value.

This is the code I'm using

```<code>            price = readUrl(apiUrl + String.valueOf(id)).split(",")[1].split(":")[1];
            String price2 = price.substring(0, price.length() - 1);
            return Integer.parseInt(price2);
</code>```

the url I'm using is

```<code>https://api.rsbuddy.com/grandExchange?a=guidePrice&i=
</code>```

parameter i = id of item, for this example we will use " 2619 "

which returns,

```<code>{"overall":49907,"buying":0,"buyingQuantity":0,"selling":49907,"sellingQuantity":2}
</code>```

the information I want is

```<code>49907
</code>```

from

```<code>{"overall":49907,
</code>```

答:
Use JSONObject:

```<code>  JSONObject jsonObject = new JSONObject(YOUR_STRING_YOU_WANT_TO_PARSE);
  Integer price = jsonObject.getInt("overall");
</code>```

Title: Java url parsing

Body:
Okay so I'm trying to parse the url and extract partial data.. However it doesn't seem to be extracting the exact data I want.. I assume it's extracting ID and not Value.

This is the code I'm using

            price = readUrl(apiUrl + String.valueOf(id)).split(",")[1].split(":")[1];
            String price2 = price.substring(0, price.length() - 1);
            return Integer.parseInt(price2);

the url I'm using is

https://api.rsbuddy.com/grandExchange?a=guidePrice&i=

parameter i = id of item, for this example we will use " 2619 "

which returns,

{"overall":49907,"buying":0,"buyingQuantity":0,"selling":49907,"sellingQuantity":2}

the information I want is

49907

from

{"overall":49907,

Body:
Use JSONObject:

  JSONObject jsonObject = new JSONObject(YOUR_STRING_YOU_WANT_TO_PARSE);
  Integer price = jsonObject.getInt("overall");


问:
about basic file organization
in file testmodule.ml

```<code>module TestModule =
struct
  type my_type = MyType1 | MyType2
end
</code>```

How can I use TestModule in top-level?

after "ocamlc -c testmodule.ml" (this generated testmodule.cmo/cmi)

I tried "open TestModule", but error "unbound module TestModule" occured.

```<code>        Objective Caml version 3.10.0

# open TestModule;;
Unbound module TestModule
</code>```

then, I tried making top-level with that module. but...

```<code>indi@www:~/std/toq$ ocamlmktop -o mytop testmodule.ml
indi@www:~/std/toq$ ./mytop
        Objective Caml version 3.10.0

# TestModule.MyType1;;
Unbound constructor TestModule.MyType1
# open TestModule;;
Unbound module TestModule
</code>```

What can I do for using my TestModule???

答:
Tu summarize: a few minor details all conspired together against you :-)

First, as mentioned previously, you need to load the code into the toplevel with either #use "testmodule.ml";; for source files or #load "testmodule.cmo";; for compiled files, or to use ocamlmktop. This explains why your first attempt did not work: you did not load the code.

Second, you defined module TestModule in a file called testmodule.ml. Keep in mind that the file defines its own module based on its name. So, in order to access your module, you need to write Testmodule.TestModule. This explains why your second attempt did not work: the code was loaded but had an unexpected name.

You might wish to remove the TestModule definition and rename the file to testModule.ml (or the perhaps more idiomatic test_module.ml).

Title: about basic file organization

Body:
in file testmodule.ml

module TestModule =
struct
  type my_type = MyType1 | MyType2
end

How can I use TestModule in top-level?

after "ocamlc -c testmodule.ml" (this generated testmodule.cmo/cmi)

I tried "open TestModule", but error "unbound module TestModule" occured.

        Objective Caml version 3.10.0

# open TestModule;;
Unbound module TestModule

then, I tried making top-level with that module. but...

indi@www:~/std/toq$ ocamlmktop -o mytop testmodule.ml
indi@www:~/std/toq$ ./mytop
        Objective Caml version 3.10.0

# TestModule.MyType1;;
Unbound constructor TestModule.MyType1
# open TestModule;;
Unbound module TestModule

What can I do for using my TestModule???


问:
XML Rename node name and convert datetime to date
I have an xml file I want to both rename the  element name and return the date part of the date only to produce

```<code><!-- reference the stylesheet -->
<?xml-stylesheet type="text/xsl" href="Dates.xsl"?>
<user>
<dob>1992-02-22T00:00:00.0000000</dob>
</user>
</code>```

I want to both rename the  element name and return the date part of the date only to produce

```<code><!-- reference the stylesheet -->
<?xml-stylesheet type="text/xsl" href="Dates.xsl"?>
<user>
<USER_DOB>1992-02-22</USER_DOB>
</user>
</code>```

In my XSL file
To change the element name this works

```<code>  <xsl:template match="dob">
    <USER_DOB><xsl:apply-templates select="node()"/></USER_DOB>
  </xsl:template>
</code>```

To change the date this works

```<code><xsl:template match="dob">
    <xsl:copy>
        <xsl:call-template name="FormatDate">
            <xsl:with-param name="DateTime" select="."/>
        </xsl:call-template>
    </xsl:copy>
</xsl:template>
<xsl:template name="FormatDate">

        <xsl:param name="DateTime" />
        <xsl:variable name="date">
                <xsl:value-of select="substring-before($DateTime,'T')" />
        </xsl:variable>

        <xsl:if test="string-length($date) != 10">
                <xsl:value-of select="$DateTime"/>
        </xsl:if>
        <xsl:if test="string-length($date) = 10">
                <xsl:value-of select="$date"/>
        </xsl:if>
</xsl:template>
</code>```

I need to know how to combine both changes to produce the single output element with the renamed node and the formatted date
Thanks,
Brevan

答:
Simply have one template matching dob that does this...

```<code><xsl:template match="dob">
    <USER_DOB>
        <xsl:call-template name="FormatDate">
            <xsl:with-param name="DateTime" select="."/>
        </xsl:call-template>
    </USER_DOB>
</xsl:template>
</code>```

Body:
I have an xml file I want to both rename the  element name and return the date part of the date only to produce

<?xml-stylesheet type="text/xsl" href="Dates.xsl"?>
<user>
<dob>1992-02-22T00:00:00.0000000</dob>
</user>

I want to both rename the  element name and return the date part of the date only to produce

<?xml-stylesheet type="text/xsl" href="Dates.xsl"?>
<user>
<USER_DOB>1992-02-22</USER_DOB>
</user>

In my XSL file
To change the element name this works

  <xsl:template match="dob">
    <USER_DOB><xsl:apply-templates select="node()"/></USER_DOB>
  </xsl:template>

To change the date this works

<xsl:template match="dob">
    <xsl:copy>
        <xsl:call-template name="FormatDate">
            <xsl:with-param name="DateTime" select="."/>
        </xsl:call-template>
    </xsl:copy>
</xsl:template>
<xsl:template name="FormatDate">

        <xsl:param name="DateTime" />
        <xsl:variable name="date">
                <xsl:value-of select="substring-before($DateTime,'T')" />
        </xsl:variable>

        <xsl:if test="string-length($date) != 10">
                <xsl:value-of select="$DateTime"/>
        </xsl:if>
        <xsl:if test="string-length($date) = 10">
                <xsl:value-of select="$date"/>
        </xsl:if>
</xsl:template>

I need to know how to combine both changes to produce the single output element with the renamed node and the formatted date
Thanks,
Brevan

Body:
Simply have one template matching dob that does this...

<xsl:template match="dob">
    <USER_DOB>
        <xsl:call-template name="FormatDate">
            <xsl:with-param name="DateTime" select="."/>
        </xsl:call-template>
    </USER_DOB>
</xsl:template>


问:
Python. Change list
I am trying to create a program that will figure out a number that the user thinks of.

```<code>nums=list(range(1,11))

def remove_odd(l):
    return [n for n in l if n % 2 == 0]

y=str(input('Is it an even number?'))
if y=='yes':
    (remove_odd(nums))

print(nums)
</code>```

I get this output:

```<code>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
</code>```

But I want to get:

```<code>[2, 4, 6, 8, 10]
</code>```

What am I doing wrong?

答:
You do not change anything on your list. Change your code to:</p>

```<code>if y=='yes':
    nums = remove_odd(nums)
</code>```

Title: Python. Change list

Body:
I am trying to create a program that will figure out a number that the user thinks of.

nums=list(range(1,11))

def remove_odd(l):
    return [n for n in l if n % 2 == 0]

y=str(input('Is it an even number?'))
if y=='yes':
    (remove_odd(nums))

print(nums)

I get this output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

But I want to get:

[2, 4, 6, 8, 10]

What am I doing wrong?

Body:
You do not change anything on your list. Change your code to:

if y=='yes':
    nums = remove_odd(nums)


问:
How to read Unicode XML values with rapidxml
RapidXML is one of the available libraries for parsing XML in c++. For getting the values, we can use something like:

```<code>node->first_node("xmlnode")->value()
</code>```

This command returns a char* data type. Is there any way to read the value as Unicode so I can assign it in a WCHAR or wstring variable?

答:
here you need convert str to wstr.
you can use for this standart std

```<code>#include <string>
#include <codecvt>
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;

std::string strSample; // convert str to wstr
std::wstring wstrValue = converter.from_bytes(strSample);

std::wstring wstrSample; // convert wstr to str
std::string strValue = converter.to_bytes(wstrSample);
</code>```

hope this help

Body:
RapidXML is one of the available libraries for parsing XML in c++. For getting the values, we can use something like:

node->first_node("xmlnode")->value()

This command returns a char* data type. Is there any way to read the value as Unicode so I can assign it in a WCHAR or wstring variable?

Body:
here you need convert str to wstr.
you can use for this standart std

#include <string>
#include <codecvt>
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;

std::string strSample; // convert str to wstr
std::wstring wstrValue = converter.from_bytes(strSample);

std::wstring wstrSample; // convert wstr to str
std::string strValue = converter.to_bytes(wstrSample);

hope this help


问:
C# interface breakage, ABI
Suppose we have the class X in version 1 of the assembly A.dll:

```<code>class X {
    SomeType Property { set; get; }
}
</code>```

and then in version 2 of the assembly A.dll:

```<code>class X {
    SomeType Property { set; get; }
    SomeType OtherProperty { set; get; }
}
</code>```

Now suppose we have a second assembly B.dll that loads A.dll and uses X. Will the addition of the property OtherProperty break the ABI? Will B.dll fail to use A.dll/X? If not, would the order of the declarations make any difference? If the properties had been virtual, had it made any difference?

I guess I'm really asking: what are the general ABI rules? I know changing interfaces after they have been published is a bad thing, but I really would like to be able to add properties in some instances, without adding subclasses.

答:
The JIT compiler will spackle a lot of this over, also the source of the error message if the change was breaking.

You are however playing a very dangerous game called DLL Hell.  The problem is not that they don't recompile their code, it is when they do.  They will, eventually.  If then there's a subtle mistake, somebody ran an old version of your installer, copied the wrong file, etcetera then all hell breaks loose.  The code won't run and they'll have an impossible job figuring out why.  This will happen long after you made the change, you won't have any way to guess what went wrong either and cannot help them.

Don't mess around with this, bump up [AssemblyFileVersion] and [AssemblyVersion].  Yes, they'll have to recompile when you change the latter one.  Or use <bindingRedirect>, which is fine too, now there's a traceable record of it.

Btw: this happened in the .NET Framework too.  WaitHandle.WaitOne(int) got added in a service pack but without an [AssemblyVersion] change.  Programmers targeted .NET 2.0 but their code wouldn't run when the target machine had the original 2.0 installed.  Very painful.

Title: C# interface breakage, ABI

Body:
Suppose we have the class X in version 1 of the assembly A.dll:

class X {
    SomeType Property { set; get; }
}

and then in version 2 of the assembly A.dll:

class X {
    SomeType Property { set; get; }
    SomeType OtherProperty { set; get; }
}

Now suppose we have a second assembly B.dll that loads A.dll and uses X. Will the addition of the property OtherProperty break the ABI? Will B.dll fail to use A.dll/X? If not, would the order of the declarations make any difference? If the properties had been virtual, had it made any difference?

I guess I'm really asking: what are the general ABI rules? I know changing interfaces after they have been published is a bad thing, but I really would like to be able to add properties in some instances, without adding subclasses.


答:
What you get from API is a JSON. So you can simply use JSONObject.
https://docs.oracle.com/javaee/7/api/javax/json/JsonObject.html

You can do something like:

```<code>    jsonObject.getInt("overall");
</code>```

Title: Java url parsing

Body:
What you get from API is a JSON. So you can simply use JSONObject.
https://docs.oracle.com/javaee/7/api/javax/json/JsonObject.html

You can do something like:

    jsonObject.getInt("overall");


答:
If you want to get the textview inside gridLayout1 just use</p>

```<code>gridLayout1.findViewById(R.id.textview);
</code>```

Title: Multiple GridLayouts, each one contains TextView with same ID, retrieve only this inside specific GridLayout

Body:
If you want to get the textview inside gridLayout1 just use

gridLayout1.findViewById(R.id.textview);


问:
Safely convert SIZE_T to WORD
In my C code, I want to convert SIZE_T WINAPI type, in either 32/64 bit system to a WORD WINAPI type.

```<code>#include <Windows.h>
SIZE_T nValueToConvert;
WORD wConvertedValue;
</code>```

In case that nValueToConvert is too big for WORD type I want to know abot it and raise an error. What is the best and safest way to do that?

答:
exist many ways do this. for example we can use next code:

```<code>if ((wConvertedValue = (WORD)nValueToConvert) == nValueToConvert)
{
    DbgPrint("convert ok\n");
}
else
{
    DbgPrint("too big for WORD\n");
}
</code>```

however this is valid only for unsigned types - both SIZE_T and WORD is unsigned. if work with signed types, say SSIZE_T nValueToConvert and SHORT wConvertedValue, task become more complex, separate signed bit create problems here. i think try truncate and check can be done next way:

```<code>BOOL Truncate(SSIZE_T nValueToConvert, SHORT* pwConvertedValue)
{
    SHORT wConvertedValue;

    if (0 > nValueToConvert)
    {
        wConvertedValue = -(wConvertedValue = ((SHORT)-nValueToConvert));
    }
    else
    {
        wConvertedValue = (SHORT)nValueToConvert;
    }

    *pwConvertedValue = wConvertedValue;

    return wConvertedValue == nValueToConvert;
}
</code>```

Truncate return true when SSIZE_T nValueToConvert in range [-0x8000, 0x7FFF], otherwise false

Title: Safely convert SIZE_T to WORD

Body:
In my C code, I want to convert SIZE_T WINAPI type, in either 32/64 bit system to a WORD WINAPI type.

#include <Windows.h>
SIZE_T nValueToConvert;
WORD wConvertedValue;

In case that nValueToConvert is too big for WORD type I want to know abot it and raise an error. What is the best and safest way to do that?

Body:
exist many ways do this. for example we can use next code:

if ((wConvertedValue = (WORD)nValueToConvert) == nValueToConvert)
{
    DbgPrint("convert ok\n");
}
else
{
    DbgPrint("too big for WORD\n");
}

however this is valid only for unsigned types - both SIZE_T and WORD is unsigned. if work with signed types, say SSIZE_T nValueToConvert and SHORT wConvertedValue, task become more complex, separate signed bit create problems here. i think try truncate and check can be done next way:

BOOL Truncate(SSIZE_T nValueToConvert, SHORT* pwConvertedValue)
{
    SHORT wConvertedValue;

    if (0 > nValueToConvert)
    {
        wConvertedValue = -(wConvertedValue = ((SHORT)-nValueToConvert));
    }
    else
    {
        wConvertedValue = (SHORT)nValueToConvert;
    }

    *pwConvertedValue = wConvertedValue;

    return wConvertedValue == nValueToConvert;
}

Truncate return true when SSIZE_T nValueToConvert in range [-0x8000, 0x7FFF], otherwise false


问:
Bootstrap accordion in Wordpress
I'm trying to get Bootstrap's accordion to work in Wordpress, but I'm not sure what else I have to add in the loop. At the moment, its expanding the first panel only no matter which one I click, and not displaying any content.

```<code>       <div class="panel-group" id="accordian" role="tablist" aria-multiselectable="true">

            <?php
                $args = array(
                    'post_type'         => 'faq_question',
                    'category_name'     => 'order',
                    'posts_per_page'    => -1
                );
                $loop = new WP_Query( $args );
                while ( $loop->have_posts() ) : $loop->the_post();
            ?>

            <div class="panel panel-default">
                <div class="panel-heading" role="tab" id="<?php the_ID(); ?>">
                    <h4 class="panel-title">
                        <a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordian" href="#collapseOne" aria-expanded="false" aria-controls="collapseOne"><?php the_title();?></a>
                    </h4>
                </div><!-- end panel heading -->
                <div id="collapseOne" class="panel-collapse collapse" role="tabpanel" aria-labelledby="<?php the_ID(); ?>">
                    <div class="panel-body">
                        <p><?php the_content(); ?></p>
                    </div><!-- end panel body -->
                </div><!-- end panel collapse -->
            </div><!-- end panel default -->
            <?php endwhile; wp_reset_query(); ?>
        </div><!-- end panel group -->
</code>```

Appreciate any help, thanks.

答:
Code for Bootstrap 4 with area Closed               </p>

```<code><!-- Accordion Collapse Bootstrap 4 -->
            <div id="accordion" role="tablist" aria-multiselectable="true">
                <?php
                    $args = array(
                        'post_type' => 'question',
                        'posts_per_page' => -1
                    );
                    $loop = new WP_Query( $args );
                    while ( $loop->have_posts() ) : $loop->the_post();
                ?>
                <div class="card">
                    <div class="card-header" role="tab" id="<?php the_ID(); ?>">
                      <h5 class="mb-0">
                        <a data-toggle="collapse" data-parent="#accordion" href="#collapse<?php the_ID(); ?>" aria-expanded="false" aria-controls="collapseOne">
                          <?php the_Title(); ?>
                        </a>
                      </h5>
                    </div>
                     <div id="collapse<?php the_ID(); ?>" class="collapse" role="tabpanel" aria-labelledby="heading<?php the_ID(); ?>">
                      <div class="card-block">
                        <?php the_Content(); ?>
                      </div>
                    </div>
                        <?php endwhile; wp_reset_query(); ?>
                </div>
            </div>

            <!-- Accordion Collapse Bootstrap 4 -->
</code>```

Title: Bootstrap accordion in Wordpress

Body:
I'm trying to get Bootstrap's accordion to work in Wordpress, but I'm not sure what else I have to add in the loop. At the moment, its expanding the first panel only no matter which one I click, and not displaying any content.

            <?php
                $args = array(
                    'post_type'         => 'faq_question',
                    'category_name'     => 'order',
                    'posts_per_page'    => -1
                );
                $loop = new WP_Query( $args );
                while ( $loop->have_posts() ) : $loop->the_post();
            ?>

                <div class="panel-heading" role="tab" id="<?php the_ID(); ?>">

                        <?php the_title();?>

                <div id="collapseOne" class="panel-collapse collapse" role="tabpanel" aria-labelledby="<?php the_ID(); ?>">

<?php the_content(); ?>

            <?php endwhile; wp_reset_query(); ?>

Appreciate any help, thanks.

Body:
Code for Bootstrap 4 with area Closed

<!-- Accordion Collapse Bootstrap 4 -->
            <div id="accordion" role="tablist" aria-multiselectable="true">
                <?php
                    $args = array(
                        'post_type' => 'question',
                        'posts_per_page' => -1
                    );
                    $loop = new WP_Query( $args );
                    while ( $loop->have_posts() ) : $loop->the_post();
                ?>
                <div class="card">
                    <div class="card-header" role="tab" id="<?php the_ID(); ?>">
                      <h5 class="mb-0">
                        <a data-toggle="collapse" data-parent="#accordion" href="#collapse<?php the_ID(); ?>" aria-expanded="false" aria-controls="collapseOne">
                          <?php the_Title(); ?>
                        </a>
                      </h5>
                    </div>
                     <div id="collapse<?php the_ID(); ?>" class="collapse" role="tabpanel" aria-labelledby="heading<?php the_ID(); ?>">
                      <div class="card-block">
                        <?php the_Content(); ?>
                      </div>
                    </div>
                        <?php endwhile; wp_reset_query(); ?>
                </div>
            </div>

            <!-- Accordion Collapse Bootstrap 4 -->


问:
Email and phone Number Validation in android
I have a registration form in my application which I am trying to validate. I'm facing some problems with my validation while validating the phone number and email fields.

Here is my code:

```<code>private boolean validate() {

    String MobilePattern = "[0-9]{10}";
    //String email1 = email.getText().toString().trim();
    String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+";

    if (name.length() > 25) {

        Toast.makeText(getApplicationContext(), "pls enter less the 25 character in user name", Toast.LENGTH_SHORT).show();
        return true;

    } else if (name.length() == 0 || number.length() == 0 || email.length() ==
             0 || subject.length() == 0 || message.length() == 0) {

        Toast.makeText(getApplicationContext(), "pls fill the empty fields", Toast.LENGTH_SHORT).show();
        return false;

    } else if (email.getText().toString().matches(emailPattern)) {

        //Toast.makeText(getApplicationContext(),"valid email address",Toast.LENGTH_SHORT).show();
        return true;

    } else if(!email.getText().toString().matches(emailPattern)) {

        Toast.makeText(getApplicationContext(),"Please Enter Valid Email Address",Toast.LENGTH_SHORT).show();
        return false;

    } else if(number.getText().toString().matches(MobilePattern)) {

        Toast.makeText(getApplicationContext(), "phone number is valid", Toast.LENGTH_SHORT).show();
        return true;

    } else if(!number.getText().toString().matches(MobilePattern)) {

        Toast.makeText(getApplicationContext(), "Please enter valid 10 digit phone number", Toast.LENGTH_SHORT).show();
        return false;
    }

    return false;
}
</code>```

I have used this code above for the validation. The problem I'm facing is in the phone number and email validation, only one validation is working. For example, if I comment out the phone number validation, the email validation is working properly. If I comment out the email validation, the phone number validation is working. If use both validations, it's not working.

答:
```<code>public boolean checkForEmail() {
        Context c;
        EditText mEtEmail=(EditText)findViewById(R.id.etEmail);
        String mStrEmail = mEtEmail.getText().toString();
        if (android.util.Patterns.EMAIL_ADDRESS.matcher(mStrEmail).matches()) {
            return true;
        }
        Toast.makeText(this,"Email is not valid", Toast.LENGTH_LONG).show();
        return false;
    }

    public boolean checkForMobile() {
        Context c;
        EditText mEtMobile=(EditText)findViewById(R.id.etMobile);
        String mStrMobile = mEtMobile.getText().toString();
        if (android.util.Patterns.PHONE.matcher(mStrMobile).matches()) {
            return true;
        }
        Toast.makeText(this,"Phone No is not valid", Toast.LENGTH_LONG).show();
        return false;
    }
</code>```

Body:
I have a registration form in my application which I am trying to validate. I'm facing some problems with my validation while validating the phone number and email fields.

Here is my code:

private boolean validate() {

    String MobilePattern = "[0-9]{10}";
    //String email1 = email.getText().toString().trim();
    String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+";

    if (name.length() > 25) {

        Toast.makeText(getApplicationContext(), "pls enter less the 25 character in user name", Toast.LENGTH_SHORT).show();
        return true;

    } else if (name.length() == 0 || number.length() == 0 || email.length() ==
             0 || subject.length() == 0 || message.length() == 0) {

        Toast.makeText(getApplicationContext(), "pls fill the empty fields", Toast.LENGTH_SHORT).show();
        return false;

    } else if (email.getText().toString().matches(emailPattern)) {

        //Toast.makeText(getApplicationContext(),"valid email address",Toast.LENGTH_SHORT).show();
        return true;

    } else if(!email.getText().toString().matches(emailPattern)) {

        Toast.makeText(getApplicationContext(),"Please Enter Valid Email Address",Toast.LENGTH_SHORT).show();
        return false;

    } else if(number.getText().toString().matches(MobilePattern)) {

        Toast.makeText(getApplicationContext(), "phone number is valid", Toast.LENGTH_SHORT).show();
        return true;

    } else if(!number.getText().toString().matches(MobilePattern)) {

        Toast.makeText(getApplicationContext(), "Please enter valid 10 digit phone number", Toast.LENGTH_SHORT).show();
        return false;
    }

    return false;
}

I have used this code above for the validation. The problem I'm facing is in the phone number and email validation, only one validation is working. For example, if I comment out the phone number validation, the email validation is working properly. If I comment out the email validation, the phone number validation is working. If use both validations, it's not working.


问:
How to find maximum value in a list of arrays
I have a very large list of arrays that looks something like this:

```<code>'apples': array([1,2,3,4]), 'pears': array([1,2,10,11]),'oranges': array([1,10,10,3])
</code>```

I want to find the maximum value out of all the arrays. In my short example above it would be 11.

I am struggling to write something that would give me the maximum value for all arrays in the list. Any thoughts would be welcome.

答:
If your data is in a dictionary variable d, then give this a try

```<code>l=[max(d[key]) for key in d.keys()]
print max(l)
</code>```

Or you can use a one liner

```<code>print max([max(d[key]) for key in d.keys()])
</code>```

Body:
I have a very large list of arrays that looks something like this:

'apples': array([1,2,3,4]), 'pears': array([1,2,10,11]),'oranges': array([1,10,10,3])

I want to find the maximum value out of all the arrays. In my short example above it would be 11.

I am struggling to write something that would give me the maximum value for all arrays in the list. Any thoughts would be welcome.

Body:
If your data is in a dictionary variable d, then give this a try

l=[max(d[key]) for key in d.keys()]
print max(l)

Or you can use a one liner

print max([max(d[key]) for key in d.keys()])


问:
Row item of recycle view in Constraint layout collapse instead taking parent width
Recently, I started using Constraint layout but today encountered very strange behaviour using it. When I am using RelativeLayout as root instead of ConstraintLayout in fragment_holiday.xml output is as expected but I want to know what is wrong with ConstraintLayout. My code is as follows for fragment,item_row

And I am getting output with constraint layout as(And on scrolling it is showing different beheviour as you can see in screenshot I am sharing) ---

fragment_holiday.xml

```<code>    <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.thepsi.psidashboard.Fragments.HolidayFragment">

    <com.thepsi.psidashboard.CustomViews.CustomDatePicker
        android:id="@+id/customDatePicker_holiday"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:dateFormat="MONTH_YEAR"/>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycle_view_holiday"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/general_margin_eight_dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/customDatePicker_holiday" />
</android.support.constraint.ConstraintLayout>
</code>```

item_holiday.xml

```<code>    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/textView25"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:text="24 - January - 2017"
        android:textColor="@color/colorPrimaryDark"
         />

    <TextView
        android:id="@+id/textView26"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:text="Saturday"
        android:layout_alignParentEnd="true"
        android:textColor="@color/colorPrimaryDark"
        />

    <TextView
        android:id="@+id/textView27"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorAccent"
        android:text="Mahavir Jayanti"
        android:textAlignment="center"
        android:textColor="@android:color/black"
        android:layout_below="@+id/textView25"
        />
</RelativeLayout>
</code>```

Expected Design -

Can someone tell me what I am missing here?

答:
Try this...

Change the width of recyclerview as matchparent

Yeah! as per the documentation the widget in ConstraintLayout doesn't support matchparent as width.

We have to assign the width as 0dp and use constraintStart_toStartOf="parent" and constraintEnd_toEndOf="parent" to reflect matchparent like you used.

But the solution I gave will work on some cases as you have.

Body:
Recently, I started using Constraint layout but today encountered very strange behaviour using it. When I am using RelativeLayout as root instead of ConstraintLayout in fragment_holiday.xml output is as expected but I want to know what is wrong with ConstraintLayout. My code is as follows for fragment,item_row

And I am getting output with constraint layout as(And on scrolling it is showing different beheviour as you can see in screenshot I am sharing) ---

fragment_holiday.xml

    <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.thepsi.psidashboard.Fragments.HolidayFragment">

    <com.thepsi.psidashboard.CustomViews.CustomDatePicker
        android:id="@+id/customDatePicker_holiday"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:dateFormat="MONTH_YEAR"/>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycle_view_holiday"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/general_margin_eight_dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/customDatePicker_holiday" />
</android.support.constraint.ConstraintLayout>

item_holiday.xml

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/textView25"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:text="24 - January - 2017"
        android:textColor="@color/colorPrimaryDark"
         />

    <TextView
        android:id="@+id/textView26"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:text="Saturday"
        android:layout_alignParentEnd="true"
        android:textColor="@color/colorPrimaryDark"
        />

    <TextView
        android:id="@+id/textView27"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorAccent"
        android:text="Mahavir Jayanti"
        android:textAlignment="center"
        android:textColor="@android:color/black"
        android:layout_below="@+id/textView25"
        />
</RelativeLayout>

Expected Design -

Can someone tell me what I am missing here?