问:
Android Studio can't find resource and resource linking failed
Recently I had problems with AAPT2. The problems were caused by my username that contained non-ascii characters. I created another Windows account(without non-ascii characters) and installed Android Studio on it. Then I opened my older project and when AS asked me to update I agreed to that. Now when I try to build my app I get these errors:

Android resource linking failed
  D:\Android_Studio\Praca\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values-v28\values-v28.xml:7: error: resource android:attr/dialogCornerRadius not found.
  D:\Android_Studio\Praca\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values-v28\values-v28.xml:11: error: resource android:attr/dialogCornerRadius not found.
  D:\Android_Studio\Praca\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml:2970: error: resource android:attr/fontVariationSettings not found.
  D:\Android_Studio\Praca\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml:2971: error: resource android:attr/ttcIndex not found.
  error: failed linking references.

Most of threads I found of StackOverflow suggest that this problem might be related to support library, they say that version of it might be wrong. How could I change the version? My project also uses OpenCV library and configuration of it might be invalid.
What I tried already was cleaning and rebuilding project and adjusting compileSDKVersion in Gradle.

Here is values-v28.xml file

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="Base.Theme.AppCompat" parent="Base.V28.Theme.AppCompat"/>
<style name="Base.Theme.AppCompat.Light" parent="Base.V28.Theme.AppCompat.Light"/>
<style name="Base.V28.Theme.AppCompat" parent="Base.V26.Theme.AppCompat">
    <!-- We can use the platform styles on API 28+ -->
    <item name="dialogCornerRadius">?android:attr/dialogCornerRadius</item>
</style>
<style name="Base.V28.Theme.AppCompat.Light" parent="Base.V26.Theme.AppCompat.Light">
    <!-- We can use the platform styles on API 28+ -->
    <item name="dialogCornerRadius">?android:attr/dialogCornerRadius</item>
</style>
</code>```

And here is Manifest:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.kawa.praca">

<uses-feature
    android:name="android.hardware.camera"
    android:required="true" />

<uses-permission
    android:name="android.permission.WRITE_EXTERNAL_STORAGE"
    android:maxSdkVersion="18" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".Powitanie">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".Trening" />
    <activity android:name=".Zdjecia" />

    <provider
        android:name=".DbProvider"
        android:authorities="com.example.kawa.praca"
        android:exported="true" />
    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="com.example.android.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths" />
    </provider>

    <activity android:name=".AddActivity" />
    <activity android:name=".UserPanel" />
    <activity android:name=".ScoringPanel" />
    <activity android:name=".Scoring" />
    <activity android:name=".NewPlanActivity" />

    <receiver
        android:name=".PlanReceiver"
        android:enabled="true"
        android:exported="true" />

    <activity android:name=".ChartsActivity"></activity>
</application>

</manifest>
</code>```

Also below is my build.gradle file app module. In this file in sub-clause 'dependencies' entries with support library are underlined and AS shows me a warning:

All com.android.support libraries must use the exact same version specification (mixing versions can lead to runtime crashes). Found versions 28.0.0, 26.1.0. Examples include com.android.support:animated-vector-drawable:28.0.0 and com.android.support:customtabs:26.1.0

I tried changing versions to newer or older but this warning still appears.

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

android {
compileSdkVersion 26
defaultConfig {
    applicationId "com.example.kawa.praca"
    minSdkVersion 24
    targetSdkVersion 26

    versionCode 1
    versionName "1.0"
    testInstrumentationRunner
 "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
sourceSets { main { jni.srcDirs = ['src/main/jni', 'src/main/jniLibs/'] }
}
// Encapsulates your external native build configurations.
externalNativeBuild {

    // Encapsulates your CMake build configurations.
    cmake {

        // Provides a relative path to your CMake build script.
        path "../CMakeLists.txt"
    }
}
//buildToolsVersion '27.0.3'
buildToolsVersion '28.0.3'
productFlavors {
}
}

repositories {
maven { url 'https://jitpack.io' }
}

dependencies {
//implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0-alpha'
}

dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support:animated-vector-drawable:28.0.0'
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support:customtabs:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
implementation 'com.android.support:support-v4:26.1.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-
core:3.0.1'
implementation project(':openCVLibrary340')
//implementation 'com.jjoe64:graphview:4.2.2'
}

dependencies {
implementation 'com.android.support.constraint:constraint-layout:+'
}
</code>```

答:
I had the same error fixed it by updating the compilesdkversion to 28, since currently my build tools version is 28.0.3 , hence the version should be same as to have a perfect build.
Also check for your  implementation 'com.android.support:appcompat-v7:28.0.0'
Change the respective Dependency versions to 28, it will prevent run time crashing</p>

Body:
Recently I had problems with AAPT2. The problems were caused by my username that contained non-ascii characters. I created another Windows account(without non-ascii characters) and installed Android Studio on it. Then I opened my older project and when AS asked me to update I agreed to that. Now when I try to build my app I get these errors:

Android resource linking failed
  D:\Android_Studio\Praca\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values-v28\values-v28.xml:7: error: resource android:attr/dialogCornerRadius not found.
  D:\Android_Studio\Praca\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values-v28\values-v28.xml:11: error: resource android:attr/dialogCornerRadius not found.
  D:\Android_Studio\Praca\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml:2970: error: resource android:attr/fontVariationSettings not found.
  D:\Android_Studio\Praca\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml:2971: error: resource android:attr/ttcIndex not found.
  error: failed linking references.

Most of threads I found of StackOverflow suggest that this problem might be related to support library, they say that version of it might be wrong. How could I change the version? My project also uses OpenCV library and configuration of it might be invalid.
What I tried already was cleaning and rebuilding project and adjusting compileSDKVersion in Gradle.

Here is values-v28.xml file

<?xml version="1.0" encoding="utf-8"?>
<resources>

And here is Manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.kawa.praca">

<uses-feature
    android:name="android.hardware.camera"
    android:required="true" />

<uses-permission
    android:name="android.permission.WRITE_EXTERNAL_STORAGE"
    android:maxSdkVersion="18" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".Powitanie">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".Trening" />
    <activity android:name=".Zdjecia" />

    <provider
        android:name=".DbProvider"
        android:authorities="com.example.kawa.praca"
        android:exported="true" />
    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="com.example.android.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths" />
    </provider>

    <activity android:name=".AddActivity" />
    <activity android:name=".UserPanel" />
    <activity android:name=".ScoringPanel" />
    <activity android:name=".Scoring" />
    <activity android:name=".NewPlanActivity" />

    <receiver
        android:name=".PlanReceiver"
        android:enabled="true"
        android:exported="true" />

    <activity android:name=".ChartsActivity"></activity>
</application>

</manifest>

Also below is my build.gradle file app module. In this file in sub-clause 'dependencies' entries with support library are underlined and AS shows me a warning:

All com.android.support libraries must use the exact same version specification (mixing versions can lead to runtime crashes). Found versions 28.0.0, 26.1.0. Examples include com.android.support:animated-vector-drawable:28.0.0 and com.android.support:customtabs:26.1.0

I tried changing versions to newer or older but this warning still appears.

apply plugin: 'com.android.application'

android {
compileSdkVersion 26
defaultConfig {
    applicationId "com.example.kawa.praca"
    minSdkVersion 24
    targetSdkVersion 26

    versionCode 1
    versionName "1.0"
    testInstrumentationRunner
 "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
sourceSets { main { jni.srcDirs = ['src/main/jni', 'src/main/jniLibs/'] }
}
// Encapsulates your external native build configurations.
externalNativeBuild {

    // Encapsulates your CMake build configurations.
    cmake {

        // Provides a relative path to your CMake build script.
        path "../CMakeLists.txt"
    }
}
//buildToolsVersion '27.0.3'
buildToolsVersion '28.0.3'
productFlavors {
}
}

repositories {
maven { url 'https://jitpack.io' }
}

dependencies {
//implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0-alpha'
}

dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support:animated-vector-drawable:28.0.0'
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support:customtabs:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
implementation 'com.android.support:support-v4:26.1.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-
core:3.0.1'
implementation project(':openCVLibrary340')
//implementation 'com.jjoe64:graphview:4.2.2'
}

dependencies {
implementation 'com.android.support.constraint:constraint-layout:+'
}


来源: stackexchange

问:
Publish a TypeScript Project to NPM without source
Problem: I have built a library that have many .ts files in structured folders. Now I want to publish my this library, but do not want to share Source (typescript files).

Attempt: When I run tsc command it generates a .js file corresponding to each .ts file. When I keep declaration: true in my tsconfig.json file then tsc also generates .d.ts file for each .ts file as well.

Challenge: All of my .js files are generated structurally as expected, but .d.ts also are generating in parallel location of .js file. Now challenge is, by this way how any consumer of this library will import types as all of them are scattered in different folders, as there is no single .d.ts file generated by tsc

I see many module on NPM (like https://github.com/winstonjs/winston) which publishes single index.d.ts file, and consumer import them to use and avail Typescript advantage.

Currently my project structure looks like as below:

```<code>- my-project-root-directory
    - src
        - demo
            - main.ts
            - sample.ts
        -lib
            - constants
                - some_constant_file1.ts
            - models
                - some_model_file1.ts
                - some_model_file2.ts
            - util
                - some_util_file.ts
    - dist
        - demo
            - main.js
            - main.d.ts
            - sample.js
            - sample.d.ts
        -lib
            - constants
                - some_constant_file1.js
                - some_constant_file1.d.ts
            - models
                - some_model_file1.js
                - some_model_file1.d.ts
                - some_model_file2.js
                - some_model_file2.d.ts
            - util
                - some_util_file.js
                - some_util_file.d.ts
    - logs
    - package.json
    - tsconfig.json
</code>```

There is obviously no index.d.ts file, how can I get single file? Is single .d.ts file approach correct way? Or I am moving into wrong direction?

I've already seen many answers on stackoverflow & tutorials on youtube, all of them showing a simple example which have only single index.ts file and index.d.ts file corresponding to it. But I can not find a perfect way that solve my purpose.

Thanks for reading my question, any help is welcome.

答:
Here's how I'd go along:

Create an index.ts file in each folder that exports types that are meaningful for library consumers. For example: src/lib/constants/index.ts, src/lib/models/index.ts, ... Each of the index.ts files exports all TypeScript types that exist in its folder, plus all index.ts files from its sub-folders.

Create a central src/index.ts file that exports everything from all src/... subfolders.

In your package.json, add a types: "dist/index.d.ts" entry.

In your .npmignore file, add a a src/ entry.

With this approach, you have all your imports referenced in one central dist/index.d.ts file, so consumers of your library do not need to import types from different locations inside your package. Also, you do not distribute TypeScript sources at all.

Here's how your directory structure could end up looking like. I excluded the dist folder, but an index.js and index.d.ts file will be generated in each folder, as well:

```<code>- my-project-root-directory
    - src
        - index.ts
        - demo
            - main.ts
            - sample.ts
        -lib
            - constants
                - some_constant_file1.ts
                - index.ts
            - models
                - some_model_file1.ts
                - some_model_file2.ts
                - index.ts
            - util
                - some_util_file.ts
                - index.ts
    - logs
    - package.json
    - tsconfig.json
