问:
hiding elements after a button is clicked - angular2 - ngFor
I am still learning Angular2 and I currently can't find a solution for my problem. I am displaying 1-3 Tiers/Packages using the ngFor, which than looks like this tiers in display mode.
After I click the edit button I only want the clicked element to go into edit mode, currently all of them switch into edit mode, which looks like this tiers in edit mode.

Here is the code, reduced it to the relevant parts.

```<code><h1 class="page-title"><span class="fw-semi-bold">Packages</span></h1>
<div class="row">
  <div class="col-md-4" *ngFor="let tier of tiers; let i=index;">
    <!-- Show Mode -->
    <ul [hidden]="editMode" class="pricing-table">
      <li class="plan-name">
        {{ tier.title }} {{i}}
      </li>
      <li>
        description
      </li>
      <li>
        description
      </li>
      <li>
        description
      </li>
      <li>
        description
      </li>
      <p class="plan-price">{{ tier.price }}</p>
      <li class="plan-action">
        <a class="btn btn-primary" (click)="this.onEdit()">Edit</a>
        <a class="btn btn-success" (click)="this.clickSave()">SaveYes</a>
        <a class="btn btn-warning" >Get</a>
      </li>
    </ul>
    <!-- Edit Mode -->
    <ul [hidden]="!editMode" class="pricing-table-edit">
      <li class="plan-name-edit">
        <input type="text" class="form-control" style=" font-size: 3rem;" placeholder="{{ tier.title }} " formControlName="package_name">

      </li>
      <li >
        <div class="rewards-edit" style="background-color: #3a3d46; ">Feature 1</div>
      </li>
      <li>
        <div class="rewards-edit" style="background-color: #3a3d46">Feature 1</div>
      </li>
      <li>
        <div class="rewards-edit" style="background-color: #3a3d46">Feature 1</div>
      </li>
      <li>
        <div class="rewards-edit" style="background-color: #3a3d46">Feature 1</div>
      </li>
      <div style="align:center; padding-left: 40%; padding-right: 40%;"><input type="text" id="package_price1" class="form-control plan-price" placeholder="4,99" formControlName="package_price"></div>

      <li class="plan-action">
        <a class="btn btn-primary">Edit</a>
        <a class="btn btn-success">Save</a>
        <a class="btn btn-warning">Publish</a>
      </li>
    </ul>
  </div>
</code>```

Components-File:

```<code>export class PackagesComponent {
  editMode = false;

  onEdit () {
    this.editMode = true;
  }
}
</code>```

Is there a way to use the index variable in my method, so that I know which of the 3 tiers is currently clicked? Or are there any other solutions or maybe ideas?

Thanks a lot :)

UPDATED CODE, thanks to Abrar:

```<code>export class PackagesComponent {  //this has to be renamed to TierComponent for less confusion
  public tierToEdit: Tier;
  editMode = false;
  tiers: Tier[] = [
    new Tier(
      10,
      'First Tier',
      [
        {id: 500, title: 'desc', description: 'crazy description'},
        {id: 501, title: 'desc', description: 'crazy description'},
        {id: 502, title: 'desc', description: 'crazy description'},
        {id: 503, title: 'desc', description: 'crazy description'}
      ],
      5.00),
      *[more code..]*
  ]

  constructor (private tierService: TierService) {}

  ngOnInit() {
  }

  onEdit (tier: Tier) {
    this.editMode = true;
    this.tierToEdit = tier;
  }
</code>```

Template-File:

```<code><h1 class="page-title"><span class="fw-semi-bold">Packages</span></h1>
<div class="row">
  <div class="col-md-4" *ngFor="let tier of tiers; let i=index;">
    <!-- Show Mode -->
    <ul *ngIf="!editMode || tierToEdit != tier" class="pricing-table">
      <li class="plan-name">
        {{ tier.title }} {{i}}
      </li>
     <li class="plan-name">
        {{ tier.title }} {{i}}
      </li>
      <li>
        description
      </li>
      <li>
        description
      </li>
      <li>
        description
      </li>
      <li>
        description
      </li>
      <p class="plan-price">{{ tier.price }}</p>
      <li class="plan-action">
        <a class="btn btn-primary" (click)="onEdit(tier)">Edit</a>
        <a class="btn btn-success" (click)="this.clickSave()">SaveYes</a>
        <a class="btn btn-warning" >Get</a>
      </li>
    </ul>
    <!-- Edit Mode -->
    <ul *ngIf="editMode && tierToEdit == tier " class="pricing-table-edit">
      <li class="plan-name-edit">
        <input type="text" class="form-control" style=" font-size: 3rem;" placeholder="{{ tier.title }} " formControlName="package_name">

      </li>
      <li >
        <div class="rewards-edit" style="background-color: #3a3d46; ">Feature 1</div>
      </li>
      <li>
        <div class="rewards-edit" style="background-color: #3a3d46">Feature 1</div>
      </li>
      <li>
        <div class="rewards-edit" style="background-color: #3a3d46">Feature 1</div>
      </li>
      <li>
        <div class="rewards-edit" style="background-color: #3a3d46">Feature 1</div>
      </li>
      <div style="align:center; padding-left: 40%; padding-right: 40%;"><input type="text" id="package_price1" class="form-control plan-price" placeholder="4,99" formControlName="package_price"></div>

      <li class="plan-action">
        <a class="btn btn-primary">Edit</a>
        <a class="btn btn-success">Save</a>
        <a class="btn btn-warning">Publish</a>
      </li>
    </ul>
  </div>
</code>```

答:
First of all, you don't actually need to call this.onEdit() or this.clickSave() in the (click) event handler. Only onEdit() or clickSave() will work alright.

Notice here that you are not passing any reference to the clicked item which you want to go into edit mode. So, here you can either pass the index like this - onEdit(i) or the object like this - onEdit(tier).

In your PackagesComponent you can set the tier that is clicked to a member variable -

```<code>export class PackagesComponent {
  public packageToEdit:Package;   // <------- new code

  editMode = false;

  onEdit (tier:Package) {
    this.packageToEdit = tier;    // <------- new code
    this.editMode = true;
  }
}
</code>```

Now, in your HTML code

```<code><!-- Edit Mode -->
<ul [hidden]="!editMode && packageToEdit==tier" class="pricing-table-edit">

  <li class="plan-name-edit">
    <input type="text" class="form-control" style=" font-size: 3rem;" placeholder="{{ tier.title }} " formControlName="package_name">

  </li>
  <li >
    <div class="rewards-edit" style="background-color: #3a3d46; ">Feature 1</div>
  </li>
  <li>
    <div class="rewards-edit" style="background-color: #3a3d46">Feature 1</div>
  </li>
  <li>
    <div class="rewards-edit" style="background-color: #3a3d46">Feature 1</div>
  </li>
  <li>
    <div class="rewards-edit" style="background-color: #3a3d46">Feature 1</div>
  </li>
  <div style="align:center; padding-left: 40%; padding-right: 40%;"><input type="text" id="package_price1" class="form-control plan-price" placeholder="4,99" formControlName="package_price"></div>

  <li class="plan-action">
    <a class="btn btn-primary">Edit</a>
    <a class="btn btn-success">Save</a>
    <a class="btn btn-warning">Publish</a>
  </li>
</ul>
</code>```

Body:
I am still learning Angular2 and I currently can't find a solution for my problem. I am displaying 1-3 Tiers/Packages using the ngFor, which than looks like this tiers in display mode.
After I click the edit button I only want the clicked element to go into edit mode, currently all of them switch into edit mode, which looks like this tiers in edit mode.

Here is the code, reduced it to the relevant parts.

Packages

        {{ tier.title }} {{i}}

        description

        description

        description

        description

{{ tier.price }}

        Edit
        SaveYes
        Get

        <input type="text" class="form-control" style=" font-size: 3rem;" placeholder="{{ tier.title }} " formControlName="package_name">

Feature 1

Feature 1

Feature 1

Feature 1

<input type="text" id="package_price1" class="form-control plan-price" placeholder="4,99" formControlName="package_price">

        Edit
        Save
        Publish

Components-File:

export class PackagesComponent {
  editMode = false;

  onEdit () {
    this.editMode = true;
  }
}

Is there a way to use the index variable in my method, so that I know which of the 3 tiers is currently clicked? Or are there any other solutions or maybe ideas?

Thanks a lot :)

UPDATED CODE, thanks to Abrar:

export class PackagesComponent {  //this has to be renamed to TierComponent for less confusion
  public tierToEdit: Tier;
  editMode = false;
  tiers: Tier[] = [
    new Tier(
      10,
      'First Tier',
      [
        {id: 500, title: 'desc', description: 'crazy description'},
        {id: 501, title: 'desc', description: 'crazy description'},
        {id: 502, title: 'desc', description: 'crazy description'},
        {id: 503, title: 'desc', description: 'crazy description'}
      ],
      5.00),
      *[more code..]*
  ]

  constructor (private tierService: TierService) {}

  ngOnInit() {
  }

  onEdit (tier: Tier) {
    this.editMode = true;
    this.tierToEdit = tier;
  }

Template-File:

Packages

        {{ tier.title }} {{i}}

        {{ tier.title }} {{i}}

        description

        description

        description

        description

{{ tier.price }}

        Edit
        SaveYes
        Get

        <input type="text" class="form-control" style=" font-size: 3rem;" placeholder="{{ tier.title }} " formControlName="package_name">

Feature 1

Feature 1

Feature 1

Feature 1

<input type="text" id="package_price1" class="form-control plan-price" placeholder="4,99" formControlName="package_price">

        Edit
        Save
        Publish

Body:
First of all, you don't actually need to call this.onEdit() or this.clickSave() in the (click) event handler. Only onEdit() or clickSave() will work alright.

Notice here that you are not passing any reference to the clicked item which you want to go into edit mode. So, here you can either pass the index like this - onEdit(i) or the object like this - onEdit(tier).

In your PackagesComponent you can set the tier that is clicked to a member variable -

export class PackagesComponent {
  public packageToEdit:Package;   // <------- new code

  editMode = false;

  onEdit (tier:Package) {
    this.packageToEdit = tier;    // <------- new code
    this.editMode = true;
  }
}

Now, in your HTML code

<!-- Edit Mode -->
<ul [hidden]="!editMode && packageToEdit==tier" class="pricing-table-edit">

  <li class="plan-name-edit">
    <input type="text" class="form-control" style=" font-size: 3rem;" placeholder="{{ tier.title }} " formControlName="package_name">

