问:
Android - Drawable - Error inflating TextView in lower API
When I run my code on Emulator with API 25,

it works fine

Instead on emulator with API 16, I get this error

android.view.InflateException: Binary XML file line #36: Error inflating class TextView

Here is the line where I get the error

```<code>public class RecipeAdapter extends RecyclerView.Adapter<RecipeAdapter.MyViewHolder> {
    ...
    static class MyViewHolder extends RecyclerView.ViewHolder{
        TextView recipe, time;
        RatingBar ratingBar;
        ImageView imageView;

        MyViewHolder(View view) {
            super(view);

            recipe = (TextView) view.findViewById(R.id.tv_recipe_name);
            time = (TextView) view.findViewById(R.id.tv_time);
            ratingBar = (RatingBar) view.findViewById(R.id.ratingBar);
            imageView = (ImageView) view.findViewById(R.id.iv_recipe);
        }
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_recipe, parent, false); // <- Error

        return new MyViewHolder(itemView);
    }
    ...
}
</code>```

This is the error message

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
       android.view.InflateException: Binary XML file line #36: Error inflating class TextView
              at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
              at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
              at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
              at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater.inflate(CalligraphyLayoutInflater.java:60)
              at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
              at com.mnm.cookrecipe.recycler.RecipeAdapter.onCreateViewHolder(RecipeAdapter.java:55) // <- this
              at com.mnm.cookrecipe.recycler.RecipeAdapter.onCreateViewHolder(RecipeAdapter.java:21) // <- this
              at android.support.v7.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:6078)
              at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5248)
              at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5158)
              at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2061)
              at android.support.v7.widget.GridLayoutManager.layoutChunk(GridLayoutManager.java:562)
              at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1408)
              at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:580)
              at android.support.v7.widget.GridLayoutManager.onLayoutChildren(GridLayoutManager.java:170)
              at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3379)
              at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3188)
              at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3632)
              at android.view.View.layout(View.java:13754)
              at android.view.ViewGroup.layout(ViewGroup.java:4364)
              at android.widget.RelativeLayout.onLayout(RelativeLayout.java:948)
              at android.view.View.layout(View.java:13754)
              at android.view.ViewGroup.layout(ViewGroup.java:4364)
              at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
              at android.view.View.layout(View.java:13754)
              at android.view.ViewGroup.layout(ViewGroup.java:4364)
              at android.widget.RelativeLayout.onLayout(RelativeLayout.java:948)
              at android.view.View.layout(View.java:13754)
              at android.view.ViewGroup.layout(ViewGroup.java:4364)
              at android.widget.RelativeLayout.onLayout(RelativeLayout.java:948)
              at android.view.View.layout(View.java:13754)
              at android.view.ViewGroup.layout(ViewGroup.java:4364)
              at android.support.v4.widget.DrawerLayout.onLayout(DrawerLayout.java:1193)
              at android.view.View.layout(View.java:13754)
              at android.view.ViewGroup.layout(ViewGroup.java:4364)
              at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
              at android.view.View.layout(View.java:13754)
              at android.view.ViewGroup.layout(ViewGroup.java:4364)
              at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1649)
              at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1507)
              at android.widget.LinearLayout.onLayout(LinearLayout.java:1420)
              at android.view.View.layout(View.java:13754)
              at android.view.ViewGroup.layout(ViewGroup.java:4364)
              at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
              at android.view.View.layout(View.java:13754)
              at android.view.ViewGroup.layout(ViewGroup.java:4364)
              at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1649)
              at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1507)
              at android.widget.LinearLayout.onLayout(LinearLayout.java:1420)
              at android.view.View.layout(View.java:13754)
              at android.view.ViewGroup.layout(ViewGroup.java:4364)
              at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
              at android.view.View.layout(View.java:13754)
              at android.view.ViewGroup.layout(ViewGroup.java:4364)
              at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:1868)
              at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1689)
              at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1000)
              at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4214)
              at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725)
</code>```

Here is the layout file

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?android:attr/selectableItemBackground"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    android:padding="@dimen/space16">

    <ImageView
        android:id="@+id/iv_recipe"
        android:layout_width="52dp"
        android:layout_height="52dp" />

    <RatingBar
        android:id="@+id/ratingBar"
        style="@style/RatingBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/space8"
        android:isIndicator="true"
        android:numStars="5"
        android:rating="3.5" />

    <TextView
        android:id="@+id/tv_recipe_name"
        style="@style/SemiBold"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/space8"
        android:gravity="center_horizontal"
        android:text="RECIPES"
        android:textColor="@color/colorTextDark"
        android:textSize="@dimen/h3" />

    <TextView
        android:id="@+id/tv_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:drawableLeft="@drawable/ic_time"
        android:drawablePadding="@dimen/space8"
        android:text="1h 20'"
        android:textAppearance="@style/Regular"
        android:textColor="@color/colorTextGrey"
        android:textSize="@dimen/h3" />
</LinearLayout>
</code>```

This is the app.gradle file

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

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.1"
    defaultConfig {
        applicationId "com.mnm.cookrecipe"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        vectorDrawables.useSupportLibrary = true
    }
    buildTypes {
        debug {
            debuggable true
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        release {
            debuggable false
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    dexOptions {
        javaMaxHeapSize '3g'
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.0.1'
    compile 'com.android.support:design:25.0.1'
    compile 'uk.co.chrisjenx:calligraphy:2.2.0'
    compile 'com.android.support:support-v4:25.0.1'
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'com.android.support:recyclerview-v7:25.0.1'
    compile 'com.android.support:cardview-v7:25.0.1'
    testCompile 'junit:junit:4.12'
}
</code>```

答:
The android:drawableLeft="@drawable/ic_time" used in the Text view seems to be the issue. Replace the drawable with better one or remove this line

```<code>android:drawableLeft="@drawable/ic_time
</code>```

After removing

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?android:attr/selectableItemBackground"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    android:padding="@dimen/space16">

    <ImageView
        android:id="@+id/iv_recipe"
        android:layout_width="52dp"
        android:layout_height="52dp" />

    <RatingBar
        android:id="@+id/ratingBar"
        style="@style/RatingBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/space8"
        android:isIndicator="true"
        android:numStars="5"
        android:rating="3.5" />

    <TextView
        android:id="@+id/tv_recipe_name"
        style="@style/SemiBold"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/space8"
        android:gravity="center_horizontal"
        android:text="RECIPES"
        android:textColor="@color/colorTextDark"
        android:textSize="@dimen/h3" />

    <TextView
        android:id="@+id/tv_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:drawablePadding="@dimen/space8"
        android:text="1h 20'"
        android:textAppearance="@style/Regular"
        android:textColor="@color/colorTextGrey"
        android:textSize="@dimen/h3" />
</LinearLayout>
</code>```

Body:
When I run my code on Emulator with API 25,

it works fine

Instead on emulator with API 16, I get this error

android.view.InflateException: Binary XML file line #36: Error inflating class TextView

Here is the line where I get the error

public class RecipeAdapter extends RecyclerView.Adapter<RecipeAdapter.MyViewHolder> {
    ...
    static class MyViewHolder extends RecyclerView.ViewHolder{
        TextView recipe, time;
        RatingBar ratingBar;
        ImageView imageView;

        MyViewHolder(View view) {
            super(view);

            recipe = (TextView) view.findViewById(R.id.tv_recipe_name);
            time = (TextView) view.findViewById(R.id.tv_time);
            ratingBar = (RatingBar) view.findViewById(R.id.ratingBar);
            imageView = (ImageView) view.findViewById(R.id.iv_recipe);
        }
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_recipe, parent, false); // <- Error

        return new MyViewHolder(itemView);
    }
    ...
}

This is the error message

E/AndroidRuntime: FATAL EXCEPTION: main
       android.view.InflateException: Binary XML file line #36: Error inflating class TextView
              at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
              at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
              at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
              at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater.inflate(CalligraphyLayoutInflater.java:60)
              at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
              at com.mnm.cookrecipe.recycler.RecipeAdapter.onCreateViewHolder(RecipeAdapter.java:55) // <- this
              at com.mnm.cookrecipe.recycler.RecipeAdapter.onCreateViewHolder(RecipeAdapter.java:21) // <- this
              at android.support.v7.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:6078)
              at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5248)
              at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5158)
              at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2061)
              at android.support.v7.widget.GridLayoutManager.layoutChunk(GridLayoutManager.java:562)
              at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1408)
              at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:580)
              at android.support.v7.widget.GridLayoutManager.onLayoutChildren(GridLayoutManager.java:170)
              at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3379)
              at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3188)
              at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3632)
              at android.view.View.layout(View.java:13754)
              at android.view.ViewGroup.layout(ViewGroup.java:4364)
              at android.widget.RelativeLayout.onLayout(RelativeLayout.java:948)
              at android.view.View.layout(View.java:13754)
              at android.view.ViewGroup.layout(ViewGroup.java:4364)
              at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
              at android.view.View.layout(View.java:13754)
              at android.view.ViewGroup.layout(ViewGroup.java:4364)
              at android.widget.RelativeLayout.onLayout(RelativeLayout.java:948)
              at android.view.View.layout(View.java:13754)
              at android.view.ViewGroup.layout(ViewGroup.java:4364)
              at android.widget.RelativeLayout.onLayout(RelativeLayout.java:948)
              at android.view.View.layout(View.java:13754)
              at android.view.ViewGroup.layout(ViewGroup.java:4364)
              at android.support.v4.widget.DrawerLayout.onLayout(DrawerLayout.java:1193)
              at android.view.View.layout(View.java:13754)
              at android.view.ViewGroup.layout(ViewGroup.java:4364)
              at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
              at android.view.View.layout(View.java:13754)
              at android.view.ViewGroup.layout(ViewGroup.java:4364)
              at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1649)
              at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1507)
              at android.widget.LinearLayout.onLayout(LinearLayout.java:1420)
              at android.view.View.layout(View.java:13754)
              at android.view.ViewGroup.layout(ViewGroup.java:4364)
              at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
              at android.view.View.layout(View.java:13754)
              at android.view.ViewGroup.layout(ViewGroup.java:4364)
              at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1649)
              at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1507)
              at android.widget.LinearLayout.onLayout(LinearLayout.java:1420)
              at android.view.View.layout(View.java:13754)
              at android.view.ViewGroup.layout(ViewGroup.java:4364)
              at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
              at android.view.View.layout(View.java:13754)
              at android.view.ViewGroup.layout(ViewGroup.java:4364)
              at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:1868)
              at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1689)
              at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1000)
              at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4214)
              at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725)