</code>```

Your src/lib/constants/index.ts file could, for example, look like this:

```<code>export * from './some_constant_file1.ts'
</code>```

Your src/lib/index.ts file:

```<code>export * from './constants';
export * from './models';
export * from './util';
</code>```

Your src/index.ts file:

```<code>export * from './lib';
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Problem: I have built a library that have many .ts files in structured folders. Now I want to publish my this library, but do not want to share Source (typescript files).

Attempt: When I run tsc command it generates a .js file corresponding to each .ts file. When I keep declaration: true in my tsconfig.json file then tsc also generates .d.ts file for each .ts file as well.

Challenge: All of my .js files are generated structurally as expected, but .d.ts also are generating in parallel location of .js file. Now challenge is, by this way how any consumer of this library will import types as all of them are scattered in different folders, as there is no single .d.ts file generated by tsc

I see many module on NPM (like https://github.com/winstonjs/winston) which publishes single index.d.ts file, and consumer import them to use and avail Typescript advantage.

Currently my project structure looks like as below:

- my-project-root-directory
    - src
        - demo
            - main.ts
            - sample.ts
        -lib
            - constants
                - some_constant_file1.ts
            - models
                - some_model_file1.ts
                - some_model_file2.ts
            - util
                - some_util_file.ts
    - dist
        - demo
            - main.js
            - main.d.ts
            - sample.js
            - sample.d.ts
        -lib
            - constants
                - some_constant_file1.js
                - some_constant_file1.d.ts
            - models
                - some_model_file1.js
                - some_model_file1.d.ts
                - some_model_file2.js
                - some_model_file2.d.ts
            - util
                - some_util_file.js
                - some_util_file.d.ts
    - logs
    - package.json
    - tsconfig.json

There is obviously no index.d.ts file, how can I get single file? Is single .d.ts file approach correct way? Or I am moving into wrong direction?

I've already seen many answers on stackoverflow & tutorials on youtube, all of them showing a simple example which have only single index.ts file and index.d.ts file corresponding to it. But I can not find a perfect way that solve my purpose.

Thanks for reading my question, any help is welcome.

Body:
Here's how I'd go along:

Create an index.ts file in each folder that exports types that are meaningful for library consumers. For example: src/lib/constants/index.ts, src/lib/models/index.ts, ... Each of the index.ts files exports all TypeScript types that exist in its folder, plus all index.ts files from its sub-folders.

Create a central src/index.ts file that exports everything from all src/... subfolders.

In your package.json, add a types: "dist/index.d.ts" entry.

In your .npmignore file, add a a src/ entry.

With this approach, you have all your imports referenced in one central dist/index.d.ts file, so consumers of your library do not need to import types from different locations inside your package. Also, you do not distribute TypeScript sources at all.

Here's how your directory structure could end up looking like. I excluded the dist folder, but an index.js and index.d.ts file will be generated in each folder, as well:

- my-project-root-directory
    - src
        - index.ts
        - demo
            - main.ts
            - sample.ts
        -lib
            - constants
                - some_constant_file1.ts
                - index.ts
            - models
                - some_model_file1.ts
                - some_model_file2.ts
                - index.ts
            - util
                - some_util_file.ts
                - index.ts
    - logs
    - package.json
    - tsconfig.json

Your src/lib/constants/index.ts file could, for example, look like this:

export * from './some_constant_file1.ts'

Your src/lib/index.ts file:

export * from './constants';
export * from './models';
export * from './util';

Your src/index.ts file:

export * from './lib';


问:
Java [unchecked] unchecked case warning
Ok, I've been looking around and done alot of google searching, but I still can't find a way to avoid this warning.

```<code>Integer result = chooser.showOpenDialog(null);
if (result.equals(0))
{
    String tempHolder = chooser.getSelectedFile().getPath();
    filenameLoad = new File(tempHolder);
    filenameSave = filenameLoad;
    FileInputStream fis = null;
    ObjectInputStream in = null;
    try
    {
        fis = new FileInputStream(filenameLoad);
        in = new ObjectInputStream(fis);;
    }
    catch(IOException ex)
    {
        ex.printStackTrace();
    }

    try
    {
        loadFile = (ArrayList<Dot>)in.readObject();
    }
    catch(IOException ex)
    {
        System.out.println("Cast fail");
    }
    catch(ClassNotFoundException ex)
    {
        System.out.println("Cast fail");
    }
    catch (ClassCastException ex)
    {
        System.out.println("Cast fail");
    }

    try
    {
        in.close();
    }
    catch(Exception ex)
    {
        System.out.println("failed to close in");
    }
    save.setEnabled(true);
      gpanel.setDotList(loadFile);
  }
</code>```

It gives me the warning at the line loadFile = (ArrayList)in.readObject();  I've added in the catchs so i'm not sure why it still says its uncatched.  Any help?  thanks?

答: What you see is a compiler warning that you are trying to convert an Object into a ArrayList<Dot> without first checking if the Object actually contains a List of Dot and not e.g. a List of Foo.

ContentLicense: CC BY-SA 3.0

Title: Java [unchecked] unchecked case warning

Body:
Ok, I've been looking around and done alot of google searching, but I still can't find a way to avoid this warning.

Integer result = chooser.showOpenDialog(null);
if (result.equals(0))
{
    String tempHolder = chooser.getSelectedFile().getPath();
    filenameLoad = new File(tempHolder);
    filenameSave = filenameLoad;
    FileInputStream fis = null;
    ObjectInputStream in = null;
    try
    {
        fis = new FileInputStream(filenameLoad);
        in = new ObjectInputStream(fis);;
    }
    catch(IOException ex)
    {
        ex.printStackTrace();
    }

    try
    {
        loadFile = (ArrayList<Dot>)in.readObject();
    }
    catch(IOException ex)
    {
        System.out.println("Cast fail");
    }
    catch(ClassNotFoundException ex)
    {
        System.out.println("Cast fail");
    }
    catch (ClassCastException ex)
    {
        System.out.println("Cast fail");
    }

    try
    {
        in.close();
    }
    catch(Exception ex)
    {
        System.out.println("failed to close in");
    }
    save.setEnabled(true);
      gpanel.setDotList(loadFile);
  }

It gives me the warning at the line loadFile = (ArrayList)in.readObject();  I've added in the catchs so i'm not sure why it still says its uncatched.  Any help?  thanks?


问:
Angular 'is not a function' caused by missing import?
Getting an 'is not a function' in Angular 7 / typescript 3-ish, using an EventEmitter.  Much has been written (a b) about this error, but very few upvotes for answers (a b c d e f ).  I'm almost there, but need some help finishing this off.

Here is one stackblitz with the error.
...and a similar one without the error.

The only difference seems to be that with the error, my event emitter and receiver are in sibling folders.  In the one that works, the event receiver is in a parent folder and the emitter is in a child folder.

It seems like some kind of an import/module tweak is required to fix the broken one, but I can't seem to get it.
Suggestions?

答:
There is a typo in your parent.component.ts file.
You named function as parentListner in ts file but used parentListener in html file.


问:
SimpleDateFormat.parse() ignores the number of characters in pattern
I'm trying to parse a date String which can have tree different formats.
Even though the String should not match the second pattern it somehow does and therefore returns a wrong date.

That's my code:

```<code>import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Start {

    public static void main(String[] args) {
        SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
        try{
            System.out.println(sdf.format(parseDate("2013-01-31")));
        } catch(ParseException ex){
            System.out.println("Unable to parse");
        }
    }

    public static Date parseDate(String dateString) throws ParseException{
        SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
        SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MM-yyyy");
        SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd");

        Date parsedDate;
        try {
            parsedDate = sdf.parse(dateString);
        } catch (ParseException ex) {
            try{
                parsedDate = sdf2.parse(dateString);
            } catch (ParseException ex2){
                parsedDate = sdf3.parse(dateString);
            }
        }
        return parsedDate;
    }
}
</code>```

With the input 2013-01-31 I get the output 05.07.0036.

If I try to parse 31-01-2013 or 31.01.2013 I get 31.01.2013 as expected.

I recognized that the programm will give me exactly the same output if I set the patterns like this:

```<code>SimpleDateFormat sdf = new SimpleDateFormat("d.M.y");
SimpleDateFormat sdf2 = new SimpleDateFormat("d-M-y");
SimpleDateFormat sdf3 = new SimpleDateFormat("y-M-d");
</code>```

Why does it ignore the number of chars in my pattern?

答:
java.time

java.time is the modern Java date and time API and behaves the way you had expected. So it’s a matter of a simple translation of your code:

```<code>private static final DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("dd.MM.yyyy");
private static final DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("dd-MM-yyyy");
private static final DateTimeFormatter formatter3 = DateTimeFormatter.ofPattern("yyyy-MM-dd");

public static LocalDate parseDate(String dateString) {
    LocalDate parsedDate;
    try {
        parsedDate = LocalDate.parse(dateString, formatter1);
    } catch (DateTimeParseException dtpe1) {
        try {
            parsedDate = LocalDate.parse(dateString, formatter2);
        } catch (DateTimeParseException dtpe2) {
            parsedDate = LocalDate.parse(dateString, formatter3);
        }
    }
    return parsedDate;
}
</code>```

(I put the formatters outside your method so they are not created anew for each call. You can put them inside if you prefer.)

Let’s try it out:

```<code>    LocalDate date = parseDate("2013-01-31");
    System.out.println(date);
</code>```

Output is:

2013-01-31

For numbers DateTimeFormatter.ofPattern takes the number of pattern letters to be the minimum field width. It furthermore assumes that the day of month is never more than two digits. So when trying the format dd-MM-yyyy it successfully parsed 20 as a day of month and then threw a DateTimeParseException because there wasn’t a hyphen (dash) after 20. Then the method went on to try the next formatter.

What went wrong in your code

The SimpleDateFormat class that you tried to use is notoriously troublesome and fortunately long outdated. You met but one of the many problems with it. Repeating the important sentence from the documentation of how it handles numbers from the answer by Teetoo:

For parsing, the number of pattern letters is ignored unless it's
  needed to separate two adjacent fields.

So new SimpleDateFormat("dd-MM-yyyy") happily parses 2013 as the day of month, 01 as the month and 31 as the year. Next we should have expected it to throw an exception because there aren’t 2013 days in January year 31. But a SimpleDateFormat with default settings doesn’t do that. It just keeps counting days through the following months and years and ends up at July 5 year 36, five and a half years later, the result you observed.

Link

Oracle tutorial: Date Time explaining how to use java.time.

Body:
I'm trying to parse a date String which can have tree different formats.
Even though the String should not match the second pattern it somehow does and therefore returns a wrong date.

That's my code:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Start {

    public static void main(String[] args) {
        SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
        try{
            System.out.println(sdf.format(parseDate("2013-01-31")));
        } catch(ParseException ex){
            System.out.println("Unable to parse");
        }
    }

    public static Date parseDate(String dateString) throws ParseException{
        SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
        SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MM-yyyy");
        SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd");

        Date parsedDate;
        try {
            parsedDate = sdf.parse(dateString);
        } catch (ParseException ex) {
            try{
                parsedDate = sdf2.parse(dateString);
            } catch (ParseException ex2){
                parsedDate = sdf3.parse(dateString);
            }
        }
        return parsedDate;
    }
}