  </li>
  <li >
    <div class="rewards-edit" style="background-color: #3a3d46; ">Feature 1</div>
  </li>
  <li>
    <div class="rewards-edit" style="background-color: #3a3d46">Feature 1</div>
  </li>
  <li>
    <div class="rewards-edit" style="background-color: #3a3d46">Feature 1</div>
  </li>
  <li>
    <div class="rewards-edit" style="background-color: #3a3d46">Feature 1</div>
  </li>
  <div style="align:center; padding-left: 40%; padding-right: 40%;"><input type="text" id="package_price1" class="form-control plan-price" placeholder="4,99" formControlName="package_price"></div>

  <li class="plan-action">
    <a class="btn btn-primary">Edit</a>
    <a class="btn btn-success">Save</a>
    <a class="btn btn-warning">Publish</a>
  </li>
</ul>


来源: stackexchange

问:
Filter a list by pattern matching
How can I filter a list, keeping the items that match a pattern, removing ones that don't?

For example, if I have a list of lists, I would like a function...

```<code>singleItemLists :: [[Int]] -> [[Int]]
</code>```

... to remove all items that don't match the pattern [x].

Ideally, answers should be fairly straightforward to convert to other patterns.

答:
You can use the list monad's >>= implementation to do this

```<code>singleItemLists :: [[Int]] -> [[Int]]
singleItemLists xs = xs >>= (\xs -> case xs of [x] -> [[x]]; _ -> [])
</code>```

As an example of filtering by pattern matching, this is a bit confusing, as it's not clear what that pattern is, and what's need to use the list monad's >>=.

A example that might be clearer would be to filter a lists of Maybe Int to just keep the Just values

```<code>justJusts :: [Maybe Int] -> [Maybe Int]
justJusts xs = xs >>= \x -> case x of Just x -> [Just x]; _ -> []
</code>```

Thanks to a comment from https://codereview.stackexchange.com/users/62002/centril at https://codereview.stackexchange.com/a/164380/34049

ContentLicense: CC BY-SA 3.0

Title: Filter a list by pattern matching

Body:
How can I filter a list, keeping the items that match a pattern, removing ones that don't?

For example, if I have a list of lists, I would like a function...

singleItemLists :: [[Int]] -> [[Int]]

... to remove all items that don't match the pattern [x].

Ideally, answers should be fairly straightforward to convert to other patterns.

Body:
You can use the list monad's >>= implementation to do this

singleItemLists :: [[Int]] -> [[Int]]
singleItemLists xs = xs >>= (\xs -> case xs of [x] -> [[x]]; _ -> [])

As an example of filtering by pattern matching, this is a bit confusing, as it's not clear what that pattern is, and what's need to use the list monad's >>=.

A example that might be clearer would be to filter a lists of Maybe Int to just keep the Just values

justJusts :: [Maybe Int] -> [Maybe Int]
justJusts xs = xs >>= \x -> case x of Just x -> [Just x]; _ -> []

Thanks to a comment from https://codereview.stackexchange.com/users/62002/centril at https://codereview.stackexchange.com/a/164380/34049


问:
Upload failed: Your Instant App APKs should contain at least one base APK
I need to  prepare an Alpha testing for an Instant App and It run like a charm on Android Studio but It is failing when I try to upload it to the PlayStore, saying:

Upload failed

Your Instant App APKs should contain at least one base APK.

The app structure is done using three modules:

-base: It contains all the code

-apk: Wrapper to obtains the installable apk

-instantApp: Wrapper to obtain the instantApp apk

This are the build.gradles:

base/build.gradle

```<code>buildscript {
    repositories {
        jcenter()
    }
}
apply plugin: 'com.android.feature'

repositories {
    jcenter()
    mavenCentral()
    flatDir {
        dirs 'libs'
    }
    maven { url 'https://maven.fabric.io/public' }
}

android {
    compileSdkVersion 25
    buildToolsVersion "26.0.0-rc2"

    baseFeature = true
    dataBinding {
        enabled = true
    }

    defaultConfig {

        minSdkVersion 18
        targetSdkVersion 25
        versionCode 7
        versionName "1.1"
    }

    signingConfigs {
        release {
            [...]
        }
    }

    buildTypes {
        debug {
            [...]
        }
        release {
            minifyEnabled false
            signingConfig signingConfigs.release
            [...]
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    lintOptions {
        abortOnError false
    }

    dexOptions {
        javaMaxHeapSize "4g"
    }
}

dependencies {

    application project(":apk")
    [...]
}
apply plugin: 'com.google.gms.google-services'
</code>```

apk/build.gradle

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

android {
    compileSdkVersion 25
    buildToolsVersion "26.0.0-rc2"

    dataBinding {
        enabled true
    }

    defaultConfig {
        applicationId “…”
        minSdkVersion 18
        targetSdkVersion 25
        versionCode 7
       versionName "1.1"
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    signingConfigs {
        release {
            [...]
        }
    }

    buildTypes {
        debug {
            […]
        }
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

            signingConfig signingConfigs.release
            […]
        }
    }
}

dependencies {
    implementation project(':base')
}
</code>```

instantApp/build.gradle

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

dependencies {
    implementation project(':base')
}
</code>```

And this are the Manifests files

base/Manifest.xml

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package=“…”>

<uses-permission android:name="android.permission.INTERNET" />
[…]

<application
    android:name=“[…].TrgApplication"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppBaseTheme">

    <activity
        android:name=“[…].LauncherActivity"
        android:screenOrientation="portrait">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />

            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />

            <data
                android:scheme="https"
                android:host=“[domain]” />
        </intent-filter>
    </activity>
    <activity
        android:name="[…].RootActivity"
        android:screenOrientation="portrait"
        android:windowSoftInputMode="adjustPan" />

    <activity
        android:name="[…].OnBoardingActivity"
        android:screenOrientation="portrait"
        android:windowSoftInputMode="adjustResize" />

    <activity
        android:name="[…].LocationPickerActivity"
        android:screenOrientation="portrait"
        android:windowSoftInputMode="adjustPan" />

    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />

    <service android:name="com.parse.PushService" />
    <receiver
        android:name="com.parse.GcmBroadcastReceiver"
        android:permission="com.google.android.c2dm.permission.SEND">
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            <action android:name="com.google.android.c2dm.intent.REGISTRATION" />

            <!--
              IMPORTANT: Change "com.parse.starter" to match your app's package name.
            -->
            <category android:name="[…]" />
        </intent-filter>
    </receiver>

    <meta-data
        android:name="com.parse.push.gcm_sender_id"
        android:value="id:[…]" />

</application>
</manifest>
</code>```

apk/Manifest.xml

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="..." />
</code>```

This package is different that the app's one

I already tried this solution: (Android Instant-release build not includes base APK) but it didn't work.

I m stuck since the last Friday so any kind of idea could be awesome

Thanks in advance

P.D: Its my first question so I m sorry if I didn't do it propertly ;)

答:
This sample project seems to be pretty close to what you're trying to achieve. Perhaps you don't need the application project(":apk") in your base/build.gradle since you only have one feature (and that is the base split). You could also try removing base = true.

This section of the docs covers your use case - but it sounds like everything is set up correctly.

Could you also add your AndroidManifests to your original post?

Body:
I need to  prepare an Alpha testing for an Instant App and It run like a charm on Android Studio but It is failing when I try to upload it to the PlayStore, saying:

Upload failed

Your Instant App APKs should contain at least one base APK.

The app structure is done using three modules:

-base: It contains all the code

-apk: Wrapper to obtains the installable apk

-instantApp: Wrapper to obtain the instantApp apk

This are the build.gradles:

base/build.gradle

buildscript {
    repositories {
        jcenter()
    }
}
apply plugin: 'com.android.feature'

repositories {
    jcenter()
    mavenCentral()
    flatDir {
        dirs 'libs'
    }
    maven { url 'https://maven.fabric.io/public' }
}

android {
    compileSdkVersion 25
    buildToolsVersion "26.0.0-rc2"

    baseFeature = true
    dataBinding {
        enabled = true
    }

    defaultConfig {

        minSdkVersion 18
        targetSdkVersion 25
        versionCode 7
        versionName "1.1"
    }

    signingConfigs {
        release {
            [...]
        }
    }

    buildTypes {
        debug {
            [...]
        }
        release {
            minifyEnabled false
            signingConfig signingConfigs.release
            [...]
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    lintOptions {
        abortOnError false
    }

    dexOptions {
        javaMaxHeapSize "4g"
    }
}

dependencies {

    application project(":apk")
    [...]
}
apply plugin: 'com.google.gms.google-services'

apk/build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "26.0.0-rc2"

    dataBinding {
        enabled true
    }

    defaultConfig {
        applicationId “…”
        minSdkVersion 18
        targetSdkVersion 25
        versionCode 7
       versionName "1.1"
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    signingConfigs {
        release {
            [...]
        }
    }

    buildTypes {
        debug {
            […]
        }
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

            signingConfig signingConfigs.release
            […]
        }
    }
}

dependencies {
    implementation project(':base')
}

instantApp/build.gradle

apply plugin: 'com.android.instantapp'

dependencies {
    implementation project(':base')
}

And this are the Manifests files

base/Manifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package=“…”>

<uses-permission android:name="android.permission.INTERNET" />
[…]

<application
    android:name=“[…].TrgApplication"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppBaseTheme">

    <activity
        android:name=“[…].LauncherActivity"
        android:screenOrientation="portrait">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />

            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />

            <data
                android:scheme="https"
                android:host=“[domain]” />
        </intent-filter>
    </activity>
    <activity
        android:name="[…].RootActivity"
        android:screenOrientation="portrait"
        android:windowSoftInputMode="adjustPan" />

    <activity
        android:name="[…].OnBoardingActivity"
        android:screenOrientation="portrait"
        android:windowSoftInputMode="adjustResize" />

    <activity
        android:name="[…].LocationPickerActivity"
        android:screenOrientation="portrait"
        android:windowSoftInputMode="adjustPan" />

    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />

    <service android:name="com.parse.PushService" />
    <receiver
        android:name="com.parse.GcmBroadcastReceiver"
        android:permission="com.google.android.c2dm.permission.SEND">
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            <action android:name="com.google.android.c2dm.intent.REGISTRATION" />

            <category android:name="[…]" />
        </intent-filter>
    </receiver>

    <meta-data
        android:name="com.parse.push.gcm_sender_id"
        android:value="id:[…]" />

</application>
</manifest>

apk/Manifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="..." />

This package is different that the app's one

I already tried this solution: (Android Instant-release build not includes base APK) but it didn't work.

I m stuck since the last Friday so any kind of idea could be awesome

Thanks in advance

P.D: Its my first question so I m sorry if I didn't do it propertly ;)


问:
Looking for this theme in Sublime text
Currently I'm taking a online video course, This theme really makes code easy to read, especially for javascript,

The images below are ".html" files , I believe the editor showed in the image is not sublime text. well, i'm the sublime text user, it will be really helpful if someone can please tell me the name of this kind of theme that is working in sublime text, thank you very much in advance.

答:
The theme is  One Dark. The editor is Atom

some similar themes:

Space Gray

Material Theme

Title: Looking for this theme in Sublime text


问:
Partial template specialization for specific type, c++
Using partial specialization of templates I would like to  create a function/method:

A) processing only one specific primitive type (int, double, float,...) of the formal parameter and for other types throwing exception

```<code>template <class T>
T min ( Point <T> p )
{
    /*if (T == int) continue;
    else throw exception*/
}
</code>```

B)  processing more non-primitive types (user defined types) of the formal parameter and for other types throwing exception...