Here is the layout file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?android:attr/selectableItemBackground"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    android:padding="@dimen/space16">

    <ImageView
        android:id="@+id/iv_recipe"
        android:layout_width="52dp"
        android:layout_height="52dp" />

    <RatingBar
        android:id="@+id/ratingBar"
        style="@style/RatingBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/space8"
        android:isIndicator="true"
        android:numStars="5"
        android:rating="3.5" />

    <TextView
        android:id="@+id/tv_recipe_name"
        style="@style/SemiBold"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/space8"
        android:gravity="center_horizontal"
        android:text="RECIPES"
        android:textColor="@color/colorTextDark"
        android:textSize="@dimen/h3" />

    <TextView
        android:id="@+id/tv_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:drawableLeft="@drawable/ic_time"
        android:drawablePadding="@dimen/space8"
        android:text="1h 20'"
        android:textAppearance="@style/Regular"
        android:textColor="@color/colorTextGrey"
        android:textSize="@dimen/h3" />
</LinearLayout>

This is the app.gradle file

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.1"
    defaultConfig {
        applicationId "com.mnm.cookrecipe"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        vectorDrawables.useSupportLibrary = true
    }
    buildTypes {
        debug {
            debuggable true
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        release {
            debuggable false
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    dexOptions {
        javaMaxHeapSize '3g'
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.0.1'
    compile 'com.android.support:design:25.0.1'
    compile 'uk.co.chrisjenx:calligraphy:2.2.0'
    compile 'com.android.support:support-v4:25.0.1'
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'com.android.support:recyclerview-v7:25.0.1'
    compile 'com.android.support:cardview-v7:25.0.1'
    testCompile 'junit:junit:4.12'
}

Body:
The android:drawableLeft="@drawable/ic_time" used in the Text view seems to be the issue. Replace the drawable with better one or remove this line

android:drawableLeft="@drawable/ic_time

After removing

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?android:attr/selectableItemBackground"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    android:padding="@dimen/space16">

    <ImageView
        android:id="@+id/iv_recipe"
        android:layout_width="52dp"
        android:layout_height="52dp" />

    <RatingBar
        android:id="@+id/ratingBar"
        style="@style/RatingBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/space8"
        android:isIndicator="true"
        android:numStars="5"
        android:rating="3.5" />

    <TextView
        android:id="@+id/tv_recipe_name"
        style="@style/SemiBold"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/space8"
        android:gravity="center_horizontal"
        android:text="RECIPES"
        android:textColor="@color/colorTextDark"
        android:textSize="@dimen/h3" />

    <TextView
        android:id="@+id/tv_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:drawablePadding="@dimen/space8"
        android:text="1h 20'"
        android:textAppearance="@style/Regular"
        android:textColor="@color/colorTextGrey"
        android:textSize="@dimen/h3" />
</LinearLayout>


来源: stackexchange

问:
How to select multiple checkbox in for loop in angular2?
I have tried angular 2 to list categories list with checkbox and user can select any category. I tried with below code. The issue is if I selected any one checkbox all the checkbox are selected and I cannot get the form values on save function. Food.category is dynamic. How can I fix this?</p>

```<code><form #f="ngForm" novalidate>
    <div class="checkbox checkbox-primary" *ngFor="let categoryname of Food.category;">
        <label for="categoryname">
            <input type = "checkbox" name="categoryname[]" [(ngModel)]="Catcheckbox" (click)="onClick(categoryname)" value="{{categoryname}}"/>
            {{categoryname}}
        </label>
    </div>
    <button type="submit" (click)="save(f.value, f.valid)" class="btn btn-default">Submit</button>
</form>

export class ExploreListComponent implements OnInit {
    Catcheckbox:true ;

    onClick(categoryname) {
        alert(categoryname + ' was clicked!');
    }

    save(isValid: boolean, f: User) {
        if (!isValid) return;
        console.log(f);
    }
}
</code>```

答:
```<code><div class="checkbox checkbox-primary" *ngFor="let categoryname of Food.category;">
            <label for="categoryname">
             <input type = "checkbox" *ngIf="selectAll" [checked]="selectedAll" name="categoryname[]" [(ngModel)]="Catcheckbox" (click)="onClick(categoryname)" value="{{categoryname}}"/>

               <input type = "checkbox" *ngIf="selectAll" [checked]="!selectedAll" name="categoryname[]" [(ngModel)]="Catcheckbox" (click)="onClick(categoryname)" value="{{categoryname}}"/>
            {{categoryname}}
            </label>
        </div>
         <button type="submit" (click)="save(f.value, f.valid)" class="btn btn-default">Submit</button>
    </form>
</code>```

on click of the select all button

```<code>this.selectAll=true
</code>```

So all the elements are selected and you have the entire array passed to *ngFor

ContentLicense: CC BY-SA 4.0

Body:
I have tried angular 2 to list categories list with checkbox and user can select any category. I tried with below code. The issue is if I selected any one checkbox all the checkbox are selected and I cannot get the form values on save function. Food.category is dynamic. How can I fix this?

<form #f="ngForm" novalidate>

            <input type = "checkbox" name="categoryname[]" [(ngModel)]="Catcheckbox" (click)="onClick(categoryname)" value="{{categoryname}}"/>
            {{categoryname}}

    <button type="submit" (click)="save(f.value, f.valid)" class="btn btn-default">Submit</button>
</form>

export class ExploreListComponent implements OnInit {
    Catcheckbox:true ;

    onClick(categoryname) {
        alert(categoryname + ' was clicked!');
    }

    save(isValid: boolean, f: User) {
        if (!isValid) return;
        console.log(f);
    }
}

Body:
<div class="checkbox checkbox-primary" *ngFor="let categoryname of Food.category;">
            <label for="categoryname">
             <input type = "checkbox" *ngIf="selectAll" [checked]="selectedAll" name="categoryname[]" [(ngModel)]="Catcheckbox" (click)="onClick(categoryname)" value="{{categoryname}}"/>

               <input type = "checkbox" *ngIf="selectAll" [checked]="!selectedAll" name="categoryname[]" [(ngModel)]="Catcheckbox" (click)="onClick(categoryname)" value="{{categoryname}}"/>
            {{categoryname}}
            </label>
        </div>
         <button type="submit" (click)="save(f.value, f.valid)" class="btn btn-default">Submit</button>
    </form>

on click of the select all button

this.selectAll=true

So all the elements are selected and you have the entire array passed to *ngFor

ContentLicense: CC BY-SA 3.0


问:
Getting lines from files
I am trying to get a to be the first line of the file and b to be the second.

This prints nothing.

```<code>f = open(filename)
line = f.readline().strip()
while line:
    a = f.readline()
    b = f.readline()
    line = f.readline()
print(a)
print(b)
</code>```

I want to assign specific lines to variables, not just read all of them.

答:
```<code>lines =[]
with open(filename) as f:
    i =0
    for line in f:
        lines[i] = line
        i += 1

print '1st Line is: ', lines[0]
print '2st Line is: ', lines[1]
</code>```

Title: Getting lines from files

Body:
I am trying to get a to be the first line of the file and b to be the second.

This prints nothing.

f = open(filename)
line = f.readline().strip()
while line:
    a = f.readline()
    b = f.readline()
    line = f.readline()
print(a)
print(b)

I want to assign specific lines to variables, not just read all of them.


答:
Check the tutorial first please, it says:

If you want to read all the lines of a file in a list you can also use
  list(f) or f.readlines().

```<code>lines = f.readlines()
a = lines[0]
b = lines[1]
</code>```

Title: Getting lines from files

Body:
Check the tutorial first please, it says:

If you want to read all the lines of a file in a list you can also use
  list(f) or f.readlines().

lines = f.readlines()
a = lines[0]
b = lines[1]


问:
Android sqlite search data in between dates
I am trying to fetch data from sqlite in between two dates...

My date value stored in sqlite 27/01/2017 15:10:42

My code to fetch data...

```<code> Cursor fetchallconsultations(String from,String to) {
    SQLiteDatabase db = this.getReadableDatabase();
    return db.rawQuery("select * from gle_consultns where consultn_create_date >= '"+from+" 00:00:00' and consultn_create_date <= '"+to+" 00:00:00'", null);
}
</code>```

Values of from and to are..

from==26/01/2017

to==01/02/2017

But the cursor is null when executing fetchallconsultations function. How can i resolve this issue.?

答:
```<code>String str="SELECT * FROM tablename WHERE date BETWEEN '"+startdate+"' AND '"+enddate+"'";

cursor = db.rawQuery(str, null);

[where date format is startdate=2017-01-26 and enddate=2017-02-01]
</code>```

Body:
I am trying to fetch data from sqlite in between two dates...

My date value stored in sqlite 27/01/2017 15:10:42

My code to fetch data...

 Cursor fetchallconsultations(String from,String to) {
    SQLiteDatabase db = this.getReadableDatabase();
    return db.rawQuery("select * from gle_consultns where consultn_create_date >= '"+from+" 00:00:00' and consultn_create_date <= '"+to+" 00:00:00'", null);
}

Values of from and to are..

from==26/01/2017

to==01/02/2017

But the cursor is null when executing fetchallconsultations function. How can i resolve this issue.?


问:
In Java, what is the order of initialization for those statements after main method
I learned that the principle for order of initialization is:

Superclass first (not discussed here in this case)

Static variable declarations and static initialization blocks in the order of appearance

Instance variable declarations and static initialization blocks in the order of appearance

The constructor

But I'm still confused by the output of this code:

```<code>public class Test1 {

    static {
        add(2);
    }

    static void add (int num) {
        System.out.println(num + " ");
    }

    public Test1() {
        add(5);
        System.out.println("Constructor!");
    }

    static {
        add(4);
    }

    {
        add(6);
    }

    static {
        new Test1();
    }

    {
        add(8);
    }

    public static void main(String[] args) {
        System.out.println("Main method!");
        add(10);
    }

    {
        add(11);
    }
    static {
        add(12);
    }
}
</code>```

The result is:

```<code>2
4
6
8
11
5
Constructor!
12
Main method!
10
</code>```

If without the statements of add(10); add(11); add(12); I can totally understand. Can you please explain the order of initialization for those 3 statements?

答:
1) Block that does not have name like below is called "Instance Initializer" which only get called when new objects will be created its like DefaultConstructor or noArg Constructor.

```<code>{
    add(11);
}
</code>```

2) In above code you have Static Block (Which get called first at the Class Loading itself), Instance Initializer (Which get called while creating the object), Explicit DefaultConstructor (Which get called while creating the object but remember always Instance initializer takes priority) and last Main method.

3) Now lets analyze your code,