With the input 2013-01-31 I get the output 05.07.0036.

If I try to parse 31-01-2013 or 31.01.2013 I get 31.01.2013 as expected.

I recognized that the programm will give me exactly the same output if I set the patterns like this:

SimpleDateFormat sdf = new SimpleDateFormat("d.M.y");
SimpleDateFormat sdf2 = new SimpleDateFormat("d-M-y");
SimpleDateFormat sdf3 = new SimpleDateFormat("y-M-d");

Why does it ignore the number of chars in my pattern?

Body:
java.time

java.time is the modern Java date and time API and behaves the way you had expected. So it’s a matter of a simple translation of your code:

private static final DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("dd.MM.yyyy");
private static final DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("dd-MM-yyyy");
private static final DateTimeFormatter formatter3 = DateTimeFormatter.ofPattern("yyyy-MM-dd");

public static LocalDate parseDate(String dateString) {
    LocalDate parsedDate;
    try {
        parsedDate = LocalDate.parse(dateString, formatter1);
    } catch (DateTimeParseException dtpe1) {
        try {
            parsedDate = LocalDate.parse(dateString, formatter2);
        } catch (DateTimeParseException dtpe2) {
            parsedDate = LocalDate.parse(dateString, formatter3);
        }
    }
    return parsedDate;
}

(I put the formatters outside your method so they are not created anew for each call. You can put them inside if you prefer.)

Let’s try it out:

    LocalDate date = parseDate("2013-01-31");
    System.out.println(date);

Output is:

2013-01-31

For numbers DateTimeFormatter.ofPattern takes the number of pattern letters to be the minimum field width. It furthermore assumes that the day of month is never more than two digits. So when trying the format dd-MM-yyyy it successfully parsed 20 as a day of month and then threw a DateTimeParseException because there wasn’t a hyphen (dash) after 20. Then the method went on to try the next formatter.

What went wrong in your code

The SimpleDateFormat class that you tried to use is notoriously troublesome and fortunately long outdated. You met but one of the many problems with it. Repeating the important sentence from the documentation of how it handles numbers from the answer by Teetoo:

For parsing, the number of pattern letters is ignored unless it's
  needed to separate two adjacent fields.

So new SimpleDateFormat("dd-MM-yyyy") happily parses 2013 as the day of month, 01 as the month and 31 as the year. Next we should have expected it to throw an exception because there aren’t 2013 days in January year 31. But a SimpleDateFormat with default settings doesn’t do that. It just keeps counting days through the following months and years and ends up at July 5 year 36, five and a half years later, the result you observed.

Link

Oracle tutorial: Date Time explaining how to use java.time.


问:
Using named pipes in c
i have this simple program that passes a value through a named pipe from child to parent process:

```<code>#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/stat.h>
#include <semaphore.h>
#include <fcntl.h>
 #include <sys/wait.h>
 #include <stdio.h>

int main()
{
 char * myfifo = "/home/tmp/myfifo";
   mkfifo(myfifo, 0666);
   int fd,rec;
   pid_t c=fork();

   if(c==0){
   fd = open(myfifo, O_WRONLY);
   rec=100;
   write(fd, rec, sizeof(rec));

   }
   if(c>0){
   sleep(1);
    fd = open(myfifo, O_RDONLY);
     read(fd, rec, sizeof(rec));
     printf("%d\n",fd);
     printf("%d\n",rec);

   }

}
</code>```

This program prints fd=-1 and instead of rec being 100 it prints rec's address.I also tried putting &rec in read and write but it did not solve anything.What am i doing wrong?

答:
There's an issue with this line:

```<code>write(fd, rec, sizeof(rec));
</code>```

This is the prototype of write():

```<code>ssize_t write(int fd, const void *buf, size_t count);
</code>```

That means that you're reading from the memory location stored in rec, not the content of rec.

The same thing applies for read(). You need to pass a pointer to rec instead of rec itself.

Also, always make sure to close files after you open and perform I/O on them.

Here's a correct copy of your code:

```<code>#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/stat.h>
#include <semaphore.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <stdio.h>

int main()
{
   const char *myfifo = "/home/tmp/myfifo";
   mkfifo(myfifo, 0666);
   int fd, rec;
   pid_t c = fork();

   if(c == 0) {
       fd = open(myfifo, O_WRONLY);
       rec = 100;
       write(fd, &rec, sizeof(rec));
       close(fd);
   }
   if(c > 0) {
       sleep(1);
       fd = open(myfifo, O_RDONLY);
       read(fd, &rec, sizeof(rec));
       printf("%d\n", fd);
       printf("%d\n", rec);
       close(fd);
   }
}
</code>```

Of course, always make sure you have the proper permissions to create, read, and write files in that directory. Also, make sure the directory /home/tmp exists.

Title: Using named pipes in c

Body:
i have this simple program that passes a value through a named pipe from child to parent process:

#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/stat.h>
#include <semaphore.h>
#include <fcntl.h>
 #include <sys/wait.h>
 #include <stdio.h>

int main()
{
 char * myfifo = "/home/tmp/myfifo";
   mkfifo(myfifo, 0666);
   int fd,rec;
   pid_t c=fork();

   if(c==0){
   fd = open(myfifo, O_WRONLY);
   rec=100;
   write(fd, rec, sizeof(rec));

   }
   if(c>0){
   sleep(1);
    fd = open(myfifo, O_RDONLY);
     read(fd, rec, sizeof(rec));
     printf("%d\n",fd);
     printf("%d\n",rec);

   }

}

This program prints fd=-1 and instead of rec being 100 it prints rec's address.I also tried putting &rec in read and write but it did not solve anything.What am i doing wrong?

Body:
There's an issue with this line:

write(fd, rec, sizeof(rec));

This is the prototype of write():

ssize_t write(int fd, const void *buf, size_t count);

That means that you're reading from the memory location stored in rec, not the content of rec.

The same thing applies for read(). You need to pass a pointer to rec instead of rec itself.

Also, always make sure to close files after you open and perform I/O on them.

Here's a correct copy of your code:

#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/stat.h>
#include <semaphore.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <stdio.h>

int main()
{
   const char *myfifo = "/home/tmp/myfifo";
   mkfifo(myfifo, 0666);
   int fd, rec;
   pid_t c = fork();

   if(c == 0) {
       fd = open(myfifo, O_WRONLY);
       rec = 100;
       write(fd, &rec, sizeof(rec));
       close(fd);
   }
   if(c > 0) {
       sleep(1);
       fd = open(myfifo, O_RDONLY);
       read(fd, &rec, sizeof(rec));
       printf("%d\n", fd);
       printf("%d\n", rec);
       close(fd);
   }
}

Of course, always make sure you have the proper permissions to create, read, and write files in that directory. Also, make sure the directory /home/tmp exists.


问:
How do I place the image beneath the paragraph when I resize the browser screen?
So I have a paragraph on the left side of the screen and my image on the right side of the screen. It is responsive but not the way I want it to be. When I resize the browser screen, I want the picture to display beneath the paragraph i.e. I want the paragraph to be on top of the image and the image should be below the paragraph. When I try to resize the window, the image just becomes short but does not move to the next line.

I am currently using  CSS grid system to display the paragraph on the left and the image on the right. I also have the whole thing inside a container. I am also using flex box to make it responsive but that just wont help. I have also tried to use media queries but I just don't know how to tell the media query to move the image below the paragraph.

答:
Perhaps it's as simple as forgetting the grid and flexbox and doing this.

CSS:

```<code>.text  { width: 50%; min-width: 20em; float: left; }
.image { width: 50%; min-width: 20em; }
</code>```

HTML:

```<code><p class="text">
    Blah blah blah.
    Blah blah blah.
    Blah blah blah.
    Blah blah blah.
    Blah blah blah.
    Blah blah blah.
</p>
<img class="image" src="./image.jpeg" />
</code>```

Body:
Perhaps it's as simple as forgetting the grid and flexbox and doing this.

CSS:

.text  { width: 50%; min-width: 20em; float: left; }
.image { width: 50%; min-width: 20em; }

HTML:

<p class="text">
    Blah blah blah.
    Blah blah blah.
    Blah blah blah.
    Blah blah blah.
    Blah blah blah.
    Blah blah blah.
</p>
<img class="image" src="./image.jpeg" />


问:
How to get character without numbers when iterating through std::string?
I am trying to iterate through each character in std::string which was passed by reference and compare it to the first element of vector of strings.

```<code>#include <iostream>
#include <vector>

bool letterFound (const std::string &s){
    std::vector<std::string> vLetters = {"A", "B", "C"};
    for (auto &letter : s) {
        if (&letter == vLetters[0]) {
            return true;
        }
    }
    return false;
}

int main() {
    std::string result = letterFound("AB")
                        ? "Letter [A] found"
                        : "Letter not found";
    std::cout << result << std::endl;
    return 0;
}
</code>```

If just one letter "A" passed to the function, then letter was found, but if I pass more than one letter, for example "AB", than actual value of the first character to compare is "65 'A'", not "A". The second character is "66 'B'".

How to get exactly one letter from string for comparison without these numbers?

Update: Letter will be found if

```<code>std::vector<std::string> vLetters = {"A", "B", "C"};
</code>```

change to

```<code>std::vector<char> vLetters = {'A', 'B', 'C'};
</code>```

However, it would be nice to know how to change the code without changing vector of strings.

答: &letter is a char*. char* is a special type in the world of pointers. It is treated like a pointer to a C style NULL terminated character array. &letter == vLetters[0] tries to form a std::string from &letter, which is not NULL terminated. Hence the undefined behavior.

