问:
WebBrowsing in C# - Libraries, Tools etc. - Anything like Mechanize in Perl?
Looking for something similar to Mechanize for .NET...

If you don't know what Mechanize is.. http://search.cpan.org/dist/WWW-Mechanize/

I will maintain a list of suggestions here.  Anything for browsing/posting/screen scraping (Other than WebRequest and WebBrowser Control).

Parsing

HTMLAgilityPack - http://www.codeplex.com/htmlagilitypack

Web App Testing

WatiN - Web Application Testing Framework (.NET) - http://watin.sourceforge.net/

Selenium - http://seleniumhq.org/

Art of Test Design Canvas - Costs Money

Tools

Firebug for Firefox

Internet Explorer Developer Toolbar for IE

Chrome has one too

Note

WatiN is close to what I am looking for, except it opens up a browser, which is annoying and awesome at the same time.  Depends on what you are doing.

答:
I have reverse engineered Python-Mechanize, and recreated it in C#, called Mechanize.NET.

https://github.com/WilliamABradley/Mechanize.NET

This should hopefully cover all use cases of Mechanize, if not, or you discover a bug, create an issue.

It uses .NET Standard, so it should be usable across .NET, such as with F#, VB, etc.

It utilises HtmlAgilityPack internally, and you can even collect the HtmlDocument for each loaded page.


来源: stackexchange

问:
Ionic2 web app routing configuration
I  am working on ionic2 project, which is web project (i.e. runs as a website on browsers not a mobile app). Here I am facing difficulty to give specific URL for pages. How do I implement routing in my project ?

I also worked with angular2. Where we can give URL to components. But here that thing is not working.

答:
Take a look at this website: https://www.joshmorony.com/a-simple-guide-to-navigation-in-ionic-2/
and read up on the nav controller here: https://ionicframework.com/docs/api/navigation/NavController/

Some Context: While Ionic2 does use the native browser for each platform, it uses a special controller to change routes

NavController is the base class for navigation controller components like Nav and Tab. You use navigation controllers to navigate to pages in your app. At a basic level, a navigation controller is an array of pages representing a particular history (of a Tab for example). This array can be manipulated to navigate throughout an app by pushing and popping pages or inserting and removing them at arbitrary locations in history.

Before diving deeper into Ionic I suggest obtaining an understanding of this controller.

This sample ionic project will also help with the understanding of navController:
https://github.com/ionic-team/ionic2-starter-sidemenu

ContentLicense: CC BY-SA 3.0

Title: Ionic2 web app routing configuration


问:
How to find out if an array is empty?
I have a boolean flag and I have to func (fun animation and fun reAninimation - it is transition between two drawables).
This is the transition between the two drawings

Idea of this class is I have two side of coins. I added it in an array. If array is empty, I only call animation, if it not empty I firstly call reAnimation and then animation.

My array:

```<code> var arrayShape: Array<Drawable>? = null
</code>```

it is a part of the OnCreate method.

```<code>override OnCreate() ...
if(isArrayEmpty(arrayShape!!)) shapeReAnimation()
      randomShape()
</code>```

it is flag method

```<code>fun isArrayEmpty(array : Array<Drawable>):Boolean {
    return array.size > 1 && array[0] !=null
  }
</code>```

and some future fun reAnimation() which now should show some Toast.

```<code>fun shapeReAnimation() {
   // if (arrayShape!![0] == resources.getDrawable(R.drawable.back_circle))
      ToastUtils.showErorMessage(context, "first")
  }
</code>```

when I run my project and click for fShape, It show me NPE (    kotlin.KotlinNullPointerException)
and project have stopded

答:
You can use like that... because null is not possible and not advisable for the list or any collection(without array), So can achieve your solution with a help of ArrayList</p>

```<code> val arrayShape = ArrayList<Drawable>()

    if (arrayShape.isEmpty())
        Toast.makeText(this, "Array is Empty", Toast.LENGTH_LONG).show()
    else
        Toast.makeText(this, "Array is not Empty", Toast.LENGTH_LONG).show()
</code>```

Title: How to find out if an array is empty?

Body:
I have a boolean flag and I have to func (fun animation and fun reAninimation - it is transition between two drawables).
This is the transition between the two drawings

Idea of this class is I have two side of coins. I added it in an array. If array is empty, I only call animation, if it not empty I firstly call reAnimation and then animation.

My array:

 var arrayShape: Array<Drawable>? = null

it is a part of the OnCreate method.

override OnCreate() ...
if(isArrayEmpty(arrayShape!!)) shapeReAnimation()
      randomShape()

it is flag method

fun isArrayEmpty(array : Array<Drawable>):Boolean {
    return array.size > 1 && array[0] !=null
  }

and some future fun reAnimation() which now should show some Toast.

fun shapeReAnimation() {
   // if (arrayShape!![0] == resources.getDrawable(R.drawable.back_circle))
      ToastUtils.showErorMessage(context, "first")
  }

when I run my project and click for fShape, It show me NPE (    kotlin.KotlinNullPointerException)
and project have stopded

Body:
You can use like that... because null is not possible and not advisable for the list or any collection(without array), So can achieve your solution with a help of ArrayList

 val arrayShape = ArrayList<Drawable>()

    if (arrayShape.isEmpty())
        Toast.makeText(this, "Array is Empty", Toast.LENGTH_LONG).show()
    else
        Toast.makeText(this, "Array is not Empty", Toast.LENGTH_LONG).show()


问:
Retrieve multiple values via SELECT Option in Django Templates
I'm using Python(3.6) & Django(1.10) and need multiple values from a drop-down option selection.

Here's what I have tried:
From template:

```<code><select id="slc" name="cluster">
<option value="{{cluster.name}}#{{cluster.zone}}"> {{ cluster.name }}</option>
</select>
</code>```

From views.py:

```<code>    def post(self, request, *args, **kwargs):
      if request.method == 'POST':
         post_data = request.POST.copy()
         form = forms.ClusterForm(post_data)
         if form.is_valid():
            project = form.cleaned_data['project']
            blocks = request.POST.get('cluster').split('#')
</code>```

How can i get the values for name & zone.I already take a deep look at the existing questions but couldn't solve my issue.So, don't mark this question as a duplicate, please!

Help me, Please!
Thanks in advance!

答:
At first change the template code like this:

```<code><select id="slc" name="cluster">
<option value="{{cluster.name}}"> {{ cluster.name }}</option>
</select>
</code>```

Then in the view:

```<code>post_data = request.POST.copy()
cluster_object = Clustermodel.objects.get(name=post_data['cluster'])
post_data['name'] = cluster_object.name
post_data['zone'] = cluster_object.zone
form = forms.ClusterForm(post_data)
</code>```

What we do here is that, we first send the name(preferably id) of cluster from post, then in the view we fetch the cluster object, retrieve name and zone, and include it in post_data and finally pass it to form.

Body:
I'm using Python(3.6) & Django(1.10) and need multiple values from a drop-down option selection.

Here's what I have tried:
From template:

<select id="slc" name="cluster">
<option value="{{cluster.name}}#{{cluster.zone}}"> {{ cluster.name }}</option>
</select>

From views.py:

    def post(self, request, *args, **kwargs):
      if request.method == 'POST':
         post_data = request.POST.copy()
         form = forms.ClusterForm(post_data)
         if form.is_valid():
            project = form.cleaned_data['project']
            blocks = request.POST.get('cluster').split('#')

How can i get the values for name & zone.I already take a deep look at the existing questions but couldn't solve my issue.So, don't mark this question as a duplicate, please!

Help me, Please!
Thanks in advance!

Body:
At first change the template code like this:

<select id="slc" name="cluster">
<option value="{{cluster.name}}"> {{ cluster.name }}</option>
</select>

Then in the view:

post_data = request.POST.copy()
cluster_object = Clustermodel.objects.get(name=post_data['cluster'])
post_data['name'] = cluster_object.name
post_data['zone'] = cluster_object.zone
form = forms.ClusterForm(post_data)

What we do here is that, we first send the name(preferably id) of cluster from post, then in the view we fetch the cluster object, retrieve name and zone, and include it in post_data and finally pass it to form.


问:
Join two Tables, ignore records from first table if exists in second
How to join to tables, if I prefer to get records only from the second table? If no second exists, take record the of the first table.

```<code>Table A         Table B         Result
pid,name,type   pid,name,type   pid,name,type
1,Anna,null     1,Anna,100      "1,Anna,100"
2,Bea,null      -               "2,Bea,Null"
3,Caro,null     3,Caro,100      "3,Caro,100"
                3,Caro,200      "3,Caro,200"
</code>```

Edit: I tried to improve my example table.

答:
You can use a Left Join, I assume the column names of TableB are Name and ID respectively.</p>

```<code>SELECT tableA.Name, tableB.Id
  FROM tableA LEFT JOIN tableB
    ON tableA.Name = tableB.Name
</code>```

ContentLicense: CC BY-SA 2.5

Body:
How to join to tables, if I prefer to get records only from the second table? If no second exists, take record the of the first table.

Table A         Table B         Result
pid,name,type   pid,name,type   pid,name,type
1,Anna,null     1,Anna,100      "1,Anna,100"
2,Bea,null      -               "2,Bea,Null"
3,Caro,null     3,Caro,100      "3,Caro,100"
                3,Caro,200      "3,Caro,200"

Edit: I tried to improve my example table.

Body:
You can use a Left Join, I assume the column names of TableB are Name and ID respectively.

SELECT tableA.Name, tableB.Id
  FROM tableA LEFT JOIN tableB
    ON tableA.Name = tableB.Name


问:
Execution failed for task ':app:transformClassesWithMultidexlistForDebug' in Android Studio 2.3
I can build my project but can not run the app. When executing app it gives me error like

Execution failed for task ':app:transformClassesWithMultidexlistForDebug'.

com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: Error while executing java process with main class com.android.multidex.ClassReferenceListBuilder with arguments {/home/Git_Projects/Test1/app/build/intermediates/multi-dex/debug/componentClasses.jar /home/Git_Projects/Test1/app/build/intermediates/transforms/jarMerging/debug/jars/1/1f/combined.jar}

I tried to clean and rebuild project and Invalidate Catche and Restart. But, nothing helped me.

build.gradle (app)

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