1st call:

```<code>static
{
   add(2); //print 2
}
</code>```

2nd call:

```<code>static {
        add(4); // print 4
}
</code>```

3rd call:

```<code>static {
    new Test1();
    // Here Object is getting created so all Instance Initialzer will be called first in a sequential manner.
}
</code>```

4th call:

```<code>{
    add(6); // print 6
}
</code>```

5th call:

```<code>{
    add(8);  // print 8
}
</code>```

6th call:

```<code>{
    add(11);   // print 11
}
</code>```

7th call : After Instance Initializer, Explicit Default Constructor will be called.

```<code>public Test1() {
    add(5);    // print 5
    System.out.println("Constructor!");   // print Constructor!
}
</code>```

8th call: Again the last Static block will be called.

```<code>static {
    add(12);   // print 12
}
</code>```

9th call: Finally the main method will be called

```<code>public static void main(String[] args) {
    System.out.println("Main method!");  // print Main method!
    add(10); // print 10
}
</code>```

Body:
I learned that the principle for order of initialization is:

Superclass first (not discussed here in this case)

Static variable declarations and static initialization blocks in the order of appearance

Instance variable declarations and static initialization blocks in the order of appearance

The constructor

But I'm still confused by the output of this code:

public class Test1 {

    static {
        add(2);
    }

    static void add (int num) {
        System.out.println(num + " ");
    }

    public Test1() {
        add(5);
        System.out.println("Constructor!");
    }

    static {
        add(4);
    }

    {
        add(6);
    }

    static {
        new Test1();
    }

    {
        add(8);
    }

    public static void main(String[] args) {
        System.out.println("Main method!");
        add(10);
    }

    {
        add(11);
    }
    static {
        add(12);
    }
}

The result is:

2
4
6
8
11
5
Constructor!
12
Main method!
10

If without the statements of add(10); add(11); add(12); I can totally understand. Can you please explain the order of initialization for those 3 statements?

Body:
1) Block that does not have name like below is called "Instance Initializer" which only get called when new objects will be created its like DefaultConstructor or noArg Constructor.

{
    add(11);
}

2) In above code you have Static Block (Which get called first at the Class Loading itself), Instance Initializer (Which get called while creating the object), Explicit DefaultConstructor (Which get called while creating the object but remember always Instance initializer takes priority) and last Main method.

3) Now lets analyze your code,

1st call:

static
{
   add(2); //print 2
}

2nd call:

static {
        add(4); // print 4
}

3rd call:

static {
    new Test1();
    // Here Object is getting created so all Instance Initialzer will be called first in a sequential manner.
}

4th call:

{
    add(6); // print 6
}

5th call:

{
    add(8);  // print 8
}

6th call:

{
    add(11);   // print 11
}

7th call : After Instance Initializer, Explicit Default Constructor will be called.

public Test1() {
    add(5);    // print 5
    System.out.println("Constructor!");   // print Constructor!
}

8th call: Again the last Static block will be called.

static {
    add(12);   // print 12
}

9th call: Finally the main method will be called

public static void main(String[] args) {
    System.out.println("Main method!");  // print Main method!
    add(10); // print 10
}


问:
changing menu structure - ionic 2
I'm building an app which contains 3 different parts, all those parts have their own menu structure. I would like to know how to update those in (as example) a settings page. I already made a start, but when I change the app, I have to refresh the app for the menu structure to show up.

Settings.html

```<code><ion-list style="margin-bottom: 0px;">
  <ion-item>
    <ion-label>Taal</ion-label>
    <ion-select [(ngModel)]="language" cancelText="Annuleer" (ngModelChange)="changeLang()">
      <ion-option value="nl">Nederlands</ion-option>
      <ion-option value="en">English</ion-option>
      <ion-option value="du">Deutsch</ion-option>
    </ion-select>
  </ion-item>
  <ion-item>
    <ion-label>Waarvoor wilt u de app gebruiken</ion-label>
    <ion-select [(ngModel)]="type" cancelText="Annuleer" (ngModelChange)="changeType()">
      <ion-option value="alg">Algemeen</ion-option>
      <ion-option value="zrk">Zerken</ion-option>
      <ion-option value="kds">Kids</ion-option>
    </ion-select>
  </ion-item>
 </ion-list>
</code>```

Settings.ts

```<code>changeLang() {
    console.log(this.language);
    this.storage.set('appLang', this.language);
  }

  changeType() {
    console.log(this.type);
    this.storage.set('appType', this.type);
  }
</code>```

app.component.ts

```<code>constructor(public platform: Platform, public popoverCtrl: PopoverController, public storage: Storage) {
    this.initializeApp();

      this.storage.get('appType').then((result) => {
        if(result == "alg") {
          this.pages = [
            { title: 'Home', component: HomePage },
            { title: 'Website', component: HomePage }
          ]
          this.menuTitle = "Algemeen";
        } else if(result == "zrk") {
          this.pages = [
            { title: 'Home', component: ZerkhomePage },
            { title: 'Plattegrond', component: PlattegrondPage },
            { title: 'Overzicht', component: LijstPage }
          ]
          this.menuTitle = "Zerken";
        } else if(result == "kds") {
          this.pages = [
            { title: 'Home', component: KidshomePage },
            { title: 'Quiz', component: QuizPage },
            { title: 'Prijs', component: PrijsPage }
          ]
          this.menuTitle = "Kids";
        }
      })

  }
</code>```

So what I kind of want is the app to 'refresh' after I made a change in my settings. I do know why this is not working, since the menu structure is loaded upon the start of the application.

Maybe someone knows a simple fix for this!

答:
You can use ionOpen event. check this link

in your template app.html

```<code><ion-menu (ionOpen)="omMenuOpen()">
</code>```

and then in your 'app.component.ts'

```<code>omMenuOpen(){
   console.log('menu oppend.');
   //here set your pages
}
</code>```

let me know if it worked.

Title: changing menu structure - ionic 2

Body:
I'm building an app which contains 3 different parts, all those parts have their own menu structure. I would like to know how to update those in (as example) a settings page. I already made a start, but when I change the app, I have to refresh the app for the menu structure to show up.

Settings.html

<ion-list style="margin-bottom: 0px;">
  <ion-item>
    <ion-label>Taal</ion-label>
    <ion-select [(ngModel)]="language" cancelText="Annuleer" (ngModelChange)="changeLang()">
      <ion-option value="nl">Nederlands</ion-option>
      <ion-option value="en">English</ion-option>
      <ion-option value="du">Deutsch</ion-option>
    </ion-select>
  </ion-item>
  <ion-item>
    <ion-label>Waarvoor wilt u de app gebruiken</ion-label>
    <ion-select [(ngModel)]="type" cancelText="Annuleer" (ngModelChange)="changeType()">
      <ion-option value="alg">Algemeen</ion-option>
      <ion-option value="zrk">Zerken</ion-option>
      <ion-option value="kds">Kids</ion-option>
    </ion-select>
  </ion-item>
 </ion-list>

Settings.ts

changeLang() {
    console.log(this.language);
    this.storage.set('appLang', this.language);
  }

  changeType() {
    console.log(this.type);
    this.storage.set('appType', this.type);
  }

app.component.ts

constructor(public platform: Platform, public popoverCtrl: PopoverController, public storage: Storage) {
    this.initializeApp();

      this.storage.get('appType').then((result) => {
        if(result == "alg") {
          this.pages = [
            { title: 'Home', component: HomePage },
            { title: 'Website', component: HomePage }
          ]
          this.menuTitle = "Algemeen";
        } else if(result == "zrk") {
          this.pages = [
            { title: 'Home', component: ZerkhomePage },
            { title: 'Plattegrond', component: PlattegrondPage },
            { title: 'Overzicht', component: LijstPage }
          ]
          this.menuTitle = "Zerken";
        } else if(result == "kds") {
          this.pages = [
            { title: 'Home', component: KidshomePage },
            { title: 'Quiz', component: QuizPage },
            { title: 'Prijs', component: PrijsPage }
          ]
          this.menuTitle = "Kids";
        }
      })

  }

So what I kind of want is the app to 'refresh' after I made a change in my settings. I do know why this is not working, since the menu structure is loaded upon the start of the application.

Maybe someone knows a simple fix for this!

Body:
You can use ionOpen event. check this link

in your template app.html

<ion-menu (ionOpen)="omMenuOpen()">

and then in your 'app.component.ts'

omMenuOpen(){
   console.log('menu oppend.');
   //here set your pages
}