Some code examples would be helpful (without c++ boost library). Thanks for your help.

答:
This is the solution of your problem (part A).

```<code>template<bool b> struct compile_time_assert;

template<>
struct compile_time_assert<true>
{};

template<class T>
struct is_int
{
     static const bool value = false;
};
template<>
struct is_int<int>
{
     static const bool value = true;
};

template <class T>
T min ( Point <T> p )
{
    /*
     since you can check error at compile time, there is no reason to
     raise exception (which is at runtime) if T is not int!
     the following assert will not compile if T is not int.
     not only that, you can even see the error message "_error_T_is_not_int"
     if T is not int;
    */

    compile_time_assert<is_int<T>::value> _error_T_is_not_int;

    //your code
}
</code>```

See these sample code.

sample
code1
when T is int. No error. Please ignore the
warning though!

sample
code2
when T is double. Now, see the error
message also. Please ignore the
warning though!

Similarly, you can write templates for other types, (double, char, whatever). Or, even better, you can simply merge all those into just one struct, and instead can define many booleans (for each type) in a single template, like static const bool is_T_int = true;. Etc. Do experiments, you'll learn!

But then, I wonder if you want your function to handle just one type, then why define template to start with?

For part(B), you get the idea from the above. Right? Do experiments!

ContentLicense: CC BY-SA 2.5

Body:
Using partial specialization of templates I would like to  create a function/method:

A) processing only one specific primitive type (int, double, float,...) of the formal parameter and for other types throwing exception

template <class T>
T min ( Point <T> p )
{
    /*if (T == int) continue;
    else throw exception*/
}

B)  processing more non-primitive types (user defined types) of the formal parameter and for other types throwing exception...

Some code examples would be helpful (without c++ boost library). Thanks for your help.

Body:
This is the solution of your problem (part A).

template<bool b> struct compile_time_assert;

template<>
struct compile_time_assert<true>
{};

template<class T>
struct is_int
{
     static const bool value = false;
};
template<>
struct is_int<int>
{
     static const bool value = true;
};

template <class T>
T min ( Point <T> p )
{
    /*
     since you can check error at compile time, there is no reason to
     raise exception (which is at runtime) if T is not int!
     the following assert will not compile if T is not int.
     not only that, you can even see the error message "_error_T_is_not_int"
     if T is not int;
    */

    compile_time_assert<is_int<T>::value> _error_T_is_not_int;

    //your code
}

See these sample code.

sample
code1
when T is int. No error. Please ignore the
warning though!

sample
code2
when T is double. Now, see the error
message also. Please ignore the
warning though!

Similarly, you can write templates for other types, (double, char, whatever). Or, even better, you can simply merge all those into just one struct, and instead can define many booleans (for each type) in a single template, like static const bool is_T_int = true;. Etc. Do experiments, you'll learn!

But then, I wonder if you want your function to handle just one type, then why define template to start with?

For part(B), you get the idea from the above. Right? Do experiments!


问:
How to select first item as default in Angular JS dropdown?
I'm trying to use a dropdown, but I'm not able to select 1st value as selected by default. It showing blank.
master_data.sch_files has 4 items, but it shows 5 in dropdown in which 1st time is blank.</p>

```<code><select ng-init="item.file_range_unit = master_data.sch_files[0].ref_key" ng-model="item.file_range_unit"
                        ng-options="x.ref_key as x.ref_value for x in master_data.sch_files" required style="height: 33px;
                       width: 140px; padding-left:5px">
                  </select>
</code>```

答:
You can use this  $scope.form = {type : $scope.typeOptions[0].value}; to select first element of option data.

Also this works here

```<code>function MyCtrl($scope) {

    // your option data
    $scope.typeOptions = [
       { name: 'Feature', value: 'feature' },
       { name: 'Bug', value: 'bug' },
       { name: 'Enhancement', value: 'enhancement' }
    ];

    $scope.form = {type : $scope.typeOptions[0].value};
}
</code>```

Body:
I'm trying to use a dropdown, but I'm not able to select 1st value as selected by default. It showing blank.
master_data.sch_files has 4 items, but it shows 5 in dropdown in which 1st time is blank.

<select ng-init="item.file_range_unit = master_data.sch_files[0].ref_key" ng-model="item.file_range_unit"
                        ng-options="x.ref_key as x.ref_value for x in master_data.sch_files" required style="height: 33px;
                       width: 140px; padding-left:5px">
                  </select>

Body:
You can use this  $scope.form = {type : $scope.typeOptions[0].value}; to select first element of option data.

Also this works here

function MyCtrl($scope) {

    // your option data
    $scope.typeOptions = [
       { name: 'Feature', value: 'feature' },
       { name: 'Bug', value: 'bug' },
       { name: 'Enhancement', value: 'enhancement' }
    ];

    $scope.form = {type : $scope.typeOptions[0].value};
}


问:
Can negamax use an asymmetric evaluation function?
TLDR: I have an asymmetric evaluation function for an implementation of negamax - is that acceptable? Or do I need to make it symmetric?

Longer:
I'm writing a game AI (for the chess-like board game "Hive") that was using minimax with alpha-beta pruning and an asymmetric evaluation function.

But I was having trouble adding transposition tables correctly, and was losing confidence in my minimax implementation, so I decided to switch to negamax using the pseudo-code here: https://en.wikipedia.org/wiki/Negamax#Negamax_with_alpha_beta_pruning_and_transposition_tables

I've got everything "working" and AFAIK accurately following the pseudo-code, but my AI is now making some wildly different moves than before and games that usually ended after 10-15 turns now take 30+, and I'm not convinced the AI is actually playing better than it was before. I'm worried that having an asymmetric evaluation function means I'm scoring nodes differently than before (because of the negamax flip-flopping).

I don't want to change to a symmetric function unless I really have to - I've been trying to produce an optimal function experimentally (AI vs AI battles) and have put in hundreds if not thousands of compute hours into producing a strong evaluation function.

答:
Negamax support asymmetric evaluation functions but it does not lead to optimal play (assuming you have no knowlege about your opponent).

I don't know enough about Hive, but in computer chess it is, in general, a bug to have an asymmetric evaluation function. The reasons behind it should be the same for chess and Hive.

For instance, take the starting position (in chess). White is next to move and let us assume your evaluation function gives the position a score of +0.08.

Now change the position, so black is first to move. Everything is the same, only that the roles of white and black has been changed. Under the assumption, that +0.08 was the optimal score for the white position, why should the position for black not also be evaluated as +0.08?

The same argument goes for any position. If you reverse everything, there is no good reason for playing the position differently.

There is only one exception to this rule. If one opponent is clearly stronger than the other, there are arguments for an asymmetric evaluation. For instance, take a completely drawn position like this:

FEN: 4k3/8/8/p1p1p1p1/PpPpPpPp/1P1P1P1P/8/4K3 b - - 0 1

This position could safely be evaluated as 0. Now imaging the starting position but white starts without one knight. This should be a strong advantage for black.

Let us assume you are Magnus Carlsen and you are playing against on opponent who does not even know the chess rules. Which position would you prefer? Here, I would argue that an asymmetric evaluation could make sense (e.g., evaluate a likely draw similar to a loss). Carlsen should avoid the drawn position, while the beginner should prefer it.

The chances that the beginner can hold its own against the world champion, even at one knight odds, are practically zero. On the other hand, in the drawn position, the skill advantage does not matter, as no order of moves can result in a win or loss.

In computer chess, Rebel had a function to prefer tactical positions when playing against humans (see ANTI GRANDMASTER PLAY). There is also the common concept of "contempt", which is the score that engines give for a remis.

But note that in both my examples, this is not optimal play. Magnus Carlsen would not choose the position without the knight when playing a strong (or unknown) opponent. Also Rebel would not use the anti-human strategy against other machines, which also excel in tactical battles. (Even though, depending on the position, Rebel 10 did use ANTI GRANDMASTER PLAY against computers.)


问:
After NodeJS script has an error, it will not start again. AWS Lambda
I have a lambda function on the nodejs4.x runtime.  If my script stops execution due to an error, lets say I try to get .length of an undefined object, then I can't start the script again.  It's not even like the script runs and hits the same error, the script doesn't run. The lambda handler function is never called the second time.

This lambda function is the endpoint for Amazon Alexa.  When I reupload the code (a zip file) then the system works again.

Is this some behavior of nodejs?  Is the script ending prematurly corrupting the files so it cannot start again?

When the server hits an error I get this message Process exited before completing request

And then subsequent requests hit the timeout limit.

Important Edit
I have pinpointed the issue to NPM request.  the module doesnt finish loading ie.

```<code>console.log('i see this message');
var request = require('request');
console.log('this never happens');
</code>```

答:
In fact there are many cases when Lambda becomes unresponsive, e.g.:

Parsing not valid json:

```<code>exports.handler = function(event, context, callback)
{
    var nonValidJson = "Not even Json";
    var jsonParse = JSON.parse(nonValidJson);
</code>```

Accessing property of undefined variable:

```<code>exports.handler = function(event, context, callback)
{
    var emptyObject = {};
    var value = emptyObject.Item.Key;
</code>```

Not closing mySql connection after accessing RDS leads to Lambda timeout and then it becomes non-responsive.

Making a lambda that reuploads the code can take a portion of time.
After some tests it's revealed that in fact Lambda tries to restart (reload the container?), there is just not enough time. If you set the timeout to be 10s, after ~4s of execution time Lambda starts working, and then in next runs comes to behave normally. I've also tried playing with setting:

```<code>context.callbackWaitsForEmptyEventLoop = false;
</code>```