android {
    dexOptions {
        javaMaxHeapSize "4g"
    }
    compileSdkVersion 26
    buildToolsVersion "26.0.1"
    useLibrary 'org.apache.http.legacy'
    defaultConfig {
        applicationId "com.app.test1"
        minSdkVersion 16
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        multiDexEnabled = true
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

repositories {
    mavenCentral()
    maven { url 'https://github.com/Kaustubh-Deshmukh/progressbar_repo/raw/master' }

    maven { url 'https://dl.bintray.com/yazeed44/maven' }
    }

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:multidex:1.0.1'
    compile 'com.google.android.gms:play-services-gcm:10.0.1'
    compile 'com.google.android.gms:play-services-places:10.0.1'
    compile 'com.google.android.gms:play-services-maps:10.0.1'
    compile 'com.google.android.gms:play-services-vision:10.0.1'

    compile 'com.github.clans:fab:1.6.4'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.jakewharton:butterknife:8.4.0'
    compile 'com.googlecode.libphonenumber:libphonenumber:7.1.1'
    compile 'com.android.support:appcompat-v7:26.0.0'
    compile 'com.android.support:design:26.0.0'
    compile 'com.android.support:recyclerview-v7:26.0.0'
    compile 'com.android.support:cardview-v7:26.0.0'
    compile 'com.android.support:support-v4:26.0.0'
    compile 'com.android.support:support-annotations:26.0.0'
    compile 'com.android.support:percent:26.0.0'
    compile 'com.android.support:support-v13:26.0.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.1'
    compile 'com.facebook.fresco:fresco:1.5.0'
    compile 'org.greenrobot:eventbus:3.0.0'
    compile 'com.kontaktio:sdk:3.3.2'

    annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0'

    testCompile 'junit:junit:4.12'
}
</code>```

If I randomly remove some dependencies, then it executes fine. Does large app size creating problem to execute app ?

I am using android studio 2.3 and java-8-openjdk-amd64 and ubuntu 16.04

One strange thing : Everything was working correct before executing command

```<code>apt-get update
</code>```

I am searching from days but nothing seems work.

答:
Try to add below to build.gradle  </p>

```<code>compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
}
</code>```

<p>Try to build by command line  </p>

```<code>gradle clean assembleDebug
</code>```

Body:
I can build my project but can not run the app. When executing app it gives me error like

Execution failed for task ':app:transformClassesWithMultidexlistForDebug'.

com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: Error while executing java process with main class com.android.multidex.ClassReferenceListBuilder with arguments {/home/Git_Projects/Test1/app/build/intermediates/multi-dex/debug/componentClasses.jar /home/Git_Projects/Test1/app/build/intermediates/transforms/jarMerging/debug/jars/1/1f/combined.jar}

I tried to clean and rebuild project and Invalidate Catche and Restart. But, nothing helped me.

build.gradle (app)

apply plugin: 'com.android.application'

android {
    dexOptions {
        javaMaxHeapSize "4g"
    }
    compileSdkVersion 26
    buildToolsVersion "26.0.1"
    useLibrary 'org.apache.http.legacy'
    defaultConfig {
        applicationId "com.app.test1"
        minSdkVersion 16
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        multiDexEnabled = true
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

repositories {
    mavenCentral()
    maven { url 'https://github.com/Kaustubh-Deshmukh/progressbar_repo/raw/master' }

    maven { url 'https://dl.bintray.com/yazeed44/maven' }
    }

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:multidex:1.0.1'
    compile 'com.google.android.gms:play-services-gcm:10.0.1'
    compile 'com.google.android.gms:play-services-places:10.0.1'
    compile 'com.google.android.gms:play-services-maps:10.0.1'
    compile 'com.google.android.gms:play-services-vision:10.0.1'

    compile 'com.github.clans:fab:1.6.4'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.jakewharton:butterknife:8.4.0'
    compile 'com.googlecode.libphonenumber:libphonenumber:7.1.1'
    compile 'com.android.support:appcompat-v7:26.0.0'
    compile 'com.android.support:design:26.0.0'
    compile 'com.android.support:recyclerview-v7:26.0.0'
    compile 'com.android.support:cardview-v7:26.0.0'
    compile 'com.android.support:support-v4:26.0.0'
    compile 'com.android.support:support-annotations:26.0.0'
    compile 'com.android.support:percent:26.0.0'
    compile 'com.android.support:support-v13:26.0.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.1'
    compile 'com.facebook.fresco:fresco:1.5.0'
    compile 'org.greenrobot:eventbus:3.0.0'
    compile 'com.kontaktio:sdk:3.3.2'

    annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0'

    testCompile 'junit:junit:4.12'
}

If I randomly remove some dependencies, then it executes fine. Does large app size creating problem to execute app ?

I am using android studio 2.3 and java-8-openjdk-amd64 and ubuntu 16.04

One strange thing : Everything was working correct before executing command

apt-get update

I am searching from days but nothing seems work.

Body:
Try to add below to build.gradle

compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
}

Try to build by command line

gradle clean assembleDebug


问:
How to cascade specific fields of the object or array to the existing object or array. (JS and React)
I'm trying to...

get the specific field of data from the object in the object

set the states with the obtained data at once (if it's possible)

Here is taggedItems which I want to edit (setState).

```<code>taggedItems = {
  0: { id: 0, width: 40, height: 40, image: null, base64: null },
  1: { id: 1, width: 200, height: 200, image: null, base64: null },
  2: { id: 2, width: 80, height: 80, image: null, base64: null }
}
</code>```

I'm cropping the taggedItems from the image. I'm getting image and base64 data.

```<code>for (var key in taggedItems) {
    ..
    // Get successURI, base64 value
    // Store it to array or object (Can store them in array, object or any type.
    // Because I don't prefer to setState in the for-loop.
    // exampleArray = [
    //   { id: 0, image: 'file:path1', base64: 'ksdnflksdf' },
    //   { id: 1, image: 'file:path2', base64: 'fldmlkflkj' },
    //   { id:2, image: 'file:path3', base64: 'glkmdlfg' },
    // ]

// HERE IS THE PROBLEM: I want to setState all of items at once(if it's possible)
setState({taggedItems: ???});
</code>```

Expected output of this.state.taggedItems after setState right above will be

```<code>taggedItems = {
   0: { id: 0, width: 40, height: 40, image: 'file:path1', base64: 'ksdnflksdf' },
   1: { id: 1, width: 200, height: 200, image: 'file:path2', base64: 'fldmlkflkj' },
   2: { id: 2, width: 80, height: 80, image: 'file:path3', base64: 'glkmdlfg' }
}
</code>```

I will convert object into array anyway to send the data into the JSON so please feel free to use any type of variable (Array or Object).

答:
Not sure if I'm understanding correctly, but it sounds like you just want to merge the objects inside two arrays. If that's the case you can do it pretty easily with .map and the spread operator:

const taggedItems = [
  {id:0, width:40, height:40, image:null, base64:null},
  {id:1, width:200, height:200, image:null, base64:null},
  {id:2, width:80, height:80, image:null, base64:null}
];

const exampleArray = [
  {id:0, image: 'file:path1', base64: 'ksdnflksdf'},
  {id:1, image: 'file:path2', base64: 'fldmlkflkj'},
  {id:2, image: 'file:path3', base64: 'glkmdlfg'},
];

const merged = taggedItems.map((tagged, i) => {
  return {
    ...tagged,
    ...exampleArray[i]
  };
});

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

<h2>More info</h2>

<p>More info about object spread and some comments that might help explain:</p>

```const merged = taggedItems.map((tagged, i) => {
  // for every item in `taggedItems` return a new object
  return {
    // take all properties from `tagged`
    ...tagged,
    // get all properties from `exampleArray[i]`
    ...exampleArray[i]
  };
  // The new object will contain all properties from `tagged` + `exampleArray[i]` in that order.
  // If there are duplicated the latter one will overwrite.
});
```

Body:
I'm trying to...

get the specific field of data from the object in the object

set the states with the obtained data at once (if it's possible)

Here is taggedItems which I want to edit (setState).

taggedItems = {
  0: { id: 0, width: 40, height: 40, image: null, base64: null },
  1: { id: 1, width: 200, height: 200, image: null, base64: null },
  2: { id: 2, width: 80, height: 80, image: null, base64: null }
}

I'm cropping the taggedItems from the image. I'm getting image and base64 data.

for (var key in taggedItems) {
    ..
    // Get successURI, base64 value
    // Store it to array or object (Can store them in array, object or any type.
    // Because I don't prefer to setState in the for-loop.
    // exampleArray = [
    //   { id: 0, image: 'file:path1', base64: 'ksdnflksdf' },
    //   { id: 1, image: 'file:path2', base64: 'fldmlkflkj' },
    //   { id:2, image: 'file:path3', base64: 'glkmdlfg' },
    // ]

// HERE IS THE PROBLEM: I want to setState all of items at once(if it's possible)
setState({taggedItems: ???});

Expected output of this.state.taggedItems after setState right above will be

taggedItems = {
   0: { id: 0, width: 40, height: 40, image: 'file:path1', base64: 'ksdnflksdf' },
   1: { id: 1, width: 200, height: 200, image: 'file:path2', base64: 'fldmlkflkj' },
   2: { id: 2, width: 80, height: 80, image: 'file:path3', base64: 'glkmdlfg' }
}

I will convert object into array anyway to send the data into the JSON so please feel free to use any type of variable (Array or Object).

Body:
Not sure if I'm understanding correctly, but it sounds like you just want to merge the objects inside two arrays. If that's the case you can do it pretty easily with .map and the spread operator:

const taggedItems = [
  {id:0, width:40, height:40, image:null, base64:null},
  {id:1, width:200, height:200, image:null, base64:null},
  {id:2, width:80, height:80, image:null, base64:null}
];

const exampleArray = [
  {id:0, image: 'file:path1', base64: 'ksdnflksdf'},
  {id:1, image: 'file:path2', base64: 'fldmlkflkj'},
  {id:2, image: 'file:path3', base64: 'glkmdlfg'},
];

const merged = taggedItems.map((tagged, i) => {
  return {
    ...tagged,
    ...exampleArray[i]
  };
});

console.log(merged);

More info

More info about object spread and some comments that might help explain:

const merged = taggedItems.map((tagged, i) => {
  // for every item in `taggedItems` return a new object
  return {
    // take all properties from `tagged`
    ...tagged,
    // get all properties from `exampleArray[i]`
    ...exampleArray[i]
  };
  // The new object will contain all properties from `tagged` + `exampleArray[i]` in that order.
  // If there are duplicated the latter one will overwrite.
});


问:
Rails 3 serialized hash values saving but not persisting
I have a model with a serialized text column. When I save and reload the record, the values seem to persist but when I query the record the values are gone.

(Demonstration below truncated for simplicity)

```<code>class Subscription < ActiveRecord::Base
   serialize :pending_changes, Hash
   attr_accessible :pending_changes
   attr_accessor :pending_changes
end

class AddPendingChangesToSubscriptions < ActiveRecord::Migration
  def change
    add_column :subscriptions, :pending_changes, :text
  end
end

s = Subscription.new

s.pending_changes = {foo: "bar"}

s.save
# => true

s.reload.pending_changes
# => {foo: "bar"}

Subscription.last.pending_changes
# => nil
</code>```

The same thing happens when saving {"foo" => "bar"} as the value.

I've also noticed that when save is called, the resulting SQL query is as follows:

```<code>UPDATE 'subscriptions' SET 'updated_at' = '2017-12-01 23:46:05', 'pending_changes' = '--- {}\n' WHERE 'subscriptions'.'id' = 2
</code>```

As per the answers to similar questions, I've made sure the db column datatype is text and I've tried using serialize :column_name with and without the appended Hash.

答:
Remove attr_accessible :pending_changes and attr_accessor :pending_changes from the model, since you have a column in the database , so no need of using attr_accessible, attr_accessor. Use the model code as below and try.</p>

```<code>class Subscription < ActiveRecord::Base
  serialize :pending_changes, Hash
end
</code>```

Body:
I have a model with a serialized text column. When I save and reload the record, the values seem to persist but when I query the record the values are gone.

(Demonstration below truncated for simplicity)

class Subscription < ActiveRecord::Base
   serialize :pending_changes, Hash
   attr_accessible :pending_changes
   attr_accessor :pending_changes
end

class AddPendingChangesToSubscriptions < ActiveRecord::Migration
  def change
    add_column :subscriptions, :pending_changes, :text
  end
end

s = Subscription.new

s.pending_changes = {foo: "bar"}

s.save
# => true

s.reload.pending_changes
# => {foo: "bar"}

Subscription.last.pending_changes
# => nil

The same thing happens when saving {"foo" => "bar"} as the value.

I've also noticed that when save is called, the resulting SQL query is as follows:

UPDATE 'subscriptions' SET 'updated_at' = '2017-12-01 23:46:05', 'pending_changes' = '--- {}\n' WHERE 'subscriptions'.'id' = 2

As per the answers to similar questions, I've made sure the db column datatype is text and I've tried using serialize :column_name with and without the appended Hash.

Body:
Remove attr_accessible :pending_changes and attr_accessor :pending_changes from the model, since you have a column in the database , so no need of using attr_accessible, attr_accessor. Use the model code as below and try.

class Subscription < ActiveRecord::Base
  serialize :pending_changes, Hash
end


问:
Unix shell script error in crontab
I'm trying to schedule my shell script but when it triggered to process on a scheduled task, there is this error prompt. but when no files are to be process it just displays the echo command.

here is my code:

```<code>if [ "$(ls -A $path)" ]
    then
    for file_name in "$path"/*; do
        filebasename=$(basename "$file_name")

        prefix=${filebasename:0:4};

        if [ "$prefix" == "abcd" ] ; then

            mv  "$file_name" "$out"

        fi

    done

    else echo "No files available at $path"
fi
</code>```

and this is the error:

```<code>SH:prefix=${filebasename:0:4}:0403-011 The specified substitution is not valid for this command
</code>```

答:
i use this code:
prefix=$(echo ${filebasename} | cut -c1-4)

instead of prefix=${filebasename:0:4};

now it completely running in my cronjob and no error as said earlier. thanks for the help guys ! :)

Title: Unix shell script error in crontab

Body:
I'm trying to schedule my shell script but when it triggered to process on a scheduled task, there is this error prompt. but when no files are to be process it just displays the echo command.

here is my code:

if [ "$(ls -A $path)" ]
    then
    for file_name in "$path"/*; do
        filebasename=$(basename "$file_name")

        prefix=${filebasename:0:4};

        if [ "$prefix" == "abcd" ] ; then

            mv  "$file_name" "$out"

        fi

    done

    else echo "No files available at $path"
fi

and this is the error:

SH:prefix=${filebasename:0:4}:0403-011 The specified substitution is not valid for this command


问:
How to make a Linkedin Rest API request the Node way (without the JS SDK)?
I'm using Node (v0.12.4) + Express (v4.0.0) + PassportJS(v0.1.17) to authenticate users with LinkedIn (OAuth2).

I'm following the steps from this tutorial:
https://developer.linkedin.com/docs/oauth2

I was able to authenticate the user and save his information along with the Auth Token provided by LinkedIn to my database.

My question: how do I make requests to the API using the token? I'm stuck in step 4 of the given tutorial.

For example, how would I make the call below (taken from the tutorial above)?

sample call

```<code>GET /v1/people/~ HTTP/1.1
Host: api.linkedin.com
Connection: Keep-Alive
Authorization: Bearer AQXdSP_W41_UPs5ioT_t8HESyODB4FqbkJ8LrV_5mff4gPODzOYR
</code>```

Seems easy, but as a node beginner, I've been struggling with it for too long.

==================

EDIT:
Following Ted Avery's advice, I tried the request module and ended up with something like this:

```<code>// LinkedIn API route
app.get('/linkedin/people', function(req,res){
    request.get('http://api.linkedin.com/v1/people/~', {
        'host': 'api.linkedin.com',
        'connection': 'Keep-Alive'
        'auth': {
            'bearer': req.user.linkedin.token
        }
    }, function(error,apiRes,body){
        res.send(apiRes);
    });
});
</code>```

And I get the following response (apiRes):

```<code>{
"statusCode":401

"body":"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<error>\n  <status>401</status>\n  <timestamp>1437750879622</timestamp>\n  <request-id>AKM2GX6BFE</request-id>\n  <error-code>0</error-code>\n  <message>ssl required</message>\n</error>\n",

"headers":{
    "server":"Apache-Coyote/1.1",
    "x-li-request-id":"AKM2GX6BFE",
    "date":"Fri, 24 Jul 2015 15:14:38 GMT",
    "vary":"*",
    "x-li-format":"xml",
    "content-type":"text/xml;charset=UTF-8",
    "content-length":"236",
    "x-li-fabric":"prod-ltx1",
    "x-li-pop":"prod-ltx1",
    "x-li-uuid":"zoW/s87q8xNQnsleUCsAAA==",
    "set-cookie":["lidc=\"b=TB60:g=105:u=27:i=1437750879:t=1437833236:s=AQFNZrhu0_0QIvH-rUkU4ElJ8Ytm_dKV\"; Expires=Sat, 25 Jul 2015 14:07:16 GMT; domain=.linkedin.com; Path=/"]
    },

"request":{
    "uri":{
        "protocol":"http:",
        "slashes":true,
        "auth":null,
        "host":"api.linkedin.com",
        "port":80,
        "hostname":"api.linkedin.com",
        "hash":null,
        "search":null,
        "query":null,
        "pathname":"/v1/people/~",
        "path":"/v1/people/~",
        "href":"http://api.linkedin.com/v1/people/~"
        },
    "method":"GET",
    "headers":{
        "authorization":"Bearer AQVYLfCs5lpbUlFdGeKXdR3z-3IiuO2N-PdJ7wgEtD_2doyxcy--mUxCN-GCJm-CaRXa-j7OF646enu_V5cp8jbiuMPesqKjWLcDdMmy8PSbEXS6Mw2iVznVF0Mk0iSAm419XlB7uMFwX0iAC71a_kjk_hZmvc90PmT471MLButnQmo3ww0"
        }
    }
}
</code>```

I know that the linkedin-passport auth process is ok because I'm getting the user name, email and token in my DB. The problem is that with this token I always get a 401 unauthorized for some reason. Any thoughts on that?

答:
I know you have asked this question a long time ago, but I have an answer and it might help others.

Replace the 'auth' with 'Authorization'

```<code>// LinkedIn API route
app.get('/linkedin/people', function(req,res){
    request.get('http://api.linkedin.com/v1/people/~', {
        'host': 'api.linkedin.com',
        'connection': 'Keep-Alive'
        'Authorization': { // <------- Replace this
            'bearer': req.user.linkedin.token
        }
    }, function(error,apiRes,body){
        res.send(apiRes);
    });
});
</code>```

Also read this: https://developer.linkedin.com/docs/oauth2#hero-par_longformtext_3_longform-text-content-par_resourceparagraph_3

You need to add state=ThisIsRandomBlaBlaDCEeFWf45A53sdfKef424 as a param

when you do the GET request to https://www.linkedin.com/oauth/v2/authorization

Body:
I'm using Node (v0.12.4) + Express (v4.0.0) + PassportJS(v0.1.17) to authenticate users with LinkedIn (OAuth2).

I'm following the steps from this tutorial:
https://developer.linkedin.com/docs/oauth2

I was able to authenticate the user and save his information along with the Auth Token provided by LinkedIn to my database.

My question: how do I make requests to the API using the token? I'm stuck in step 4 of the given tutorial.

For example, how would I make the call below (taken from the tutorial above)?

sample call

GET /v1/people/~ HTTP/1.1
Host: api.linkedin.com
Connection: Keep-Alive
Authorization: Bearer AQXdSP_W41_UPs5ioT_t8HESyODB4FqbkJ8LrV_5mff4gPODzOYR

Seems easy, but as a node beginner, I've been struggling with it for too long.

==================

EDIT:
Following Ted Avery's advice, I tried the request module and ended up with something like this:

// LinkedIn API route
app.get('/linkedin/people', function(req,res){
    request.get('http://api.linkedin.com/v1/people/~', {
        'host': 'api.linkedin.com',
        'connection': 'Keep-Alive'
        'auth': {
            'bearer': req.user.linkedin.token
        }
    }, function(error,apiRes,body){
        res.send(apiRes);
    });
});

And I get the following response (apiRes):

{
"statusCode":401

"body":"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<error>\n  <status>401</status>\n  <timestamp>1437750879622</timestamp>\n  <request-id>AKM2GX6BFE</request-id>\n  <error-code>0</error-code>\n  <message>ssl required</message>\n</error>\n",

"headers":{
    "server":"Apache-Coyote/1.1",
    "x-li-request-id":"AKM2GX6BFE",
    "date":"Fri, 24 Jul 2015 15:14:38 GMT",
    "vary":"*",
    "x-li-format":"xml",
    "content-type":"text/xml;charset=UTF-8",
    "content-length":"236",
    "x-li-fabric":"prod-ltx1",
    "x-li-pop":"prod-ltx1",
    "x-li-uuid":"zoW/s87q8xNQnsleUCsAAA==",
    "set-cookie":["lidc=\"b=TB60:g=105:u=27:i=1437750879:t=1437833236:s=AQFNZrhu0_0QIvH-rUkU4ElJ8Ytm_dKV\"; Expires=Sat, 25 Jul 2015 14:07:16 GMT; domain=.linkedin.com; Path=/"]
    },

"request":{
    "uri":{
        "protocol":"http:",
        "slashes":true,
        "auth":null,
        "host":"api.linkedin.com",
        "port":80,
        "hostname":"api.linkedin.com",
        "hash":null,
        "search":null,
        "query":null,
        "pathname":"/v1/people/~",
        "path":"/v1/people/~",
        "href":"http://api.linkedin.com/v1/people/~"
        },
    "method":"GET",
    "headers":{
        "authorization":"Bearer AQVYLfCs5lpbUlFdGeKXdR3z-3IiuO2N-PdJ7wgEtD_2doyxcy--mUxCN-GCJm-CaRXa-j7OF646enu_V5cp8jbiuMPesqKjWLcDdMmy8PSbEXS6Mw2iVznVF0Mk0iSAm419XlB7uMFwX0iAC71a_kjk_hZmvc90PmT471MLButnQmo3ww0"
        }
    }
}

I know that the linkedin-passport auth process is ok because I'm getting the user name, email and token in my DB. The problem is that with this token I always get a 401 unauthorized for some reason. Any thoughts on that?

Body:
I know you have asked this question a long time ago, but I have an answer and it might help others.

Replace the 'auth' with 'Authorization'

// LinkedIn API route
app.get('/linkedin/people', function(req,res){
    request.get('http://api.linkedin.com/v1/people/~', {
        'host': 'api.linkedin.com',
        'connection': 'Keep-Alive'
        'Authorization': { // <------- Replace this
            'bearer': req.user.linkedin.token
        }
    }, function(error,apiRes,body){
        res.send(apiRes);
    });
});

Also read this: https://developer.linkedin.com/docs/oauth2#hero-par_longformtext_3_longform-text-content-par_resourceparagraph_3

You need to add state=ThisIsRandomBlaBlaDCEeFWf45A53sdfKef424 as a param

when you do the GET request to https://www.linkedin.com/oauth/v2/authorization


问:
Setuptools pip wheel failed with error code 2 (Pycharm)
System: ubuntu16.04
Version of pycharm: Community 2017.3

When I create a new project,

I get the information as follows:

What is the problem? Thank you.

答:
Now, I can create a project without getting disturbing information. I choose another interpreter.
enter image description here</p>


问:
Keeping session information between a primary domain and a subdomain
I was wondering if it is possible to retain session information between a primary domain and a subdomain. For example, I login on http://www.mydomain.com/ but I want to use the same session on http://something.mydomain.com/. </p>

答:
Yes, if the session data is accessible from both domains (e.g. same server) and if the same session ID is used for both domains, you can share the same session in both domains.

As for the session ID, if you use a cookie for the session ID, you need to adjust the session cookie’s domain parameter to make the cookie available on both domains (i.e. .example.com for example.com and all its subdomains):

```<code>ini_set('session.cookie_domain', '.example.com');
</code>```

Body:
Yes, if the session data is accessible from both domains (e.g. same server) and if the same session ID is used for both domains, you can share the same session in both domains.

As for the session ID, if you use a cookie for the session ID, you need to adjust the session cookie’s domain parameter to make the cookie available on both domains (i.e. .example.com for example.com and all its subdomains):

ini_set('session.cookie_domain', '.example.com');


问:
CallKit - "Touch to return to call" not removing
I am using CallKit in my project. "Touch to return to call" is still showing even when after the call is rejected by user those who called by us.

```<code>let provider = CXProvider(...) // this object declared globally
provider.reportCall(with: UUID(), endedAt: Date(), reason: CXCallEndedReason.declinedElsewhere)
</code>```

I am using above code avoid this. But didn't worked for me.

答:
To end the call, use cxendcallaction and add the cxtransaction objects.
Make sure you are using the correct uuid. </p>

```<code>CXEndCallAction *action = [[CXEndCallAction alloc] initWithCallUUID:callUUID];
[self.callController requestTransaction:[CXTransaction transactionWithActions:@[action]] completion:completion];
</code>```

Body:
I am using CallKit in my project. "Touch to return to call" is still showing even when after the call is rejected by user those who called by us.

let provider = CXProvider(...) // this object declared globally
provider.reportCall(with: UUID(), endedAt: Date(), reason: CXCallEndedReason.declinedElsewhere)

I am using above code avoid this. But didn't worked for me.

Body:
To end the call, use cxendcallaction and add the cxtransaction objects.
Make sure you are using the correct uuid.

CXEndCallAction *action = [[CXEndCallAction alloc] initWithCallUUID:callUUID];
[self.callController requestTransaction:[CXTransaction transactionWithActions:@[action]] completion:completion];


问:
How to find correct min / max values of a list in Perl 6
New to Perl6, trying to figure out what I'm doing wrong here. The problem is a simple checksum that takes the difference of the max and min values for each row in the csv

The max and min values it returns are completely wrong. For the first row in the csv, it returns the max as 71, and the min as 104, which is incorrect.

Here's the link to the repo for reference, and the link to the corresponding problem.

```<code>#!/usr/bin/env perl6

use Text::CSV;

sub checksum {
    my $sum = 0;
    my @data = csv(in => "input.csv");
    for @data -> @value {
        $sum += (max @value) - (min @value);
    }
    say $sum;
}

checksum
</code>```

答:
I assume your input contains numbers, but since CSV is a text format, the input is being read in as strings. min and max are operating based on string sorting, so max("4", "10") is 4 but max("04", "10") is 10. To solve this, you can either cast each element to Numeric (int, floating point, etc.) before you get the min/max:

```<code>@input.map(*.Numeric).max
</code>```

or pass a conversion function to min and max so each element is parsed as a number as it's compared:

```<code>@input.max(*.Numeric)
</code>```

The first solution is better for your case, since the second solution is an ephemeral conversion, converting internally but still returning a string. Final note: in normal code I would write +* or { +$_ } to mean "treat X as a number", but in this case I prefer being explicit: .Numeric.

Body:
New to Perl6, trying to figure out what I'm doing wrong here. The problem is a simple checksum that takes the difference of the max and min values for each row in the csv

The max and min values it returns are completely wrong. For the first row in the csv, it returns the max as 71, and the min as 104, which is incorrect.

Here's the link to the repo for reference, and the link to the corresponding problem.

#!/usr/bin/env perl6

use Text::CSV;

sub checksum {
    my $sum = 0;
    my @data = csv(in => "input.csv");
    for @data -> @value {
        $sum += (max @value) - (min @value);
    }
    say $sum;
}

checksum

Body:
I assume your input contains numbers, but since CSV is a text format, the input is being read in as strings. min and max are operating based on string sorting, so max("4", "10") is 4 but max("04", "10") is 10. To solve this, you can either cast each element to Numeric (int, floating point, etc.) before you get the min/max:

@input.map(*.Numeric).max

or pass a conversion function to min and max so each element is parsed as a number as it's compared:

@input.max(*.Numeric)

The first solution is better for your case, since the second solution is an ephemeral conversion, converting internally but still returning a string. Final note: in normal code I would write +* or { +$_ } to mean "treat X as a number", but in this case I prefer being explicit: .Numeric.


问:
Multiple lists input to a file
I have 4 lists with equal length.
like:

```<code>List1: x1,x2,x3,x4...
List2: y1,y2,y3,y4...
List3: z1,z2,z3,z4,...
list4: a1,a2,a3,a4,....
</code>```

I want to read them and write to a file as:

x1,y1,z1,a1....

for that :

```<code>with open('do.txt','a+') as writefile:
   for i in iter(List1):
      writefile.write(i)
</code>```

how can we write all the in the file at the same time.

答:
Just for fun this is one line solution :)

```<code>[open('writing_file.txt', 'a+').write("{},{},{},{}\n".format(a,b,c,d)) for a,b,c,d in zip(list1,list2,list3,list4)]
</code>```

Above list comprehension is same as:

```<code>with open('writing_file.txt','a+') as file_1:
    for a,b,c,d in zip(list1,list2,list3,list4):
        file_1.write("{},{},{},{}\n".format(a,b,c,d))
</code>```

Title: Multiple lists input to a file

Body:
I have 4 lists with equal length.
like:

List1: x1,x2,x3,x4...
List2: y1,y2,y3,y4...
List3: z1,z2,z3,z4,...
list4: a1,a2,a3,a4,....

I want to read them and write to a file as:

x1,y1,z1,a1....

for that :

with open('do.txt','a+') as writefile:
   for i in iter(List1):
      writefile.write(i)

how can we write all the in the file at the same time.

Body:
Just for fun this is one line solution :)

[open('writing_file.txt', 'a+').write("{},{},{},{}\n".format(a,b,c,d)) for a,b,c,d in zip(list1,list2,list3,list4)]

Above list comprehension is same as:

with open('writing_file.txt','a+') as file_1:
    for a,b,c,d in zip(list1,list2,list3,list4):
        file_1.write("{},{},{},{}\n".format(a,b,c,d))


问:
getting subdocument from document
I have a collection that has a sub-document in it and I'm trying to find an easy way to get an exact document.

```<code>{
    "_id" : ObjectId("59b0303bfe409a21fccc9523"),
    "CreatedOn" : ISODate("2017-07-22T15:55:00.000+0000"),
    "UpdatedOn" : ISODate("2017-07-22T15:55:00.000+0000"),
    "Guid" : "4F1D7541-FF27-4FEF-9BC4-CF27D2CB92BA",
    "Company" : "Demo Co.",
    "Departments" : [
        {
            "CreatedOn" : ISODate("2017-07-22T15:55:00.000+0000"),
            "UpdatedOn" : ISODate("2017-07-22T15:55:00.000+0000"),
            "Guid" : "D5950FC8-91B1-48A3-8B6A-F3A72FAC9175",
            "Title" : "Execute"
        }
    ]
}
</code>```

what I'd like to do is get a certain department based on its guid but so far I'm not finding anything that is clean to get just the document I want.

I'd want to get a result like this:

```<code>{
    "CreatedOn" : ISODate("2017-07-22T15:55:00.000+0000"),
    "UpdatedOn" : ISODate("2017-07-22T15:55:00.000+0000"),
    "Guid" : "D5950FC8-91B1-48A3-8B6A-F3A72FAC9175",
    "Title" : "Execute"
}
</code>```

I've been looking around the mongodb documentation but nothing is working so far, the closest I'm getting is using array_search, but I'd like to fetch it straight from mongo itself if possible to avoid hacking it with PHP.

Title: getting subdocument from document

Body:
I have a collection that has a sub-document in it and I'm trying to find an easy way to get an exact document.

{
    "_id" : ObjectId("59b0303bfe409a21fccc9523"),
    "CreatedOn" : ISODate("2017-07-22T15:55:00.000+0000"),
    "UpdatedOn" : ISODate("2017-07-22T15:55:00.000+0000"),
    "Guid" : "4F1D7541-FF27-4FEF-9BC4-CF27D2CB92BA",
    "Company" : "Demo Co.",
    "Departments" : [
        {
            "CreatedOn" : ISODate("2017-07-22T15:55:00.000+0000"),
            "UpdatedOn" : ISODate("2017-07-22T15:55:00.000+0000"),
            "Guid" : "D5950FC8-91B1-48A3-8B6A-F3A72FAC9175",
            "Title" : "Execute"
        }
    ]
}

what I'd like to do is get a certain department based on its guid but so far I'm not finding anything that is clean to get just the document I want.

I'd want to get a result like this:

{
    "CreatedOn" : ISODate("2017-07-22T15:55:00.000+0000"),
    "UpdatedOn" : ISODate("2017-07-22T15:55:00.000+0000"),
    "Guid" : "D5950FC8-91B1-48A3-8B6A-F3A72FAC9175",
    "Title" : "Execute"
}

I've been looking around the mongodb documentation but nothing is working so far, the closest I'm getting is using array_search, but I'd like to fetch it straight from mongo itself if possible to avoid hacking it with PHP.

Body:
You can try out this,

db.foo.find({"_id" : ObjectId("59b0303bfe409a21fccc9523")})
.map(function(u){
        return u.Departments
                .filter(p => p.Guid == "D5950FC8-91B1-48A3-8B6A-F3A72FAC9175")
    }
)

This will only return:

[
    [
        {
            "CreatedOn" : ISODate("2017-07-22T21:25:00.000+05:30"),
            "UpdatedOn" : ISODate("2017-07-22T21:25:00.000+05:30"),
            "Guid" : "D5950FC8-91B1-48A3-8B6A-F3A72FAC9175",
            "Title" : "Execute"
        }
    ]
]


问:
how to translate update set SQL to scala quill?
I have a schema in PostgreSql in which I want do update set for users_id field:

```<code>CREATE TABLE if not exists rooms (
  oid char(24),
  owner_id char(24) not null,
  users_id text[],

  PRIMARY KEY (oid)
);
</code>```

The execute sql as this:

```<code>update rooms set users_id = (select array_agg(distinct e) from
unnest(users_id || '{5a16f7ce77c8a2b22406fb86}') e) where  oid =
'5a16f7ce77c8a2b22406fb86';
</code>```

it update users_id array filed and do distinct operation.

In Quill, I have attempt with the method:

```<code>def addUserInRoom(userId: ObjectId, roomId: ObjectId): Unit = {
    val q = quote(
      (uid: String, rid: String) =>
        infix"""update rooms set users_id = (select array_agg(distinct e) from unnest(users_id || '{${uid}}') e) where  oid = '${rid}'""".as[Query[Long]]
    )

    run(q(lift(userId.toString), lift(roomId.toString)))
}
</code>```

A exception occurred:

```<code>Exception in thread "main" org.postgresql.util.PSQLException: The column index is out of range: 1, number of columns: 0.
    at org.postgresql.core.v3.SimpleParameterList.bind(SimpleParameterList.java:65)
    at org.postgresql.core.v3.SimpleParameterList.setStringParameter(SimpleParameterList.java:128)
    at org.postgresql.jdbc.PgPreparedStatement.bindString(PgPreparedStatement.java:1029)
    at org.postgresql.jdbc.PgPreparedStatement.setString(PgPreparedStatement.java:369)
    at org.postgresql.jdbc.PgPreparedStatement.setString(PgPreparedStatement.java:353)
    at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.setString(HikariProxyPreparedStatement.java)
    at io.getquill.context.jdbc.Encoders.$anonfun$stringEncoder$2(Encoders.scala:44)
    at io.getquill.context.jdbc.Encoders.$anonfun$stringEncoder$2$adapted(Encoders.scala:44)
...
</code>```

How can I execute the sql with scala Quill library?
Different way always welcome!

Thanks

Update - more information

dependency is :

```<code>  "org.postgresql" % "postgresql" % "42.1.4",
  "io.getquill" %% "quill-jdbc" % "2.2.0",
</code>```

My driver instance is:

```<code>lazy val ctx = new PostgresJdbcContext(
    NamingStrategy(SnakeCase, PostgresEscape),
    AppConfig.quill
  )
</code>```

Besides, some simple sql has test successful.

答:
```<code>  lazy val ctx = new PostgresJdbcContext(SnakeCase, "ctx")
  import ctx._

  case class Rooms(oid: String, ownerId: String, usersId: Seq[String])

  def foo(oid: String, uid: String) = {
    val uids: Seq[String] = Seq(uid)
    val v = quote(infix"(select array_agg(distinct e) from unnest(users_id || ${lift(uids)}) e)".as[Seq[String]])

    val q = quote {
      query[Rooms].filter(_.oid == lift(oid))
        .update(_.usersId -> unquote(v))
    }
    ctx.run(q)
  }
  def main(args: Array[String]): Unit = {
    println(foo("1", "2"))
  }
</code>```

Body:
I have a schema in PostgreSql in which I want do update set for users_id field:

CREATE TABLE if not exists rooms (
  oid char(24),
  owner_id char(24) not null,
  users_id text[],

  PRIMARY KEY (oid)
);

The execute sql as this:

update rooms set users_id = (select array_agg(distinct e) from
unnest(users_id || '{5a16f7ce77c8a2b22406fb86}') e) where  oid =
'5a16f7ce77c8a2b22406fb86';

it update users_id array filed and do distinct operation.

In Quill, I have attempt with the method:

def addUserInRoom(userId: ObjectId, roomId: ObjectId): Unit = {
    val q = quote(
      (uid: String, rid: String) =>
        infix"""update rooms set users_id = (select array_agg(distinct e) from unnest(users_id || '{${uid}}') e) where  oid = '${rid}'""".as[Query[Long]]
    )

    run(q(lift(userId.toString), lift(roomId.toString)))
}

A exception occurred:

Exception in thread "main" org.postgresql.util.PSQLException: The column index is out of range: 1, number of columns: 0.
    at org.postgresql.core.v3.SimpleParameterList.bind(SimpleParameterList.java:65)
    at org.postgresql.core.v3.SimpleParameterList.setStringParameter(SimpleParameterList.java:128)
    at org.postgresql.jdbc.PgPreparedStatement.bindString(PgPreparedStatement.java:1029)
    at org.postgresql.jdbc.PgPreparedStatement.setString(PgPreparedStatement.java:369)
    at org.postgresql.jdbc.PgPreparedStatement.setString(PgPreparedStatement.java:353)
    at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.setString(HikariProxyPreparedStatement.java)
    at io.getquill.context.jdbc.Encoders.$anonfun$stringEncoder$2(Encoders.scala:44)
    at io.getquill.context.jdbc.Encoders.$anonfun$stringEncoder$2$adapted(Encoders.scala:44)
...

How can I execute the sql with scala Quill library?
Different way always welcome!

Thanks

Update - more information

dependency is :

  "org.postgresql" % "postgresql" % "42.1.4",
  "io.getquill" %% "quill-jdbc" % "2.2.0",

My driver instance is:

lazy val ctx = new PostgresJdbcContext(
    NamingStrategy(SnakeCase, PostgresEscape),
    AppConfig.quill
  )

Besides, some simple sql has test successful.


问:
Are unit-test names important?
If unit-test names can become outdated over time and if you consider that the test itself is the most important thing, then is it important to choose wise test names?

ie

```<code>[Test]
public void ShouldValidateUserNameIsLessThan100Characters() {}
</code>```

verse

```<code>[Test]
public void UserNameTestValidation1() {}
</code>```

答:
```<code>[RowTest]
[Row("GoodName")]
[Row("GoodName2")]
public void Should_validate_username()
{
}

[RowTest]
[Row("BadUserName")]
[Row("Bad%!Name")]
public void Should_invalidate_username()
{
}
</code>```

This might make more sense for more complex types of validation really.

OwnerDisplayName: Xian

Title: Are unit-test names important?

Body:
If unit-test names can become outdated over time and if you consider that the test itself is the most important thing, then is it important to choose wise test names?

ie

[Test]
public void ShouldValidateUserNameIsLessThan100Characters() {}

verse

[Test]
public void UserNameTestValidation1() {}

Body:
[RowTest]
[Row("GoodName")]
[Row("GoodName2")]
public void Should_validate_username()
{
}

[RowTest]
[Row("BadUserName")]
[Row("Bad%!Name")]
public void Should_invalidate_username()
{
}

This might make more sense for more complex types of validation really.

OwnerDisplayName: JC


问:
ArrayList with formatting
Struggling with my ArrayList code.
I needed to generate 20 random numbers between 1 and 200.
It works but when I show all in array list it, it all comes out horizontal
(ie: [190.9873874849,3.45694033,67.900034...] and SUPER long. It needs to have each number print out in a list format, with the only four digits after the decimal. (%10.4)

I tried this:

```<code>    System.out.printf("%10.4", num[0]);
</code>```

which works for the formatting but I can't seem to get the whole arraylist to work.

My array is this:

```<code>    ArrayList<Number> num = new ArrayList<Number>();

    for (int i = 0; i<20; i++) {
        num.add(Math.random() *200 +1);
        }
</code>```

It works like I said for getting and listing the numbers -- but not in the "correct" way.

I also have to save the numbers to a file, and be able to let the user choose an index for them and tell them their number they chose from the file, which I am also struggling with.

Any help would be amazing!!!

[EDIT]
This worked (from Ole V.V.):

```<code>        for (int i = 0; i<20; i++) {
        num.add(Math.random() *200 +1);
        System.out.printf("%10.4f%n", num.get(i));
</code>```

[ADDITIONAL]
**I have to post here and can't make a new question because some jerk downvoted me? **

I have all of the numbers in my array read in and saved to a text file (with the right formatting!) but now I have to be able to ask the user for an index, and be able to find the object according to that index... but it isn't working!

I don't know how to assign indexes to variables when the numbers are no longer in array format (they're in a column similar to what is in the column).

答:
You need to trim the extra digits by this simple trick.</p>

```<code> double number = Math.random()*200 + 1;
 number = (long)( number * 10000 );
 number = number / 10000;
</code>```

Title: ArrayList with formatting

Body:
Struggling with my ArrayList code.
I needed to generate 20 random numbers between 1 and 200.
It works but when I show all in array list it, it all comes out horizontal
(ie: [190.9873874849,3.45694033,67.900034...] and SUPER long. It needs to have each number print out in a list format, with the only four digits after the decimal. (%10.4)

I tried this:

    System.out.printf("%10.4", num[0]);

which works for the formatting but I can't seem to get the whole arraylist to work.

My array is this:

    ArrayList<Number> num = new ArrayList<Number>();

    for (int i = 0; i<20; i++) {
        num.add(Math.random() *200 +1);
        }

It works like I said for getting and listing the numbers -- but not in the "correct" way.

I also have to save the numbers to a file, and be able to let the user choose an index for them and tell them their number they chose from the file, which I am also struggling with.

Any help would be amazing!!!

[EDIT]
This worked (from Ole V.V.):

        for (int i = 0; i<20; i++) {
        num.add(Math.random() *200 +1);
        System.out.printf("%10.4f%n", num.get(i));

[ADDITIONAL]
**I have to post here and can't make a new question because some jerk downvoted me? **

I have all of the numbers in my array read in and saved to a text file (with the right formatting!) but now I have to be able to ask the user for an index, and be able to find the object according to that index... but it isn't working!

I don't know how to assign indexes to variables when the numbers are no longer in array format (they're in a column similar to what is in the column).

Body:
You need to trim the extra digits by this simple trick.

 double number = Math.random()*200 + 1;
 number = (long)( number * 10000 );
 number = number / 10000;


问:
Laravel Delete function not work
First project on laravel :  When I am going to delete row it throws an Error : SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails.
My controller function

```<code> public function delete(Request $request) {
    try {
        Venue::findOrFail($request->id)->delete();
    } catch (\Exception $ex) {
        return response()->json([
                'error' => $ex->getCode(),
                'message' => $ex->getMessage()
            ]);
    }

    return response()->json([
            'message' => trans('admin.venue.delete_success')
        ]);
}
</code>```

Model  :

```<code>protected static function boot()
{
    parent::boot();

    self::deleting(function (Venue $venue) {
        $venue->occasions()->delete();
        $venue->contact()->delete();
        $venue->gallery()->delete(); // here i am gtng error
        $venue->venueParameter()->delete();
    });
}
</code>```

Error in detail :

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or
  update a parent row: a foreign key constraint fails
  (red_carpet.media, CONSTRAINT media_gallery_id_foreign FOREIGN
  KEY (gallery_id) REFERENCES galleries (id)) (SQL: delete from
  galleries where galleries.source_id = 2 and
  galleries.source_id is not null and galleries.source_type =
  App\Venue)

Schema of table :

```<code>Schema::create('venues', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedInteger('client_id');
        $table->string('name');
        $table->string('logo');
        $table->unsignedInteger('venue_type_id');
        $table->boolean('is_premium');
        $table->boolean('is_verified');
        $table->string('tripadvisor_url')->nullable();
        $table->enum('status',['Active','Inactive']);
        $table->timestamps();

        $table->foreign('client_id')->references('id')->on('clients');
        $table->foreign('venue_type_id')->references('id')->on('venue_types');
    });

  Schema::create('galleries', function (Blueprint $table) {
        $table->increments('id');
        $table->string('source_type');
        $table->unsignedInteger('source_id');
        $table->string('title');
        $table->unsignedInteger('sort_order');
        $table->enum('status',['Active','Inactive']);
        $table->timestamps();
    });
    Schema::create('media', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedInteger('gallery_id');
        $table->enum('type',['Image','Video']);
        $table->string('caption');
        $table->string('path')->nullable();
        $table->string('thumbnail')->nullable();
        $table->longText('video_code')->nullable();
        $table->boolean('is_banner_image')->default(false);
        $table->boolean('is_thumb_image')->default(false);
        $table->unsignedInteger('sort_order');
        $table->enum('status',['Active','Inactive']);
        $table->timestamps();

        $table->foreign('gallery_id')->references('id')->on('galleries');
    });
</code>```

答:
You can add</p>

```<code>  onDelete('cascade')
</code>```

Title: Laravel Delete function not work

Body:
First project on laravel :  When I am going to delete row it throws an Error : SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails.
My controller function

 public function delete(Request $request) {
    try {
        Venue::findOrFail($request->id)->delete();
    } catch (\Exception $ex) {
        return response()->json([
                'error' => $ex->getCode(),
                'message' => $ex->getMessage()
            ]);
    }

    return response()->json([
            'message' => trans('admin.venue.delete_success')
        ]);
}

Model  :

protected static function boot()
{
    parent::boot();

    self::deleting(function (Venue $venue) {
        $venue->occasions()->delete();
        $venue->contact()->delete();
        $venue->gallery()->delete(); // here i am gtng error
        $venue->venueParameter()->delete();
    });
}

Error in detail :

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or
  update a parent row: a foreign key constraint fails
  (red_carpet.media, CONSTRAINT media_gallery_id_foreign FOREIGN
  KEY (gallery_id) REFERENCES galleries (id)) (SQL: delete from
  galleries where galleries.source_id = 2 and
  galleries.source_id is not null and galleries.source_type =
  App\Venue)

Schema of table :

Schema::create('venues', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedInteger('client_id');
        $table->string('name');
        $table->string('logo');
        $table->unsignedInteger('venue_type_id');
        $table->boolean('is_premium');
        $table->boolean('is_verified');
        $table->string('tripadvisor_url')->nullable();
        $table->enum('status',['Active','Inactive']);
        $table->timestamps();

        $table->foreign('client_id')->references('id')->on('clients');
        $table->foreign('venue_type_id')->references('id')->on('venue_types');
    });

  Schema::create('galleries', function (Blueprint $table) {
        $table->increments('id');
        $table->string('source_type');
        $table->unsignedInteger('source_id');
        $table->string('title');
        $table->unsignedInteger('sort_order');
        $table->enum('status',['Active','Inactive']);
        $table->timestamps();
    });
    Schema::create('media', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedInteger('gallery_id');
        $table->enum('type',['Image','Video']);
        $table->string('caption');
        $table->string('path')->nullable();
        $table->string('thumbnail')->nullable();
        $table->longText('video_code')->nullable();
        $table->boolean('is_banner_image')->default(false);
        $table->boolean('is_thumb_image')->default(false);
        $table->unsignedInteger('sort_order');
        $table->enum('status',['Active','Inactive']);
        $table->timestamps();

        $table->foreign('gallery_id')->references('id')->on('galleries');
    });

Body:
You can add

  onDelete('cascade')


问:
Wordpress does not create multiple widget instances
I thought Wordpress supports creating multiple widget instances in the same location but it looks like it does not in my code. I have created a plugin that shows recent posts. And in it I have created a widget that I want to be able to display multiple times in the same location.

```<code>class My_Recent_Posts_Widget extends WP_Widget {

    function __construct() {
        parent::__construct(
            'recent_posts', // Base ID
            esc_html__( 'Recent posts', 'text_domain' ), // Name
            array( 'description' => esc_html__( 'Display posts via widgets', 'text_domain' ), ) // Args
        );
    }
</code>```

And I register the widget like this;

```<code>function register_my_recent_posts_widget() {
    register_widget( 'My_Recent_Posts_Widget' );
}
add_action( 'widgets_init', 'register_my_recent_posts_widget' );
</code>```

The problem is if I try to place 2 instances of the same widget in the same location on the Widgets page in the admin the second widget does not show up.

答:
Try this code </p>

```<code>class My_Recent_Posts_Widget extends WP_Widget {
    public function __construct() {
        $widget_ops = array('classname' => 'my_widget_recent_entries', 'description' => esc_html__( "Your most recent Posts.",'text_domain') );
        parent::__construct('my-recent-posts', esc_html__('My Recent Posts Widget','text_domain'), $widget_ops);
        $this->alt_option_name = 'my_widget_recent_entries';
    }
</code>```

Body:
I thought Wordpress supports creating multiple widget instances in the same location but it looks like it does not in my code. I have created a plugin that shows recent posts. And in it I have created a widget that I want to be able to display multiple times in the same location.

class My_Recent_Posts_Widget extends WP_Widget {

    function __construct() {
        parent::__construct(
            'recent_posts', // Base ID
            esc_html__( 'Recent posts', 'text_domain' ), // Name
            array( 'description' => esc_html__( 'Display posts via widgets', 'text_domain' ), ) // Args
        );
    }

And I register the widget like this;

function register_my_recent_posts_widget() {
    register_widget( 'My_Recent_Posts_Widget' );
}
add_action( 'widgets_init', 'register_my_recent_posts_widget' );

The problem is if I try to place 2 instances of the same widget in the same location on the Widgets page in the admin the second widget does not show up.

Body:
Try this code

class My_Recent_Posts_Widget extends WP_Widget {
    public function __construct() {
        $widget_ops = array('classname' => 'my_widget_recent_entries', 'description' => esc_html__( "Your most recent Posts.",'text_domain') );
        parent::__construct('my-recent-posts', esc_html__('My Recent Posts Widget','text_domain'), $widget_ops);
        $this->alt_option_name = 'my_widget_recent_entries';
    }


问:
Import CSV file with mixed data types
I'm working with MATLAB for few days and I'm having difficulties to import a CSV-file to a matrix.

My problem is that my CSV-file contains almost only Strings and some integer values, so that csvread() doesn't work. csvread() only gets along with integer values.

How can I store my strings in some kind of a 2-dimensional array to have free access to each element?

Here's a sample CSV for my needs:

04;abc;def;ghj;klm;;;;;
;;;;;Test;text;0xFF;;
;;;;;asdfhsdf;dsafdsag;0x0F0F;;
```

The main thing are the empty cells and the texts within the cells.
As you see, the structure may vary.

答:
I recommend looking at the dataset array.

The dataset array is a data type that ships with Statistics Toolbox.
It is specifically designed to store hetrogeneous data in a single container.

The Statistics Toolbox demo page contains a couple vidoes that show some of the dataset array features.  The first is titled "An Introduction to Dataset Arrays". The second is titled "An Introduction to Joins".

http://www.mathworks.com/products/statistics/demos.html

Title: Import CSV file with mixed data types

Body:
I'm working with MATLAB for few days and I'm having difficulties to import a CSV-file to a matrix.

My problem is that my CSV-file contains almost only Strings and some integer values, so that csvread() doesn't work. csvread() only gets along with integer values.

How can I store my strings in some kind of a 2-dimensional array to have free access to each element?

Here's a sample CSV for my needs:

04;abc;def;ghj;klm;;;;;
;;;;;Test;text;0xFF;;
;;;;;asdfhsdf;dsafdsag;0x0F0F;;

The main thing are the empty cells and the texts within the cells.
As you see, the structure may vary.


问:
Why I'm not getting a 'Warning: Cannot modify header information - headers already sent by' as I expected to get one?
I'm using PHP 7.1.11 on a machine that runs on Windows 10 Home Single Language edition.

I'm using XAMPP server on my machine.

I'm using following browsers on this machine :

Google Chrome(Version 62.0.3202.94 (Official Build) (64-bit))

Firefox Quantum(57.0.1 (64-bit))

Opera(Version : 49.0.2725.47)

Microsoft Edge 41.16299.15.0

I know the details of header() function and how it works.

But following program is behaving in really a weird way on all of the above four web browsers. Even after sending output to the client the header() function is working.

How can this be possible?

Below is my code(It's getting redirected to the URL I mentioned) :

```<code>    <!DOCTYPE html>
    <html>
      <body>
        <p>Welcome to my website!</p><br />
        <?php
          ini_set('display_errors', 1);
          ini_set('display_startup_errors', 1);
          error_reporting(E_ALL);
          if($test) {
            echo 'Welcome to my website<br />You\'re in!';
          } else {
            header('Location: http://www.espncricinfo.com');
          }
        ?>
      </body>
    </html>
</code>```

I was expecting to get the warning 'Cannot modify header information - headers already sent by' but surprisingly it's getting redirected me to the URL http://www.espncricinfo.com/?

Why?

答:
If you are somehow using output buffering — either manually, or because your PHP is configured to automatically do this — you are still allowed to add headers, so long as the initial buffer has not been flushed.

What output buffering does is what the name hints at: put output in a buffer to be sent at a later stage, in stead of immediately outputting data. Because of this, so long as no body data of the HTTP response message has been sent, you are still able to send header data.

To check whether PHP is configured to automatically buffer output, you can do one of the following:

check the php.ini configuration file and search for the string output_buffering

var_dump( ini_get( 'output_buffering' ) );

phpinfo(); (dumps the whole configuration) and search for the string output_buffering

If output buffering is enabled, the value will either be the buffer size in bytes (if configured as such), or "On" or true, or something to that effect.

Body:
I'm using PHP 7.1.11 on a machine that runs on Windows 10 Home Single Language edition.

I'm using XAMPP server on my machine.

I'm using following browsers on this machine :

Google Chrome(Version 62.0.3202.94 (Official Build) (64-bit))

Firefox Quantum(57.0.1 (64-bit))

Opera(Version : 49.0.2725.47)

Microsoft Edge 41.16299.15.0

I know the details of header() function and how it works.

But following program is behaving in really a weird way on all of the above four web browsers. Even after sending output to the client the header() function is working.

How can this be possible?

Below is my code(It's getting redirected to the URL I mentioned) :

    <!DOCTYPE html>

Welcome to my website!

        <?php
          ini_set('display_errors', 1);
          ini_set('display_startup_errors', 1);
          error_reporting(E_ALL);
          if($test) {
            echo 'Welcome to my website
You\'re in!';
          } else {
            header('Location: http://www.espncricinfo.com');
          }
        ?>

I was expecting to get the warning 'Cannot modify header information - headers already sent by' but surprisingly it's getting redirected me to the URL http://www.espncricinfo.com/?

Why?


问:
Android - IllegalStateException : cursor.getString(idx) must not be null
I have follow all the stuffs here, but Why does cursor.getString(idx) said it must not be null? I supply all the necessary params..

here's my getfilepath:

```<code>fun getFilePathFromUri(context: Context, imageURI: Uri): String? {

        var cursor : Cursor? = null
        var result: String

        try {
            val projection = arrayOf(MediaStore.Images.Media.DATA)

            cursor = context.contentResolver.query(imageURI, projection, null, null, null)

            if (cursor == null) {
                result = imageURI.path
            } else {
                Log.d(AppConstants.TAG, "Path_img = " + imageURI)
                Log.d(AppConstants.TAG, "Path_pth = " + imageURI.path)
                Log.d(AppConstants.TAG, "Path_cursor = " + cursor)

                cursor.moveToFirst()
                val idx = cursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA)
                result = cursor.getString(idx)
            }
            return result
        } finally {
                cursor!!.close()
        }
    }
</code>```

here's the error:

```<code>12-04 14:34:44.971 2008-2008/com.xxx.project k E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.xxx.proj, PID: 2008
    java.lang.IllegalStateException: cursor.getString(idx) must not be null
    at com.xxx.proj.utils.ImageUtils$Companion.getFilePathFromUri(ImageUtils.kt:78)
    at com.xxx.proj.api.Layer.createNewLayer(Layer.java:84)
    at com.xxx.proj.dialog.EventMapCreationDialog.registerNewMap(EventMapCreationDialog.kt:266)
    at com.xxx.proj.dialog.EventMapCreationDialog.onClick(EventMapCreationDialog.kt:82)
    at android.view.View.performClick(View.java:5204)
    at android.view.View$PerformClick.run(View.java:21153)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
</code>```

答:
Per the documentation of cursor.getString():

Returns the value of the requested column as a String.

The result and whether this method throws an exception when the column
  value is null or the column type is not a string type is
  implementation-defined.

You're getting an IllegalStateException. Though broad, this generally means that a method has been invoked at a wrong/illegal time. That is, the the application or environment is not in the proper state for this method. This could mean that the parameter, cursor, or value is null.

Check the return type of the column before calling the method:

```<code>if (cursor.getType(idx) == FIELD_TYPE_STRING) {
    result = cursor.getString(idx);
}
</code>```

Body:
I have follow all the stuffs here, but Why does cursor.getString(idx) said it must not be null? I supply all the necessary params..

here's my getfilepath:

fun getFilePathFromUri(context: Context, imageURI: Uri): String? {

        var cursor : Cursor? = null
        var result: String

        try {
            val projection = arrayOf(MediaStore.Images.Media.DATA)

            cursor = context.contentResolver.query(imageURI, projection, null, null, null)

            if (cursor == null) {
                result = imageURI.path
            } else {
                Log.d(AppConstants.TAG, "Path_img = " + imageURI)
                Log.d(AppConstants.TAG, "Path_pth = " + imageURI.path)
                Log.d(AppConstants.TAG, "Path_cursor = " + cursor)

                cursor.moveToFirst()
                val idx = cursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA)
                result = cursor.getString(idx)
            }
            return result
        } finally {
                cursor!!.close()
        }
    }

here's the error:

12-04 14:34:44.971 2008-2008/com.xxx.project k E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.xxx.proj, PID: 2008
    java.lang.IllegalStateException: cursor.getString(idx) must not be null
    at com.xxx.proj.utils.ImageUtils$Companion.getFilePathFromUri(ImageUtils.kt:78)
    at com.xxx.proj.api.Layer.createNewLayer(Layer.java:84)
    at com.xxx.proj.dialog.EventMapCreationDialog.registerNewMap(EventMapCreationDialog.kt:266)
    at com.xxx.proj.dialog.EventMapCreationDialog.onClick(EventMapCreationDialog.kt:82)
    at android.view.View.performClick(View.java:5204)
    at android.view.View$PerformClick.run(View.java:21153)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Body:
Per the documentation of cursor.getString():

Returns the value of the requested column as a String.

The result and whether this method throws an exception when the column
  value is null or the column type is not a string type is
  implementation-defined.

You're getting an IllegalStateException. Though broad, this generally means that a method has been invoked at a wrong/illegal time. That is, the the application or environment is not in the proper state for this method. This could mean that the parameter, cursor, or value is null.

Check the return type of the column before calling the method:

if (cursor.getType(idx) == FIELD_TYPE_STRING) {
    result = cursor.getString(idx);
}


问:
null response usin Retrofit Library in android
Here is my JSONArray Response from Web service:

And Class Java :

```<code>public class Product {

  private int id,price,discount;
  private String name,image,description,discount_type,discount_exp;

  @SerializedName("products")
  private List<Product> products;

  public Product()
  {

  }

}
</code>```

response is null

答: The issue is that the products are contained within the data field of the JSON response. Retrofit doesn't know this so it can't deserialize the response into a Product array.

Body:
Here is my JSONArray Response from Web service:

And Class Java :

public class Product {

  private int id,price,discount;
  private String name,image,description,discount_type,discount_exp;

  @SerializedName("products")
  private List<Product> products;

  public Product()
  {

  }

}

response is null


问:
ng-repeat and ng-if to set value of td
I am trying to set td value based on condition, here is my code

```<code><td>
<span ng-init="tdValue=true;"></span>
<span ng-repeat="value in data_report" ng-if="fellow.F_Id==value.fellowship_id">
<span ng-init="tdValue=false;">{{value.Completed}}</span>
</span>
<span ng-if="tdValue">0</span>
</td>
</code>```

In the following code I am checking
1. If the condition matches set the value to value.completed
2. If not keep default value as zero

But the result i am getting is
14 0

14 is value.completes and 0 is default value (Both the values are getting printed)

答:
You Can use ternary operator</p>

```<code><td>
<span ng-init="tdValue=true;"></span>
<span ng-repeat="value in data_report" ng-if="fellow.F_Id==value.fellowship_id">
<span>{{tdValue==true?value.Completed:0}}</span>
</span>
</td>
</code>```

Title: ng-repeat and ng-if to set value of td

Body:
I am trying to set td value based on condition, here is my code

{{value.Completed}}

0

In the following code I am checking
1. If the condition matches set the value to value.completed
2. If not keep default value as zero

But the result i am getting is
14 0

14 is value.completes and 0 is default value (Both the values are getting printed)

Body:
You Can use ternary operator

<td>
<span ng-init="tdValue=true;"></span>
<span ng-repeat="value in data_report" ng-if="fellow.F_Id==value.fellowship_id">
<span>{{tdValue==true?value.Completed:0}}</span>
</span>
</td>


问:
Verify that clicks are coming from own website
I have a file go.php on my website that tracks the clicks on certain links and I want to count only the clicks that are made on my website and not on other sites that copy that link (site.com/go.php?id=). I have tried with this code

```<code>if($_SERVER[HTTP_REFERER] && !preg_match("/site\.com/", $_SERVER[HTTP_REFERER])) {
    header("Location: http:// www .site.com");
    die();
}
</code>```

but is not working properly, clicks from other sites are counted. Is there any way to count only the clicks made on my website?

EDIT: I formatted the code, but I left the spaces near http:// and www. -gore

答:
$_SERVER[HTTP_REFERER] is not worth of considering as there is no guarantee that it will be send by the user. Also its value might be modified.

You could use quite common technique that uses unique tokens:

```<code>//some-file.php:
$uniqueToken = substr(sha1(uniqid()), 0, 8); // 8-characters long unique token, eg "2fac223a"
$_SESSION['token'] = $uniqueToken;

// ...

<a href="go.php?id=123&token=<?php echo $uniqueToken ?>">Click here</a>

//go.php:
if (!isset($_GET['token']) || $_SESSION['token'] !== $_GET['token']) {
    // invalid request
    exit;
}

// ...
</code>```

Body:
I have a file go.php on my website that tracks the clicks on certain links and I want to count only the clicks that are made on my website and not on other sites that copy that link (site.com/go.php?id=). I have tried with this code

if($_SERVER[HTTP_REFERER] && !preg_match("/site\.com/", $_SERVER[HTTP_REFERER])) {
    header("Location: http:// www .site.com");
    die();
}

but is not working properly, clicks from other sites are counted. Is there any way to count only the clicks made on my website?

EDIT: I formatted the code, but I left the spaces near http:// and www. -gore

Body:
$_SERVER[HTTP_REFERER] is not worth of considering as there is no guarantee that it will be send by the user. Also its value might be modified.

You could use quite common technique that uses unique tokens:

//some-file.php:
$uniqueToken = substr(sha1(uniqid()), 0, 8); // 8-characters long unique token, eg "2fac223a"
$_SESSION['token'] = $uniqueToken;

// ...

<a href="go.php?id=123&amp;token=<?php echo $uniqueToken ?>">Click here</a>

//go.php:
if (!isset($_GET['token']) || $_SESSION['token'] !== $_GET['token']) {
    // invalid request
    exit;
}

// ...


问:
S/MIME email encryption library for iOS
I am trying to find a S/MIME email encryption library for an iOS email app I am creating in Swift. I have been having trouble trying to find a library for the encryption, has anyone had any experience with this?
I have tried OpenSSL but have run into issues with importing all the files in need in the bridging header, for example I need to use functions in pem.h but if I try import pem.h the bridging header fails to be imported altogether.

Any help with this would be greatly appreciated.

答:
I had a similar requirement. Eventually I had to import openSSL and write my own code to handle the decrypt of PKCS7. I made a small github repo which should help

https://github.com/zkrige/iOS-pkcs7-decrypt

here is the gist of the code

```<code>#include <openssl/bio.h>
#include <openssl/cms.h>
#include <openssl/err.h>
#include <openssl/pem.h>
#include <openssl/ssl.h>
#include <openssl/crypto.h>
#include <openssl/rand.h>

X509 *getCert(const char *certificate) {
    BIO *membuf = BIO_new(BIO_s_mem());
    BIO_puts(membuf, certificate);
    X509 *x509 = PEM_read_bio_X509(membuf, NULL, NULL, NULL);
    return x509;
}

EVP_PKEY *getKey(const char *privateKey) {
    BIO *membuf = BIO_new(BIO_s_mem());
    BIO_puts(membuf, privateKey);
    EVP_PKEY *key = PEM_read_bio_PrivateKey(membuf, NULL, 0, NULL);
    return key;
}

PKCS7 *getContainer(const char *encrypted) {
    BIO* membuf = BIO_new(BIO_s_mem());
    BIO_set_mem_eof_return(membuf, 0);
    BIO_puts(membuf, encrypted);
    PKCS7* pkcs7 = SMIME_read_PKCS7(membuf, NULL);
    if (!pkcs7) {
        fprintf(stderr, "error: %ld\n", ERR_get_error());
    }
    return pkcs7;
}

char *decrypt(PKCS7 *pkcs7, EVP_PKEY *pkey, X509 *cert) {

    BIO *out = BIO_new(BIO_s_mem());
    if (PKCS7_decrypt(pkcs7, pkey, cert, out, 0) != 1) {
        X509_free(cert);
        EVP_PKEY_free(pkey);
        PKCS7_free(pkcs7);
        fprintf(stderr, "Error decrypting PKCS#7 object: %ld\n", ERR_get_error());
        return NULL;
    }
    BUF_MEM* mem;
    BIO_get_mem_ptr(out, &mem);
    char *data = malloc(mem->length + 1);
    memcpy(data, mem->data, mem->length + 1);
    BIO_flush(out);
    BIO_free(out);
    return data;

}

char *decrypt_smime(const char *encrypted, const char *privateKey, const char *certificate) {

    OpenSSL_add_all_algorithms();
    ERR_load_crypto_strings();

    X509 *cert = getCert(certificate);
    if (!cert) {
        return NULL;
    }

    EVP_PKEY *pkey = getKey(privateKey);
    if (!pkey) {
        X509_free(cert);
        return NULL;
    }

    PKCS7 *pkcs7 = getContainer(encrypted);
    if (!pkcs7) {
        X509_free(cert);
        EVP_PKEY_free(pkey);
        return NULL;
    }

    char *data = decrypt(pkcs7, pkey, cert);

    X509_free(cert);
    EVP_PKEY_free(pkey);
    PKCS7_free(pkcs7);

    return data;
}
</code>```

Title: S/MIME email encryption library for iOS

Body:
I had a similar requirement. Eventually I had to import openSSL and write my own code to handle the decrypt of PKCS7. I made a small github repo which should help

https://github.com/zkrige/iOS-pkcs7-decrypt

here is the gist of the code

#include <openssl/bio.h>
#include <openssl/cms.h>
#include <openssl/err.h>
#include <openssl/pem.h>
#include <openssl/ssl.h>
#include <openssl/crypto.h>
#include <openssl/rand.h>

X509 *getCert(const char *certificate) {
    BIO *membuf = BIO_new(BIO_s_mem());
    BIO_puts(membuf, certificate);
    X509 *x509 = PEM_read_bio_X509(membuf, NULL, NULL, NULL);
    return x509;
}

EVP_PKEY *getKey(const char *privateKey) {
    BIO *membuf = BIO_new(BIO_s_mem());
    BIO_puts(membuf, privateKey);
    EVP_PKEY *key = PEM_read_bio_PrivateKey(membuf, NULL, 0, NULL);
    return key;
}

PKCS7 *getContainer(const char *encrypted) {
    BIO* membuf = BIO_new(BIO_s_mem());
    BIO_set_mem_eof_return(membuf, 0);
    BIO_puts(membuf, encrypted);
    PKCS7* pkcs7 = SMIME_read_PKCS7(membuf, NULL);
    if (!pkcs7) {
        fprintf(stderr, "error: %ld\n", ERR_get_error());
    }
    return pkcs7;
}

char *decrypt(PKCS7 *pkcs7, EVP_PKEY *pkey, X509 *cert) {

    BIO *out = BIO_new(BIO_s_mem());
    if (PKCS7_decrypt(pkcs7, pkey, cert, out, 0) != 1) {
        X509_free(cert);
        EVP_PKEY_free(pkey);
        PKCS7_free(pkcs7);
        fprintf(stderr, "Error decrypting PKCS#7 object: %ld\n", ERR_get_error());
        return NULL;
    }
    BUF_MEM* mem;
    BIO_get_mem_ptr(out, &mem);
    char *data = malloc(mem->length + 1);
    memcpy(data, mem->data, mem->length + 1);
    BIO_flush(out);
    BIO_free(out);
    return data;

}

char *decrypt_smime(const char *encrypted, const char *privateKey, const char *certificate) {

    OpenSSL_add_all_algorithms();
    ERR_load_crypto_strings();

    X509 *cert = getCert(certificate);
    if (!cert) {
        return NULL;
    }

    EVP_PKEY *pkey = getKey(privateKey);
    if (!pkey) {
        X509_free(cert);
        return NULL;
    }

    PKCS7 *pkcs7 = getContainer(encrypted);
    if (!pkcs7) {
        X509_free(cert);
        EVP_PKEY_free(pkey);
        return NULL;
    }

    char *data = decrypt(pkcs7, pkey, cert);

    X509_free(cert);
    EVP_PKEY_free(pkey);
    PKCS7_free(pkcs7);

    return data;
}


答: The $_SERVER['HTTP_REFERER'] variable is, at best optional, and even user-settable, and so is not a serious source of information. It you have previously set a cookie on another page (and you may want to use browser-side cookies, not server side $_SESSION's that can expire in a default 30 minutes) then checking for that information would tell you if they visited other pages on the site before landing on the 'go.php' page.

Title: Verify that clicks are coming from own website


答:
You must target the nested , not the repeater  itself :

```<code><td>
  <span ng-init="tdValue=true"></span>
  <span ng-repeat="value in data_report">
     <span ng-if="fellow.F_Id==value.fellowship_id" ng-init="$parent.$parent.tdValue=false">{{value.Completed}}</span>
  </span>
  <span ng-if="tdValue==true">0</span>
</td>
</code>```

Also

both ng-repeat and ng-if creates nested child scopes, thus $parent.$parent is needed to address the outer tdValue

ng-if must consist of expressions, i.e ng-if="tdValue == true"

Title: ng-repeat and ng-if to set value of td

Body:
You must target the nested <span>, not the repeater <span> itself :

<td>
  <span ng-init="tdValue=true"></span>
  <span ng-repeat="value in data_report">
     <span ng-if="fellow.F_Id==value.fellowship_id" ng-init="$parent.$parent.tdValue=false">{{value.Completed}}</span>
  </span>
  <span ng-if="tdValue==true">0</span>
</td>

Also

both ng-repeat and ng-if creates nested child scopes, thus $parent.$parent is needed to address the outer tdValue

ng-if must consist of expressions, i.e ng-if="tdValue == true"


问:
Angular4 fullcalendar version mismatch
could somebody help to fix issue.
suddenly project compile error:

```<code>ERROR in Error: Metadata version mismatch for module node_modules/ap-angular2-fullcalendar/index.d.ts, found version 4, expected 3, resolving symbol SystemModule in
</code>```

/src/app/system/system.module.ts, resolving symbol SystemModule in F:/javascript/ics-frontend-angular2/src/app/system/system.module.ts
        at Error (native)

node version

```<code>@angular/cli: 1.4.1
node: 6.9.1
</code>```

package.json
"ap-angular2-fullcalendar": "^1.3.5",
how can I fix that?

full package.json

```<code>  "dependencies": {
    "@angular/animations": "^4.3.2",
    "@angular/common": "^4.3.2",
    "@angular/compiler": "^4.3.2",
    "@angular/core": "^4.3.2",
    "@angular/forms": "^4.3.2",
    "@angular/http": "^4.3.2",
    "@angular/platform-browser": "^4.3.2",
    "@angular/platform-browser-dynamic": "^4.3.2",
    "@angular/router": "^4.3.2",
    "angular-datatables": "^4.4.0",
    "angular-select2-component": "^1.0.4",
    "angular2-fontawesome": "~0.9.0",
    "angular2-moment": "^1.7.0",
    "angular2-select": "^1.0.0-beta.3",
    "ap-angular2-fullcalendar": "^1.3.5",
    "bootstrap": "3.3.7",
    "core-js": "^2.4.1",
    "datatables.net": "^1.10.16",
    "datatables.net-dt": "^1.10.16",
    "datatables.net-responsive": "^2.2.0",
    "datatables.net-responsive-dt": "^2.2.0",
    "font-awesome": "~4.7.0",
    "jquery": "^3.2.1",
    "metismenu": "^2.5.0",
    "moment-timezone": "^0.5.13",
    "ng-pick-datetime": "^5.0.0-beta.6",
    "ng2-stomp-service": "^1.2.2",
    "ng2-toastr": "^4.1.2",
    "rxjs": "^5.4.2",
    "sockjs-client": "^1.1.4",
    "stompjs": "^2.3.3",
    "zone.js": "^0.8.16"
  },
  "devDependencies": {
    "@angular/cli": "1.4.1",
    "@angular/compiler-cli": "^4.3.2",
    "@angular/language-service": "^4.3.2",
    "@types/datatables.net": "^1.10.6",
    "@types/jasmine": "~2.5.53",
    "@types/jasminewd2": "~2.0.2",
    "@types/jquery": "^3.2.12",
    "@types/moment-timezone": "^0.5.0",
    "@types/node": "~6.0.60",
    "codelyzer": "~3.1.1",
    "jasmine-core": "~2.6.2",
    "jasmine-spec-reporter": "~4.1.0",
    "karma": "~1.7.0",
    "karma-chrome-launcher": "~2.1.1",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.1.2",
    "ts-node": "~3.2.0",
    "tslint": "~5.3.2",
    "typescript": "~2.3.3"
  }
}
</code>```

答:
I have reinstalled "ap-angular2-fullcalendar" to version "1.3.1". It's work for me.

Command:
npm install ap-angular2-fullcalendar@1.3.1

Title: Angular4 fullcalendar version mismatch

Body:
could somebody help to fix issue.
suddenly project compile error:

ERROR in Error: Metadata version mismatch for module node_modules/ap-angular2-fullcalendar/index.d.ts, found version 4, expected 3, resolving symbol SystemModule in

/src/app/system/system.module.ts, resolving symbol SystemModule in F:/javascript/ics-frontend-angular2/src/app/system/system.module.ts
        at Error (native)

node version

@angular/cli: 1.4.1
node: 6.9.1

package.json
"ap-angular2-fullcalendar": "^1.3.5",
how can I fix that?

full package.json

  "dependencies": {
    "@angular/animations": "^4.3.2",
    "@angular/common": "^4.3.2",
    "@angular/compiler": "^4.3.2",
    "@angular/core": "^4.3.2",
    "@angular/forms": "^4.3.2",
    "@angular/http": "^4.3.2",
    "@angular/platform-browser": "^4.3.2",
    "@angular/platform-browser-dynamic": "^4.3.2",
    "@angular/router": "^4.3.2",
    "angular-datatables": "^4.4.0",
    "angular-select2-component": "^1.0.4",
    "angular2-fontawesome": "~0.9.0",
    "angular2-moment": "^1.7.0",
    "angular2-select": "^1.0.0-beta.3",
    "ap-angular2-fullcalendar": "^1.3.5",
    "bootstrap": "3.3.7",
    "core-js": "^2.4.1",
    "datatables.net": "^1.10.16",
    "datatables.net-dt": "^1.10.16",
    "datatables.net-responsive": "^2.2.0",
    "datatables.net-responsive-dt": "^2.2.0",
    "font-awesome": "~4.7.0",
    "jquery": "^3.2.1",
    "metismenu": "^2.5.0",
    "moment-timezone": "^0.5.13",
    "ng-pick-datetime": "^5.0.0-beta.6",
    "ng2-stomp-service": "^1.2.2",
    "ng2-toastr": "^4.1.2",
    "rxjs": "^5.4.2",
    "sockjs-client": "^1.1.4",
    "stompjs": "^2.3.3",
    "zone.js": "^0.8.16"
  },
  "devDependencies": {
    "@angular/cli": "1.4.1",
    "@angular/compiler-cli": "^4.3.2",
    "@angular/language-service": "^4.3.2",
    "@types/datatables.net": "^1.10.6",
    "@types/jasmine": "~2.5.53",
    "@types/jasminewd2": "~2.0.2",
    "@types/jquery": "^3.2.12",
    "@types/moment-timezone": "^0.5.0",
    "@types/node": "~6.0.60",
    "codelyzer": "~3.1.1",
    "jasmine-core": "~2.6.2",
    "jasmine-spec-reporter": "~4.1.0",
    "karma": "~1.7.0",
    "karma-chrome-launcher": "~2.1.1",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.1.2",
    "ts-node": "~3.2.0",
    "tslint": "~5.3.2",
    "typescript": "~2.3.3"
  }
}


答:
Can you instead remove this ng-init="tdValue=true;" and declare it inside your controller.

$scope.tdValue=true;

Title: ng-repeat and ng-if to set value of td