let me know if it worked.


问:
How to learn to write idiomatic c++ code
I recently forced myself to study C++ and I just finished reading the book C++: The Complete Reference, by Herbert Schildt. I liked the book and think I got more or less the big picture. I noticed though that when I try to check with other people the things I code using the material I learned, they are usually considered non-idiomatic and superseded by an STL way to do it that is safer and easier (well, the book doesn't cover STL and Boost libraries).

So I'd like to ask: what are good sources to learn the patterns of a good C++ program? Where can I learn basic patterns from the "C++ way" to do things and not just repeating C patterns in C++?

I'd be particularly interested in sources that included STL and Boost stuff.

答: Accelerated C++ is an introduction to C++ that uses the STL from the very beginning.  It's not a long book, but it's "dense" and a great choice for someone in your situation IMO.  My experience with C++ was similar to yours when I read it.</p>

ContentLicense: CC BY-SA 2.5


问:
The requested URL /about was not found on this server
The home page of my wordpress website seems to be displaying correctly but if you click through to any of the other pages I get the following error message:

```<code>Not Found

The requested URL /about was not found on this server.

Apache/2 Server at www.wildlionmedia.co.uk Port 80
</code>```

I'm not sure whether it's a problem with the theme or the .htaccess file that is not being rewritten correctly.

http://www.wildlionmedia.co.uk/

Any ideas how I can resolve the issue?

```<code># Switch rewrite engine off in case this was installed under HostPay.
RewriteEngine On

SetEnv DEFAULT_PHP_VERSION 53

DirectoryIndex index.cgi index.php

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine Off
RewriteBase /wildlionmedia.co.uk/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /wildlionmedia.co.uk/index.php [L]
</IfModule>

# END WordPress
</code>```

答:
I deleted the previous .htaccess file and created new one by clicking on save button in Settings->Permalinks

and now that pages started working fine...

Body:
The home page of my wordpress website seems to be displaying correctly but if you click through to any of the other pages I get the following error message:

Not Found

The requested URL /about was not found on this server.

Apache/2 Server at www.wildlionmedia.co.uk Port 80

I'm not sure whether it's a problem with the theme or the .htaccess file that is not being rewritten correctly.

http://www.wildlionmedia.co.uk/

Any ideas how I can resolve the issue?

# Switch rewrite engine off in case this was installed under HostPay.
RewriteEngine On

SetEnv DEFAULT_PHP_VERSION 53

DirectoryIndex index.cgi index.php

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine Off
RewriteBase /wildlionmedia.co.uk/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /wildlionmedia.co.uk/index.php [L]
</IfModule>

# END WordPress


问:
Why use binary shifts in enums
I'm looking at this code:

```<code>/**
 * Bitmask of states
 */
export const enum ViewState {
    FirstCheck = 1 << 0,      // result is 1
    ChecksEnabled = 1 << 1,   // result is 2
    Errored = 1 << 2,         // result is 4
    Destroyed = 1 << 3        // result is 8
}
</code>```

I don't understand why not simply specify the integer results there or integer numbers 0,1,2,3. Does anyone have any idea?

答:
This enum models the idea of four flags, each of which can be either on/true/one or off/false/zero. You can set the enum to a value by logically OR-ing together the values you want. For example:

```<code>z = ViewState.FirstCheck | ViewState.ChecksEnabled
</code>```

Later in the code you can check these values independently of each other by logicall AND-ing the value with the one you want to check:

```<code>if (z & ViewState.FirstCheck) {
  do_something();
}

if (z & ViewState.ChecksEnabled) {
  do_something_else();
}
</code>```

The simplest way to ensure you can decompose the enum value into a distinct, unambiguous set of flags is to have the separate values as powers of two.

Title: Why use binary shifts in enums

Body:
I'm looking at this code:

/**
 * Bitmask of states
 */
export const enum ViewState {
    FirstCheck = 1 << 0,      // result is 1
    ChecksEnabled = 1 << 1,   // result is 2
    Errored = 1 << 2,         // result is 4
    Destroyed = 1 << 3        // result is 8
}

I don't understand why not simply specify the integer results there or integer numbers 0,1,2,3. Does anyone have any idea?

Body:
This enum models the idea of four flags, each of which can be either on/true/one or off/false/zero. You can set the enum to a value by logically OR-ing together the values you want. For example:

z = ViewState.FirstCheck | ViewState.ChecksEnabled

Later in the code you can check these values independently of each other by logicall AND-ing the value with the one you want to check:

if (z & ViewState.FirstCheck) {
  do_something();
}

if (z & ViewState.ChecksEnabled) {
  do_something_else();
}

The simplest way to ensure you can decompose the enum value into a distinct, unambiguous set of flags is to have the separate values as powers of two.


问:
how to count no of records in and display in view

This error will show when i want to display no. of records in a table.
  A PHP Error was encountered

Severity: Notice

Message: Undefined variable: h

Filename: views/index.php

A PHP Error was encountered

Severity: Warning

Message: Invalid argument supplied for foreach()

Filename: views/index.php

Controller

```<code>public function index() {
    if ($this->session->userdata('admin_logged_in')) {
        $data['h']= $this->admin_model->visitor_count();

        $this->load->view('header');
        $this->load->view('sidebar');
        $this->load->view('index',$data);
        $this->load->view('footer');
    } else {
        $this->load->view('login');
    }
}
</code>```

model

```<code>function visitor_count() {
    $query = $this->db->query("SELECT COUNT(*) FROM create_new_pass");
    return $query->num_rows();
}
</code>```

view

```<code><div class="inner">
<?php foreach ($h as $counts){?>
            <h3><?php echo $counts; ?></h3>
<?php } ?>
          <p>Total No. of Visitors till yet</p>
        </div>
</code>```

答:
Change your view as per

```<code><div class="inner">
    <h3><?php echo $h; ?></h3>
    <p>Total No. of Visitors till yet</p>
</div>
</code>```

you return number of records in model so you don't use foreach loop in view direct use data variable.

Body:
This error will show when i want to display no. of records in a table.
  A PHP Error was encountered

Severity: Notice

Message: Undefined variable: h

Filename: views/index.php

A PHP Error was encountered

Severity: Warning

Message: Invalid argument supplied for foreach()

Filename: views/index.php

Controller

public function index() {
    if ($this->session->userdata('admin_logged_in')) {
        $data['h']= $this->admin_model->visitor_count();

        $this->load->view('header');
        $this->load->view('sidebar');
        $this->load->view('index',$data);
        $this->load->view('footer');
    } else {
        $this->load->view('login');
    }
}

model

function visitor_count() {
    $query = $this->db->query("SELECT COUNT(*) FROM create_new_pass");
    return $query->num_rows();
}

view

<?php foreach ($h as $counts){?>

<?php echo $counts; ?>

<?php } ?>

Total No. of Visitors till yet

Body:
Change your view as per

<div class="inner">
    <h3><?php echo $h; ?></h3>
    <p>Total No. of Visitors till yet</p>
</div>

you return number of records in model so you don't use foreach loop in view direct use data variable.


问:
C - Display all lines from a c executable in a file for debugging purpose
I'm having issues with a c program that I want to debug.
I would like to know how to get a file that contains every lines of my executable, so I can later set breakpoints with gdb in it.
Thanks :)</p>

答:
For GCC specify -g when compiling.

More here: https://gcc.gnu.org/onlinedocs/gcc/Debugging-Options.html


问:
Why my music won't play on Android Studio?
I'm using Android Studio.I tried all the codes that I've seen on the internet but my app doesn't work. I have a raw folder which contains the music that I'll be use but still I don't know what is the error in my code.

Here's my code:

```<code> package com.example.aloja.babysteps;

import android.app.Activity;
import android.content.Context;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

/**
 * Created by Aloja on 3/27/2017.
 */

public class A extends Activity {
    Button btnBack3,btnPlay;

    ImageView ivApple;
    MediaPlayer apple;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.a);
        btnBack3 = (Button) findViewById(R.id.btnBack3);
        btnPlay =(Button) findViewById(R.id.btnPlay);
        ivApple = (ImageView) findViewById(R.id.ivApple);
        ivApple.setImageResource(R.drawable.apple);

        apple= MediaPlayer.create(this, R.raw.apple);

        btnPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                apple.start();

            }
        });
    }

        protected void onPause(){
            super.onPause();
            apple.stop();
            apple.release();

    }

}
</code>```

P.S Sorry for my english. Hope you understand what I'm trying to ask

答:
I test your code on MX5 and it works well.

Did you enable your phone's music volume ?

(In MX5, you can see tone, media, notification and system volume.)

Body:
I'm using Android Studio.I tried all the codes that I've seen on the internet but my app doesn't work. I have a raw folder which contains the music that I'll be use but still I don't know what is the error in my code.

Here's my code:

 package com.example.aloja.babysteps;

import android.app.Activity;
import android.content.Context;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

/**
 * Created by Aloja on 3/27/2017.
 */

public class A extends Activity {
    Button btnBack3,btnPlay;

    ImageView ivApple;
    MediaPlayer apple;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.a);
        btnBack3 = (Button) findViewById(R.id.btnBack3);
        btnPlay =(Button) findViewById(R.id.btnPlay);
        ivApple = (ImageView) findViewById(R.id.ivApple);
        ivApple.setImageResource(R.drawable.apple);

        apple= MediaPlayer.create(this, R.raw.apple);

        btnPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                apple.start();

            }
        });
    }

        protected void onPause(){
            super.onPause();
            apple.stop();
            apple.release();

    }

}

P.S Sorry for my english. Hope you understand what I'm trying to ask


问:
How to delete a file in parse.com
how can I delete a file in Parse? I try to delete them through the REST API but it doesn't work.

I always  get this error:

```<code>"Cannot DELETE /parse/files/appName/e462b99d0e7ed9b98d837493d95c102d_profilePicture.jpg\n"
</code>```