Body:
I am trying to iterate through each character in std::string which was passed by reference and compare it to the first element of vector of strings.

#include <iostream>
#include <vector>

bool letterFound (const std::string &s){
    std::vector<std::string> vLetters = {"A", "B", "C"};
    for (auto &letter : s) {
        if (&letter == vLetters[0]) {
            return true;
        }
    }
    return false;
}

int main() {
    std::string result = letterFound("AB")
                        ? "Letter [A] found"
                        : "Letter not found";
    std::cout << result << std::endl;
    return 0;
}

If just one letter "A" passed to the function, then letter was found, but if I pass more than one letter, for example "AB", than actual value of the first character to compare is "65 'A'", not "A". The second character is "66 'B'".

How to get exactly one letter from string for comparison without these numbers?

Update: Letter will be found if

std::vector<std::string> vLetters = {"A", "B", "C"};

change to

std::vector<char> vLetters = {'A', 'B', 'C'};

However, it would be nice to know how to change the code without changing vector of strings.


问:
How to update/change object in array?
I have array with object in localstorage
image

Some a function return object with new data. I need to write new data to object in localstorage (identify by ID).

I tried but... See my code below

```<code>      const result = {
        type: 'mobile',
        id: 'tsy152ivm',
        score: 55
      }

      const links = JSON.parse(localStorage.getItem('links'));
      const item = links.find(item => item.id === result.id);
      //localStorage.setItem('links', JSON.stringify(item));
</code>```

答:
Use .findIndex() to find the index of the object you want to modify, and use Object.assign() to update the object's properties.

let arr = [{id: 34, name: 'Peter'}, {id: 'tsy152ivm', name: 'Sam'}]

const result = {
        type: 'mobile',
        id: 'tsy152ivm',
        score: 55
      }

const index = arr.findIndex(item => item.id === result.id);

const updated = [...arr.slice(0, index),Object.assign({}, arr[index], { id: result.id, name: 'Samantha' }),
...arr.slice(index + 1)
]

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

<p>or just modify the object directly, using an index.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let arr = [{id: 34, name: 'Peter'}, {id: 'tsy152ivm', name: 'Sam'}]

const result = {
        type: 'mobile',
        id: 'tsy152ivm',
        score: 55
      }

const index = arr.findIndex(item => item.id === result.id);

arr[index] = Object.assign({}, arr[index], { name: 'Samantha'})

console.log(arr);</code>```

Title: How to update/change object in array?

Body:
I have array with object in localstorage
image

Some a function return object with new data. I need to write new data to object in localstorage (identify by ID).

I tried but... See my code below

      const result = {
        type: 'mobile',
        id: 'tsy152ivm',
        score: 55
      }

      const links = JSON.parse(localStorage.getItem('links'));
      const item = links.find(item => item.id === result.id);
      //localStorage.setItem('links', JSON.stringify(item));

Body:
Use .findIndex() to find the index of the object you want to modify, and use Object.assign() to update the object's properties.

let arr = [{id: 34, name: 'Peter'}, {id: 'tsy152ivm', name: 'Sam'}]

const result = {
        type: 'mobile',
        id: 'tsy152ivm',
        score: 55
      }

const index = arr.findIndex(item => item.id === result.id);

const updated = [...arr.slice(0, index),Object.assign({}, arr[index], { id: result.id, name: 'Samantha' }),
...arr.slice(index + 1)
]

console.log(updated);

or just modify the object directly, using an index.

let arr = [{id: 34, name: 'Peter'}, {id: 'tsy152ivm', name: 'Sam'}]

const result = {
        type: 'mobile',
        id: 'tsy152ivm',
        score: 55
      }

const index = arr.findIndex(item => item.id === result.id);

arr[index] = Object.assign({}, arr[index], { name: 'Samantha'})

console.log(arr);


问:
How to hide multiple columns in multiple worksheets
I am going through 25 workbooks in a specific directory and need to hide the same columns in each workbook.

I've set the code up so that it cycles through each workbook, but it fails when it comes to the hiding of the columns. I've done the googling, but am missing something.

The specific code that isn't working:

```<code>Worksheets("Ops1").Range("F:AE,AG:AQ,AS:CP,CW:EF").EntireColumn.Hidden = True
                 Worksheets("Ops2").Range("F:AE,AG:AQ,AS:CP,CW:EF").EntireColumn.Hidden = True
</code>```

And the whole thing:

```<code> Dim xFd As FileDialog
    Dim xFdItem As Variant
    Dim xFileName As String
    Set xFd = Application.FileDialog(msoFileDialogFolderPicker)
    If xFd.Show = -1 Then
        xFdItem = xFd.SelectedItems(1) & Application.PathSeparator
        xFileName = Dir(xFdItem & "*.xls*")
        Do While xFileName <> ""
            With Workbooks.Open(xFdItem & xFileName)
                 'your code here
                 Worksheets("Ops1").Range("F:AE,AG:AQ,AS:CP,CW:EF").EntireColumn.Hidden = True
                 Worksheets("Ops2").Range("F:AE,AG:AQ,AS:CP,CW:EF").EntireColumn.Hidden = True
            End With
        xFileName = Dir
        Loop
   End If
</code>```

I receive a runtime error code '9' subscript out of range.

答:
You can try seting the range to a variable like this.

Dim xFd As FileDialog
    Dim xFdItem As Variant
    Dim xFileName As String
    Dim sht1ColumnsToHide As Range
    Dim sht2ColumnsToHide As Range
    Dim ws1 As Worksheet
    Dim ws2 As Worksheet

    Set ws1 = Worksheet("Ops1")
    Set ws2 = Worksheet("Ops2")
    Set xFd = Application.FileDialog(msoFileDialogFolderPicker)
    If xFd.Show = -1 Then
        xFdItem = xFd.SelectedItems(1) & Application.PathSeparator
        xFileName = Dir(xFdItem & "*.xls*")
        Do While xFileName <> ""
            With Workbooks.Open(xFdItem & xFileName)
                 'your code here
                    Set ws1 = Worksheets("Ops1")
                    Set ws2 = Worksheets("Ops2")

                 With ws1
                 Set sht1ColumnsToHide = Application.Union(.Columns("F:AE"), _
                                            .Columns("AG:AQ"), _
                                            .Columns("AS:CP"), _
                                            .Columns("CW:EF"))
                 sht1ColumnsToHide.EntireColumn.Hidden = True
                 End With

                 With ws2
                 Set sht2ColumnsToHide = Application.Union(.Columns("F:AE"), _
                                            .Columns("AG:AQ"), _
                                            .Columns("AS:CP"), _
                                            .Columns("CW:EF"))
                 sht2ColumnsToHide.EntireColumn.Hidden = True
               End With
            End With
        xFileName = Dir
        Loop
   End If
```

Body:
I am going through 25 workbooks in a specific directory and need to hide the same columns in each workbook.

I've set the code up so that it cycles through each workbook, but it fails when it comes to the hiding of the columns. I've done the googling, but am missing something.

The specific code that isn't working:

Worksheets("Ops1").Range("F:AE,AG:AQ,AS:CP,CW:EF").EntireColumn.Hidden = True
                 Worksheets("Ops2").Range("F:AE,AG:AQ,AS:CP,CW:EF").EntireColumn.Hidden = True

And the whole thing:

 Dim xFd As FileDialog
    Dim xFdItem As Variant
    Dim xFileName As String
    Set xFd = Application.FileDialog(msoFileDialogFolderPicker)
    If xFd.Show = -1 Then
        xFdItem = xFd.SelectedItems(1) & Application.PathSeparator
        xFileName = Dir(xFdItem & "*.xls*")
        Do While xFileName <> ""
            With Workbooks.Open(xFdItem & xFileName)
                 'your code here
                 Worksheets("Ops1").Range("F:AE,AG:AQ,AS:CP,CW:EF").EntireColumn.Hidden = True
                 Worksheets("Ops2").Range("F:AE,AG:AQ,AS:CP,CW:EF").EntireColumn.Hidden = True
            End With
        xFileName = Dir
        Loop
   End If

I receive a runtime error code '9' subscript out of range.


问:
how to clear form data without refresh page
After I submit the form, I want to add a new entry which is working, but i don't want the data to remain in the form i.e. reset the form

here is the form code

```<code> <form id="add_multycontact" action="#" method="POST">

  <div class="row">
      <div class="large-6 columns">
         <label>Company Name</label>
          <input name="company" type="text">
      </div>

     <div class="large-6 columns">
        <label>Contact Name </label>
         <input name="contact_name" type="text">
    </div>
  </div><!--end row-->

  <div class="row">
   <div class="large-6 columns">
       <label>Main Phone</label>
       <input name="mainPhone" type="text">
    </div>

     <div class="large-6 columns">
       <label>Alt Phone</label>
       <input name="altPhone" type="text">
    </div>
  </div><!--end row-->

  <div class="row">
  <div class="large-6 columns">
      <label>Street Address </label>
        <input name="street_address" type="text">
  </div>

   <div class="large-6 columns">
      <label>City </label>
        <input name="city" type="text">
   </div>
   </div>

   <div class="row">
    <div class="large-6 columns">
      <label>Province</label>
         <select name="province">
            <option>Select Province</option>
            <?php foreach($provinces as $key => $value) : ?>
                <option value="<?php echo $key; ?>"><?php echo $value; ?></option>
            <?php endforeach; ?>
        </select>
    </div>

   <div class="large-6 columns">
      <label>Postal Code </label>
        <input name="postal" type="text">
   </div>

  </div><!--end row-->

    <div class="row">
  <div class="large-4 columns">
       <label>Group
        <select name="contact_group">
            <option>Select Contact Group</option>
          <option value="client">Client</option>
          <option value="supplier">Supplier</option>
          <option value="employee">Employee</option>
          <option value="other">Other</option>
        </select>
      </label>
      </div>
     </div>
     <input name="submit" type="submit" class="add_btn button right small" value="submit">
     <a class="close-reveal-modal" aria-label="Close">×</a>

</form>

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

 <!--Loading Image-->
<div id="loaderImage">
    <img src="../images/ajax-loader.gif">
 </div>

 <!--Main Content-->
    <div id="pageContent"></div>

 <script src="../js/vendor/jquery.js"></script>
 <script src="../js/foundation.min.js"></script>
 <script src="../js/vendor/fastclick.js"></script>
 <script src="../js/multyCONTACTscript.js"></script>

    <script>
      $(document).foundation();
    </script>

  </body>
</html>
</code>```

and here is the javascript code