and putting all 'require' blocks inside handler, nothing really worked. So the good way to prevent Lambda becoming dead is setting bigger timeout, 10s should be more than enough as a workaround protection against this bug.

Body:
I have a lambda function on the nodejs4.x runtime.  If my script stops execution due to an error, lets say I try to get .length of an undefined object, then I can't start the script again.  It's not even like the script runs and hits the same error, the script doesn't run. The lambda handler function is never called the second time.

This lambda function is the endpoint for Amazon Alexa.  When I reupload the code (a zip file) then the system works again.

Is this some behavior of nodejs?  Is the script ending prematurly corrupting the files so it cannot start again?

When the server hits an error I get this message Process exited before completing request

And then subsequent requests hit the timeout limit.

Important Edit
I have pinpointed the issue to NPM request.  the module doesnt finish loading ie.

console.log('i see this message');
var request = require('request');
console.log('this never happens');

Body:
In fact there are many cases when Lambda becomes unresponsive, e.g.:

Parsing not valid json:

exports.handler = function(event, context, callback)
{
    var nonValidJson = "Not even Json";
    var jsonParse = JSON.parse(nonValidJson);

Accessing property of undefined variable:

exports.handler = function(event, context, callback)
{
    var emptyObject = {};
    var value = emptyObject.Item.Key;

Not closing mySql connection after accessing RDS leads to Lambda timeout and then it becomes non-responsive.

Making a lambda that reuploads the code can take a portion of time.
After some tests it's revealed that in fact Lambda tries to restart (reload the container?), there is just not enough time. If you set the timeout to be 10s, after ~4s of execution time Lambda starts working, and then in next runs comes to behave normally. I've also tried playing with setting:

context.callbackWaitsForEmptyEventLoop = false;

and putting all 'require' blocks inside handler, nothing really worked. So the good way to prevent Lambda becoming dead is setting bigger timeout, 10s should be more than enough as a workaround protection against this bug.


问:
Square Root to 2 Decimal places
I've been trying to do some homework and was getting on fine until I came across a particular task.

The Task is: Ask the user to enter an integer that is over 500. Work out the square root of that number and display it to 2 decimal places.

My current code is below I have managed to make it do the square root part but it is not displaying it to 2 decimal places.

```<code>import math
number = float(input("Please Input a number over 500 and i will work out the square root of that number and display it to 2 decimal places! "))

if number < 500:
    print("That number is not above 500!")
else:
    print(math.sqrt(round(number,2)))
</code>```

Title: Square Root to 2 Decimal places

Body:
I've been trying to do some homework and was getting on fine until I came across a particular task.

The Task is: Ask the user to enter an integer that is over 500. Work out the square root of that number and display it to 2 decimal places.

My current code is below I have managed to make it do the square root part but it is not displaying it to 2 decimal places.

import math
number = float(input("Please Input a number over 500 and i will work out the square root of that number and display it to 2 decimal places! "))

if number < 500:
    print("That number is not above 500!")
else:
    print(math.sqrt(round(number,2)))

Body:
>>> format(math.sqrt(500), '.2f')
'22.36'


问:
C# .Net 3.5 Code to replace a file extension using LINQ
I've written this very simple function to replace a file extension using LINQ in C#.NET 3.5 however I have a feeling that there's a more elegant way to do this. (I'm not committed to using LINQ here - just looking for a more elegant approach.) Ideas?

```<code>    private string ReplaceFileExtension(string fileName, string newExtension)
    {
        string[] dotSplit = fileName.Split('.');
        return String.Join(".", dotSplit.Take(dotSplit.Length - 1).ToArray()) + "." + newExtension;
    }
</code>```

(I'm aware of the fact that this won't work if the original file name doesn't have a dot.)

答: It's very easy... just use System.IO.Path.ChangeExtension</p>

OwnerDisplayName: Guy

Body:
I've written this very simple function to replace a file extension using LINQ in C#.NET 3.5 however I have a feeling that there's a more elegant way to do this. (I'm not committed to using LINQ here - just looking for a more elegant approach.) Ideas?

    private string ReplaceFileExtension(string fileName, string newExtension)
    {
        string[] dotSplit = fileName.Split('.');
        return String.Join(".", dotSplit.Take(dotSplit.Length - 1).ToArray()) + "." + newExtension;
    }

(I'm aware of the fact that this won't work if the original file name doesn't have a dot.)

OwnerDisplayName: Doozer


问:
How do I open a dialog as soon as an application is initialized?
I'm trying to open a modal dialog as soon as a WPF application has started (using ShowDialog(this)). I tried the following methods, both of which throw an InvalidOperationException, presumably because the window hasn't been initialized yet:

```<code>public MainWindow()
{
    InitializeComponent();

    ShowMyDialogDammit();
}
</code>```

and:

```<code>public MainWindow()
{
    InitializeComponent();
}

protected override void OnInitialized(EventArgs e)
{
    base.OnInitialized(e);
    ShowMyDialogDammit();
}
</code>```

How do I do this?

答:
Try this:

```<code>var w = new MainWindow();
w.ShowDialog();
</code>```

You don't need the "ShowDialog" call inside the MainWindow class anywhere.

Body:
I'm trying to open a modal dialog as soon as a WPF application has started (using ShowDialog(this)). I tried the following methods, both of which throw an InvalidOperationException, presumably because the window hasn't been initialized yet:

public MainWindow()
{
    InitializeComponent();

    ShowMyDialogDammit();
}

and:

public MainWindow()
{
    InitializeComponent();
}

protected override void OnInitialized(EventArgs e)
{
    base.OnInitialized(e);
    ShowMyDialogDammit();
}

How do I do this?

Body:
Try this:

var w = new MainWindow();
w.ShowDialog();

You don't need the "ShowDialog" call inside the MainWindow class anywhere.


问:
Robot Framework - check if element defined by xpath exists
I'm wondering, I'd love to find or write condition to check if some element exists. If it does than I want to execute body of IF condition. If it doesn't exist than to execute body of ELSE.

Is there some condition like this or is it necessary to write by myself somehow?

答:
I prefer using Get Matching XPath Count since the accepted answer throws error if element is not found</p>

```<code>${count}= Get Matching XPath Count ${Xpath}
Run Keyword And Return If   ${count} > 0 Keyword args*
</code>```

Body:
I prefer using Get Matching XPath Count since the accepted answer throws error if element is not found

${count}= Get Matching XPath Count ${Xpath}
Run Keyword And Return If   ${count} > 0 Keyword args*


问:
How to programmatically determine the current checked out Git branch
In a Unix or GNU scripting environment (e.g. a Linux distro, Cygwin, OSX), what is the best way to determine which Git branch is currently checked out in a working directory?

One use of this technique would be automatically labeling a release (like svnversion would do with Subversion).

Please also see my related question: How to programmatically determine whether a Git checkout is a tag, and if so what is the tag name?

答:
If you are on a detached head (i.e. you've checked out a release) and have an output from git status such as

```<code>HEAD detached at v1.7.3.1
</code>```

And you want the release version, we use the following command...

```<code>git status --branch | head -n1 | tr -d 'A-Za-z: '
</code>```

This returns 1.7.3.1, which we replace in our parameters.yml (Symfony) with

```<code># RevNum=`svn status -u | grep revision | tr -d 'A-Za-z: '`  # the old SVN version
RevNum=`git status --branch | head -n1 | tr -d 'A-Za-z: '` # Git (obvs)

sed -i "/^    app_version:/c\    app_version:$RevNum" app/config/parameters.yml
</code>```

Hope this helps :) Obviously if you have non-numerics in your branch name, you'll need to alter the arguments to the tr command.

Body:
If you are on a detached head (i.e. you've checked out a release) and have an output from git status such as

HEAD detached at v1.7.3.1

And you want the release version, we use the following command...

git status --branch | head -n1 | tr -d 'A-Za-z: '

This returns 1.7.3.1, which we replace in our parameters.yml (Symfony) with

# RevNum=`svn status -u | grep revision | tr -d 'A-Za-z: '`  # the old SVN version
RevNum=`git status --branch | head -n1 | tr -d 'A-Za-z: '` # Git (obvs)

sed -i "/^    app_version:/c\    app_version:$RevNum" app/config/parameters.yml

Hope this helps :) Obviously if you have non-numerics in your branch name, you'll need to alter the arguments to the tr command.


问:
How to upload a file to a local folder with React.js and Node.js?
I have tried this php and html file upload:
https://www.w3schools.com/php/php_file_upload.asp

and I was wondering If the same could be done using React.js/Nodes.js.
I'm not really used to coding and have never worked with React.js before.

答:
You can split that up into to parts:
The backend part which is done in Node.js. Therefore you can use something like ExpressJS as framework. Add a POST route and handle your file upload.

The second part would be React. React has nothing to do with the backend system. It's only used to build GUIs. It's a combination of fancy HTML and JavaScript.


问:
Java library for writing a table on the command line
Does anybody know a library that would transform a String[][] into a String table as below?

```
| title1 | title2 |
|________|________|
| blah   | blih   |
| blah2  | blih2  |
etc...
```

I could write formatted strings for this, but it will be non-generic code, tied to the parameters.
Writing generic code for this purpose would be more expensive than what I'm willing to invest.

So all in all, I think a library would be justified for this.

Any idea if this exists already?

答:
I am not aware of any library that does this, but take a look at this SO question:

Java: Print a 2D String array as a right-justified table

It shows you how you can create a generic method which dynamically-generates format strings for each column.

Body:
Does anybody know a library that would transform a String[][] into a String table as below?

| title1 | title2 |
|________|________|
| blah   | blih   |
| blah2  | blih2  |
etc...

I could write formatted strings for this, but it will be non-generic code, tied to the parameters.
Writing generic code for this purpose would be more expensive than what I'm willing to invest.

So all in all, I think a library would be justified for this.

Any idea if this exists already?


问:
How can I redefine an operator as a function?
I've been thinking about a way to stop repeating myself when I create new code for a class, for instance, I need to sum all the values within a case class when the same class appears.

An example might better explain what I'm currently doing:

```<code>case class A(a: Double, b: Double) {
    def +(that: A): A {
        A(a + that.a, b + that.b)
    }
    def *(that: A): A {
        A(a * that.a, b * that.b)
    }
}
</code>```

which allows me to do:

```<code>val a = A(1, 2)
val b = A(3, 4)
val c = a + b
</code>```

where c = A(4, 6), right?

Well, what if I want to generalize the operation? For instance, let me give you an example of something that does not work but that I believe portrays my intention perfectly.

```<code>case class A(a: Double, b: Double) {
    def operation(op: (x: Double, y: Double) => Double)(that: => A) = {
        A(op(a, that.a), op(b, that.b))
    }
}
</code>```

Now, I know that doesn't work because I probably got some extremely important concepts mixed up which I haven't pinpointed yet, but I came up with this idea thinking of this possibility:

```<code>val a = A(1, 2)
val b = B(3, 4)
val + = (x: Double, y: Double) => (x + y)
val res = a + b
</code>```

I know that this can be done in different ways which will achieve the same result, but is there a way to portray generic operations like this?

答:
You can do this like that:</p>

```<code>case class A(a: Double, b: Double) {
  def + = operation(_ + _) _
  def * = operation(_ * _) _

  private def operation(op: (Double, Double) => Double)(that: => A) =
    A(op(a, that.a), op(b, that.b))
}
</code>```

Body:
I've been thinking about a way to stop repeating myself when I create new code for a class, for instance, I need to sum all the values within a case class when the same class appears.

An example might better explain what I'm currently doing:

case class A(a: Double, b: Double) {
    def +(that: A): A {
        A(a + that.a, b + that.b)
    }
    def *(that: A): A {
        A(a * that.a, b * that.b)
    }
}

which allows me to do:

val a = A(1, 2)
val b = A(3, 4)
val c = a + b

where c = A(4, 6), right?

Well, what if I want to generalize the operation? For instance, let me give you an example of something that does not work but that I believe portrays my intention perfectly.

case class A(a: Double, b: Double) {
    def operation(op: (x: Double, y: Double) => Double)(that: => A) = {
        A(op(a, that.a), op(b, that.b))
    }
}

Now, I know that doesn't work because I probably got some extremely important concepts mixed up which I haven't pinpointed yet, but I came up with this idea thinking of this possibility:

val a = A(1, 2)
val b = B(3, 4)
val + = (x: Double, y: Double) => (x + y)
val res = a + b

I know that this can be done in different ways which will achieve the same result, but is there a way to portray generic operations like this?

Body:
You can do this like that:

case class A(a: Double, b: Double) {
  def + = operation(_ + _) _
  def * = operation(_ * _) _

  private def operation(op: (Double, Double) => Double)(that: => A) =
    A(op(a, that.a), op(b, that.b))
}


问:
How to read eml file contains in eml file using Javamail API
I have an EML file which contains another EML file as an attachment.
When I try to fetch an attachment file using JAVAMAIL API, getDisposition value indicates attachment but getfileName() displays NULL.

```<code>    Properties props = new Properties();
            Session mailSession = Session.getDefaultInstance(props, null);
            InputStream source = new FileInputStream("C:\\Mail1496085.eml");
            MimeMessage message = new MimeMessage(mailSession, source);
            System.out.println("Subject : " + message.getSubject());
            System.out.println("From : " + message.getFrom()[0]);
            System.out.println("--------------");
            System.out.println("Body : " +  message.getContent());
            String contentType = message.getContentType();
            if (contentType.contains("multipart")) {
System.out.println("Multipart EMail File");
            Multipart multiPart = (Multipart) message.getContent();
            int numberOfParts = multiPart.getCount();
            System.out.println("Parts:::"+numberOfParts);
            String wi="IM-67890-PROCESS";
            String saveDir = System.getProperty("user.dir")+"\\Docs";
            saveDir=saveDir + File.separator+wi;
            boolean file =new File(saveDir).mkdir();
           if (file) {
                  System.out.println("Directory: " + wi + " created");
                 // logger.debug("Directory: " + workItem + " created");
                }

            for (int partCount = 0; partCount < numberOfParts; partCount++) {
                MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
                String disposition=part.getDisposition();
                if (Part.ATTACHMENT.equalsIgnoreCase(disposition)) {
                    // this part is attachment
                    String fileName = part.getFileName();
                    String extension="";
                    System.out.println("Attached File Name::"+fileName);
                    saveDir=saveDir + File.separator + fileName;
                    int i=fileName.lastIndexOf(".");
                        if(i>0)
                        {
                            extension=fileName.substring(i+1);
                        }
                     if(extension.equalsIgnoreCase("eml"))
                     {
                         part.saveFile(saveDir);
                         extractEML(saveDir, wi);
                         System.out.println("This is a eml file");
                     }
                     else if(extension.equalsIgnoreCase("msg"))
                     {
                         part.saveFile(saveDir);
                         extractMSG(saveDir,wi);
                         System.out.println("This is a msg file");
                     }
                     else
                     {
                         System.out.println("This is other file");
                     }
                   } else {
                        System.out.println("Not an eml file");
               System.out.println("File Name::"+part.getFileName());
                }
            }
        }
}

public static void extractEML(String emlPath,String wi) throws MessagingException, IOException
    {
        //String fileName="";
        String path=System.getProperty("user.dir") + File.separator + "Docs" + File.separator + wi + File.separator + "EML_PDF";
         boolean file =new File(path).mkdir();
         if(file)
         {
             System.out.println("Folder EML_PDF Created Successfully");
         }
        Properties props = new Properties();
        Session mailSession = Session.getDefaultInstance(props, null);
        InputStream source = new FileInputStream(emlPath);
        MimeMessage message = new MimeMessage(mailSession, source);
        System.out.println("Subject : " + message.getSubject());
        System.out.println("From : " + message.getFrom()[0]);
        System.out.println("--------------");
        System.out.println("Body : " +  message.getContent());
        String contentType = message.getContentType();
        if (contentType.contains("multipart")) {
            System.out.println("Multipart EMail File");
            Multipart multiPart = (Multipart) message.getContent();
            int numberOfParts = multiPart.getCount();
            System.out.println("Parts:::"+numberOfParts);
            for (int partCount = 0; partCount < numberOfParts; partCount++) {
                MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
                if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
                     String fileName = part.getFileName();
                     String extension="";
                     path=path + File.separator + fileName;
                     int i=fileName.lastIndexOf(".");
                     if(i>0)
                     {
                        extension=fileName.substring(i+1);
                     }
                     if(extension.equalsIgnoreCase("pdf"))
                     {
                         part.saveFile(path);
                     }
                }
            }
        }
    }
</code>```

答: File names for attachments are optional.  You need to fix your program to work without a file name.</p>

Body:
I have an EML file which contains another EML file as an attachment.
When I try to fetch an attachment file using JAVAMAIL API, getDisposition value indicates attachment but getfileName() displays NULL.

    Properties props = new Properties();
            Session mailSession = Session.getDefaultInstance(props, null);
            InputStream source = new FileInputStream("C:\\Mail1496085.eml");
            MimeMessage message = new MimeMessage(mailSession, source);
            System.out.println("Subject : " + message.getSubject());
            System.out.println("From : " + message.getFrom()[0]);
            System.out.println("--------------");
            System.out.println("Body : " +  message.getContent());
            String contentType = message.getContentType();
            if (contentType.contains("multipart")) {
System.out.println("Multipart EMail File");
            Multipart multiPart = (Multipart) message.getContent();
            int numberOfParts = multiPart.getCount();
            System.out.println("Parts:::"+numberOfParts);
            String wi="IM-67890-PROCESS";
            String saveDir = System.getProperty("user.dir")+"\\Docs";
            saveDir=saveDir + File.separator+wi;
            boolean file =new File(saveDir).mkdir();
           if (file) {
                  System.out.println("Directory: " + wi + " created");
                 // logger.debug("Directory: " + workItem + " created");
                }

            for (int partCount = 0; partCount < numberOfParts; partCount++) {
                MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
                String disposition=part.getDisposition();
                if (Part.ATTACHMENT.equalsIgnoreCase(disposition)) {
                    // this part is attachment
                    String fileName = part.getFileName();
                    String extension="";
                    System.out.println("Attached File Name::"+fileName);
                    saveDir=saveDir + File.separator + fileName;
                    int i=fileName.lastIndexOf(".");
                        if(i>0)
                        {
                            extension=fileName.substring(i+1);
                        }
                     if(extension.equalsIgnoreCase("eml"))
                     {
                         part.saveFile(saveDir);
                         extractEML(saveDir, wi);
                         System.out.println("This is a eml file");
                     }
                     else if(extension.equalsIgnoreCase("msg"))
                     {
                         part.saveFile(saveDir);
                         extractMSG(saveDir,wi);
                         System.out.println("This is a msg file");
                     }
                     else
                     {
                         System.out.println("This is other file");
                     }
                   } else {
                        System.out.println("Not an eml file");
               System.out.println("File Name::"+part.getFileName());
                }
            }
        }
}

public static void extractEML(String emlPath,String wi) throws MessagingException, IOException
    {
        //String fileName="";
        String path=System.getProperty("user.dir") + File.separator + "Docs" + File.separator + wi + File.separator + "EML_PDF";
         boolean file =new File(path).mkdir();
         if(file)
         {
             System.out.println("Folder EML_PDF Created Successfully");
         }
        Properties props = new Properties();
        Session mailSession = Session.getDefaultInstance(props, null);
        InputStream source = new FileInputStream(emlPath);
        MimeMessage message = new MimeMessage(mailSession, source);
        System.out.println("Subject : " + message.getSubject());
        System.out.println("From : " + message.getFrom()[0]);
        System.out.println("--------------");
        System.out.println("Body : " +  message.getContent());
        String contentType = message.getContentType();
        if (contentType.contains("multipart")) {
            System.out.println("Multipart EMail File");
            Multipart multiPart = (Multipart) message.getContent();
            int numberOfParts = multiPart.getCount();
            System.out.println("Parts:::"+numberOfParts);
            for (int partCount = 0; partCount < numberOfParts; partCount++) {
                MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
                if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
                     String fileName = part.getFileName();
                     String extension="";
                     path=path + File.separator + fileName;
                     int i=fileName.lastIndexOf(".");
                     if(i>0)
                     {
                        extension=fileName.substring(i+1);
                     }
                     if(extension.equalsIgnoreCase("pdf"))
                     {
                         part.saveFile(path);
                     }
                }
            }
        }
    }


问:
Elastic search Request Body Search not working
I am trying to use elastic search for searching I am successful to search keyword using URI search using rest client but I am unable to search using request body search below is the code for requestbody search please suggest what i am doing wrong there.</p>

```<code> RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200, "http")).build();
 HttpEntity entity = new NStringEntity("{\n" +
            "    \"query\" : {\n" +
            "        \"term\" : { \"chaData\" : \"ADMINISTRATOR\" }\n" +
            "    }\n" +
            "}", ContentType.APPLICATION_JSON);
 Response indexResponse = restClient.performRequest("POST",
            "/cha/elasticSearch/_search?pretty",Collections.<String, String>emptyMap(),entity);
 System.out.println(EntityUtils.toString(indexResponse.getEntity()));
 restClient.close();
</code>```

答: Have you tried without the ?pretty - part. It looks like the restclient.performRequest() would like the query string as a map instead of as part of the endpoint? (you are passing an empty map instead)</p>

Body:
I am trying to use elastic search for searching I am successful to search keyword using URI search using rest client but I am unable to search using request body search below is the code for requestbody search please suggest what i am doing wrong there.

 RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200, "http")).build();
 HttpEntity entity = new NStringEntity("{\n" +
            "    \"query\" : {\n" +
            "        \"term\" : { \"chaData\" : \"ADMINISTRATOR\" }\n" +
            "    }\n" +
            "}", ContentType.APPLICATION_JSON);
 Response indexResponse = restClient.performRequest("POST",
            "/cha/elasticSearch/_search?pretty",Collections.<String, String>emptyMap(),entity);
 System.out.println(EntityUtils.toString(indexResponse.getEntity()));
 restClient.close();


问:
How to return a custom object from a Spring Data JPA GROUP BY query
I'm developing a Spring Boot application with Spring Data JPA. I'm using a custom JPQL query to group by some field and get the count. Following is my repository method.

```<code>@Query(value = "select count(v) as cnt, v.answer from Survey v group by v.answer")
public List<?> findSurveyCount();
</code>```

It's working and result is obtained as follows:

```<code>[
  [1, "a1"],
  [2, "a2"]
]
</code>```

I would like to get something like this:

```<code>[
  { "cnt":1, "answer":"a1" },
  { "cnt":2, "answer":"a2" }
]
</code>```

How can I achieve this?

答:
I know this is an old question and it has already been answered, but here's another approach: </p>

```<code>@Query("select new map(count(v) as cnt, v.answer) from Survey v group by v.answer")
public List<?> findSurveyCount();
</code>```

Body:
I'm developing a Spring Boot application with Spring Data JPA. I'm using a custom JPQL query to group by some field and get the count. Following is my repository method.

@Query(value = "select count(v) as cnt, v.answer from Survey v group by v.answer")
public List<?> findSurveyCount();

It's working and result is obtained as follows:

[
  [1, "a1"],
  [2, "a2"]
]

I would like to get something like this:

[
  { "cnt":1, "answer":"a1" },
  { "cnt":2, "answer":"a2" }
]

How can I achieve this?

Body:
I know this is an old question and it has already been answered, but here's another approach:

@Query("select new map(count(v) as cnt, v.answer) from Survey v group by v.answer")
public List<?> findSurveyCount();


问:
Session cookies disappearing from Chrome with PHP/Apache server
Update: Looks like the issue that started a few days ago was due to incorrect handling of the cookie "secure" flag. We still haven't resolved the problem that started on February 1 though.

I run an internal PHP/Apache site where I work. On February 1 we started getting reports that employees were being logged out of it randomly several times a day. We had not changed any of the authentication code in years, but we noticed that Chrome received a significant update that day: https://chromereleases.googleblog.com/2017/02/stable-channel-update-for-desktop.html.

In the last few days, the issue has gotten significantly worse and Chrome is not storing the session cookie at all for some users. After navigating to the site, the server tries to set a cookie and the employee is redirected to Google for auth, and then when they get back to the site their cookie is gone.

I reproduced the issue with minimal code in this simple php file:

```<code><?php

session_set_cookie_params(60 * 60 * 24 * 7, '/', '.corp.company.com', false, true);
session_name('CompanySessionID');
session_start();
$_SESSION['UserName'] = 'test';
</code>```

When an affected employee visits the page, the set cookie header comes through as expected, but Chrome does not store the cookie.

Additional details:

I've tried all the suggestions on PHP session lost after redirect

Originally the problem did not affect incognito mode, but starting a few days ago it does

Clearing cache/cookies has never helped the issue

Reinstalling Chrome previously would resolve the issue for around a week

The problem is not present in Firefox or Safari

Not all employees are affected

All employees use OS X

Changing the session name from CompanySessionID to CompanySession fixed the problem for a subset of users, and broke it for another subset of users

The sessions are still there on the server, it's just the cookie that's missing from the browser

Using a proxy to watch requests I can see that there are no headers that should be deleting the cookie.

We're using PHP 5.4.24

How can I find the source of this issue? Should I file a bug with Chrome?

答:
I figured out the more recent issue with help from @cmorrissey. We rolled out HTTPS to the server recently, and when people got new cookies over HTTPS they'd get the secure flag set.

After that, the cookie would no longer be sent on requests over HTTP (as expected). However, what was unexpected is that Chrome would also no longer allow the server to set an insecure session cookie with the same name, since the secure one existed already. That's why the example PHP file shown in the question could not set the cookie at all unless the session name changed.

Body:
Update: Looks like the issue that started a few days ago was due to incorrect handling of the cookie "secure" flag. We still haven't resolved the problem that started on February 1 though.

I run an internal PHP/Apache site where I work. On February 1 we started getting reports that employees were being logged out of it randomly several times a day. We had not changed any of the authentication code in years, but we noticed that Chrome received a significant update that day: https://chromereleases.googleblog.com/2017/02/stable-channel-update-for-desktop.html.

In the last few days, the issue has gotten significantly worse and Chrome is not storing the session cookie at all for some users. After navigating to the site, the server tries to set a cookie and the employee is redirected to Google for auth, and then when they get back to the site their cookie is gone.

I reproduced the issue with minimal code in this simple php file:

<?php

session_set_cookie_params(60 * 60 * 24 * 7, '/', '.corp.company.com', false, true);
session_name('CompanySessionID');
session_start();
$_SESSION['UserName'] = 'test';

When an affected employee visits the page, the set cookie header comes through as expected, but Chrome does not store the cookie.

Additional details:

I've tried all the suggestions on PHP session lost after redirect

Originally the problem did not affect incognito mode, but starting a few days ago it does

Clearing cache/cookies has never helped the issue

Reinstalling Chrome previously would resolve the issue for around a week

The problem is not present in Firefox or Safari

Not all employees are affected

All employees use OS X

Changing the session name from CompanySessionID to CompanySession fixed the problem for a subset of users, and broke it for another subset of users

The sessions are still there on the server, it's just the cookie that's missing from the browser

Using a proxy to watch requests I can see that there are no headers that should be deleting the cookie.

We're using PHP 5.4.24

How can I find the source of this issue? Should I file a bug with Chrome?


问:
How would I tell a browser to render a string, not display it
I have this extension method I created and it returns a string of all the categories in my database as hyperlinks. Great!

```<code>@Html.MyMenu()
</code>```

The problem is that the links are being displayed as text and not rendered as hyperlinks.

When viewing the source code I see:

```<code><div id="menucontainer">

                <a href="/Anuncio/Electronics">Electronics</a><a href="/Anuncio/Clothes">Clothes</a><a href="/Anuncio/Domestic">Domestic</a><a href="/Anuncio/Garden">Garden</a>

            </div>
</code>```

I think I may be wrong but I remember that in MVC2 (using the default view engine) you had:

```<code><%: this is rendered, right? %>
</code>```

Or am I mistaken? Anyways, I'm using MVC3 and the Razor engine. Thanks a lot for your help guys. I'm really enjoying learning as much as I can about this.

答:
RC2 supports @Html.Raw() to output raw HTML

From Scott Guthrie's RC2 anouncement

With RC2 we are adding a Html.Raw() helper method that you can use to explicitly indicate that you do not want to HTML encode your output, and instead want to render the content “as-is”

OwnerDisplayName: delete

Body:
I have this extension method I created and it returns a string of all the categories in my database as hyperlinks. Great!

@Html.MyMenu()

The problem is that the links are being displayed as text and not rendered as hyperlinks.

When viewing the source code I see:

                ElectronicsClothesDomesticGarden

I think I may be wrong but I remember that in MVC2 (using the default view engine) you had:

<%: this is rendered, right? %>

Or am I mistaken? Anyways, I'm using MVC3 and the Razor engine. Thanks a lot for your help guys. I'm really enjoying learning as much as I can about this.


问:
How to create 2-layers neural network using TensorFlow and python on MNIST data
I'm a newbie in machine learning and I am following tensorflow's tutorial to create some simple Neural Networks which learn the MNIST data.

I have built a single layer network (following the tutotial), accuracy was about 0.92 which is ok for me. But then I added one more layer, the accuracy reduced to 0.113, which is very bad.

Below is the relation between 2 layers:

```<code>import tensorflow as tf
x = tf.placeholder(tf.float32, [None, 784])

#layer 1
W1 = tf.Variable(tf.zeros([784, 100]))
b1 = tf.Variable(tf.zeros([100]))
y1 = tf.nn.softmax(tf.matmul(x, W1) + b1)

#layer 2
W2 = tf.Variable(tf.zeros([100, 10]))
b2 = tf.Variable(tf.zeros([10]))
y2 = tf.nn.softmax(tf.matmul(y1, W2) + b2)

#output
y = y2
y_ = tf.placeholder(tf.float32, [None, 10])
</code>```

Is my structure fine? What is the reason that makes it perform so bad? How should I modify my network?

答:
I tried to run the code snippets above. Results below 90% was discarded and I never really felt sure I did what the comments above had. Here is my full code. </p>

```<code>import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
x = tf.placeholder(tf.float32, [None, 784])

#layer 1
W1 = tf.get_variable('w1', [784, 100], initializer=tf.random_normal_initializer())
b1 = tf.get_variable('b1', [1,], initializer=tf.random_normal_initializer())
y1 = tf.nn.sigmoid(tf.matmul(x, W1) + b1)

#layer 2
W2 = tf.get_variable('w2',[100,10], initializer=
tf.random_normal_initializer())
b2 = tf.get_variable('b2',[1,], initializer=tf.random_normal_initializer())
y2 = tf.nn.softmax(tf.matmul(y1, W2) + b2)

#output
y = y2
y_ = tf.placeholder(tf.float32, [None, 10])

cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y),
reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(0.2).minimize(cross_entropy)
sess = tf.InteractiveSession()
tf.global_variables_initializer().run()

for _ in range(10000):
  batch_xs, batch_ys = mnist.train.next_batch(100)
  sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})

correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_:
mnist.test.labels}))
</code>```

<p>By changing 10000 -> 200000 i reached 95,5%. </p>

Body:
I'm a newbie in machine learning and I am following tensorflow's tutorial to create some simple Neural Networks which learn the MNIST data.

I have built a single layer network (following the tutotial), accuracy was about 0.92 which is ok for me. But then I added one more layer, the accuracy reduced to 0.113, which is very bad.

Below is the relation between 2 layers:

import tensorflow as tf
x = tf.placeholder(tf.float32, [None, 784])

#layer 1
W1 = tf.Variable(tf.zeros([784, 100]))
b1 = tf.Variable(tf.zeros([100]))
y1 = tf.nn.softmax(tf.matmul(x, W1) + b1)

#layer 2
W2 = tf.Variable(tf.zeros([100, 10]))
b2 = tf.Variable(tf.zeros([10]))
y2 = tf.nn.softmax(tf.matmul(y1, W2) + b2)

#output
y = y2
y_ = tf.placeholder(tf.float32, [None, 10])

Is my structure fine? What is the reason that makes it perform so bad? How should I modify my network?

Body:
I tried to run the code snippets above. Results below 90% was discarded and I never really felt sure I did what the comments above had. Here is my full code.

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
x = tf.placeholder(tf.float32, [None, 784])

#layer 1
W1 = tf.get_variable('w1', [784, 100], initializer=tf.random_normal_initializer())
b1 = tf.get_variable('b1', [1,], initializer=tf.random_normal_initializer())
y1 = tf.nn.sigmoid(tf.matmul(x, W1) + b1)

#layer 2
W2 = tf.get_variable('w2',[100,10], initializer=
tf.random_normal_initializer())
b2 = tf.get_variable('b2',[1,], initializer=tf.random_normal_initializer())
y2 = tf.nn.softmax(tf.matmul(y1, W2) + b2)

#output
y = y2
y_ = tf.placeholder(tf.float32, [None, 10])

cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y),
reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(0.2).minimize(cross_entropy)
sess = tf.InteractiveSession()
tf.global_variables_initializer().run()

for _ in range(10000):
  batch_xs, batch_ys = mnist.train.next_batch(100)
  sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})

correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_:
mnist.test.labels}))

By changing 10000 -> 200000 i reached 95,5%.


问:
Execution failed for app:clean in android studio 2.2
I currently switch to android studio 2.2 and I have a big problem. when I build project to deploy on emulator I got this error:

```<code>Error:Execution failed for task ':app:clean'.
> Unable to delete directory: /mnt/D/Document/WorkSpace/Android/Test/app/build/intermediates/exploded-aar/com.android.support/animated-vector-drawable/25.0.0/jars
</code>```

I clean that path and again it tell me that:

```<code>Error:Execution failed for task ':app:clean'.
> Unable to delete directory: /mnt/D/Document/WorkSpace/Android/Test/app/build/intermediates/exploded-aar/com.android.support/cardview-v7/25.0.0/jars
</code>```

I clean it handy and again:

```<code>Error:Execution failed for task ':app:clean'.
> Unable to delete directory: /mnt/D/Document/WorkSpace/Android/Test/app/build/intermediates/exploded-aar/com.android.support/support-compat/25.0.0/jars/libs
</code>```

I don't know how many steps exists and if I pass all these steps, may be I mentally!
I don't have these issues in android 1.4. is this a bug about android studio or related to my system(Arch Linux)?
Thanks in advance.

答:
For me there was a stuck debug test inside of Android Studio and mockable-jar was used inside of that JVM and couldn't be deleted.