I'm using Parse on a Ubuntu 16.04 system, Parse version is 2.2.23.

答:
This solution is for parse server. parse.com shut down

first remove 'appName' from your link then use this code

```<code>curl -X DELETE
-H "X-Parse-Application-Id: $appid"
-H "X-Parse-Master-Key: $masterKey"
http://myAPP.herokuapp.com/parse/files/e462b99d0e7ed9b98d837493d95c102d_profilePicture.jpg
</code>```

This is source link
https://github.com/ParsePlatform/parse-server/issues/1411

Title: How to delete a file in parse.com

Body:
how can I delete a file in Parse? I try to delete them through the REST API but it doesn't work.

I always  get this error:

"Cannot DELETE /parse/files/appName/e462b99d0e7ed9b98d837493d95c102d_profilePicture.jpg\n"

I'm using Parse on a Ubuntu 16.04 system, Parse version is 2.2.23.

Body:
This solution is for parse server. parse.com shut down

first remove 'appName' from your link then use this code

curl -X DELETE
-H "X-Parse-Application-Id: $appid"
-H "X-Parse-Master-Key: $masterKey"
http://myAPP.herokuapp.com/parse/files/e462b99d0e7ed9b98d837493d95c102d_profilePicture.jpg

This is source link
https://github.com/ParsePlatform/parse-server/issues/1411


问:
how to distribute a java-application with libraries such as itext?
I have written an application in java. It uses iText, jXL and JAI.

How do I build a jar which contains all these libraries? Or do I have to force the user to install these too?

答: You could pack all jars into one while building your project with Ant. If you use NetBeans, This page describes how can modify NetBeans' build scripts to do it for you.</p>


问:
ZeroMQ: socket per data type or just one socket?
I've got a program which receives information from about 10 other (sensor reading) programs (all controlled by myself). I now want to make them communicate using ZeroMQ.

For most of the queues the important thing is that the central receiving program always has the latest sensor data, all older messages are not important anymore. If a couple messages get lost I don't care. So for all of them I started out with a separate PUB/SUB socket; one for each program. But I'm not sure if that is the right way to do it. As far as I understand I have two options:

Make a separate socket for every program and read them out in a loop. That way I know by the socket what the information is I'm receiving (I'm often just sending an int).

Make one socket to which all the programs connect, and with every message I send a string which tells the receiving end what the message is about.

All connections are on a PUB/SUB basis, so creating one socket would well work out. I'm just not sure if that is the most efficient way to do it.

All tips are welcome!

答:
- PUB/SUB is fine and allows an easy conversion from N-sensors:1-logger into N-sensors:2+-loggers
- one might also benefit from a conceptual separation of a socket from an access-port, where more than one sockets may get connected

How to get always JUST THE ACTUAL ( LAST ) SENSOR READOUT:

If not bound, due to system-integration constraints, to some early ZeroMQ API, there is a lovely feature exactly for this via a .setsockopt( ZMQ_CONFLATE, True ) method:

ZMQ_CONFLATE: Keep only last message

  If set, a socket shall keep only one message in its inbound/outbound queue, this message being the last message received/the last message to be sent.
 Ignores ZMQ_RCVHWM and ZMQ_SNDHWM options. Does not support multi-part messages, in particular, only one part of it is kept in the socket internal queue.

On design dilemma:

Unless your real-time control stability introduces some hard-real-time limit, the PUB-side freely decides, how often a new value is instructed to .send() to SUB(-s). Here no magic is needed, the less with ZMQ_CONFLATE option set on the internal outgoing queue managed.

The SUB(-s) side receiver(s) will also benefit from the ZMQ_CONFLATE option set on the internal incoming queue managed, but given a set of individual .bind()-s instantiate separate landing ports for delivery of different individual sensoric readouts, your "last" values will remain consistently the "last"-readouts. If all readouts would go into a common landing pad, your receiving process will get masked-out ( lost ) all readouts but the one that was just accidentally the "last" right before .recv() took place, which would not help much, would it?

If some I/O-performance related tweaking becomes necessary, the .Context( n_IO_threads ) + ZMQ_AFFINITY-mapping options may increase and prioritise the resources the ioDataPump may harness for increased IO-performance


问:
Finding the averege in a loop counting to 100
I need to find the averege after using a loop counting ever 3rd to a 100. The loop part is easy enough, but I need to sum every value then divide the sum on the total of values.

```<code>for ($x = 3; $x < 100; $x+=3) {
    echo $x.", ";
}
</code>```

This is the loop I need to use. How to I sum the values this produces and how do I find how many values this loop produces?

答:
I believe the intention here is to learn about loops, otherwise this stuff can be done without looping too.

For learning purpose, you can simply introduce two variables count and sum and compute them inside the loop. For count, you just increment it on each iteration. For sum, you add the current value of x into sum. After the loop you print both variables.

```<code>$count = 0;
$sum = 0;
for ($x = 3; $x < 100; $x+=3) {
    echo $x.", ";
    $count++;
    $sum+=$x;
}

echo $sum;
echo $count;
</code>```

Body:
I need to find the averege after using a loop counting ever 3rd to a 100. The loop part is easy enough, but I need to sum every value then divide the sum on the total of values.

for ($x = 3; $x < 100; $x+=3) {
    echo $x.", ";
}

This is the loop I need to use. How to I sum the values this produces and how do I find how many values this loop produces?

Body:
I believe the intention here is to learn about loops, otherwise this stuff can be done without looping too.

For learning purpose, you can simply introduce two variables count and sum and compute them inside the loop. For count, you just increment it on each iteration. For sum, you add the current value of x into sum. After the loop you print both variables.

$count = 0;
$sum = 0;
for ($x = 3; $x < 100; $x+=3) {
    echo $x.", ";
    $count++;
    $sum+=$x;
}

echo $sum;
echo $count;


问:
Export an html table with an image to a spreadsheet using Jquery
Need to export an html table with an image to a spreadsheet using Jquery. I used CSV for export, but image is not exported</p>

```<code>$("#btnExport").click(function (e) {
 $("#tbContainer").tableToCSV();
});
</code>```

答:
The CSV format can not contain images. However it could contain URLs pointing to the images. You can then load them with a macro:</p>

```<code>For Each cel In Selection
    cel.Offset(0, 1).Select
    ActiveSheet.Pictures.Insert(cel.Value).Select
Next cel
</code>```

Body:
Need to export an html table with an image to a spreadsheet using Jquery. I used CSV for export, but image is not exported

$("#btnExport").click(function (e) {
 $("#tbContainer").tableToCSV();
});

Body:
The CSV format can not contain images. However it could contain URLs pointing to the images. You can then load them with a macro:

For Each cel In Selection
    cel.Offset(0, 1).Select
    ActiveSheet.Pictures.Insert(cel.Value).Select
Next cel


问:
How to merge calls in Android
I am working on a call forwarding Android app. Call divert is working very well, but I need to implement call conferencing as well. If I am calling from my number to a second number, then the call should be divert to another number and all three participants should be in conference conference. I don't know how to do this.</p>

答:
You can't do this as of now. You can check this thread. However you can make conference call using VOIP.

These are some VOIP providers:

Twilio

Plivo

Asterisk

Title: How to merge calls in Android


问:
Copy content from a Word document to another with the style
I want to copy the content of a section in a Word document to a new document.

I do this to copy :

```<code>var docPath = @"C:\temp\myDoc.docx";
var doc = word.Documents.Open(FileName: docPath, ReadOnly: true);
var emptyDoc = word.Documents.Add();

doc.Sections.First.Range.Copy();
emptyDoc.Sections.First.Range.Paste();
</code>```

This works well to copy content, but the style is not the same. How can I copy the complete section and have it rendered exactly the same way in the new document ?

If there is a better solution involving the OpenXML SDK instead of VSTO, I can take it.

答:
You will find it much easier to automate Word if you do things manually first. That way you can get a better understanding of the various options available etc. You can also record a macro which will often, though not always, provide the answer.

In this instance you need to automate selecting 'Keep Source Formatting' from the context toolbar that appears after pasting. The code you need for that is:

```<code>emptyDoc.Sections.First.Range.PasteAndFormat wdFormatOriginalFormatting
</code>```

Body:
I want to copy the content of a section in a Word document to a new document.

I do this to copy :

var docPath = @"C:\temp\myDoc.docx";
var doc = word.Documents.Open(FileName: docPath, ReadOnly: true);
var emptyDoc = word.Documents.Add();

doc.Sections.First.Range.Copy();
emptyDoc.Sections.First.Range.Paste();

This works well to copy content, but the style is not the same. How can I copy the complete section and have it rendered exactly the same way in the new document ?

If there is a better solution involving the OpenXML SDK instead of VSTO, I can take it.

Body:
You will find it much easier to automate Word if you do things manually first. That way you can get a better understanding of the various options available etc. You can also record a macro which will often, though not always, provide the answer.

In this instance you need to automate selecting 'Keep Source Formatting' from the context toolbar that appears after pasting. The code you need for that is:

emptyDoc.Sections.First.Range.PasteAndFormat wdFormatOriginalFormatting


问:
How to send values through an directive tag in angular 2
I am trying to send data through the directive metatags from one component to another but it shows error undefined when i consoled it.Can anyone please suggest me help.Thanks.

My component,