```<code>$(document).ready(function(){
    //show loader image
$('#loaderImage').show();

    //show contacts on page load
    showContacts();

    //add contact
    $(document).on('submit','#add_multycontact', function(){
        //show loader image
    $('#loaderImage').show();

    //post data from form
    $.post('../multy/add_multyCONTACT.php',$(this).serialize())
        .done(function(data){
            console.log(data);
                $('#addModal').foundation('reveal', 'close');
                    showContacts();
        });
        return false;
    });

    //edit contact
    $(document).on('submit','#edit_multycontact', function(){
        //show loader image
    $('#loaderImage').show();

    //post data from form
    $.post("../multy/edit_multyCONTACT.php",$(this).serialize())
        .done(function(data){
            console.log(data);
                $('.editModal').foundation('reveal', 'close');
                    showContacts();
        });
        return false;
    });

    //delete contact
    $(document).on('submit','#delete_multycontact', function(){
        //show loader image
    $('#loaderImage').show();

    //post data from form
    $.post("../multy/delete_multyCONTACT.php",$(this).serialize())
        .done(function(data){
            console.log(data);
                showContacts();
        });
        return false;
    });

});
    //show contacts
    function showContacts() {
    console.log('Showing Contacts...');
    setTimeout("$('#pageContent').load('../multy/multycontacts.php',function(){$('#loaderImage').hide();})", 1000);
}

//close the modal
$(document).on('click', '.close-reveal-modal', function() {

//this is the latest attempt that is just plain desperate!!
document.getElementById("add_multycontact").reset()

$('.reveal-modal').foundation('reveal', 'close');

});

</code>```

I want to make consecutive multiple entries but after adding one entry and then clicking to add another, the pop up opens with the data from the prvious entry, unless i refresh the web page...and i dont wanna do that!

答: You may try to use <button type="button> </button> in your html it shouldn't refresh the page and you may use js click events on your button to continue the application running next steps. If you want require elements of the form to continue you may use js to make the button have a not-allowed cursor style if the form isn't filled.

Body:
After I submit the form, I want to add a new entry which is working, but i don't want the data to remain in the form i.e. reset the form

here is the form code

 <form id="add_multycontact" action="#" method="POST">

         Company Name
          <input name="company" type="text">

        Contact Name
         <input name="contact_name" type="text">

       Main Phone
       <input name="mainPhone" type="text">

       Alt Phone
       <input name="altPhone" type="text">

      Street Address
        <input name="street_address" type="text">

      City
        <input name="city" type="text">

      Province
         <select name="province">
            <option>Select Province</option>
            <?php foreach($provinces as $key => $value) : ?>
                <option value="<?php echo $key; ?>"><?php echo $value; ?></option>
            <?php endforeach; ?>
        </select>

      Postal Code
        <input name="postal" type="text">

       Group
        <select name="contact_group">
            <option>Select Contact Group</option>
          <option value="client">Client</option>
          <option value="supplier">Supplier</option>
          <option value="employee">Employee</option>
          <option value="other">Other</option>
        </select>

     <input name="submit" type="submit" class="add_btn button right small" value="submit">
     ×

</form>

and here is the javascript code

$(document).ready(function(){
    //show loader image
$('#loaderImage').show();

    //show contacts on page load
    showContacts();

    //add contact
    $(document).on('submit','#add_multycontact', function(){
        //show loader image
    $('#loaderImage').show();

    //post data from form
    $.post('../multy/add_multyCONTACT.php',$(this).serialize())
        .done(function(data){
            console.log(data);
                $('#addModal').foundation('reveal', 'close');
                    showContacts();
        });
        return false;
    });

    //edit contact
    $(document).on('submit','#edit_multycontact', function(){
        //show loader image
    $('#loaderImage').show();

    //post data from form
    $.post("../multy/edit_multyCONTACT.php",$(this).serialize())
        .done(function(data){
            console.log(data);
                $('.editModal').foundation('reveal', 'close');
                    showContacts();
        });
        return false;
    });

    //delete contact
    $(document).on('submit','#delete_multycontact', function(){
        //show loader image
    $('#loaderImage').show();

    //post data from form
    $.post("../multy/delete_multyCONTACT.php",$(this).serialize())
        .done(function(data){
            console.log(data);
                showContacts();
        });
        return false;
    });

});
    //show contacts
    function showContacts() {
    console.log('Showing Contacts...');
    setTimeout("$('#pageContent').load('../multy/multycontacts.php',function(){$('#loaderImage').hide();})", 1000);
}

//close the modal
$(document).on('click', '.close-reveal-modal', function() {

//this is the latest attempt that is just plain desperate!!
document.getElementById("add_multycontact").reset()

$('.reveal-modal').foundation('reveal', 'close');

});

I want to make consecutive multiple entries but after adding one entry and then clicking to add another, the pop up opens with the data from the prvious entry, unless i refresh the web page...and i dont wanna do that!


问:
What is the output of my ConvLSTM network in Keras
My input is a tensor of X_train.shape=(4291, 1, 278, 29, 1). My output is a tensor of Y_train.shape=(4291, 1, 9). When  it conducted fit(X_train,Y_train), it showed me an error of

"ValueError: Error when checking target: expected dense_1 to have 2 dimensions, but got array with shape (4291, 1, 9)"

So how do I deal with the shape of output?

model = Sequential()
model.add(ConvLSTM2D(filters=8, kernel_size=5, strides=2,
                   input_shape=(1, 278, 29, 1),activation='relu',
                   padding='same',return_sequences=False))
model.add(Flatten())
model.add(Dense(9))
model.compile(loss="mse", optimizer="Adam", metrics=['mse'])
model.fit(X_train, Y_train,batch_size=batch_size, epochs=epochs, verbose=2, shuffle=False)
```

答:
The output of your model has a shape of (None, 9). Therefore, the target array (i.e. Y_train) must have the same shape, i.e. (num_samples, 9). Try to reshape it:

```<code>Y_train = Y_train.reshape(-1, 9)  # -1 indicates that the dimension of that axis should be automatically inferred.
</code>```

Body:
The output of your model has a shape of (None, 9). Therefore, the target array (i.e. Y_train) must have the same shape, i.e. (num_samples, 9). Try to reshape it:

Y_train = Y_train.reshape(-1, 9)  # -1 indicates that the dimension of that axis should be automatically inferred.


问:
When the underlying data changes, do we need to drop and create the partition in Hive?
Let's say I have a hive table partitioned by date with its data stored in S3 as Parquet files. Let's also assume that for a particular partition (date), there were originally 20 records.

If I then delete the original files and put new Parquet files with 50 records in the same folder, do I need to drop and recreate that partition for the new data to reflect?

My understanding was that we don't have to recreate partitions. So I tried removing old data from the respective folder and keeping the new data without "updating" the Hive partition. However, then when I took  count(*) for that date, it still showed as 20 records instead of 50. Upon dropping and creating the partition again, it started showing the correct count. Is that the expected behavior?

答:
Hive optimizes simple queries like select count(*) using statistics. If this property is set:

```<code>set hive.compute.query.using.stats=true;
</code>```

Then Hive will take count from statistics stored in the metadata.

When you replaced file with new one, statistics remains the same. When you deleted partition, all related statistics was also deleted, this is why you got correct count after re-creating partition.

See also this answer: HIVE select count() non null returns higher value than select count() - Predicate prevents statistics usage in this case.

This behavior is quite expected. You can either

```<code>set hive.compute.query.using.stats=false;
</code>```

To switch-off statistics usage for query result calculation, your partition recreation effectively does the same because it removed statistics, this is why statistics was not used and file was scanned.

Or you can analyze table to have statistics updated and keep above parameter set true, so next time you will perform simple aggregation, it will work fast:

```<code>ANALYZE TABLE tablename [PARTITION(partcol1[=val1], partcol2[=val2], ...)]
  COMPUTE STATISTICS
</code>```

For small file with 50 records only performance difference is not so big. But better to have statistics updated, it also being used by optimizer to build optimal query plan.

More details here: analyze table

And if you inserting data using INSERT OVERWRITE, you can enable statistics auto-gathering:

```<code>set hive.stats.autogather=true;
</code>```

Body:
Hive optimizes simple queries like select count(*) using statistics. If this property is set:

set hive.compute.query.using.stats=true;

Then Hive will take count from statistics stored in the metadata.

When you replaced file with new one, statistics remains the same. When you deleted partition, all related statistics was also deleted, this is why you got correct count after re-creating partition.

See also this answer: HIVE select count() non null returns higher value than select count() - Predicate prevents statistics usage in this case.

This behavior is quite expected. You can either

set hive.compute.query.using.stats=false;

To switch-off statistics usage for query result calculation, your partition recreation effectively does the same because it removed statistics, this is why statistics was not used and file was scanned.

Or you can analyze table to have statistics updated and keep above parameter set true, so next time you will perform simple aggregation, it will work fast:

ANALYZE TABLE tablename [PARTITION(partcol1[=val1], partcol2[=val2], ...)]
  COMPUTE STATISTICS

For small file with 50 records only performance difference is not so big. But better to have statistics updated, it also being used by optimizer to build optimal query plan.

More details here: analyze table

And if you inserting data using INSERT OVERWRITE, you can enable statistics auto-gathering:

set hive.stats.autogather=true;


问:
Group and sum list of dictionaries by parameter
I have a list of dictionaries of my products (drinks, food, etc), some of the products may be added several times. I need to group my products by product_id parameter and sum product_cost and product_quantity of each group to get the total product price.

I'm a newbie in python, understand how to group list of dictionaries but can't figure out how to sum some parameter values.

```<code>"products_list": [
    {
        "product_cost": 25,
        "product_id": 1,
        "product_name": "Coca-cola",
        "product_quantity": 14,
    },
    {
        "product_cost": 176.74,
        "product_id": 2,
        "product_name": "Apples",
        "product_quantity": 800,

    },
    {
        "product_cost": 13,
        "product_id": 1,
        "product_name": "Coca-cola",
        "product_quantity": 7,
    }
]
</code>```

I need to achieve something like that:

```<code>"products_list": [
    {
        "product_cost": 38,
        "product_id": 1,
        "product_name": "Coca-cola",
        "product_quantity": 21,
    },
    {
        "product_cost": 176.74,
        "product_id": 2,
        "product_name": "Apples",
        "product_quantity": 800,

    }
]
</code>```

答:
You can try with pandas:

```<code>d = {"products_list": [
    {
        "product_cost": 25,
        "product_id": 1,
        "product_name": "Coca-cola",
        "product_quantity": 14,
    },
    {
        "product_cost": 176.74,
        "product_id": 2,
        "product_name": "Apples",
        "product_quantity": 800,

    },
    {
        "product_cost": 13,
        "product_id": 1,
        "product_name": "Coca-cola",
        "product_quantity": 7,
    }
]}
</code>```

```<code>df=pd.DataFrame(d["products_list"])
</code>```

Pass dict to pandas and perform groupby.
Then convert it back to dict with to_dict function.

```<code>result={}
result["products_list"]=df.groupby("product_name",as_index=False).sum().to_dict(orient="records")
</code>```

Result:

```<code>{'products_list': [{'product_cost': 176.74,
   'product_id': 2,
   'product_name': 'Apples',
   'product_quantity': 800},
  {'product_cost': 38.0,
   'product_id': 2,
   'product_name': 'Coca-cola',
   'product_quantity': 21}]}