What I had to do is.. stop the frozen JVM from Task Manager, then clean.

What I'll do the next time this happens is.. stop the frozen debug test from Android Studio, then clean.

Body:
I currently switch to android studio 2.2 and I have a big problem. when I build project to deploy on emulator I got this error:

Error:Execution failed for task ':app:clean'.
> Unable to delete directory: /mnt/D/Document/WorkSpace/Android/Test/app/build/intermediates/exploded-aar/com.android.support/animated-vector-drawable/25.0.0/jars

I clean that path and again it tell me that:

Error:Execution failed for task ':app:clean'.
> Unable to delete directory: /mnt/D/Document/WorkSpace/Android/Test/app/build/intermediates/exploded-aar/com.android.support/cardview-v7/25.0.0/jars

I clean it handy and again:

Error:Execution failed for task ':app:clean'.
> Unable to delete directory: /mnt/D/Document/WorkSpace/Android/Test/app/build/intermediates/exploded-aar/com.android.support/support-compat/25.0.0/jars/libs

I don't know how many steps exists and if I pass all these steps, may be I mentally!
I don't have these issues in android 1.4. is this a bug about android studio or related to my system(Arch Linux)?
Thanks in advance.


问:
TestFlight is Currently Unavailable Message
I am getting message "TestFlight is Currently is Currently Unavailable. Try again later" when trying to install from TestFlight app. My outside testers get a message "[App Name] beta has expired" when trying to run the app. When trying to renew from TestFlight they get "TestFlight is currently unavailable. Try again later." I've been trying again later all day and just wanted to see if anyone else is experiencing this.</p>