```<code>import { ModalComponent } from './modal/modal.component';
@Component({
  selector: 'my-app',
  template: `<modal [hero]="value"></modal>'
})
export class CommonComponent  {
  value : anny ='1';
</code>```

}

```<code>@Component({
  selector: 'modal',
  templateUrl : './modal/model.component.html'
})
export class CommonComponent  {
  @Input() hero:any;
  consrtuctor(){
  console.log(this.hero) ///// shows o/p as undefined
</code>```

}

答:
The issue you're facing is that at the point where your constructor is called, the @Input and @Output bindings haven't been set up yet by Angular. That's why your hero property is showing as undefined. If you want to make use of @Input and/or @Output bindings during the initialization of your component, you have to wait until Angular initializes those bindings first before trying to make use of them.

Angular provides a life cycle hook to accomplish this very same thing. Basically, if you define a method called ngOnInit on your component, after Angular has finished initializing your component, it will call that method. And at that point, your bindings will have the values you expect.

So, your class should be more like:

```<code>export class CommonComponent  {
  @Input() hero:any;
  constructor(){ }

  ngOnInit() {
    console.log(this.hero) // will be defined at this point
  }
}
</code>```

In general, you really should not have any real initialization logic in your constructor (because again, at the point your constructor is called, none of your bindings are in place). For the vast majority of components, your constructor is used solely to request service dependencies by listing those services as parameters to the constructor - initialization of the component happens in ngOnInit.

See the lifecycle hooks guide to learn more.

Body:
I am trying to send data through the directive metatags from one component to another but it shows error undefined when i consoled it.Can anyone please suggest me help.Thanks.

My component,

import { ModalComponent } from './modal/modal.component';
@Component({
  selector: 'my-app',
  template: `<modal [hero]="value"></modal>'
})
export class CommonComponent  {
  value : anny ='1';

}

@Component({
  selector: 'modal',
  templateUrl : './modal/model.component.html'
})
export class CommonComponent  {
  @Input() hero:any;
  consrtuctor(){
  console.log(this.hero) ///// shows o/p as undefined

}

Body:
The issue you're facing is that at the point where your constructor is called, the @Input and @Output bindings haven't been set up yet by Angular. That's why your hero property is showing as undefined. If you want to make use of @Input and/or @Output bindings during the initialization of your component, you have to wait until Angular initializes those bindings first before trying to make use of them.

Angular provides a life cycle hook to accomplish this very same thing. Basically, if you define a method called ngOnInit on your component, after Angular has finished initializing your component, it will call that method. And at that point, your bindings will have the values you expect.

So, your class should be more like:

export class CommonComponent  {
  @Input() hero:any;
  constructor(){ }

  ngOnInit() {
    console.log(this.hero) // will be defined at this point
  }
}

In general, you really should not have any real initialization logic in your constructor (because again, at the point your constructor is called, none of your bindings are in place). For the vast majority of components, your constructor is used solely to request service dependencies by listing those services as parameters to the constructor - initialization of the component happens in ngOnInit.

See the lifecycle hooks guide to learn more.


问:
finding peak start and end points
I have a series of peaks Peaks image, I used matlab findpeaks to find the peak points .

I need to find peak widths and the peak start and end points ? I have started

with this code , but it is not giving me the right width calculation :

```<code>% If the peak is at index 150
% Scan to the right.
for k = 151:length(signal)
   if signal(k) < signal(k-1)
    % Signal is starting to fall.
    rightIndex = k-1;
    break;
  end
end
% Scan to the left.
for k = 149: -1 : 1
   if signal(k) < signal(k+1)
     % Signal is starting to fall.
     leftIndex = k+1;
     break;
  end
end
peakWidth = rightIndex - leftIndex;
</code>```

答:
here there are two kinds of widths, on computed by findpeaks and one computed naively by comparing derivative to zero:

```<code>% generate sinal
x = 0:0.1:10;
y = x.*sin(x/5).*sin(5*x.^2);
% get derivatives
dy = diff(y);
dx = diff(x);
dy_dx = [0 dy./dx];
% plot default annotated peaks
subplot(211);
findpeaks(y,x,'Annotate','extents');
% get peaks with width computed by 'findpeaks'
[pks,locs,peakWidth1,p] = findpeaks(y,x);
subplot(212);
plot(x,y);
hold on
plot(locs,pks,'*m')
% compute starting and ending points
startpoint = zeros(size(pks));
endpoint = zeros(size(pks));
for ii = 1:length(pks)
    plot(locs(ii) + peakWidth1(ii)*[-.5 .5],pks(ii) - p(ii)/2 + [0 0],'y')
    sp = find((x < locs(ii)) & (dy_dx <= 0),1,'last');
    if isempty(sp)
        sp = 1;
    end
    startpoint(ii) = sp;
    ep = find((x > locs(ii)) & (dy_dx >= 0),1,'first') - 1;
    if isempty(ep)
        ep = length(x);
    end
    endpoint(ii) = ep;
    plot(x(startpoint(ii)),y(startpoint(ii)),'og')
    plot(x(endpoint(ii)),y(endpoint(ii)),'sr')
end
% compute second type of width using ending and starting points
peakWidth2 = x(endpoint) - x(startpoint);
</code>```

Title: finding peak start and end points

Body:
I have a series of peaks Peaks image, I used matlab findpeaks to find the peak points .

I need to find peak widths and the peak start and end points ? I have started

with this code , but it is not giving me the right width calculation :

% If the peak is at index 150
% Scan to the right.
for k = 151:length(signal)
   if signal(k) < signal(k-1)
    % Signal is starting to fall.
    rightIndex = k-1;
    break;
  end
end
% Scan to the left.
for k = 149: -1 : 1
   if signal(k) < signal(k+1)
     % Signal is starting to fall.
     leftIndex = k+1;
     break;
  end
end
peakWidth = rightIndex - leftIndex;

Body:
here there are two kinds of widths, on computed by findpeaks and one computed naively by comparing derivative to zero:

% generate sinal
x = 0:0.1:10;
y = x.*sin(x/5).*sin(5*x.^2);
% get derivatives
dy = diff(y);
dx = diff(x);
dy_dx = [0 dy./dx];
% plot default annotated peaks
subplot(211);
findpeaks(y,x,'Annotate','extents');
% get peaks with width computed by 'findpeaks'
[pks,locs,peakWidth1,p] = findpeaks(y,x);
subplot(212);
plot(x,y);
hold on
plot(locs,pks,'*m')
% compute starting and ending points
startpoint = zeros(size(pks));
endpoint = zeros(size(pks));
for ii = 1:length(pks)
    plot(locs(ii) + peakWidth1(ii)*[-.5 .5],pks(ii) - p(ii)/2 + [0 0],'y')
    sp = find((x < locs(ii)) & (dy_dx <= 0),1,'last');
    if isempty(sp)
        sp = 1;
    end
    startpoint(ii) = sp;
    ep = find((x > locs(ii)) & (dy_dx >= 0),1,'first') - 1;
    if isempty(ep)
        ep = length(x);
    end
    endpoint(ii) = ep;
    plot(x(startpoint(ii)),y(startpoint(ii)),'og')
    plot(x(endpoint(ii)),y(endpoint(ii)),'sr')
end
% compute second type of width using ending and starting points
peakWidth2 = x(endpoint) - x(startpoint);


问:
Is there a means to disable Typesafe Activator UI
I have created a project and I want to prevent the user from starting the activator UI by accident and generating tons of files that it generates. Is there a property I can set or some other means? I read the documentation abotu the benefits of activator over SBT and I don't want to re-litigate that, I just want it to disable certain features. </p>

答:
As far as I know, no. The UI is started when the user types activator ui, and I think it's a fair assumption that users don't type ui by accident.

Also, I don't think activator ui generates files, certainly not tons. What files are you referring to?

Activator is open source. You could fork https://github.com/typesafehub/activator and provide a modified version to your users. For example you could (I haven't tried, by I assume) delete line https://github.com/typesafehub/activator/blob/master/launcher/src/main/scala/activator/ActivatorLauncher.scala#L81 to prevent Activator from displaying its docs in the browser when started in a non-project directory.

Lastly, you may want to reconsider just using plain sbt.  sbt new is the new recommended way to create projects from templates, replacing Activator.


问:
How NuGet determines if reinstallation is required
There is a 'requireReinstallation' tag in packages.config, which purpose is pretty clear. However, I was wondering how exactly NuGet decides whether the package requires reinstallation or not. I've had a project with Serilog and RayGun packages and after upgrading the .NET version, only Serilog got the tag set. What's the algorithm behind this? </p>

答:
The algorithm is the same as the algorithm that is used to determine which assembly is the best match for the project if the NuGet package was to be installed into the project if it had the new target framework. If the assembly is different then NuGet considers that a reinstallation is required.

So if you had Foo and Bar NuGet packages installed with:

Foo

lib/net45

Bar

lib/net45

lib/net46

And your project was targeting .NET 4.5, and you changed it to .NET 4.6, then NuGet would mark Bar as needing reinstallation. Bar has an assembly that targets .NET 4.6 so it is considered a better match. Foo would not need to be reinstalled.


问:
Implementing Tree structures in IPad
How to implement a tree structure in iPad, tree structure which contain parent & child nodes.</p>

答: The apple-y way of doing this is to drill into a new list leaving a button to go back to its parent. This is done through UINavigationController. If your dead-set on indenting then as KingofBliss says change the cell indentationLevel

Title: Implementing Tree structures in IPad


答:
add your elements into an array and then use array_sum to sum the array elements , then divide the sum by the count of your array</p>

```<code>$arr = [];
for ($x = 3; $x < 100; $x+=3) {
    // echo $x.", \n";
    $arr[] = $x;
}

print_r(array_sum($arr) / count($arr));
// Output : 51
</code>```

Title: Finding the averege in a loop counting to 100

Body:
add your elements into an array and then use array_sum to sum the array elements , then divide the sum by the count of your array

$arr = [];
for ($x = 3; $x < 100; $x+=3) {
    // echo $x.", \n";
    $arr[] = $x;
}

print_r(array_sum($arr) / count($arr));
// Output : 51


问:
How to make the imagebutton permanent even when moving out of the activity?
I am trying to make an app where there are many cities and i want to add favorites cities. I am doing this by making a heart shaped button on the below of city's image. When the Favorites button is clicked, the button goes pink. Just like Instagram. But whenever I am moving out of the selected city, the button goes back to its normal state. And i want it to be selected as favorite.What I have done is that whenever the button is clicked it is added to favorites and when clicked again it is removed from favorites. Please. Can anybody help? here is my code CitySelectedActivity.java

```<code> private String PICK_CITYSELECTED=" ";
private ImageView imageView;
private StorageReference mStorage;
private TextView mTextView;
private ViewPager viewPager;
//int[] mResources={R.drawable.manali,R.drawable.manali2,R.drawable.manali3,R.drawable.manali4};
CustomSwipeAdapter adapter;
private static int currentpage=0;
private static int numpages=0;
private int[] img;
private FirebaseDatabase firebaseDatabase;
private DatabaseReference databaseReference;
private TextView textView;
private ImageButton favouriteBtn;
private boolean showingFirst=true;
private SharedPreferences pref;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_city_selected);
    mStorage= FirebaseStorage.getInstance().getReference();
    Intent intent=getIntent();
    PICK_CITYSELECTED=intent.getExtras().getString("PICK_CITY");
    Toast.makeText(this, PICK_CITYSELECTED, Toast.LENGTH_SHORT).show();
    final Boolean isFirstRun=getSharedPreferences("PREFERENCE",MODE_PRIVATE).getBoolean("isFirstrun",true);
    favouriteBtn=(ImageButton) findViewById(R.id.buttonfav);
    favouriteBtn.setImageResource(R.drawable.like24);
    favouriteBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
           if(showingFirst==true)
           {
               getSharedPreferences("PREFERENCE",MODE_PRIVATE).edit().putBoolean("isFirstrun",false).apply();
               favouriteBtn.setImageResource(R.drawable.likepink24);
               //showingFirst=false;
           }
           else
           {
               favouriteBtn.setImageResource(R.drawable.like24);
               showingFirst=true;
           }
        }
    });
</code>```

Here is my code for Xml file activity_city_selected.xml

```<code><ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.srushtee.dummy.CitySelectedActivity"
android:fillViewport="true"
>
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/relativelayout1">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/relativelayout"
    android:layout_marginBottom="20dp">
    <android.support.v4.view.ViewPager
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:id="@+id/view_pager"
        tools:layout_editor_absoluteY="8dp"
        tools:layout_editor_absoluteX="8dp"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />
    <me.relex.circleindicator.CircleIndicator
        android:layout_width="match_parent"
        android:layout_height="10dp"
        android:layout_alignBottom="@+id/view_pager"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_marginBottom="10dp"
        android:id="@+id/indicator">

    </me.relex.circleindicator.CircleIndicator>

</RelativeLayout>
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|center"
    android:layout_alignParentBottom="true"
    android:layout_alignBottom="@+id/relativelayout1"
    android:gravity="bottom"
    android:id="@+id/linearLayout2">
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/continue_booking"
        android:text="Continue Booking"
        android:layout_weight="1"/>

</LinearLayout>

    <ImageButton
        android:id="@+id/buttonfav"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/linearLayout2"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="205dp"
        android:background="@null" />

</RelativeLayout>
</code>```

答:
1. make a new class file. I named it as ConstantNames.java

this is the code of ConstantNames.java file

(nameArrayList is a static so it will contain values after closing the app too)

```<code>public class ConstantNames {
    public final static HashSet<String> nameArrayList=new HashSet<>();
}
</code>```

2. In Your MainActivity.java  =>  in onClickListener  =>  add the value into nameArrayList

This is the code to add values in nameArrayList

NOTE: HashSet contanins only unique values if you want dublicate values then you can use arraylist

```<code>oneImageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               ConstantNames.nameArrayList.add("your_value_name");
                Toast.makeText(Main2Activity.this, "saved", Toast.LENGTH_SHORT).show();
            }
        });
</code>```

Body:
I am trying to make an app where there are many cities and i want to add favorites cities. I am doing this by making a heart shaped button on the below of city's image. When the Favorites button is clicked, the button goes pink. Just like Instagram. But whenever I am moving out of the selected city, the button goes back to its normal state. And i want it to be selected as favorite.What I have done is that whenever the button is clicked it is added to favorites and when clicked again it is removed from favorites. Please. Can anybody help? here is my code CitySelectedActivity.java