</code>```

Body:
I have a list of dictionaries of my products (drinks, food, etc), some of the products may be added several times. I need to group my products by product_id parameter and sum product_cost and product_quantity of each group to get the total product price.

I'm a newbie in python, understand how to group list of dictionaries but can't figure out how to sum some parameter values.

"products_list": [
    {
        "product_cost": 25,
        "product_id": 1,
        "product_name": "Coca-cola",
        "product_quantity": 14,
    },
    {
        "product_cost": 176.74,
        "product_id": 2,
        "product_name": "Apples",
        "product_quantity": 800,

    },
    {
        "product_cost": 13,
        "product_id": 1,
        "product_name": "Coca-cola",
        "product_quantity": 7,
    }
]

I need to achieve something like that:

"products_list": [
    {
        "product_cost": 38,
        "product_id": 1,
        "product_name": "Coca-cola",
        "product_quantity": 21,
    },
    {
        "product_cost": 176.74,
        "product_id": 2,
        "product_name": "Apples",
        "product_quantity": 800,

    }
]

Body:
You can try with pandas:

d = {"products_list": [
    {
        "product_cost": 25,
        "product_id": 1,
        "product_name": "Coca-cola",
        "product_quantity": 14,
    },
    {
        "product_cost": 176.74,
        "product_id": 2,
        "product_name": "Apples",
        "product_quantity": 800,

    },
    {
        "product_cost": 13,
        "product_id": 1,
        "product_name": "Coca-cola",
        "product_quantity": 7,
    }
]}

df=pd.DataFrame(d["products_list"])

Pass dict to pandas and perform groupby.
Then convert it back to dict with to_dict function.

result={}
result["products_list"]=df.groupby("product_name",as_index=False).sum().to_dict(orient="records")

Result:

{'products_list': [{'product_cost': 176.74,
   'product_id': 2,
   'product_name': 'Apples',
   'product_quantity': 800},
  {'product_cost': 38.0,
   'product_id': 2,
   'product_name': 'Coca-cola',
   'product_quantity': 21}]}


问:
RegEx for capturing and replacing digits in a pattern
I would like to replace the 3rd argument in the string with a new number (let's say 100).  The matched string always starts with function, with the first argument either true or false, and with the number as second argument.

                                               Expected
                    |                             |
                    v                             v
'function(true, 0, 15)'   --> 'function(true, 0, 100)'
'function(false, 0, 23)'  --> 'function(false, 0, 100)'
```

<p>I have been reading the related posts but I believe I must have misunderstood some regex concept. The following code is that I had tried but it always replaces the whole string:</p>

<pre class="lang-py prettyprint-override"><code>import re
string = 'function(true, 0, 15)'
regex = re.compile('function\([a-zA-Z]*, [0-9]*, ([0-9]*)\)')
res = re.sub(regex, '100', string)

print(res) # 100
           # Expected: function(true, 0, 100)
</code>```

Question: Could you point me out why the above code doesn't work? How would I write the code to achieve the expected result?

答:
An alternative, you can print everything before the match and everything after the match, then print it out with the new result like so:

```<code>regex = re.compile( '(function\([a-zA-Z]*, [0-9]*, )([0-9]*)(\))' )
res = re.sub( regex, r'\1 100\3', string )
</code>```

Basically, I placed parenthesis around the text before the expected match and after the expected match. Then I print it out as \1 (first match) 100 (new text) \3 (third match).

The reason why I propose this particular expression is in case OP specifically needs to only match strings that also contain the preceding "function(" section (or some other pattern). Plus, this is just an extension of OP's solution, so it may be more intuitive to OP.

Body:
I would like to replace the 3rd argument in the string with a new number (let's say 100).  The matched string always starts with function, with the first argument either true or false, and with the number as second argument.

                                               Expected
                    |                             |
                    v                             v
'function(true, 0, 15)'   --> 'function(true, 0, 100)'
'function(false, 0, 23)'  --> 'function(false, 0, 100)'

I have been reading the related posts but I believe I must have misunderstood some regex concept. The following code is that I had tried but it always replaces the whole string:

import re
string = 'function(true, 0, 15)'
regex = re.compile('function\([a-zA-Z]*, [0-9]*, ([0-9]*)\)')
res = re.sub(regex, '100', string)

print(res) # 100
           # Expected: function(true, 0, 100)

Question: Could you point me out why the above code doesn't work? How would I write the code to achieve the expected result?

Body:
An alternative, you can print everything before the match and everything after the match, then print it out with the new result like so:

regex = re.compile( '(function\([a-zA-Z]*, [0-9]*, )([0-9]*)(\))' )
res = re.sub( regex, r'\1 100\3', string )

Basically, I placed parenthesis around the text before the expected match and after the expected match. Then I print it out as \1 (first match) 100 (new text) \3 (third match).

The reason why I propose this particular expression is in case OP specifically needs to only match strings that also contain the preceding "function(" section (or some other pattern). Plus, this is just an extension of OP's solution, so it may be more intuitive to OP.


问:
Cannot unselect the checkmark when scroll the tableView
I'm trying to do checkmark button in tableViewCell. The checkmark image will be hide/showing when user tap on the checkmark button. The problem I'm facing right now is checkmark button acting weird when I scroll the table view which is I need to double tap to unselect the checkmark.

When I do not scroll the tableView it's working great. Below are the video and code. Thanks in advance.

https://youtu.be/cQBIuIXJlRY

```<code>    func tableView(_ tableView: UITableView, cellForRowAt
   indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "dtvc") as! DeviceTableViewCell

    let scannedDevice = devices[indexPath.row]

    // Set the tag & addTarget for addButton
    cell.addButton.addTarget(self, action: #selector(addButtonTapped), for: .touchUpInside)
    cell.addButton.isEnabled = true
    cell.addButton.tag = indexPath.row

    cell.configureCell(with: scannedDevice)
    cell.isSelected = checked[indexPath.row] ?? false
    print("cell isSelected at \(indexPath.row) cellForRow \(cell.isSelected)")
    print("checked value at \(indexPath.row) is \(checked[indexPath.row])")

    if checked[indexPath.row] == true {
        cell.deviceMake.textColor = UIColor.white
        cell.backgroundColor = UIColor(red: 233/255, green: 72/255, blue: 85/255, alpha: 1)
        cell.addButton.setImage(UIImage(named: "Checkmark"), for: .normal)
        cell.addButton.bgColor = UIColor.green

    } else {
        cell.deviceMake.textColor = UIColor.gray
        cell.backgroundColor = UIColor.clear
        cell.addButton.setImage(nil, for: .normal)
        cell.addButton.bgColor = UIColor(red: 233/255, green: 72/255, blue: 85/255, alpha: 1)
    }

    return cell

}