答: I was ultimately able to fix this message by uninstalling and reinstalling the TestFlight app from scratch. Worth a try if the other answers don't fix your problem.</p>


问:
Why dosnt my webdriver method wait until 'Max timeout' for an element to be visible?
Why dosnt my webdriver method wait until 'Max timeout' for an element to be visible?

My method:

```<code>    public boolean WaitUntilWebElementIsVisible(WebElement element) {
    try {
        WebDriverWait tempWait = new WebDriverWait(driver, 30);
        tempWait.pollingEvery(100, TimeUnit.MILLISECONDS);
        tempWait.until(ExpectedConditions.visibilityOf(element));
        System.out.println("WebElement is visible using locator: " + element.toString());
        return true;
    } catch (Exception e) {
        System.out.println("WebElement is NOT visible, using locator: " + element.toString() + " ,Exception: " + e.getMessage());
        Assert.fail("Method failed: WaitUntilWebElementIsVisible");
        //Assert.fail("WebElement is NOT visible, using locator: " + element.toString());
        return false;
    }
}
</code>```

TestNG call:

```<code>    @Test(priority = 27)
public void confirm_BillingAddress_Header_IsVisible_BillingAndPaymentDetails_Section() throws Exception {
    //Verify whether the panel title: 'BILLING ADDRESS:' is visible
    Thread.sleep(1000);
    basePage.WaitUntilWebElementIsVisible(checkoutPage.subheader_BillingAddress);
    Assert.assertEquals(checkoutPage.subheader_BillingAddress.getText(), "BILLING ADDRESS:");
}
</code>```

Example of the issue (during the test the header easily appears before 30seconds):

答:
Actually your code will wait for checkoutPage.subheader_BillingAddress to be visible
with a max of 30 seconds

That doesn't mean it will wait for 30 seconds then complete the execution

but it means

If the element appeared before  30 seconds it will complete the execution

But if the element took more than 30 seconds to appear your code will throw an exception

Body:
Why dosnt my webdriver method wait until 'Max timeout' for an element to be visible?

My method:

    public boolean WaitUntilWebElementIsVisible(WebElement element) {
    try {
        WebDriverWait tempWait = new WebDriverWait(driver, 30);
        tempWait.pollingEvery(100, TimeUnit.MILLISECONDS);
        tempWait.until(ExpectedConditions.visibilityOf(element));
        System.out.println("WebElement is visible using locator: " + element.toString());
        return true;
    } catch (Exception e) {
        System.out.println("WebElement is NOT visible, using locator: " + element.toString() + " ,Exception: " + e.getMessage());
        Assert.fail("Method failed: WaitUntilWebElementIsVisible");
        //Assert.fail("WebElement is NOT visible, using locator: " + element.toString());
        return false;
    }
}

TestNG call:

    @Test(priority = 27)
public void confirm_BillingAddress_Header_IsVisible_BillingAndPaymentDetails_Section() throws Exception {
    //Verify whether the panel title: 'BILLING ADDRESS:' is visible
    Thread.sleep(1000);
    basePage.WaitUntilWebElementIsVisible(checkoutPage.subheader_BillingAddress);
    Assert.assertEquals(checkoutPage.subheader_BillingAddress.getText(), "BILLING ADDRESS:");
}

Example of the issue (during the test the header easily appears before 30seconds):


问:
De Morgan's rules explained
Could you please explain the De Morgan's rules as simply as possible (e.g. to someone with only a secondary school mathematics background)?</p>

答:
Not sure why I've retained this all these years, but it has proven useful on a number of occasions. Thanks to Mr Bailey, my grade 10 math teacher. He called it deMorgan's Theorem.

```<code>!(A || B) <==> (!A && !B)
!(A && B) <==> (!A || !B)
</code>```

When you move the negation in or out of the brackets, the logical operator (AND, OR) changes.

ContentLicense: CC BY-SA 4.0

Title: De Morgan's rules explained

Body:
Not sure why I've retained this all these years, but it has proven useful on a number of occasions. Thanks to Mr Bailey, my grade 10 math teacher. He called it deMorgan's Theorem.

!(A || B) <==> (!A && !B)
!(A && B) <==> (!A || !B)

When you move the negation in or out of the brackets, the logical operator (AND, OR) changes.


问:
Pass in any number of arguments into a Javascript function
I want to be able to pass in any number of arguments into a function and then be able to use those arguments later. I know I can pass in default arguments but I don't know what to declare in my function.

For example,

```<code>function test(????) {
  console.log(a)
  console.log(b)
  console.log(c)
}

test(a="a", b="b", c="c")
</code>```

I'm also challenged by being given this function and to make as little changes to the var declarations as much as possible. So here, variables, a, b, and c are declared and I'm not able to edit these variables. I should be able to pass in arguments that will then know to assign itself to these variables.

```<code>function test(???) {
  var a,b,c
  if (a>b){
    c = a + b
  }
}

test(a=2,b=3)
</code>```

答:
You should use an array or an object.

In that array add as many arguments you want.

function test(arr) {
   console.log(arr.a);
   console.log(arr.b);
   console.log(arr.c);
}

arr = {}

arr.a = "a";
arr.b = "b";
arr.c = "c";

k = test(arr);

    ```

Body:
I want to be able to pass in any number of arguments into a function and then be able to use those arguments later. I know I can pass in default arguments but I don't know what to declare in my function.

For example,

function test(????) {
  console.log(a)
  console.log(b)
  console.log(c)
}

test(a="a", b="b", c="c")

I'm also challenged by being given this function and to make as little changes to the var declarations as much as possible. So here, variables, a, b, and c are declared and I'm not able to edit these variables. I should be able to pass in arguments that will then know to assign itself to these variables.

function test(???) {
  var a,b,c
  if (a>b){
    c = a + b
  }
}

test(a=2,b=3)


问:
Counter in arrays c++
i have a really simple code right there that counts how much values you need in arrays.

```<code>for (int i = 0; i < dm; i++)
    {
        if (arr[i] == c)
        {
            counter++;
        }
    };