 private String PICK_CITYSELECTED=" ";
private ImageView imageView;
private StorageReference mStorage;
private TextView mTextView;
private ViewPager viewPager;
//int[] mResources={R.drawable.manali,R.drawable.manali2,R.drawable.manali3,R.drawable.manali4};
CustomSwipeAdapter adapter;
private static int currentpage=0;
private static int numpages=0;
private int[] img;
private FirebaseDatabase firebaseDatabase;
private DatabaseReference databaseReference;
private TextView textView;
private ImageButton favouriteBtn;
private boolean showingFirst=true;
private SharedPreferences pref;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_city_selected);
    mStorage= FirebaseStorage.getInstance().getReference();
    Intent intent=getIntent();
    PICK_CITYSELECTED=intent.getExtras().getString("PICK_CITY");
    Toast.makeText(this, PICK_CITYSELECTED, Toast.LENGTH_SHORT).show();
    final Boolean isFirstRun=getSharedPreferences("PREFERENCE",MODE_PRIVATE).getBoolean("isFirstrun",true);
    favouriteBtn=(ImageButton) findViewById(R.id.buttonfav);
    favouriteBtn.setImageResource(R.drawable.like24);
    favouriteBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
           if(showingFirst==true)
           {
               getSharedPreferences("PREFERENCE",MODE_PRIVATE).edit().putBoolean("isFirstrun",false).apply();
               favouriteBtn.setImageResource(R.drawable.likepink24);
               //showingFirst=false;
           }
           else
           {
               favouriteBtn.setImageResource(R.drawable.like24);
               showingFirst=true;
           }
        }
    });

Here is my code for Xml file activity_city_selected.xml

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.srushtee.dummy.CitySelectedActivity"
android:fillViewport="true"
>
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/relativelayout1">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/relativelayout"
    android:layout_marginBottom="20dp">
    <android.support.v4.view.ViewPager
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:id="@+id/view_pager"
        tools:layout_editor_absoluteY="8dp"
        tools:layout_editor_absoluteX="8dp"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />
    <me.relex.circleindicator.CircleIndicator
        android:layout_width="match_parent"
        android:layout_height="10dp"
        android:layout_alignBottom="@+id/view_pager"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_marginBottom="10dp"
        android:id="@+id/indicator">

    </me.relex.circleindicator.CircleIndicator>

</RelativeLayout>
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|center"
    android:layout_alignParentBottom="true"
    android:layout_alignBottom="@+id/relativelayout1"
    android:gravity="bottom"
    android:id="@+id/linearLayout2">
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/continue_booking"
        android:text="Continue Booking"
        android:layout_weight="1"/>

</LinearLayout>

    <ImageButton
        android:id="@+id/buttonfav"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/linearLayout2"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="205dp"
        android:background="@null" />

</RelativeLayout>

Body:
1. make a new class file. I named it as ConstantNames.java

this is the code of ConstantNames.java file

(nameArrayList is a static so it will contain values after closing the app too)

public class ConstantNames {
    public final static HashSet<String> nameArrayList=new HashSet<>();
}

2. In Your MainActivity.java  =>  in onClickListener  =>  add the value into nameArrayList

This is the code to add values in nameArrayList

NOTE: HashSet contanins only unique values if you want dublicate values then you can use arraylist

oneImageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               ConstantNames.nameArrayList.add("your_value_name");
                Toast.makeText(Main2Activity.this, "saved", Toast.LENGTH_SHORT).show();
            }
        });


问:
C linking error (with tcc)
I'm trying to run the example from tiny cc (tcc-0.9.26-win64-bin.zip) called libtcc_test.c.

I've copied libtcc.h from libtcc into include and libtcc.def into lib.

Then I ran tcc ./examples/libtcc_test.c and got a linking error :/

```<code>tcc: error: undefined symbol 'tcc_new'
tcc: error: undefined symbol 'tcc_set_lib_path'
tcc: error: undefined symbol 'tcc_set_output_type'
tcc: error: undefined symbol 'tcc_compile_string'
tcc: error: undefined symbol 'tcc_add_symbol'
tcc: error: undefined symbol 'tcc_relocate'
tcc: error: undefined symbol 'tcc_get_symbol'
tcc: error: undefined symbol 'tcc_delete'
</code>```

What am I missing ?

More info:

```<code>P:\cpp\tcc>tcc ./examples/libtcc_test.c -vv
tcc version 0.9.26 (i386 Win32)
-> ./examples/libtcc_test.c
-> p:/cpp/tcc/include/stdlib.h
->  p:/cpp/tcc/include/_mingw.h
->   p:/cpp/tcc/include/stddef.h
->   p:/cpp/tcc/include/stdarg.h
->  p:/cpp/tcc/include/limits.h
->  p:/cpp/tcc/include/sec_api/stdlib_s.h
->   p:/cpp/tcc/include/stdlib.h
->  p:/cpp/tcc/include/malloc.h
-> p:/cpp/tcc/include/stdio.h
->  p:/cpp/tcc/include/vadefs.h
->  p:/cpp/tcc/include/sec_api/stdio_s.h
->   p:/cpp/tcc/include/stdio.h
-> p:/cpp/tcc/include/string.h
->  p:/cpp/tcc/include/sec_api/string_s.h
->   p:/cpp/tcc/include/string.h
-> p:/cpp/tcc/include/libtcc.h
-> p:/cpp/tcc/lib/libtcc1.a
-> p:/cpp/tcc/lib/msvcrt.def
-> p:/cpp/tcc/lib/kernel32.def
tcc: error: undefined symbol 'tcc_new'
tcc: error: undefined symbol 'tcc_set_lib_path'
tcc: error: undefined symbol 'tcc_set_output_type'
tcc: error: undefined symbol 'tcc_compile_string'
tcc: error: undefined symbol 'tcc_add_symbol'
tcc: error: undefined symbol 'tcc_relocate'
tcc: error: undefined symbol 'tcc_get_symbol'
tcc: error: undefined symbol 'tcc_delete'
</code>```