@objc func addButtonTapped(_ sender: UIButton) {

    let indexPath = IndexPath(row: sender.tag, section: 0)
    let scannedDevice = devices[sender.tag]

    let cell = tableView.cellForRow(at: indexPath) as! DeviceTableViewCell
    cell.isSelected = !cell.isSelected

    print("cell.isSelected is at button \(sender.tag) tapped is \(cell.isSelected)")

    if cell.isSelected == true {
    // Main color RGB is  233,72,85 ... hex is E94855
        cell.deviceMake.textColor = UIColor.white
        cell.backgroundColor = UIColor(red: 233/255, green: 72/255, blue: 85/255, alpha: 1)
        cell.addButton.setImage(UIImage(named: "Checkmark"), for: .normal)
        cell.addButton.bgColor = UIColor.green
        checked[sender.tag] = cell.isSelected
        print("Checked 1 at tag \(sender.tag) is \(checked[sender.tag])")

        //show selectedDeviceView
        if selectedDeviceView.isHidden {
            UIView.animate(withDuration: 2.5, delay: 0.7, options: .curveEaseInOut, animations: {
                self.tableViewHeightConstraint.constant = self.tableViewHeightConstraint.constant - self.selectedDeviceViewTopConstraint.constant - self.selectedDeviceView.frame.height
                self.selectedDeviceViewTopConstraint.constant = 0
                self.selectedDeviceView.isHidden = false
            }, completion: nil)
        }

    }
    else {
        cell.deviceMake.textColor = UIColor.gray
        cell.backgroundColor = UIColor.clear
        cell.addButton.setImage(nil, for: .normal)
        cell.addButton.bgColor = UIColor(red: 233/255, green: 72/255, blue: 85/255, alpha: 1)
        checked[sender.tag] = cell.isSelected
        print("Checked 2 at tag \(sender.tag) is \(checked[sender.tag])")

    }

}
</code>```

答:
First of all put the selected state into the devices class/struct rather than using an extra array

```<code>class Device {
    var isSelected = false

...
</code>```

Second of all don't think in terms of the view think in terms of the model. That means toggle isSelected in the model and reload the row. The benefit is that the view is manipulated reliably only in cellForRow.

For example

```<code>@objc func addButtonTapped(_ sender: UIButton) {

    let indexPath = IndexPath(row: sender.tag, section: 0)
    devices[indexPath.row].isSelected.toggle()
    self.tableView.reloadRows(at: [indexPath], with: .none)
    if devices[indexPath.row].isSelected && selectedDeviceView.isHidden {
        UIView.animate(withDuration: 2.5, delay: 0.7, options: .curveEaseInOut, animations: {
            self.tableViewHeightConstraint.constant = self.tableViewHeightConstraint.constant - self.selectedDeviceViewTopConstraint.constant - self.selectedDeviceView.frame.height
            self.selectedDeviceViewTopConstraint.constant = 0
            self.selectedDeviceView.isHidden = false
        }, completion: nil)
    }
}
</code>```

And in cellForRow change

```<code>cell.isSelected = scannedDevice.isSelected
</code>```

Body:
I'm trying to do checkmark button in tableViewCell. The checkmark image will be hide/showing when user tap on the checkmark button. The problem I'm facing right now is checkmark button acting weird when I scroll the table view which is I need to double tap to unselect the checkmark.

When I do not scroll the tableView it's working great. Below are the video and code. Thanks in advance.

https://youtu.be/cQBIuIXJlRY

    func tableView(_ tableView: UITableView, cellForRowAt
   indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "dtvc") as! DeviceTableViewCell

    let scannedDevice = devices[indexPath.row]

    // Set the tag & addTarget for addButton
    cell.addButton.addTarget(self, action: #selector(addButtonTapped), for: .touchUpInside)
    cell.addButton.isEnabled = true
    cell.addButton.tag = indexPath.row

    cell.configureCell(with: scannedDevice)
    cell.isSelected = checked[indexPath.row] ?? false
    print("cell isSelected at \(indexPath.row) cellForRow \(cell.isSelected)")
    print("checked value at \(indexPath.row) is \(checked[indexPath.row])")

    if checked[indexPath.row] == true {
        cell.deviceMake.textColor = UIColor.white
        cell.backgroundColor = UIColor(red: 233/255, green: 72/255, blue: 85/255, alpha: 1)
        cell.addButton.setImage(UIImage(named: "Checkmark"), for: .normal)
        cell.addButton.bgColor = UIColor.green

    } else {
        cell.deviceMake.textColor = UIColor.gray
        cell.backgroundColor = UIColor.clear
        cell.addButton.setImage(nil, for: .normal)
        cell.addButton.bgColor = UIColor(red: 233/255, green: 72/255, blue: 85/255, alpha: 1)
    }

    return cell

}

@objc func addButtonTapped(_ sender: UIButton) {

    let indexPath = IndexPath(row: sender.tag, section: 0)
    let scannedDevice = devices[sender.tag]

    let cell = tableView.cellForRow(at: indexPath) as! DeviceTableViewCell
    cell.isSelected = !cell.isSelected

    print("cell.isSelected is at button \(sender.tag) tapped is \(cell.isSelected)")

    if cell.isSelected == true {
    // Main color RGB is  233,72,85 ... hex is E94855
        cell.deviceMake.textColor = UIColor.white
        cell.backgroundColor = UIColor(red: 233/255, green: 72/255, blue: 85/255, alpha: 1)
        cell.addButton.setImage(UIImage(named: "Checkmark"), for: .normal)
        cell.addButton.bgColor = UIColor.green
        checked[sender.tag] = cell.isSelected
        print("Checked 1 at tag \(sender.tag) is \(checked[sender.tag])")

        //show selectedDeviceView
        if selectedDeviceView.isHidden {
            UIView.animate(withDuration: 2.5, delay: 0.7, options: .curveEaseInOut, animations: {
                self.tableViewHeightConstraint.constant = self.tableViewHeightConstraint.constant - self.selectedDeviceViewTopConstraint.constant - self.selectedDeviceView.frame.height
                self.selectedDeviceViewTopConstraint.constant = 0
                self.selectedDeviceView.isHidden = false
            }, completion: nil)
        }

    }
    else {
        cell.deviceMake.textColor = UIColor.gray
        cell.backgroundColor = UIColor.clear
        cell.addButton.setImage(nil, for: .normal)
        cell.addButton.bgColor = UIColor(red: 233/255, green: 72/255, blue: 85/255, alpha: 1)
        checked[sender.tag] = cell.isSelected
        print("Checked 2 at tag \(sender.tag) is \(checked[sender.tag])")

    }

}

Body:
First of all put the selected state into the devices class/struct rather than using an extra array

class Device {
    var isSelected = false

...

Second of all don't think in terms of the view think in terms of the model. That means toggle isSelected in the model and reload the row. The benefit is that the view is manipulated reliably only in cellForRow.

For example

@objc func addButtonTapped(_ sender: UIButton) {

    let indexPath = IndexPath(row: sender.tag, section: 0)
    devices[indexPath.row].isSelected.toggle()
    self.tableView.reloadRows(at: [indexPath], with: .none)
    if devices[indexPath.row].isSelected && selectedDeviceView.isHidden {
        UIView.animate(withDuration: 2.5, delay: 0.7, options: .curveEaseInOut, animations: {
            self.tableViewHeightConstraint.constant = self.tableViewHeightConstraint.constant - self.selectedDeviceViewTopConstraint.constant - self.selectedDeviceView.frame.height
            self.selectedDeviceViewTopConstraint.constant = 0
            self.selectedDeviceView.isHidden = false
        }, completion: nil)
    }
}

And in cellForRow change

cell.isSelected = scannedDevice.isSelected


问:
How to check which RecyclerView has been clicked
I have a view with two RecyclerViews. They have different ArrayLists, but the same kind of adapters. In the OnClick method in my activity, I want to get which of the Recyclers has been clicked, and then get the item selected.

I tried using view instanceof RecylcerView but that didn't do the trick.

答:
I think what you are looking for is just setting onClickListener on each RecyclerView in its Adapter. You can do it by using interfaces, in this case you need to create 2 interfaces:

```<code>interface clickListenerInFirstRecycler{
void onFirstClick(int position);
}

interface clickListenerInSecondRecycler{
    void onSecondClick(int position);
}
</code>```

Depending on which information you want retrieve from an item, just change parameters in interfaces. In this case I'll use only to retrieve item's position.

Then in your Adapter class make global variables of those interfaces and its setter methods:

```<code>private  clickListenerInFirstRecycler listener;

public void setOnClickListener(clickListenerInFirstRecycler listener){
    this.listener = listener;
}
</code>```

Do analogically with second interface and adapter.

Then in onBindViewHolder call this variable, in this case listener, method which you created (in first case onFirstClick) and pass appropriate argument. In this case it's just position:

```<code>listener.onFirstClick(position);
</code>```

Then go to your activity and make them implement those interfaces. You will need to override methods from interfaces and from there you will be able to handle clicks from specified RecyclerView and data from there.
Do not forget to call in onCreate or after you initialised an Adapter to set up those interfaces:
adapter.setOnClickListener(this)

Body:
I think what you are looking for is just setting onClickListener on each RecyclerView in its Adapter. You can do it by using interfaces, in this case you need to create 2 interfaces:

interface clickListenerInFirstRecycler{
void onFirstClick(int position);
}

interface clickListenerInSecondRecycler{
    void onSecondClick(int position);
}

Depending on which information you want retrieve from an item, just change parameters in interfaces. In this case I'll use only to retrieve item's position.

Then in your Adapter class make global variables of those interfaces and its setter methods:

private  clickListenerInFirstRecycler listener;

public void setOnClickListener(clickListenerInFirstRecycler listener){
    this.listener = listener;
}

Do analogically with second interface and adapter.

Then in onBindViewHolder call this variable, in this case listener, method which you created (in first case onFirstClick) and pass appropriate argument. In this case it's just position:

listener.onFirstClick(position);

Then go to your activity and make them implement those interfaces. You will need to override methods from interfaces and from there you will be able to handle clicks from specified RecyclerView and data from there.
Do not forget to call in onCreate or after you initialised an Adapter to set up those interfaces:
adapter.setOnClickListener(this)


答:
In your parent ts. You have a function:

```<code>parentListner($event) {
    this.childMessage = $event
 }
</code>```

While in html you are calling:

```<code><app-child (childEvent)="parentListener($event)"></app-child>
</code>```

Names have to be the same.

Title: Angular 'is not a function' caused by missing import?

Body:
Getting an 'is not a function' in Angular 7 / typescript 3-ish, using an EventEmitter.  Much has been written (a b) about this error, but very few upvotes for answers (a b c d e f ).  I'm almost there, but need some help finishing this off.

Here is one stackblitz with the error.
...and a similar one without the error.

The only difference seems to be that with the error, my event emitter and receiver are in sibling folders.  In the one that works, the event receiver is in a parent folder and the emitter is in a child folder.

It seems like some kind of an import/module tweak is required to fix the broken one, but I can't seem to get it.
Suggestions?

Body:
In your parent ts. You have a function:

parentListner($event) {
    this.childMessage = $event
 }

While in html you are calling:

<app-child (childEvent)="parentListener($event)"></app-child>

Names have to be the same.


问:
How to bypass the VPN for specific connections in PHP?
My (Windows) computer is connected with OpenVPN to my VPN provider. That means that everything goes through it, alternatively using its proxies as well for a little bit of variation.

In many situations, I don't want it to go through the VPN (or any proxy) when making a request. For example, when I use PHP to log in to my bank. Or when all proxies/VPNs are blocked from downloading a file, or loading a webpage, etc., which happens frequently. But then I'm stuck, because to the best of my knowledge, there is no way to tell PHP to "bypass the VPN and use my home IP address directly".

I would like something like:

```<code>php_bypass_VPN();
/* make cURL requests here */
php_restore_VPN();
</code>```

Is it possible at all? If not, why is this not a major problem for anyone else? Or is it? It has caused countless issues for me, and not just in PHP context. For example, I would want the buffering local Internet radio station to go through my normal IP address as well, but no software I've ever seen provides any means to "bypass VPN".

If the solution involves hacking the OS and/or installing a bunch of spyware, I'll not be happy. Please tell me there is some simple way to do this, such as:

```<code>shell_exec('somebinary bypassvpntemporarily');
</code>```

That would be swell, although a cross-platform solution would be vastly preferred.

答:
Most VPNs work in a way that they install a new network interface driver on your PC and make sure all traffic goes through it so it can encrypt it on the way out.
I guess you could try to go through a specific interface but I'm not sure that will overcome the VPN (heres how to get a specific interface how to bind raw socket to specific interface).
Other than that you could create your own driver...</p>

Body:
My (Windows) computer is connected with OpenVPN to my VPN provider. That means that everything goes through it, alternatively using its proxies as well for a little bit of variation.

In many situations, I don't want it to go through the VPN (or any proxy) when making a request. For example, when I use PHP to log in to my bank. Or when all proxies/VPNs are blocked from downloading a file, or loading a webpage, etc., which happens frequently. But then I'm stuck, because to the best of my knowledge, there is no way to tell PHP to "bypass the VPN and use my home IP address directly".

I would like something like:

php_bypass_VPN();
/* make cURL requests here */
php_restore_VPN();

Is it possible at all? If not, why is this not a major problem for anyone else? Or is it? It has caused countless issues for me, and not just in PHP context. For example, I would want the buffering local Internet radio station to go through my normal IP address as well, but no software I've ever seen provides any means to "bypass VPN".

If the solution involves hacking the OS and/or installing a bunch of spyware, I'll not be happy. Please tell me there is some simple way to do this, such as:

shell_exec('somebinary bypassvpntemporarily');

That would be swell, although a cross-platform solution would be vastly preferred.


答:
First of all, you are calling the reset method document.getElementById("add_multycontact").reset() at the wrong place. This will only be called once on $(document).ready. So, you need to call that before or just after opening the modal with form.

Even if that does not work, then try this in place of reset:

```<code>$('#add_multycontact select').prop('selectedIndex',0);
$('#add_multycontact input[type="text"]').val('');
</code>```

Title: how to clear form data without refresh page

Body:
First of all, you are calling the reset method document.getElementById("add_multycontact").reset() at the wrong place. This will only be called once on $(document).ready. So, you need to call that before or just after opening the modal with form.

Even if that does not work, then try this in place of reset:

$('#add_multycontact select').prop('selectedIndex',0);
$('#add_multycontact input[type="text"]').val('');


问:
This code doesn't work in IE
Hi so I have this jQuery/JS script. That basically takes an encoded URL string and parses it and saves variable values into variables.

Basically what PHP's $_GET does.

```<code>function getUrlVars()
{
 var map = {};
 var parts = window.location.search.replace(/[?&]+([^=&]+)(=[^&]*)?/gi,

   function(m,key,value)
     { map[key] = (value === undefined) ? true : value.substring(1); });

 return map;
}
</code>```

Basically this script does what I want. From this URL string:

```<code>/autopop.html?Email=test%40test.com&LastName=Test+last&&FirstName=+Test+First
</code>```

I get the values:

```<code>Email = test%40test.com

LastName = Test+last

FirstName = +Test+First
</code>```

What I want to do is Auto-populate a form on this same page with this information.
(I know what you're thinking a server-side script would be a better solution but the boss says we don't have access to that, trust me, I've tried)

Long story short, here's the rest of my code:

```<code>var keys = getUrlVars();

$(document).ready(function(){
    var fname = keys['FirstName'].replace(/\+/g , " ").trim();
    var lname = keys['LastName'].replace(/\+/g , " ").trim();
    var email = decodeURIComponent(keys['Contact0Email'].replace(/\+/g , " ")).trim();
    $("#Email").val(email);
    $("#FirstName").val(fname);
    $("#LastName").val(lname);
});
</code>```

This code gets the job done. All except for one browser. IE.

IE doesn't support decodeURIComponent or so I've read. In any case, I tried using other functions like decodeURI and escape all producing unwanted results.

My google searches have yielded nothing but, semi-interesting articles (totally off-topic but thought I'd just share that).

No solutions. Can anyone shed some light? How do I make this work on IE?

答:
You have read wrong, decodeURIComponent works just fine in IE, even in IE6.

However, trim doesn't work in IE browsers prior to IE 9 and that's what causing your script to crash.

For working alternative, see the accepted answer here: .trim() in JavaScript not working in IE

Or use the jQuery trim() method as you're already using jQuery anyway.

Title: This code doesn't work in IE

Body:
Hi so I have this jQuery/JS script. That basically takes an encoded URL string and parses it and saves variable values into variables.

Basically what PHP's $_GET does.

function getUrlVars()
{
 var map = {};
 var parts = window.location.search.replace(/[?&]+([^=&]+)(=[^&]*)?/gi,

   function(m,key,value)
     { map[key] = (value === undefined) ? true : value.substring(1); });

 return map;
}

Basically this script does what I want. From this URL string:

/autopop.html?Email=test%40test.com&LastName=Test+last&&FirstName=+Test+First

I get the values:

Email = test%40test.com

LastName = Test+last

FirstName = +Test+First

What I want to do is Auto-populate a form on this same page with this information.
(I know what you're thinking a server-side script would be a better solution but the boss says we don't have access to that, trust me, I've tried)

Long story short, here's the rest of my code:

var keys = getUrlVars();

$(document).ready(function(){
    var fname = keys['FirstName'].replace(/\+/g , " ").trim();
    var lname = keys['LastName'].replace(/\+/g , " ").trim();
    var email = decodeURIComponent(keys['Contact0Email'].replace(/\+/g , " ")).trim();
    $("#Email").val(email);
    $("#FirstName").val(fname);
    $("#LastName").val(lname);
});

This code gets the job done. All except for one browser. IE.

IE doesn't support decodeURIComponent or so I've read. In any case, I tried using other functions like decodeURI and escape all producing unwanted results.

My google searches have yielded nothing but, semi-interesting articles (totally off-topic but thought I'd just share that).

No solutions. Can anyone shed some light? How do I make this work on IE?


问:
Enabling Integer Overflow in Python
I'd like to create a 2D environment in which the top & bottom and left & right are connected  (similar to a Torus or Doughnut). However, rather than doing a check on an object's x/y coordinate every frame, I'd like to simulate it using integer overflow.

While normal iteration (as shown in the sample code below) can be done, it may be slightly more effective (though dangerous) to simply enable overflow on some variables, especially when dealing with hundreds or thousands of objects in each frame/iteration.

I can find some examples which also simulate integer overflow in Python like this. However, I'm looking for something that can overflow just by enabling overflow in certain variables and skipping the checks in general.

```<code># With normal checking of every instance
import random

width = 100
height = 100

class item():
    global width, height

    def __init__(self):
        self.x = random.randint(0, width)
        self.y = random.randint(0, height)

items = [item for _ in range(10)] # create 10 instances

while True:
    for obj in items:
        obj.x += 10
        obj.y += 20
        while obj.x > width:
            obj.x -= width
        while obj.y > height:
            obj.y -= height
        while obj.x < width:
            obj.x += width
        while obj.y < height:
            obj.y += height
</code>```

I'd like to simulate integer overflow for only some certain classes/objects. Is there a way to have some variables automatically overflow and loop back to their min/max values?

答:
You can use properties to implement getters/setters with customized behaviour. For example like this:

import random

WIDTH = 100
HEIGHT = 100

class item():

    def __init__(self):
        self._x = random.randint(0, WIDTH - 1)
        self._y = random.randint(0, HEIGHT - 1)

    def __str__(self):
        return '(%r, %r)' % (self._x, self._y)

    @property
    def x(self):
        return self._x

    @x.setter
    def x(self, new_value):
        self._x = new_value % WIDTH

    @property
    def y(self):
        return self._y

    @y.setter
    def y(self, new_value):
        self._y = new_value % HEIGHT

items = [item() for _ in range(10)]

while True:
    for pos in items:
        pos.x += 10
        pos.y += 20
        print(pos)  # to show the results
```

Title: Enabling Integer Overflow in Python

Body:
I'd like to create a 2D environment in which the top & bottom and left & right are connected  (similar to a Torus or Doughnut). However, rather than doing a check on an object's x/y coordinate every frame, I'd like to simulate it using integer overflow.

While normal iteration (as shown in the sample code below) can be done, it may be slightly more effective (though dangerous) to simply enable overflow on some variables, especially when dealing with hundreds or thousands of objects in each frame/iteration.

I can find some examples which also simulate integer overflow in Python like this. However, I'm looking for something that can overflow just by enabling overflow in certain variables and skipping the checks in general.

# With normal checking of every instance
import random

width = 100
height = 100

class item():
    global width, height

    def __init__(self):
        self.x = random.randint(0, width)
        self.y = random.randint(0, height)

items = [item for _ in range(10)] # create 10 instances

while True:
    for obj in items:
        obj.x += 10
        obj.y += 20
        while obj.x > width:
            obj.x -= width
        while obj.y > height:
            obj.y -= height
        while obj.x < width:
            obj.x += width
        while obj.y < height:
            obj.y += height

I'd like to simulate integer overflow for only some certain classes/objects. Is there a way to have some variables automatically overflow and loop back to their min/max values?


问:
What format of input does this function expect to parse from std::istream?
I am following along the great book C++17 by Example, which introduces C++17 by showcasing a series of mini projects -- very cool.

However, in chapter 2, where a Set is implemented on top of a LinkedList, there is this code:

void Set::read(std::istream& inStream) {
  int size;
  inStream >> size;

  int count = 0;
  while (count < size) {
    double value;
    inStream >> value;
    insert(value);
    ++count;
  }
}
```

<pre class="lang-cpp prettyprint-override"><code>void Set::write(std::ostream& outStream) {
  outStream << "{";

  bool firstValue = true;
  Iterator iterator = first();

  while (iterator.hasNext()) {
    outStream << (firstValue ? "" : ", ") << iterator.getValue();
    firstValue = false;
    iterator.next();
  }

  outStream << "}";
}
</code>```

int main() {
  Set s, t;

  s.read(std::cin);
  t.read(std::cin);

  std::cout << std::endl << "s = ";
  s.write(std::cout);
  std::cout << std::endl;

  std::cout << std::endl << "t = ";
  t.write(std::cout);
  std::cout << std::endl << std::endl;

  // snip
}
```

<p>I am fairly new to C++, and I do not know how to run this. Of course, I did some research before asking, but the way I came up with does not produce the expected results:</p>

```lambdarookies-MacBook:02-the-set-class lambdarookie$ ./02-the-set-class
1 2 3
3 4 5

s = {2}         // Expected: s = {1, 2, 3}
t = {3, 4, 5}
```

Now I am wondering:

Is this simply not the right way to supply arguments, or

it is the right way, and the bug must be elsewhere in the code?

答:
The first number Set::read reads is the size of the set. Then it reads that many numbers, and adds them to the set. The rest of the line is ignored by the current invocation of read, and is picked up by the next one, which is, by coincidence, the size of the next set you are testing with. Therefore, inputting 1 2 3 results in a set of size 1, with the only elem 2.

Please note: hasNext is a java-ism, unlike how the usual C++ iterators work. Perhaps you could consider also taking a look at a different manual.

Body:
I am following along the great book C++17 by Example, which introduces C++17 by showcasing a series of mini projects -- very cool.

However, in chapter 2, where a Set is implemented on top of a LinkedList, there is this code:

void Set::read(std::istream& inStream) {
  int size;
  inStream >> size;

  int count = 0;
  while (count < size) {
    double value;
    inStream >> value;
    insert(value);
    ++count;
  }
}

void Set::write(std::ostream& outStream) {
  outStream << "{";

  bool firstValue = true;
  Iterator iterator = first();

  while (iterator.hasNext()) {
    outStream << (firstValue ? "" : ", ") << iterator.getValue();
    firstValue = false;
    iterator.next();
  }

  outStream << "}";
}

int main() {
  Set s, t;

  s.read(std::cin);
  t.read(std::cin);

  std::cout << std::endl << "s = ";
  s.write(std::cout);
  std::cout << std::endl;

  std::cout << std::endl << "t = ";
  t.write(std::cout);
  std::cout << std::endl << std::endl;

  // snip
}

I am fairly new to C++, and I do not know how to run this. Of course, I did some research before asking, but the way I came up with does not produce the expected results:

lambdarookies-MacBook:02-the-set-class lambdarookie$ ./02-the-set-class
1 2 3
3 4 5

s = {2}         // Expected: s = {1, 2, 3}
t = {3, 4, 5}

Now I am wondering:

Is this simply not the right way to supply arguments, or

it is the right way, and the bug must be elsewhere in the code?