</code>```

But i need to make it a little bit tricky.I need to count number of same values. Imagine i have an array {4,4,4,3,3,2,2,1,1,0,0,0} and i need to find how much "twins" there. So 3,2,1 are twins because they have only 1 exact friend.
I tried something like 2 fors and 2 counters but still have troubles. Thanks. Hope you understand what i mean by "twin". x and x are twins and y,y,y are not ( just in case)

答:
You can do that in one pass and use binary search for efficiency:

```<code>int arr[] = { 4,4,4,3,3,2,2,1,1,0,0,0 };
int twins = 0;
for( auto i = std::begin( arr ); i != std::end( arr ); ) {
    auto next = std::upper_bound( i, std::end( arr ), *i, std::greater<int>() );
    if( std::distance( i, next ) == 2 ) ++twins;
    i = next;
}
</code>```

Live example

In case there are not too many duplicates in the array std::upper_bound could be not efficient and can be easily replaced:

```<code>    auto next = std::find_if( std::next( i ), std::end( arr ), [i]( int n ) { return *i != n; } );
</code>```

Title: Counter in arrays c++

Body:
i have a really simple code right there that counts how much values you need in arrays.

for (int i = 0; i < dm; i++)
    {
        if (arr[i] == c)
        {
            counter++;
        }
    };

But i need to make it a little bit tricky.I need to count number of same values. Imagine i have an array {4,4,4,3,3,2,2,1,1,0,0,0} and i need to find how much "twins" there. So 3,2,1 are twins because they have only 1 exact friend.
I tried something like 2 fors and 2 counters but still have troubles. Thanks. Hope you understand what i mean by "twin". x and x are twins and y,y,y are not ( just in case)

Body:
You can do that in one pass and use binary search for efficiency:

int arr[] = { 4,4,4,3,3,2,2,1,1,0,0,0 };
int twins = 0;
for( auto i = std::begin( arr ); i != std::end( arr ); ) {
    auto next = std::upper_bound( i, std::end( arr ), *i, std::greater<int>() );
    if( std::distance( i, next ) == 2 ) ++twins;
    i = next;
}

Live example

In case there are not too many duplicates in the array std::upper_bound could be not efficient and can be easily replaced:

    auto next = std::find_if( std::next( i ), std::end( arr ), [i]( int n ) { return *i != n; } );


问:
Set <select> element depending on another <select> element
I need a select element's options to change depending on the value of another.

```<code><select id="first">
    <option value="1">one</option> // When you click this one, all the values of #second change (arbitrary number of entries)
    <option value="2">two</option> // When you click this one, all the values of #second change to something else (not necessarily the same number)
</select>
<select id="second">
    <option value="thisChanges">soDoesThis</option>
    <option value="thisToo">andThis</option>
</select>

<script>
    $("#first").on("change", function() {
        <pseudo>
            if #first == "1"
                #second = {"this", "that", "the other"}
            else if #first == "2"
                #second = {"more", "even more", "yet another", "still more"}
        </pseudo>
    }
</script>
</code>```

This is pretty much what I'm after (took me years to figure out how to completely replace the values of a select box), but the button click event doesn't even work. It was working a minute ago, although the for loop was not.

Obviously for my use case I would check if the select is clicked and retrieve its value with .val(), but I figured this button is easier for debugging.

JSFiddle

HTML:

```<code><select id="sel">
  <option value="1">One</option>
  <option value="2">Two</option>
</select>

<button>
Click me
</button>
</code>```

JS:

```<code>var list = ['11', 'Eleven', '12', 'Twelve', '13', 'Thirteen'];
$('button').on('click', function () {
        alert('click');
    var sel = $('#sel');
    alert('1');
    sel.empty();
    alert('2');
    for (i = 0, i < list.length; i+2) {
        $('#sel').append('<option value="' + list[i] + '">' + list[i+1] + '</option>');
    }
    alert('3');
});
</code>```

答:
To get the text found in the first Select field, use the .text() function after using find(":selected") on your desired select field.

```<code> $("#two").focus(function() {
    document.getElementById("option1").innerHTML = $("#one").find(":selected").text();
});
</code>```

Body:
I need a select element's options to change depending on the value of another.

<select id="first">
    <option value="1">one</option> // When you click this one, all the values of #second change (arbitrary number of entries)
    <option value="2">two</option> // When you click this one, all the values of #second change to something else (not necessarily the same number)
</select>
<select id="second">
    <option value="thisChanges">soDoesThis</option>
    <option value="thisToo">andThis</option>
</select>

This is pretty much what I'm after (took me years to figure out how to completely replace the values of a select box), but the button click event doesn't even work. It was working a minute ago, although the for loop was not.

Obviously for my use case I would check if the select is clicked and retrieve its value with .val(), but I figured this button is easier for debugging.

JSFiddle

HTML:

<select id="sel">
  <option value="1">One</option>
  <option value="2">Two</option>
</select>

<button>
Click me
</button>

JS:

var list = ['11', 'Eleven', '12', 'Twelve', '13', 'Thirteen'];
$('button').on('click', function () {
        alert('click');
    var sel = $('#sel');
    alert('1');
    sel.empty();
    alert('2');
    for (i = 0, i < list.length; i+2) {
        $('#sel').append('<option value="' + list[i] + '">' + list[i+1] + '</option>');
    }
    alert('3');
});

Body:
To get the text found in the first Select field, use the .text() function after using find(":selected") on your desired select field.

 $("#two").focus(function() {
    document.getElementById("option1").innerHTML = $("#one").find(":selected").text();
});


问:
Export a parameterized SSRS report from C# code
Currently I have SQL Reporting Services 2005 set up, with the report manager at a URL on which users can access reports. The reports are working great there.

My issue is trying to generate these reports in C# .net 4.0 code without any user interaction (such as using the report viewer on screen). I would like to generate and export a report to a PDF file in a C# .net application. The reports have required parameters so I would need to pass the parameters to the report. How can I do this?

I have been searching around online, and either I'm using the wrong keywords or there isn't much information on this. I am quite amazed at how difficult it has been to find information on this, as I would expect it to be a fairly common question. Any and all advice / help is appreciated.

答:
I've not used the 2005 version of the ReportViewer much. But you should be able to do something like this:

```<code>ServerReport serverReport = new ServerReport();
serverReport.ReportPath = "path/to/report";
serverReport.ReportServerCredentials = ...;
serverReport.ReportServerUrl = "http://....";
serverReport.SetParameters(...);
string mimeType;
string encoding;
string extension;
string[] streams;
Warning[] warnings;
byte[] asPdf = serverReport.Render("PDF", string.Empty, out mimeType, out encoding, out extension, out streams, out warnings);
</code>```

The general takeaway being that ServerReport and LocalReport were both designed to be usable outside of a ReportViewer.

Body:
I've not used the 2005 version of the ReportViewer much. But you should be able to do something like this:

ServerReport serverReport = new ServerReport();
serverReport.ReportPath = "path/to/report";
serverReport.ReportServerCredentials = ...;
serverReport.ReportServerUrl = "http://....";
serverReport.SetParameters(...);
string mimeType;
string encoding;
string extension;
string[] streams;
Warning[] warnings;
byte[] asPdf = serverReport.Render("PDF", string.Empty, out mimeType, out encoding, out extension, out streams, out warnings);

The general takeaway being that ServerReport and LocalReport were both designed to be usable outside of a ReportViewer.


问:
Float or wrap text around a chart?
I've been searching and searching for an answer to my question, but I can't seem to find anything.  Does anyone know of a way to wrap/float text around a chart or image in SSRS?  I was hoping for some kind of option similar to the blue one below in Word, but no luck there:

I found the following post, which has a good example image of what I'm looking for, but doesn't have any helpful answers (I'm not using Crystal Reports, I'm using BIDS SSRS through Visual Studio 2015).

Crystal report (or SSRS) flowing text around image

I've tried the following:

Overlaying a text box on top of the image (rendering shoves the image below the text)

Trying to find or create a mad scientist algorithm that can split the text after a certain number of characters, but not in the middle of a word, chop off the rest, and continue the rest of the text in a separate textbox under the image (not a mad scientist, so no luck)

Thanks for any tips!

答:
There's no built in way to do this in SSRS.

Someone wrote a function that determines how many pixels are in a given text string.

Truncate textbox content with ellipsis in SSRS

```<code>Public Function TextWidth(str As String) AS Double
    'Returns the width, in pixels, of a string, assuming Tahoma size 8.
    Dim size As System.Drawing.SizeF
    Dim font As New system.Drawing.Font("Tahoma", 8)
    size = System.Windows.Forms.TextRenderer.MeasureText(str, font)
    TextWidth = size.Width
End Function
</code>```

You may be able to use this to figure out where to make a break in the first text box and spill the rest to the second. You'd just need to do testing to figure out how many pixels of text your first text box holds.

Once you figure out how many pixels would fit (I would just fill the first text box with text then use the function to see how many pixels that text is), change the other TextCap function to return either the first or second part at the pixel split. You could add an Argument in the function to indicate whether to return the first or second part of the text. Then use the function in the first text box to return the first part and the second part in the second text box.

It's a bit of work but seems feasible. It depends on how bad you want it and how much time you have.

Title: Float or wrap text around a chart?

Body:
There's no built in way to do this in SSRS.

Someone wrote a function that determines how many pixels are in a given text string.

Truncate textbox content with ellipsis in SSRS

Public Function TextWidth(str As String) AS Double
    'Returns the width, in pixels, of a string, assuming Tahoma size 8.
    Dim size As System.Drawing.SizeF
    Dim font As New system.Drawing.Font("Tahoma", 8)
    size = System.Windows.Forms.TextRenderer.MeasureText(str, font)
    TextWidth = size.Width
End Function

You may be able to use this to figure out where to make a break in the first text box and spill the rest to the second. You'd just need to do testing to figure out how many pixels of text your first text box holds.

Once you figure out how many pixels would fit (I would just fill the first text box with text then use the function to see how many pixels that text is), change the other TextCap function to return either the first or second part at the pixel split. You could add an Argument in the function to indicate whether to return the first or second part of the text. Then use the function in the first text box to return the first part and the second part in the second text box.

It's a bit of work but seems feasible. It depends on how bad you want it and how much time you have.