答:
To link in a library, you need to add a -l${library_basename} flag after all c files or o files.
If the library is named libtcc.a or libtcc.so (on Windows it's probably tcc.dll or libtcc.dll), you need to add -ltcc.

```<code>tcc  ./examples/libtcc_test.c  -ltcc
</code>```

You might also need to add an -L flag to add a search path in case the library you want to link in is not your system's standard library directories:

```<code>tcc -L . ./examples/libtcc_test.c -ltcc
#also look for libtcc.so or libtcc.a in the current directory (.)
</code>```

The libtcc_test.c from test/libtcc_test.c in the tinycc repo also needed the dl library (standard library for dynamic loading) to build:

```<code>tcc -L .  tests/libtcc_test.c  -ltcc -ldl #worked
</code>```

(it complained about undefined dlopen, dlclose, and dlsym which are known to come from libdl).

Title: C linking error (with tcc)

Body:
I'm trying to run the example from tiny cc (tcc-0.9.26-win64-bin.zip) called libtcc_test.c.

I've copied libtcc.h from libtcc into include and libtcc.def into lib.

Then I ran tcc ./examples/libtcc_test.c and got a linking error :/

tcc: error: undefined symbol 'tcc_new'
tcc: error: undefined symbol 'tcc_set_lib_path'
tcc: error: undefined symbol 'tcc_set_output_type'
tcc: error: undefined symbol 'tcc_compile_string'
tcc: error: undefined symbol 'tcc_add_symbol'
tcc: error: undefined symbol 'tcc_relocate'
tcc: error: undefined symbol 'tcc_get_symbol'
tcc: error: undefined symbol 'tcc_delete'

What am I missing ?

More info:

P:\cpp\tcc>tcc ./examples/libtcc_test.c -vv
tcc version 0.9.26 (i386 Win32)
-> ./examples/libtcc_test.c
-> p:/cpp/tcc/include/stdlib.h
->  p:/cpp/tcc/include/_mingw.h
->   p:/cpp/tcc/include/stddef.h
->   p:/cpp/tcc/include/stdarg.h
->  p:/cpp/tcc/include/limits.h
->  p:/cpp/tcc/include/sec_api/stdlib_s.h
->   p:/cpp/tcc/include/stdlib.h
->  p:/cpp/tcc/include/malloc.h
-> p:/cpp/tcc/include/stdio.h
->  p:/cpp/tcc/include/vadefs.h
->  p:/cpp/tcc/include/sec_api/stdio_s.h
->   p:/cpp/tcc/include/stdio.h
-> p:/cpp/tcc/include/string.h
->  p:/cpp/tcc/include/sec_api/string_s.h
->   p:/cpp/tcc/include/string.h
-> p:/cpp/tcc/include/libtcc.h
-> p:/cpp/tcc/lib/libtcc1.a
-> p:/cpp/tcc/lib/msvcrt.def
-> p:/cpp/tcc/lib/kernel32.def
tcc: error: undefined symbol 'tcc_new'
tcc: error: undefined symbol 'tcc_set_lib_path'
tcc: error: undefined symbol 'tcc_set_output_type'
tcc: error: undefined symbol 'tcc_compile_string'
tcc: error: undefined symbol 'tcc_add_symbol'
tcc: error: undefined symbol 'tcc_relocate'
tcc: error: undefined symbol 'tcc_get_symbol'
tcc: error: undefined symbol 'tcc_delete'

Body:
To link in a library, you need to add a -l${library_basename} flag after all c files or o files.
If the library is named libtcc.a or libtcc.so (on Windows it's probably tcc.dll or libtcc.dll), you need to add -ltcc.

tcc  ./examples/libtcc_test.c  -ltcc

You might also need to add an -L flag to add a search path in case the library you want to link in is not your system's standard library directories:

tcc -L . ./examples/libtcc_test.c -ltcc
#also look for libtcc.so or libtcc.a in the current directory (.)

The libtcc_test.c from test/libtcc_test.c in the tinycc repo also needed the dl library (standard library for dynamic loading) to build:

tcc -L .  tests/libtcc_test.c  -ltcc -ldl #worked

(it complained about undefined dlopen, dlclose, and dlsym which are known to come from libdl).


问:
How to parse file name in Java?
I have a java file path

/opt/test/myfolder/myinsidefolder/myfile.jar

I want  to replace the  file path  to
here root path will remain same but want to change file name from myfile.jar to Test.xml

/opt/test/myfolder/myinsidefolder/Test.xml

How can i do this in java any help?

答:
To rename the file you can use Files.move from java.nio.file.Files</p>

```<code>File oldFile=new File("/opt/test/myfolder/myinsidefolder/myfile.jar");
File newFile=new File(oldFile.getParent+"/"+"Test.xml");
try
{
  Files.move(oldFile.toPath(),newFile.toPath());
}
catch (IOException ex)
{
  System.err.println("File was not renamed!");
}
</code>```

Title: How to parse file name in Java?

Body:
To rename the file you can use Files.move from java.nio.file.Files

File oldFile=new File("/opt/test/myfolder/myinsidefolder/myfile.jar");
File newFile=new File(oldFile.getParent+"/"+"Test.xml");
try
{
  Files.move(oldFile.toPath(),newFile.toPath());
}
catch (IOException ex)
{
  System.err.println("File was not renamed!");
}


问:
Password Protected HTML Data in QlikView
I am looking to grab data from an HTML table using the URL to define the data range.

The problem is that the site is password protected.  How do I send a userid/password to then grab the data?

答:
You should into some kind of proxy. This is because Qlikview can't handle cookies (except for in extensions on Qlikview 10 but that's not the point) while loading.

I created a php script on my own webserver which basically is a proxy written in php using cURL.

I then do something like this in Qlikview (half pseudo code):
let usr = myusername;
let pwd = mypassword;
let dataURL = urlwheretofetchdatafrom;
let loginURL = urltotheloginwindow;

table:
LOAD

FROM
http://mywebsite.com/myproxy.php?user=$(user)&password=$(pwd)... and so on

The script then uses my parameters to log me in and then sends a request to the dataURL and fetches the data. The qlikview loading script will then read the data from my website instead.

Down sides?
This is not applicable for large quantities of data. It is also not possible to send password and username encrypted.

I might release some scripts for this in the future but as of now it's only in the testing phase.

/Jonas


问:
How to fetch rows between two values in a column MySQL?
I have saved dates in my MySQL table as VARCHAR format.

I want to fetch rows between two dates.

```<code>SELECT * FROM orders WHERE date BETWEEN '01-02-2017' AND '28-02-2017'
</code>```

This one didn't work. Is there any way to do that?

答:
Try This..

and store date data type as a date

select Date from emp_tbl where eid = 1 and Date >= '2016/03/31' and Date <= '2017/03/31'

Body:
I have saved dates in my MySQL table as VARCHAR format.

I want to fetch rows between two dates.

SELECT * FROM orders WHERE date BETWEEN '01-02-2017' AND '28-02-2017'

This one didn't work. Is there any way to do that?


问:
Checkbox is not updating model in ngstrap modal dialog
In directive, we have set $scope.checkValue = true, and the same scope is passed to ngstrap modal dialog.

below is the code from directive link function which is called on button click and popup the dialog:

```<code>return {
        templateUrl: "../Views/userSubscriptionView.html",
        restrict: 'E',
        scope: {},
        link: function ($scope, element, attributes) {
$scope.checkValue = false; //this is bind to checkbox model but not updating on check/uncheck.
    function DoOpenDialog()
    {
       //other code
        var myOtherModal = $modal({ scope: $scope, templateUrl: "../Views/SubscribePopup.html", show: false , persist:false});
                                myOtherModal.$promise.then(myOtherModal.show);
    }
</code>```

Below is the code from dialog:

```<code><input type="checkbox" ng-model="checkValue"/>
{{checkValue}}
</code>```

The problem is: when I check the checkbox to true or false, model 'checkValue' is not updating. I need to change the state of other control based on the checkbox check state.

Thanks

答:
I use to solve this by explicitly setting the ng-true-value and ng-false-value properties :

```<code><input type="checkbox"
  ng-true-value="'true'"
  ng-false-value="'false'"
  ng-model="checkValue"
/>
</code>```

Notice the single quotes around 'true'. Ultimately everything is passed as strings, not as booleans or integers. I use the same approach when I have to deal with a boolean (tinyint) 0 / 1 value from mysql: ng-true-value="'1'" and so on.

Body:
In directive, we have set $scope.checkValue = true, and the same scope is passed to ngstrap modal dialog.

below is the code from directive link function which is called on button click and popup the dialog:

return {
        templateUrl: "../Views/userSubscriptionView.html",
        restrict: 'E',
        scope: {},
        link: function ($scope, element, attributes) {
$scope.checkValue = false; //this is bind to checkbox model but not updating on check/uncheck.
    function DoOpenDialog()
    {
       //other code
        var myOtherModal = $modal({ scope: $scope, templateUrl: "../Views/SubscribePopup.html", show: false , persist:false});
                                myOtherModal.$promise.then(myOtherModal.show);
    }

Below is the code from dialog:

<input type="checkbox" ng-model="checkValue"/>
{{checkValue}}

The problem is: when I check the checkbox to true or false, model 'checkValue' is not updating. I need to change the state of other control based on the checkbox check state.

Thanks

Body:
I use to solve this by explicitly setting the ng-true-value and ng-false-value properties :

<input type="checkbox"
  ng-true-value="'true'"
  ng-false-value="'false'"
  ng-model="checkValue"
/>

Notice the single quotes around 'true'. Ultimately everything is passed as strings, not as booleans or integers. I use the same approach when I have to deal with a boolean (tinyint) 0 / 1 value from mysql: ng-true-value="'1'" and so on.