问:
Does CDI @RequestScoped prevent concurrency problems?
Let us say we have a class:

```<code>@RequestScoped
public class FooService {
     private NonThreadSafeGenerator generator = new NonThreadSafeGenerator();

     public String generateId() {
          return this.generator.generateId();
     }
}
</code>```

And we run our application under some servlet-container. Will it be thread-safe? In other words, is it guaranteed that RequestScoped's bean is always visible only within single thread?

答:
Yes, it is guaranteed. Firstly you can take a look at CDI specification, at 6.3 Normal scopes. Take your time reading it, it takes a bit of time but the conclusion is that normal scoped are basically thread-bound.

Then, to really convince you, let's take a look directly to Weld codebase. All implementations of normal scoped context are based on several abstract predecessor classes. If you do a bit of digging, you can come up with two of them - AbstractBoundContext and AbstractUnboundContext. Both use ThreadLocal to implement an underlying bean store - this is what will guarantee you the thread-based behaviour.

Body:
Let us say we have a class:

@RequestScoped
public class FooService {
     private NonThreadSafeGenerator generator = new NonThreadSafeGenerator();

     public String generateId() {
          return this.generator.generateId();
     }
}

And we run our application under some servlet-container. Will it be thread-safe? In other words, is it guaranteed that RequestScoped's bean is always visible only within single thread?


来源: stackexchange

问:
Running scripts parallel in Chrome and Firefox
Here is my Test Scenario:
I have an issue while running  parallel test using Selenium Webdriver + Nunit. When I run my script using two browsers (each script with 21 test methods), i.e Chrome and Firefox, at one point my test fails in only one browser. When running the same script again it passes but I get error in some other test method. Sometimes, Chrome works perfectly fine while Firefox fails because of "Element is not visible error" but I can see the element on the screen or vice versa. At one point both the browsers would work fine and my
test passes. Moreover, the script runs perfectly fine when I execute it individually. I have no clue why this happens.
Am I lacking something in settings or my script?

答:
The philosophy behind NUnit's parallel execution feature is that it launches your tests in parallel and reports their success or failure but does nothing special to make it possible for them to run in parallel. That's up to you.

From your description, it seems likely that your failing test is not written in a way that allows two instances to run in parallel. Without seeing some code it's not possible to give specific advice but you should look for fixture members that are using common object state. If you add some sample code, then it might be possible to tell you more.

ContentLicense: CC BY-SA 3.0


问:
Plugin with id 'com.android.application' not found. I have run some modules today and suddenly have got this message
I tried File -> Invalidate caches\Restart, that didn't help me.

Log:

16:05   Gradle sync started

16:05   Gradle sync failed: Plugin with id 'com.android.application' not found.
            Consult IDE log for more details (Help | Show Log) (34s 987ms)

build.gradle application

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

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.1.2'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

android {
    compileSdkVersion 27
    buildToolsVersion "27.0.1"
    defaultConfig {
        applicationId "ru.startandroid.androidlessons"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:27.+'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
}
</code>```

答:
First, any project creates by Android Studio has two separated build.gradle files. That shouldn't cause any problems, for Gradle itself, but Android Studio might not be expecting that.

It's probably a sign that you're continuing to use the new SDK and features, but neglecting to upgrade your build tools along with it. E.g com.android.tools.build:gradle:2.1.2

You should upgrade that Gradle plugin to the latest version

https://developer.android.com/studio/releases/gradle-plugin.html

And upgrade Gradle itself, via the Gradle wrapper or install it externally to Android Studio

Body:
I tried File -> Invalidate caches\Restart, that didn't help me.

Log:

16:05   Gradle sync started

16:05   Gradle sync failed: Plugin with id 'com.android.application' not found.
            Consult IDE log for more details (Help | Show Log) (34s 987ms)

build.gradle application

apply plugin: 'com.android.application'

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.1.2'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

android {
    compileSdkVersion 27
    buildToolsVersion "27.0.1"
    defaultConfig {
        applicationId "ru.startandroid.androidlessons"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:27.+'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
}


问:
props from father component is undefined in child although it work correctly
So I pass data from father component to child and in child display it in view. Everything is working fine but when I go to consol I found out that I have issue occure there although code is working just fine and displayed data is what I expected.

Father component:

```<code><article-header :article="articles"></article-header>
</code>```

this line is in <template> tags. Article variable is value gathered in API backend http request.

In child component which is
 I use this data like so:

```<code><template>
<p>{{ article[0].title }}</p>
</template>
<script>

    export default {
        props:['article']
    }

</script>
</code>```

And it is working fine it show me my title from database exacly like I want but it also give error in browser console:

[Vue warn]: Error in render: "TypeError: Cannot read property 'title' of undefined"

found in
   --->  at src\components\no_related\article\elements\articleHeader.vue
         at src\components\no_related\article\article.vue
           at src\App.vue

Anyone know what could cause such behavior?

答:
Vue is rendering your component before your backend http request has finished, i.e. your article is still undefined. That's what's causing the entry in the console.

Once your http request has finished, Vue updates the component with the now existing data. That's what you see in the browser.

Body:
So I pass data from father component to child and in child display it in view. Everything is working fine but when I go to consol I found out that I have issue occure there although code is working just fine and displayed data is what I expected.

Father component:

this line is in <template> tags. Article variable is value gathered in API backend http request.

In child component which is
 I use this data like so:

<template>

{{ article[0].title }}

</template>

And it is working fine it show me my title from database exacly like I want but it also give error in browser console:

[Vue warn]: Error in render: "TypeError: Cannot read property 'title' of undefined"

found in
   --->  at src\components\no_related\article\elements\articleHeader.vue
         at src\components\no_related\article\article.vue
           at src\App.vue

Anyone know what could cause such behavior?


问:
Implementing inner operator for derived class
Assume I have a general Matrix class, for which I have already implemented the operator * which performs the usual matrix multiplication.

Such an operator has the following signature :

```<code>Matrix operator*(const Matrix & ) const;
</code>```

I now wish to implement another * operator for an inherited class Matrix3 that represents 3x3 matrices.

It would have the following signature :

```<code>Matrix3 operator*(const Matrix3 &) const;
</code>```

I am looking for the proper way of implementing this operator in order to re-use the code already written for the base class, and to minimize cost (i.e. copying).

答:
This should work just fine:</p>

```<code>// Either return base class
Matrix operator*(const Matrix3& other) const
{
    return Matrix::operator*(other);
}

// Or construct from a Matrix
Matrix3 operator*(const Matrix3& other) const
{
    return Matrix3(Matrix::operator*(other));
}

// Either construct the Matrix data in the Matrix3
Matrix3(const Matrix& other)
{
    // Initialize Matrix specifics
    // Initialize Matrix3 specifics
}

// Or pass the Matrix to it's base class so it can take care of the copy
Matrix3(const Matrix& other) : Matrix(other)
{
    // Initialize Matrix3 specifics
}
</code>```

Body:
Assume I have a general Matrix class, for which I have already implemented the operator * which performs the usual matrix multiplication.

Such an operator has the following signature :

Matrix operator*(const Matrix & ) const;

I now wish to implement another * operator for an inherited class Matrix3 that represents 3x3 matrices.

It would have the following signature :

Matrix3 operator*(const Matrix3 &) const;

I am looking for the proper way of implementing this operator in order to re-use the code already written for the base class, and to minimize cost (i.e. copying).

Body:
This should work just fine:

// Either return base class
Matrix operator*(const Matrix3& other) const
{
    return Matrix::operator*(other);
}

// Or construct from a Matrix
Matrix3 operator*(const Matrix3& other) const
{
    return Matrix3(Matrix::operator*(other));
}

// Either construct the Matrix data in the Matrix3
Matrix3(const Matrix& other)
{
    // Initialize Matrix specifics
    // Initialize Matrix3 specifics
}

// Or pass the Matrix to it's base class so it can take care of the copy
Matrix3(const Matrix& other) : Matrix(other)
{
    // Initialize Matrix3 specifics
}


问:
Display sum of column from table
Hey there I have a table (named vanzari) with a column named totaldeplata
i want to display the sum of all numbers from column nammed totaldeplata from current date, there is a column nammed datainregistrarii where is registered the date by this

format Dec 7, 2017 - 12:51

this is the code, i don't get any errors but it does not display the sum

```<code><?php
$query = "SELECT * FROM vanzari WHERE datainregistrarii >= CURRENT_DATE()";
 $query_run = mysql_query($query);

 $qty= 0;
 while ($num = mysql_fetch_assoc ($query_run)) {
  $qty += $num['totaldeplata'];
 }
 echo $qty;

  ?>
</code>```

Any idea why it doesn't display the sum of column from the current day?

答:
There 2 possibilities :

Using Query you can get total.
SELECT SUM(totaldeplata) FROM vanzari WHERE datainregistrarii >= CURRENT_DATE()

You can Type Cast the variable. ie: (int)$num['totaldeplata'];

     $query = "SELECT * FROM vanzari WHERE datainregistrarii >= CURRENT_DATE()";
     $query_run = mysql_query($query);

```<code> $qty= 0;
 while ($num = mysql_fetch_assoc ($query_run)) {
   $qty += (int)$num['totaldeplata'];
 }
 echo $qty;

?>
</code>```

Thanks

Title: Display sum of column from table

Body:
Hey there I have a table (named vanzari) with a column named totaldeplata
i want to display the sum of all numbers from column nammed totaldeplata from current date, there is a column nammed datainregistrarii where is registered the date by this

format Dec 7, 2017 - 12:51

this is the code, i don't get any errors but it does not display the sum

<?php
$query = "SELECT * FROM vanzari WHERE datainregistrarii >= CURRENT_DATE()";
 $query_run = mysql_query($query);

 $qty= 0;
 while ($num = mysql_fetch_assoc ($query_run)) {
  $qty += $num['totaldeplata'];
 }
 echo $qty;

  ?>

Any idea why it doesn't display the sum of column from the current day?

Body:
There 2 possibilities :

Using Query you can get total.
SELECT SUM(totaldeplata) FROM vanzari WHERE datainregistrarii >= CURRENT_DATE()

You can Type Cast the variable. ie: (int)$num['totaldeplata'];

     $query = "SELECT * FROM vanzari WHERE datainregistrarii >= CURRENT_DATE()";
     $query_run = mysql_query($query);

 $qty= 0;
 while ($num = mysql_fetch_assoc ($query_run)) {
   $qty += (int)$num['totaldeplata'];
 }
 echo $qty;

?>

Thanks


问:
Simple Mongoid associations
I'm just starting with Mongodb using Mongoid in Rails and I'm wondering how to create the simple associations between these three models:

User which has many Photos which has many Tags which has many Photos…

I don't want to embed any of the models since I want to be able to present a list of for instance all Photos or all Tags in certain views…

Thanks!

答:
Check out the Mongoid Docs on Associations. Look under "RELATIONAL ASSOCIATIONS"</p>

```<code>class User
  include Mongoid::Document
  references_many :photos
end

class Photos
  include Mongoid::Document
  referenced_in :user
end
</code>```

ContentLicense: CC BY-SA 2.5

Title: Simple Mongoid associations

Body:
Check out the Mongoid Docs on Associations. Look under "RELATIONAL ASSOCIATIONS"

class User
  include Mongoid::Document
  references_many :photos
end

class Photos
  include Mongoid::Document
  referenced_in :user
end


问:
Remove item in *ngFor from *ngFor with Angular
I would like to remove item in *ngFor from *ngFor.

When I removed the reply 'test2',

and after I added an other reply, the 'test3' became empty.

```<code><hello name="{{ name }}"></hello>

<form #form="ngForm" (ngSubmit)="submit()" ngNativeValidate class="mt-4">

  <div *ngFor="let content of contents; let indexContent = index; let firstContent = first;">

    <div *ngFor="let message of content.messages; let indexMessage = index; let firstMessage = first;">
      <table>
        <thead>
        <tr>
          <th>Id</th>
          <th>Text</th>
          <th class="text-right">Action</th>
        </tr>
        </thead>
        <tbody>
        <tr *ngFor="let reply of message.replies; let indexReply = index; let firstReply = first;">
          <td [innerHtml]='reply.id'></td>
          <td>
            <input type="text"
            id="{{indexContent}}-{{indexMessage}}-{{indexReply}}-reply-text"
            [(ngModel)]=content.messages[indexMessage].replies[indexReply].text
            name="[[indexContent]]-[{{indexMessage}}]-[{{indexReply}}]-reply-text">
            <br>
            <span [innerHtml]="contents[indexContent].messages[0].replies[indexReply].text"></span>
          </td>
          <td>
            <span (click)="message.removeReply(reply)">Remove Reply</span>
          </td>
        </tr>
        </tbody>
      </table>

      <br>

      <span (click)="message.addNewReply()">
        Add Reply
      </span>
    </div>

  </div>
  <br>
  <button type="submit" class="btn btn-primary">Save</button>
</form>
</code>```

And my message model with different function to add reply, remove reply

message.model.ts

```<code>import { Reply } from "./reply";

export class Message {

    constructor(public id: number         = 0,
                public text: string       = '',
                public replies: any[]     = []) {
    }

    public setModel(obj) {
        Object.assign(this, obj);
    }

    addReply(new_reply) {
        this.replies.push(new_reply);
    }

    addNewReply() {
        let new_reply = new Reply();

        this.replies.push(new_reply);
    }

    removeReply(reply) {
      this.replies.splice(this.replies.indexOf(reply), 1);
    }
}
</code>```

I reproduce my problem just here: Remove object from array in *ngFor in Angular

https://stackblitz.com/edit/angular-clmi7d

答:
I would use trackBy option to avoid unexpected situations

html

```<code><tr *ngFor="let reply of message.replies; trackBy: trackByFn;
                                          ^^^^^^^^^^^^^^^^^^
</code>```

app.component.ts

```<code>trackByFn(i: number) {
  return i
}
</code>```

Body:
I would like to remove item in *ngFor from *ngFor.

When I removed the reply 'test2',

and after I added an other reply, the 'test3' became empty.

<hello name="{{ name }}"></hello>

<form #form="ngForm" (ngSubmit)="submit()" ngNativeValidate class="mt-4">

          Id
          Text
          Action

            <input type="text"
            id="{{indexContent}}-{{indexMessage}}-{{indexReply}}-reply-text"
            [(ngModel)]=content.messages[indexMessage].replies[indexReply].text
            name="[[indexContent]]-[{{indexMessage}}]-[{{indexReply}}]-reply-text">

            Remove Reply

        Add Reply

  <button type="submit" class="btn btn-primary">Save</button>
</form>

And my message model with different function to add reply, remove reply

message.model.ts

import { Reply } from "./reply";

export class Message {

    constructor(public id: number         = 0,
                public text: string       = '',
                public replies: any[]     = []) {
    }

    public setModel(obj) {
        Object.assign(this, obj);
    }

    addReply(new_reply) {
        this.replies.push(new_reply);
    }

    addNewReply() {
        let new_reply = new Reply();

        this.replies.push(new_reply);
    }

    removeReply(reply) {
      this.replies.splice(this.replies.indexOf(reply), 1);
    }
}

I reproduce my problem just here: Remove object from array in *ngFor in Angular

https://stackblitz.com/edit/angular-clmi7d

Body:
I would use trackBy option to avoid unexpected situations

html

<tr *ngFor="let reply of message.replies; trackBy: trackByFn;
                                          ^^^^^^^^^^^^^^^^^^

app.component.ts

trackByFn(i: number) {
  return i
}


问:
Automatic logout in Angular 2 after few minutes
I want to implement a feature (in Angular2) i.e. After login, if a user keeps browser idle for 30 minutes, he should be logged out when coming back after 30 minutes. This has to be done by the front end only.

I am using angular CLI of Angular version 2.4

How can I implement this feature in my Angular2 application?

答:
I needed to do similar thing and created this: https://github.com/harunurhan/idlejs

It is not specifically for angular, but it is written in typescript so you get official typings.

It is simple and configurable without any dependencies. Some examples:

```<code>import { Idle } from 'idlejs/dist';

// with predefined events on `document`
const idle = new Idle()
  .whenNotInteractive()
  .within(60)
  .do(() => console.log('IDLE'))
  .start();
</code>```

You can also use custom event targets and events:

```<code>const idle = new Idle()
  .whenNot([{
    events: ['click', 'hover'],
    target: buttonEl,
  },
  {
    events: ['click', 'input'],
    target: inputEl,
  },
  ])
  .within(10)
  .do(() => called = true)
  .start();
</code>```

Body:
I needed to do similar thing and created this: https://github.com/harunurhan/idlejs

It is not specifically for angular, but it is written in typescript so you get official typings.

It is simple and configurable without any dependencies. Some examples:

import { Idle } from 'idlejs/dist';

// with predefined events on `document`
const idle = new Idle()
  .whenNotInteractive()
  .within(60)
  .do(() => console.log('IDLE'))
  .start();

You can also use custom event targets and events:

const idle = new Idle()
  .whenNot([{
    events: ['click', 'hover'],
    target: buttonEl,
  },
  {
    events: ['click', 'input'],
    target: inputEl,
  },
  ])
  .within(10)
  .do(() => called = true)
  .start();


问:
React-Redux: filtering an array of objects from state by whether their properties match other arrays from state
I have a connected React component which gets an array of Plot objects from state.

It also gets several arrays of strings from state. Like this:

```<code>function mapStateToProps(state) {
    return {
        plots: state.plots.plots,
        varietyFilter: state.plots.varietyFilter,
        regionFilter: state.plots.regionFilter,
        growerFilter: state.plots.growerFilter,
        plotNameFilter: state.plots.plotNameFilter
    };
}
</code>```

Each plot looks something like this:

```<code>{ name, variety, region, grower}
</code>```

...with each property being a string.

I want to filter the plots by whether the appropriate properties are in those filter arrays.

The standard solution is to use something like

```<code>const filteredArray = inputArray.filter( a => filterArray.indexOf(a.property)
</code>```

There are three problems I have with this approach. First, if the filter array is empty, no elements of the filtered array will pass, while I want them all to pass. Second, what happens when those filter arrays, which show up from state, have not yet been initialized? There will be an error, since indexOf in not available. Third, I want to chain these filter methods, but only chain the ones which have some sort of filter array initialized.

So far, I've come up with this:

```<code>if (this.props.plots) {
            filteredProps = this.props.plots.filter(function(plot) {
                if (!varietyFilter.indexOf) {
                    return true;
                }
                return varietyFilter.indexOf(plot.variety) > -1;
            });
        }
</code>```

That just seems to pass everything through, though. If I remove the first return statement, I get an error-the indexOf method is not there when the component first initializes.

So, two questions. First, how do I filter an array of objects for whether a given property of each object is included in an array of strings which may or may not exist in state? Second, how do I do this for a series of arrays, each corresponding to a different property of the objects in the original array?

答:
To let pass all elements if filterArray is an empty array and to prevent errors if it's null or undefined, you can do:

```<code>const filteredArray = inputArray.filter( a => (filterArray || []).length === 0 || filterArray.includes(a.property));
</code>```

The code below set an empty array as a default value of filterArray in case it's null or undefined:

```<code>filterArray || []
</code>```

And the part below do the filtering if array length is positive:

```<code>|| filterArray.includes(a.property)
</code>```

These codes are equivalents to:

```<code>const filteredArray = inputArray.filter( a => {
    if (!filterArray) {
        filterArray = [];
    }
    if (filterArray.length === 0) {
        return true;
    } else {
        return filterArray.includes(a.property);
    }
}
</code>```

Chaining mutliple filters can be done by:

```<code>var filters = [
    { prop: 'prop1', filterArray: ['abc', 'def'] },
    { prop: 'prop2', filterArray: ['abc'] },
    { prop: 'prop3', filterArray: ['abc', 'cde'] }
];

var filteredArray = [...inputArray];   // Copy inputArray

filters.forEach(filterObj => {
    filteredArray= filteredArray.filter( a => (filterObj.filterArray || []).length === 0 || filterObj.filterArray.includes(a[filterObj.prop]));
});
</code>```

Body:
I have a connected React component which gets an array of Plot objects from state.

It also gets several arrays of strings from state. Like this:

function mapStateToProps(state) {
    return {
        plots: state.plots.plots,
        varietyFilter: state.plots.varietyFilter,
        regionFilter: state.plots.regionFilter,
        growerFilter: state.plots.growerFilter,
        plotNameFilter: state.plots.plotNameFilter
    };
}

Each plot looks something like this:

{ name, variety, region, grower}

...with each property being a string.

I want to filter the plots by whether the appropriate properties are in those filter arrays.

The standard solution is to use something like

const filteredArray = inputArray.filter( a => filterArray.indexOf(a.property)

There are three problems I have with this approach. First, if the filter array is empty, no elements of the filtered array will pass, while I want them all to pass. Second, what happens when those filter arrays, which show up from state, have not yet been initialized? There will be an error, since indexOf in not available. Third, I want to chain these filter methods, but only chain the ones which have some sort of filter array initialized.

So far, I've come up with this:

if (this.props.plots) {
            filteredProps = this.props.plots.filter(function(plot) {
                if (!varietyFilter.indexOf) {
                    return true;
                }
                return varietyFilter.indexOf(plot.variety) > -1;
            });
        }

That just seems to pass everything through, though. If I remove the first return statement, I get an error-the indexOf method is not there when the component first initializes.

So, two questions. First, how do I filter an array of objects for whether a given property of each object is included in an array of strings which may or may not exist in state? Second, how do I do this for a series of arrays, each corresponding to a different property of the objects in the original array?

Body:
To let pass all elements if filterArray is an empty array and to prevent errors if it's null or undefined, you can do:

const filteredArray = inputArray.filter( a => (filterArray || []).length === 0 || filterArray.includes(a.property));

The code below set an empty array as a default value of filterArray in case it's null or undefined:

filterArray || []

And the part below do the filtering if array length is positive:

|| filterArray.includes(a.property)

These codes are equivalents to:

const filteredArray = inputArray.filter( a => {
    if (!filterArray) {
        filterArray = [];
    }
    if (filterArray.length === 0) {
        return true;
    } else {
        return filterArray.includes(a.property);
    }
}

Chaining mutliple filters can be done by:

var filters = [
    { prop: 'prop1', filterArray: ['abc', 'def'] },
    { prop: 'prop2', filterArray: ['abc'] },
    { prop: 'prop3', filterArray: ['abc', 'cde'] }
];

var filteredArray = [...inputArray];   // Copy inputArray

filters.forEach(filterObj => {
    filteredArray= filteredArray.filter( a => (filterObj.filterArray || []).length === 0 || filterObj.filterArray.includes(a[filterObj.prop]));
});


问:
I want to create links in record fields in DataTables from JSON data
I'm creating a dataTables table to use as an archive of pages for a site that produces a comic strip. On that archives page, I'd like to have the title of the comic be a link to the page of that comic strip.

Initialization:

```<code>    <script type="text/javascript" charset="utf-8">
            $(document).ready(function() {
            $('#example').dataTable( {
            "bProcessing": true,
            "sAjaxSource": "archive/archive.txt"
    } );
} );

        </script>
</code>```

HTML:

```<code><table cellpadding="0" cellspacing="0" border="0" class="display" id="example">
    <thead>
        <tr>
            <th width="20%">Author</th>

            <th width="25%">Title</th>
            <th width="25%">Episode</th>
            <th width="15%">Date</th>
            <th width="15%">Tags</th>
        </tr>
    </thead>
    <tbody>

    </tbody>

</table>
</code>```

JSON Data:

```<code>{ "aaData": [
    ["Bob","Title One","Episode 1","9/30/2010","tag1,tag2,tag3"],
    ["Bob","Title One","Episode 2","10/2/2010","tag1,tag2,tag3"],
    ["Bob","Title One","Episode 3","10/4/2010","tag1,tag2,tag3"],
    ["Bob","Title Four","Episode 1","10/8/2010","tag1,tag2,tag3"],
    ["Bob","Title Five","Episode 1","10/11/2010","tag1,tag2,tag3"],
    ["Bob","Title Six","Episode 1","10/12/2010","tag1,tag2,tag3"],
    ["Kevin","Title Seven","Episode 1","10/15/2010","tag1,tag2,tag3"],
    ["Kevin","Title Eight","Episode 1","10/17/2010","tag1,tag2,tag3"],
    ["Kevin","Title Eight","Episode 2","10/20/2010","tag1,tag2,tag3"],
    ["Kevin","Title Ten","Episode 1","10/22/2010","tag1,tag2,tag3"],
    ["Kevin","Title Eleven","Episode 1","10/23/2010","tag1,tag2,tag3"],
    ["Kevin","Title Twelve","Episode 1","10/24/2010","tag1,tag2,tag3"]
] }
</code>```

Where "Title One" or "Title Four" etc, would be a link to the page of that comic. Admittedly, I don't have much in the way of chops with dataTables, so if you might be explicit in your solution, that would be well appreciated.

答:
If using the latest version v1.10.16 can use render function callback.

```<code>$('#example').dataTable({
   "data": responseObj,
   "columns": [
      { "data": "information" },
      {
         "data": "weblink",
         "render": function(data, type, row, meta){
            if(type === 'display'){
                data = '<a href="' + row.myid + '">' + data + '</a>';
            }
            return data;
         }
      }
   ]
});
</code>```

I have just changed the render function. data refers to only current column data, while row object refers to entire row of data. Hence we can use this to get any other data for that row.

If you wnat to link based on the value of current column, can use

```<code>if(type === 'display'){
    data = '<a href="' + data + '">' + data + '</a>';
}
</code>```

Body:
I'm creating a dataTables table to use as an archive of pages for a site that produces a comic strip. On that archives page, I'd like to have the title of the comic be a link to the page of that comic strip.

Initialization:

HTML:

            Author

            Title
            Episode
            Date
            Tags

JSON Data:

{ "aaData": [
    ["Bob","Title One","Episode 1","9/30/2010","tag1,tag2,tag3"],
    ["Bob","Title One","Episode 2","10/2/2010","tag1,tag2,tag3"],
    ["Bob","Title One","Episode 3","10/4/2010","tag1,tag2,tag3"],
    ["Bob","Title Four","Episode 1","10/8/2010","tag1,tag2,tag3"],
    ["Bob","Title Five","Episode 1","10/11/2010","tag1,tag2,tag3"],
    ["Bob","Title Six","Episode 1","10/12/2010","tag1,tag2,tag3"],
    ["Kevin","Title Seven","Episode 1","10/15/2010","tag1,tag2,tag3"],
    ["Kevin","Title Eight","Episode 1","10/17/2010","tag1,tag2,tag3"],
    ["Kevin","Title Eight","Episode 2","10/20/2010","tag1,tag2,tag3"],
    ["Kevin","Title Ten","Episode 1","10/22/2010","tag1,tag2,tag3"],
    ["Kevin","Title Eleven","Episode 1","10/23/2010","tag1,tag2,tag3"],
    ["Kevin","Title Twelve","Episode 1","10/24/2010","tag1,tag2,tag3"]
] }

Where "Title One" or "Title Four" etc, would be a link to the page of that comic. Admittedly, I don't have much in the way of chops with dataTables, so if you might be explicit in your solution, that would be well appreciated.

Body:
If using the latest version v1.10.16 can use render function callback.

$('#example').dataTable({
   "data": responseObj,
   "columns": [
      { "data": "information" },
      {
         "data": "weblink",
         "render": function(data, type, row, meta){
            if(type === 'display'){
                data = '<a href="' + row.myid + '">' + data + '</a>';
            }
            return data;
         }
      }
   ]
});

I have just changed the render function. data refers to only current column data, while row object refers to entire row of data. Hence we can use this to get any other data for that row.

If you wnat to link based on the value of current column, can use

if(type === 'display'){
    data = '<a href="' + data + '">' + data + '</a>';
}


问:
Converting List<Map<String, List<String>>> to String[][]
I have a use case where I scrape some data, and for some records some keys have multiple values. The final output I want is CSV, which I have a library for, and it expects a 2-dimensional array.

So my input structure looks like List<TreeMap<String, List<String>>> (I use TreeMap to ensure stable key order), and my output needs to be String[][].

I wrote a generic transformation which calculates the number of columns for each key based on max number of values among all records, and leaves empty cells for records that have less than max values, but it turned out more complex than expected.

My question is: can it be written in a more concise/effective (but still generic) way? Especially using Java 8 streams/lambdas etc.?

Sample data and my algorithm follows below (not tested beyond sample data yet):

```<code>package org.example.import;

import java.util.*;
import java.util.stream.Collectors;

public class Main {

    public static void main(String[] args) {
        List<TreeMap<String, List<String>>> rows = new ArrayList<>();
        TreeMap<String, List<String>> row1 = new TreeMap<>();
        row1.put("Title", Arrays.asList("Product 1"));
        row1.put("Category", Arrays.asList("Wireless", "Sensor"));
        row1.put("Price",Arrays.asList("20"));
        rows.add(row1);
        TreeMap<String, List<String>> row2 = new TreeMap<>();
        row2.put("Title", Arrays.asList("Product 2"));
        row2.put("Category", Arrays.asList("Sensor"));
        row2.put("Price",Arrays.asList("35"));
        rows.add(row2);
        TreeMap<String, List<String>> row3 = new TreeMap<>();
        row3.put("Title", Arrays.asList("Product 3"));
        row3.put("Price",Arrays.asList("15"));
        rows.add(row3);

        System.out.println("Input:");
        System.out.println(rows);
        System.out.println("Output:");
        System.out.println(Arrays.deepToString(multiValueListsToArray(rows)));
    }

    public static String[][] multiValueListsToArray(List<TreeMap<String, List<String>>> rows)
    {
        Map<String, IntSummaryStatistics> colWidths = rows.
                stream().
                flatMap(m -> m.entrySet().stream()).
                collect(Collectors.groupingBy(e -> e.getKey(), Collectors.summarizingInt(e -> e.getValue().size())));
        Long tableWidth = colWidths.values().stream().mapToLong(IntSummaryStatistics::getMax).sum();
        String[][] array = new String[rows.size()][tableWidth.intValue()];
        Iterator<TreeMap<String, List<String>>> rowIt = rows.iterator(); // iterate rows
        int rowIdx = 0;
        while (rowIt.hasNext())
        {
            TreeMap<String, List<String>> row = rowIt.next();
            Iterator<String> colIt = colWidths.keySet().iterator(); // iterate columns
            int cellIdx = 0;
            while (colIt.hasNext())
            {
                String col = colIt.next();
                long colWidth = colWidths.get(col).getMax();
                for (int i = 0; i < colWidth; i++) // iterate cells within column
                    if (row.containsKey(col) && row.get(col).size() > i)
                        array[rowIdx][cellIdx + i] = row.get(col).get(i);
                cellIdx += colWidth;
            }
            rowIdx++;
        }
        return array;
    }

}
</code>```

Program output:

```<code>Input:
[{Category=[Wireless, Sensor], Price=[20], Title=[Product 1]}, {Category=[Sensor], Price=[35], Title=[Product 2]}, {Price=[15], Title=[Product 3]}]
Output:
[[Wireless, Sensor, 20, Product 1], [Sensor, null, 35, Product 2], [null, null, 15, Product 3]]
</code>```

答:
This is quite concise way to do it using some java-8 features.

This solution assumes that only the Category data is dynamic, whereas you will have always only one price and one product name.

Considering you have the initial data

```<code>// your initial complex data list
List<Map<String, List<String>>> initialList = new ArrayList<>();
</code>```

you can do

```<code>// values holder before final conversion
final List<List<String>> tempValues = new ArrayList<>();
initialList.forEach( map -> {
    // discard the keys, we do not need them... so only pack the data and put in a temporary array
    tempValues.add(new ArrayList<String>() {{
        map.forEach((key, value) -> addAll(value));          // foreach (string, list) : Map<String, List<String>>
    }});
});
// get the biggest data list; in our case, the one that contains most categories...
// this is going to be the final data size
final int maxSize = tempValues.stream().max(Comparator.comparingInt(List::size)).get().size();
// now we finally know the data size
final String[][] finalValues = new String[initialList.size()][maxSize];
// now it's time to uniform the bundle data size and shift the elements if necessary

// can't use streams/lambda as I need to keep an iteration counter
for (int i = 0; i < tempValues.size(); i++) {
    final List<String> tempEntry = tempValues.get(i);
    if (tempEntry.size() == maxSize) {
        finalValues[i] = tempEntry.toArray(finalValues[i]);
        continue;
    }
    final String[] s = new String[maxSize];
    // same shifting game as before
    final int delta = maxSize - tempEntry.size();
    for (int j = 0; j < maxSize; j++) {
        if (j < delta) continue;
        s[j] = tempEntry.get(j - delta);
    }
    finalValues[i] = s;
}
</code>```

and that's it...

You can fill and test the data with this method below (I have added some more categories...)

```<code>static void initData(List<Map<String, List<String>>> l) {
    l.add(new TreeMap<String, List<String>>() {{
        put("Category", new ArrayList<String>() {{ add("Wireless"); add("Sensor"); }});
        put("Price", new ArrayList<String>() {{ add("20"); }});
        put("Title", new ArrayList<String>() {{ add("Product 1"); }});
    }});
    l.add(new TreeMap<String, List<String>>() {{
        put("Category", new ArrayList<String>() {{ add("Sensor"); }});
        put("Price", new ArrayList<String>() {{ add("35"); }});
        put("Title", new ArrayList<String>() {{ add("Product 2"); }});
    }});
    l.add(new TreeMap<String, List<String>>() {{
        put("Price", new ArrayList<String>() {{ add("15"); }});
        put("Title", new ArrayList<String>() {{ add("Product 3"); }});
    }});
    l.add(new TreeMap<String, List<String>>() {{
        put("Category", new ArrayList<String>() {{ add("Wireless"); add("Sensor"); add("Category14"); }});
        put("Price", new ArrayList<String>() {{ add("15"); }});
        put("Title", new ArrayList<String>() {{ add("Product 3"); }});
    }});
    l.add(new TreeMap<String, List<String>>() {{
        put("Category", new ArrayList<String>() {{ add("Wireless"); add("Sensor"); add("Category541"); add("SomeCategory");}});
        put("Price", new ArrayList<String>() {{ add("15"); }});
        put("Title", new ArrayList<String>() {{ add("Product 3"); }});
    }});
}
</code>```

I'd still say, the accepted answer looks less computationally expansive, but you wanted to see some Java 8...

Body:
I have a use case where I scrape some data, and for some records some keys have multiple values. The final output I want is CSV, which I have a library for, and it expects a 2-dimensional array.

So my input structure looks like List<TreeMap<String, List<String>>> (I use TreeMap to ensure stable key order), and my output needs to be String[][].

I wrote a generic transformation which calculates the number of columns for each key based on max number of values among all records, and leaves empty cells for records that have less than max values, but it turned out more complex than expected.

My question is: can it be written in a more concise/effective (but still generic) way? Especially using Java 8 streams/lambdas etc.?

Sample data and my algorithm follows below (not tested beyond sample data yet):

package org.example.import;

import java.util.*;
import java.util.stream.Collectors;

public class Main {

    public static void main(String[] args) {
        List<TreeMap<String, List<String>>> rows = new ArrayList<>();
        TreeMap<String, List<String>> row1 = new TreeMap<>();
        row1.put("Title", Arrays.asList("Product 1"));
        row1.put("Category", Arrays.asList("Wireless", "Sensor"));
        row1.put("Price",Arrays.asList("20"));
        rows.add(row1);
        TreeMap<String, List<String>> row2 = new TreeMap<>();
        row2.put("Title", Arrays.asList("Product 2"));
        row2.put("Category", Arrays.asList("Sensor"));
        row2.put("Price",Arrays.asList("35"));
        rows.add(row2);
        TreeMap<String, List<String>> row3 = new TreeMap<>();
        row3.put("Title", Arrays.asList("Product 3"));
        row3.put("Price",Arrays.asList("15"));
        rows.add(row3);

        System.out.println("Input:");
        System.out.println(rows);
        System.out.println("Output:");
        System.out.println(Arrays.deepToString(multiValueListsToArray(rows)));
    }

    public static String[][] multiValueListsToArray(List<TreeMap<String, List<String>>> rows)
    {
        Map<String, IntSummaryStatistics> colWidths = rows.
                stream().
                flatMap(m -> m.entrySet().stream()).
                collect(Collectors.groupingBy(e -> e.getKey(), Collectors.summarizingInt(e -> e.getValue().size())));
        Long tableWidth = colWidths.values().stream().mapToLong(IntSummaryStatistics::getMax).sum();
        String[][] array = new String[rows.size()][tableWidth.intValue()];
        Iterator<TreeMap<String, List<String>>> rowIt = rows.iterator(); // iterate rows
        int rowIdx = 0;
        while (rowIt.hasNext())
        {
            TreeMap<String, List<String>> row = rowIt.next();
            Iterator<String> colIt = colWidths.keySet().iterator(); // iterate columns
            int cellIdx = 0;
            while (colIt.hasNext())
            {
                String col = colIt.next();
                long colWidth = colWidths.get(col).getMax();
                for (int i = 0; i < colWidth; i++) // iterate cells within column
                    if (row.containsKey(col) && row.get(col).size() > i)
                        array[rowIdx][cellIdx + i] = row.get(col).get(i);
                cellIdx += colWidth;
            }
            rowIdx++;
        }
        return array;
    }

}

Program output:

Input:
[{Category=[Wireless, Sensor], Price=[20], Title=[Product 1]}, {Category=[Sensor], Price=[35], Title=[Product 2]}, {Price=[15], Title=[Product 3]}]
Output:
[[Wireless, Sensor, 20, Product 1], [Sensor, null, 35, Product 2], [null, null, 15, Product 3]]

Body:
This is quite concise way to do it using some java-8 features.

This solution assumes that only the Category data is dynamic, whereas you will have always only one price and one product name.

Considering you have the initial data

// your initial complex data list
List<Map<String, List<String>>> initialList = new ArrayList<>();

you can do

// values holder before final conversion
final List<List<String>> tempValues = new ArrayList<>();
initialList.forEach( map -> {
    // discard the keys, we do not need them... so only pack the data and put in a temporary array
    tempValues.add(new ArrayList<String>() {{
        map.forEach((key, value) -> addAll(value));          // foreach (string, list) : Map<String, List<String>>
    }});
});
// get the biggest data list; in our case, the one that contains most categories...
// this is going to be the final data size
final int maxSize = tempValues.stream().max(Comparator.comparingInt(List::size)).get().size();
// now we finally know the data size
final String[][] finalValues = new String[initialList.size()][maxSize];
// now it's time to uniform the bundle data size and shift the elements if necessary

// can't use streams/lambda as I need to keep an iteration counter
for (int i = 0; i < tempValues.size(); i++) {
    final List<String> tempEntry = tempValues.get(i);
    if (tempEntry.size() == maxSize) {
        finalValues[i] = tempEntry.toArray(finalValues[i]);
        continue;
    }
    final String[] s = new String[maxSize];
    // same shifting game as before
    final int delta = maxSize - tempEntry.size();
    for (int j = 0; j < maxSize; j++) {
        if (j < delta) continue;
        s[j] = tempEntry.get(j - delta);
    }
    finalValues[i] = s;
}

and that's it...

You can fill and test the data with this method below (I have added some more categories...)

static void initData(List<Map<String, List<String>>> l) {
    l.add(new TreeMap<String, List<String>>() {{
        put("Category", new ArrayList<String>() {{ add("Wireless"); add("Sensor"); }});
        put("Price", new ArrayList<String>() {{ add("20"); }});
        put("Title", new ArrayList<String>() {{ add("Product 1"); }});
    }});
    l.add(new TreeMap<String, List<String>>() {{
        put("Category", new ArrayList<String>() {{ add("Sensor"); }});
        put("Price", new ArrayList<String>() {{ add("35"); }});
        put("Title", new ArrayList<String>() {{ add("Product 2"); }});
    }});
    l.add(new TreeMap<String, List<String>>() {{
        put("Price", new ArrayList<String>() {{ add("15"); }});
        put("Title", new ArrayList<String>() {{ add("Product 3"); }});
    }});
    l.add(new TreeMap<String, List<String>>() {{
        put("Category", new ArrayList<String>() {{ add("Wireless"); add("Sensor"); add("Category14"); }});
        put("Price", new ArrayList<String>() {{ add("15"); }});
        put("Title", new ArrayList<String>() {{ add("Product 3"); }});
    }});
    l.add(new TreeMap<String, List<String>>() {{
        put("Category", new ArrayList<String>() {{ add("Wireless"); add("Sensor"); add("Category541"); add("SomeCategory");}});
        put("Price", new ArrayList<String>() {{ add("15"); }});
        put("Title", new ArrayList<String>() {{ add("Product 3"); }});
    }});
}

I'd still say, the accepted answer looks less computationally expansive, but you wanted to see some Java 8...


问:
Using Multiple Kinect v2 on one PC
I'm currently attempting to use multiple Kinect v2.0s as part of my dissertation. I've looked around on the subject and I'm aware of the issue with usb bandwidth so the two Kinects I'm currently using are on different usb controllers.

The issue I'm having is that as part of the GetDefault() function (2.0 SDK) it, as the name suggests, simply gets the default Kinect. Is there a way of either determining which Kinect to 'get' or determining which Kinect is the 'default'? (I know the SDK only allows for one but I'm exploring the idea of having a separate application handling each Kinect).

Thanks in advance for any input.

答: Kinect for windows are only supported for virtual machines, (not including kinect for xbox one and kinect for 360 with adapters) </p>

Title: Using Multiple Kinect v2 on one PC


问:
Multi select drop down
I am writing code for multi select using selenium(java) where i need the following task to be performed :

select multiple options in drop down

to click on button first selected which will print the first selected option from drop down.

to click on button get all selected which will print the all selected options in order .

I have this code which returns me undefined as a result for 2nd task.

```<code>public class MultipleSlectList {

    public static WebDriver driver ;

    @BeforeTest
    public void startbrowser () throws Exception {
        System.out.println("launching browser");
        System.setProperty("webdriver.gecko.driver", "H:\\Selenium3\\geckodriver-v0.19.1-win32\\geckodriver.exe");
        driver = new FirefoxDriver();
        driver.get("http://www.seleniumeasy.com/test/basic-select-dropdown-demo.html");

    }

    @Test

    public void selectlist () throws Exception {

        WebElement ele1 = driver.findElement(By.id("multi-select"));
        Select se= new Select(ele1);
        se.selectByValue("New Jersey");
        Thread.sleep(2000);
        se.selectByValue("Texas");
        Thread.sleep(2000);
        se.selectByValue("Florida");
        Thread.sleep(2000);
        //Thread.sleep(10000);
        WebElement btn1= driver.findElement(By.id("printMe"));
        btn1.click(); // it is supposed to return New Jersy
        WebElement firstOption = se.getFirstSelectedOption();
        System.out.println("The First selected option is::" +firstOption.getText());
        List <WebElement> oSize = se.getAllSelectedOptions();

        int iListSize = oSize.size();
        // Setting up the loop to print all the options
        for (int i = 0; i < iListSize; i++)
        {
            // Storing the value of the option
            String sValue = oSize.get(i).getText();
            // Printing the stored value
            System.out.println(sValue);
        }
    }
}
</code>```

Please help me to proceed further.

I have tried with jquery as well but no luck .The result is same as "undefined" in both case .

Thanks !

答:
Steps to select all dropdown options:

Find the SELECT WebElement by webdriver.

Create Select class which is used to operate dropdown list.

Get all options list in the dropdown list.

Loop the options list, get each option value and use

Select.selectByValue(optionValue) to select it.

Then all the dropdown option has been selected.

Below article has the code example to implement above scenario.

http://www.dev2qa.com/select-dropdown-list-selenium-webdriver/

Title: Multi select drop down

Body:
I am writing code for multi select using selenium(java) where i need the following task to be performed :

select multiple options in drop down

to click on button first selected which will print the first selected option from drop down.

to click on button get all selected which will print the all selected options in order .

I have this code which returns me undefined as a result for 2nd task.

public class MultipleSlectList {

    public static WebDriver driver ;

    @BeforeTest
    public void startbrowser () throws Exception {
        System.out.println("launching browser");
        System.setProperty("webdriver.gecko.driver", "H:\\Selenium3\\geckodriver-v0.19.1-win32\\geckodriver.exe");
        driver = new FirefoxDriver();
        driver.get("http://www.seleniumeasy.com/test/basic-select-dropdown-demo.html");

    }

    @Test

    public void selectlist () throws Exception {

        WebElement ele1 = driver.findElement(By.id("multi-select"));
        Select se= new Select(ele1);
        se.selectByValue("New Jersey");
        Thread.sleep(2000);
        se.selectByValue("Texas");
        Thread.sleep(2000);
        se.selectByValue("Florida");
        Thread.sleep(2000);
        //Thread.sleep(10000);
        WebElement btn1= driver.findElement(By.id("printMe"));
        btn1.click(); // it is supposed to return New Jersy
        WebElement firstOption = se.getFirstSelectedOption();
        System.out.println("The First selected option is::" +firstOption.getText());
        List <WebElement> oSize = se.getAllSelectedOptions();

        int iListSize = oSize.size();
        // Setting up the loop to print all the options
        for (int i = 0; i < iListSize; i++)
        {
            // Storing the value of the option
            String sValue = oSize.get(i).getText();
            // Printing the stored value
            System.out.println(sValue);
        }
    }
}

Please help me to proceed further.

I have tried with jquery as well but no luck .The result is same as "undefined" in both case .

Thanks !


问:
jQuery - run a function when DOM changes
I've been using livequery so far which works, but it makes the page browsing seem really slow.
So I'm trying to find a alternative solution for this.

I'm attaching a function that runs some ajax on elements with a certain class, like:

```<code>$(".blah").each(function(){
  $.ajax({
      ...
      success: function(data) {
        $(this).removeClass(".blah");
        // do other stuff
      }
  });
});
</code>```

Now I have several events hooked on different elements that can append html in the DOM, like:

```<code>$(".button").click(function(){
  $.ajax({
      ...
      success: function(data) {
        $(this).append(data);
        // here, new elements with ".blah" class could be inserted in the DOM
        // the event above won't be fired...
      }
  });
});
</code>```

How could I make so the first ajax function above runs when the DOM gets updated in the other events?

Update:

I also found this plugin:
http://www.thunderguy.com/semicolon/2007/08/14/elementready-jquery-plugin/

Do you think it would be a better solution? From a quick look it seems to, because it allows you to set a "polling" interval, which might decrease cpu usage if you set it to 1 sec or somehting. I'm testing it now :)

Update 2:

Unfortunately it only works with element IDs for some weird reason :(

答:
Most major browsers (but sadly not IE <= 8) support DOM mutation events (also see MDN). If you're interested in just nodes being added to the DOM, use the DOMNodeInserted event. If you want to be informed about any DOM change, use the catch-all DOMSubtreeModified event.

For example:

```<code>document.addEventListener("DOMNodeInserted", function(evt) {
    alert("Node inserted. Parent of inserted node: " + evt.relatedNode.nodeName);
}, false);

document.body.appendChild( document.createElement("div") );
</code>```

Update 13 December 2012

DOM mutation events are now deprecated and browsers are gradually moving to mutation observers. The most sensible strategy at the moment seems to be to use mutation observers and fall back to mutation events.

Body:
I've been using livequery so far which works, but it makes the page browsing seem really slow.
So I'm trying to find a alternative solution for this.

I'm attaching a function that runs some ajax on elements with a certain class, like:

$(".blah").each(function(){
  $.ajax({
      ...
      success: function(data) {
        $(this).removeClass(".blah");
        // do other stuff
      }
  });
});

Now I have several events hooked on different elements that can append html in the DOM, like:

$(".button").click(function(){
  $.ajax({
      ...
      success: function(data) {
        $(this).append(data);
        // here, new elements with ".blah" class could be inserted in the DOM
        // the event above won't be fired...
      }
  });
});

How could I make so the first ajax function above runs when the DOM gets updated in the other events?

Update:

I also found this plugin:
http://www.thunderguy.com/semicolon/2007/08/14/elementready-jquery-plugin/

Do you think it would be a better solution? From a quick look it seems to, because it allows you to set a "polling" interval, which might decrease cpu usage if you set it to 1 sec or somehting. I'm testing it now :)

Update 2:

Unfortunately it only works with element IDs for some weird reason :(

Body:
Most major browsers (but sadly not IE <= 8) support DOM mutation events (also see MDN). If you're interested in just nodes being added to the DOM, use the DOMNodeInserted event. If you want to be informed about any DOM change, use the catch-all DOMSubtreeModified event.

For example:

document.addEventListener("DOMNodeInserted", function(evt) {
    alert("Node inserted. Parent of inserted node: " + evt.relatedNode.nodeName);
}, false);

document.body.appendChild( document.createElement("div") );

Update 13 December 2012

DOM mutation events are now deprecated and browsers are gradually moving to mutation observers. The most sensible strategy at the moment seems to be to use mutation observers and fall back to mutation events.


问:
With Tensorflow, 2 class classification using Neural Network
I'm trying 2 class classification of images by neural network using Tensorflow.

I want to extract 1000 pixels randomly.
However, I am in trouble with error:

```<code>"logits = inference(images_placeholder, keep_prob)
     File "train5.py", line 83, in inference
        list = random.sample(x_image(IMAGE_PIXELS),SAMPLE_PIXELS)

TypeError: 'Tensor' object is not callable"
</code>```

Please tell me what should I do.

I will attach a code below.

```<code>import sys
sys.path.append('/usr/local/opt/opencv3/lib/python3.5.4/site-packages')
import cv2
import numpy as np
import tensorflow as tf
import tensorflow.python.platform
import tensorboard as tb
import os
import math
import time
import random
start_time = time.time()

# TensorBoard output information directory
log_dir = '/tmp/data1'  #tensorboard --logdir=/tmp/data1

#directory delete and reconstruction
if tf.gfile.Exists(log_dir):
    tf.gfile.DeleteRecursively(log_dir)
tf.gfile.MakeDirs(log_dir)

# Reserve memory
config = tf.ConfigProto(
   gpu_options=tf.GPUOptions(allow_growth=True))
sess = sess = tf.Session(config=config)

NUM_CLASSES = 2
IMAGE_SIZE_x = 1024
IMAGE_SIZE_y = 768
IMAGE_CHANNELS = 1
IMAGE_PIXELS = IMAGE_SIZE_x*IMAGE_SIZE_y*IMAGE_CHANNELS
SAMPLE_PIXELS = 1000

flags = tf.app.flags
FLAGS = flags.FLAGS
flags.DEFINE_string('train', 'train.txt', 'File name of train data')
flags.DEFINE_string('test', 'test.txt', 'File name of train data')
flags.DEFINE_string('image_dir', 'trdata', 'Directory of images')
flags.DEFINE_string('train_dir', '/tmp/data', 'Directory to put the training data.')
flags.DEFINE_integer('max_steps', 20000, 'Number of steps to run trainer.')
flags.DEFINE_integer('batch_size', 10, 'Batch size'
                     'Must divide evenly into the dataset sizes.')
flags.DEFINE_float('learning_rate', 1e-5, 'Initial learning rate.')

def inference(images_placeholder, keep_prob):
    """ Function to create predictive model

   argument:
        images_placeholder: image placeholder
        keep_prob: dropout rate placeholder

    Return:
        y_conv:
    """
    # Initialie with normal distribution with weight of 0.1
    def weight_variable(shape):
      initial = tf.truncated_normal(shape, stddev=0.1)
      return tf.Variable(initial)

    # Initialized with normal distribution with bias of 0.1
    def bias_variable(shape):
      initial = tf.constant(0.1, shape=shape)
      return tf.Variable(initial)

    # Reshape input
    x_image = images_placeholder
    # ramdom sumpling pixels
    list = random.sample(x_image(IMAGE_PIXELS),SAMPLE_PIXELS)
    x_list = [samples[i] for i in list]

    # Input
    with tf.name_scope('fc1') as scope:
        W_fc1 = weight_variable([x_list,10])
        b_fc1 = bias_variable([10])
        h_fc1 = tf.nn.relu(tf.matmul(x_image,W_fc1) + b_fc1)

    # Affine1
    with tf.name_scope('fc2') as scope:
        W_fc2 = weight_variable([10,10])
        b_fc2 = bias_variable([10])
        h_fc2 = tf.nn.relu(tf.matmul(h_fc1,W_fc2) + b_fc2)

    # Affine2
    with tf.name_scope('fc3') as scope:
        W_fc3 = weight_variable([10,10])
        b_fc3 = bias_variable([10])
        h_fc3 = tf.nn.relu(tf.matmul(h_fc2,W_fc3) + b_fc3)

    # Affine3
    with tf.name_scope('fc4') as scope:
        W_fc4 = weight_variable([10,10])
        b_fc4 = bias_variable([10])
        h_fc4 = tf.nn.relu(tf.matmul(h_fc3,W_fc4) + b_fc4)
    # Affine4
    with tf.name_scope('fc5') as scope:
        W_fc5 = weight_variable([10,2])
        b_fc5 = bias_variable([2])

    # softmax regression
    with tf.name_scope('softmax') as scope:
        y_out=tf.nn.softmax(tf.matmul(h_fc4, W_fc5) + b_fc5)

    # return
    return y_out

def loss(logits, labels):
    """ loss function

    引数:
        logits: logit tensor, float - [batch_size, NUM_CLASSES]
        labels: labrl tensor, int32 - [batch_size, NUM_CLASSES]

    返り値:
        cross_entropy:tensor, float

    """
    # cross entropy
    cross_entropy = -tf.reduce_sum(labels*tf.log(tf.clip_by_value(logits,1e-10,1.0)))
    # TensorBoard
    tf.summary.scalar("cross_entropy", cross_entropy)
    return cross_entropy

def training(loss, learning_rate):

    #Adam
    train_step = tf.train.AdamOptimizer(learning_rate).minimize(loss)
    return train_step

def accuracy(logits, labels):

    correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(labels, 1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
    tf.summary.scalar("accuracy", accuracy)
    return accuracy

if __name__ == '__main__':
    f = open(FLAGS.train, 'r')
    # array data
    train_image = []
    train_label = []
    for line in f:
        # Separate space and remove newlines
        line = line.rstrip()
        l = line.split()
        # Load data and resize
        img = cv2.imread(FLAGS.image_dir + '/' + l[0])
        img = cv2.resize(img, (IMAGE_SIZE_x, IMAGE_SIZE_y))
        #transrate grayscale
        img_gry = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        # transrate one row and 0-1 float
        train_image.append(img_gry.flatten().astype(np.float32)/255.0)
        # Prepare with label 1-of-k method
        tmp = np.zeros(NUM_CLASSES)
        tmp[int(l[1])] = 1
        train_label.append(tmp)
    # transrate numpy
    train_image = np.asarray(train_image)
    train_label = np.asarray(train_label)
    f.close()

    f = open(FLAGS.test, 'r')
    test_image = []
    test_label = []
    for line in f:
        line = line.rstrip()
        l = line.split()
        img = cv2.imread(FLAGS.image_dir + '/' + l[0])
        img = cv2.resize(img, (IMAGE_SIZE_x, IMAGE_SIZE_y))
        #transrate grayscale
        img_gry = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        #  transrate one row and 0-1 float
        test_image.append(img_gry.flatten().astype(np.float32)/255.0)
        tmp = np.zeros(NUM_CLASSES)
        tmp[int(l[1])] = 1
        test_label.append(tmp)
    test_image = np.asarray(test_image)
    test_label = np.asarray(test_label)
    f.close()

    with tf.Graph().as_default():
        # Put the image Tensor
        images_placeholder = tf.placeholder("float", shape=(None, IMAGE_PIXELS))
        # Put the label Tensor
        labels_placeholder = tf.placeholder("float", shape=(None, NUM_CLASSES))
        # Put dropout rate Tensor
        keep_prob = tf.placeholder("float")
        # Load inference() and make model
        logits = inference(images_placeholder, keep_prob)
        # Load loss() and calculate loss
        loss_value = loss(logits, labels_placeholder)
        # Load training() and train
        train_op = training(loss_value, FLAGS.learning_rate)
        # calculate accuracy
        acc = accuracy(logits, labels_placeholder)
        # save
        saver = tf.train.Saver()
        # Make Session
        sess = tf.Session()
        # Initialize variable
        sess.run(tf.global_variables_initializer())
        # TensorBoard
        summary_op = tf.summary.merge_all()
        summary_writer = tf.summary.FileWriter(FLAGS.train_dir, sess.graph)

# Start training
for step in range(FLAGS.max_steps):
    for i in range(int(len(train_image)/FLAGS.batch_size)):
        batch = FLAGS.batch_size*i
        sess.run(train_op, feed_dict={
          images_placeholder: train_image[batch:batch+FLAGS.batch_size],
          labels_placeholder: train_label[batch:batch+FLAGS.batch_size],
          keep_prob: 0.5})

    # Accuracy calculation for every steps
    train_accuracy = sess.run(acc, feed_dict={
        images_placeholder: train_image,
        labels_placeholder: train_label,
        keep_prob: 1.0})
    print("step %d, training accuracy %g" %(step, train_accuracy))

    # Added value to be displayed in Tensorflow every 1step
    summary_str = sess.run(summary_op, feed_dict={
        images_placeholder: train_image,
        labels_placeholder: train_label,
        keep_prob: 1.0})
    summary_writer.add_summary(summary_str, step)

    # Display accuracy on test data after training
    print("        test accuracy     %g"%sess.run(acc, feed_dict={
        images_placeholder: test_image,
        labels_placeholder: test_label,
        keep_prob: 1.0}))

    duration = time.time() - start_time

    print('%.3f sec' %duration)

    # Save model
    save_path = saver.save(sess, os.getcwd() + "\\model.ckpt")
</code>```

答:
The error is this:

images_placeholder = tf.placeholder("float", shape=(None, IMAGE_PIXELS))
...
x_image = images_placeholder
list = random.sample(x_image(IMAGE_PIXELS),SAMPLE_PIXELS)
```

x_image, just like images_placeholder is a variable node, so x_image(...) doesn't make sense and obviously leads to an error "TypeError: 'Tensor' object is not callable".

I assume you're trying to sample SAMPLE_PIXELS from each image in a batch. Note that random.sample won't work here, because x_image is a symbolic variable, its value is only known during the session. You have to use tf.boolean_mask with a random mask in order to select random pixels from the image.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying 2 class classification of images by neural network using Tensorflow.

I want to extract 1000 pixels randomly.
However, I am in trouble with error:

"logits = inference(images_placeholder, keep_prob)
     File "train5.py", line 83, in inference
        list = random.sample(x_image(IMAGE_PIXELS),SAMPLE_PIXELS)

TypeError: 'Tensor' object is not callable"

Please tell me what should I do.

I will attach a code below.

import sys
sys.path.append('/usr/local/opt/opencv3/lib/python3.5.4/site-packages')
import cv2
import numpy as np
import tensorflow as tf
import tensorflow.python.platform
import tensorboard as tb
import os
import math
import time
import random
start_time = time.time()

# TensorBoard output information directory
log_dir = '/tmp/data1'  #tensorboard --logdir=/tmp/data1

#directory delete and reconstruction
if tf.gfile.Exists(log_dir):
    tf.gfile.DeleteRecursively(log_dir)
tf.gfile.MakeDirs(log_dir)

# Reserve memory
config = tf.ConfigProto(
   gpu_options=tf.GPUOptions(allow_growth=True))
sess = sess = tf.Session(config=config)

NUM_CLASSES = 2
IMAGE_SIZE_x = 1024
IMAGE_SIZE_y = 768
IMAGE_CHANNELS = 1
IMAGE_PIXELS = IMAGE_SIZE_x*IMAGE_SIZE_y*IMAGE_CHANNELS
SAMPLE_PIXELS = 1000

flags = tf.app.flags
FLAGS = flags.FLAGS
flags.DEFINE_string('train', 'train.txt', 'File name of train data')
flags.DEFINE_string('test', 'test.txt', 'File name of train data')
flags.DEFINE_string('image_dir', 'trdata', 'Directory of images')
flags.DEFINE_string('train_dir', '/tmp/data', 'Directory to put the training data.')
flags.DEFINE_integer('max_steps', 20000, 'Number of steps to run trainer.')
flags.DEFINE_integer('batch_size', 10, 'Batch size'
                     'Must divide evenly into the dataset sizes.')
flags.DEFINE_float('learning_rate', 1e-5, 'Initial learning rate.')

def inference(images_placeholder, keep_prob):
    """ Function to create predictive model

   argument:
        images_placeholder: image placeholder
        keep_prob: dropout rate placeholder

    Return:
        y_conv:
    """
    # Initialie with normal distribution with weight of 0.1
    def weight_variable(shape):
      initial = tf.truncated_normal(shape, stddev=0.1)
      return tf.Variable(initial)

    # Initialized with normal distribution with bias of 0.1
    def bias_variable(shape):
      initial = tf.constant(0.1, shape=shape)
      return tf.Variable(initial)

    # Reshape input
    x_image = images_placeholder
    # ramdom sumpling pixels
    list = random.sample(x_image(IMAGE_PIXELS),SAMPLE_PIXELS)
    x_list = [samples[i] for i in list]

    # Input
    with tf.name_scope('fc1') as scope:
        W_fc1 = weight_variable([x_list,10])
        b_fc1 = bias_variable([10])
        h_fc1 = tf.nn.relu(tf.matmul(x_image,W_fc1) + b_fc1)

    # Affine1
    with tf.name_scope('fc2') as scope:
        W_fc2 = weight_variable([10,10])
        b_fc2 = bias_variable([10])
        h_fc2 = tf.nn.relu(tf.matmul(h_fc1,W_fc2) + b_fc2)

    # Affine2
    with tf.name_scope('fc3') as scope:
        W_fc3 = weight_variable([10,10])
        b_fc3 = bias_variable([10])
        h_fc3 = tf.nn.relu(tf.matmul(h_fc2,W_fc3) + b_fc3)

    # Affine3
    with tf.name_scope('fc4') as scope:
        W_fc4 = weight_variable([10,10])
        b_fc4 = bias_variable([10])
        h_fc4 = tf.nn.relu(tf.matmul(h_fc3,W_fc4) + b_fc4)
    # Affine4
    with tf.name_scope('fc5') as scope:
        W_fc5 = weight_variable([10,2])
        b_fc5 = bias_variable([2])

    # softmax regression
    with tf.name_scope('softmax') as scope:
        y_out=tf.nn.softmax(tf.matmul(h_fc4, W_fc5) + b_fc5)

    # return
    return y_out

def loss(logits, labels):
    """ loss function

    引数:
        logits: logit tensor, float - [batch_size, NUM_CLASSES]
        labels: labrl tensor, int32 - [batch_size, NUM_CLASSES]

    返り値:
        cross_entropy:tensor, float

    """
    # cross entropy
    cross_entropy = -tf.reduce_sum(labels*tf.log(tf.clip_by_value(logits,1e-10,1.0)))
    # TensorBoard
    tf.summary.scalar("cross_entropy", cross_entropy)
    return cross_entropy

def training(loss, learning_rate):

    #Adam
    train_step = tf.train.AdamOptimizer(learning_rate).minimize(loss)
    return train_step

def accuracy(logits, labels):

    correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(labels, 1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
    tf.summary.scalar("accuracy", accuracy)
    return accuracy

if __name__ == '__main__':
    f = open(FLAGS.train, 'r')
    # array data
    train_image = []
    train_label = []
    for line in f:
        # Separate space and remove newlines
        line = line.rstrip()
        l = line.split()
        # Load data and resize
        img = cv2.imread(FLAGS.image_dir + '/' + l[0])
        img = cv2.resize(img, (IMAGE_SIZE_x, IMAGE_SIZE_y))
        #transrate grayscale
        img_gry = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        # transrate one row and 0-1 float
        train_image.append(img_gry.flatten().astype(np.float32)/255.0)
        # Prepare with label 1-of-k method
        tmp = np.zeros(NUM_CLASSES)
        tmp[int(l[1])] = 1
        train_label.append(tmp)
    # transrate numpy
    train_image = np.asarray(train_image)
    train_label = np.asarray(train_label)
    f.close()

    f = open(FLAGS.test, 'r')
    test_image = []
    test_label = []
    for line in f:
        line = line.rstrip()
        l = line.split()
        img = cv2.imread(FLAGS.image_dir + '/' + l[0])
        img = cv2.resize(img, (IMAGE_SIZE_x, IMAGE_SIZE_y))
        #transrate grayscale
        img_gry = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        #  transrate one row and 0-1 float
        test_image.append(img_gry.flatten().astype(np.float32)/255.0)
        tmp = np.zeros(NUM_CLASSES)
        tmp[int(l[1])] = 1
        test_label.append(tmp)
    test_image = np.asarray(test_image)
    test_label = np.asarray(test_label)
    f.close()

    with tf.Graph().as_default():
        # Put the image Tensor
        images_placeholder = tf.placeholder("float", shape=(None, IMAGE_PIXELS))
        # Put the label Tensor
        labels_placeholder = tf.placeholder("float", shape=(None, NUM_CLASSES))
        # Put dropout rate Tensor
        keep_prob = tf.placeholder("float")
        # Load inference() and make model
        logits = inference(images_placeholder, keep_prob)
        # Load loss() and calculate loss
        loss_value = loss(logits, labels_placeholder)
        # Load training() and train
        train_op = training(loss_value, FLAGS.learning_rate)
        # calculate accuracy
        acc = accuracy(logits, labels_placeholder)
        # save
        saver = tf.train.Saver()
        # Make Session
        sess = tf.Session()
        # Initialize variable
        sess.run(tf.global_variables_initializer())
        # TensorBoard
        summary_op = tf.summary.merge_all()
        summary_writer = tf.summary.FileWriter(FLAGS.train_dir, sess.graph)

# Start training
for step in range(FLAGS.max_steps):
    for i in range(int(len(train_image)/FLAGS.batch_size)):
        batch = FLAGS.batch_size*i
        sess.run(train_op, feed_dict={
          images_placeholder: train_image[batch:batch+FLAGS.batch_size],
          labels_placeholder: train_label[batch:batch+FLAGS.batch_size],
          keep_prob: 0.5})

    # Accuracy calculation for every steps
    train_accuracy = sess.run(acc, feed_dict={
        images_placeholder: train_image,
        labels_placeholder: train_label,
        keep_prob: 1.0})
    print("step %d, training accuracy %g" %(step, train_accuracy))

    # Added value to be displayed in Tensorflow every 1step
    summary_str = sess.run(summary_op, feed_dict={
        images_placeholder: train_image,
        labels_placeholder: train_label,
        keep_prob: 1.0})
    summary_writer.add_summary(summary_str, step)

    # Display accuracy on test data after training
    print("        test accuracy     %g"%sess.run(acc, feed_dict={
        images_placeholder: test_image,
        labels_placeholder: test_label,
        keep_prob: 1.0}))

    duration = time.time() - start_time

    print('%.3f sec' %duration)

    # Save model
    save_path = saver.save(sess, os.getcwd() + "\\model.ckpt")

Body:
The error is this:

images_placeholder = tf.placeholder("float", shape=(None, IMAGE_PIXELS))
...
x_image = images_placeholder
list = random.sample(x_image(IMAGE_PIXELS),SAMPLE_PIXELS)

x_image, just like images_placeholder is a variable node, so x_image(...) doesn't make sense and obviously leads to an error "TypeError: 'Tensor' object is not callable".

I assume you're trying to sample SAMPLE_PIXELS from each image in a batch. Note that random.sample won't work here, because x_image is a symbolic variable, its value is only known during the session. You have to use tf.boolean_mask with a random mask in order to select random pixels from the image.


问:
toLowerCase wrong lower characters " İ "
I actually have a simple problem. you will understand what I mean when you examine the following code.

```<code>function isPalindrome(string){
  string = string.toLowerCase();
  var charArr = string.split('');

  charArr.forEach( char => {
    console.log(char);
  })
  console.log(charArr.length)
}

isPalindrome("İris");
</code>```

output

```<code>i
 ̇  <- what is this ?
r
i
s
5
</code>```

adding extra characters as you see. I could not solve this problem. Is there a way to solve this ?

答:
This is working.
You've to remove the possible special chars after using toLowerCase. You could use replace(/[^\w\s]/gi, '')

Fiddle

```<code>function isPalindrome(str){
  var charArr = str.toLowerCase().replace(/[^\w\s]/gi, '').split(""); //toLowerCase --> remove special characters --> split the string

  charArr.forEach( char => {
    console.log(char);
  })
  console.log(charArr.length)
}

isPalindrome("İris");
</code>```

Body:
I actually have a simple problem. you will understand what I mean when you examine the following code.

function isPalindrome(string){
  string = string.toLowerCase();
  var charArr = string.split('');

  charArr.forEach( char => {
    console.log(char);
  })
  console.log(charArr.length)
}

isPalindrome("İris");

output

i
 ̇  <- what is this ?
r
i
s
5

adding extra characters as you see. I could not solve this problem. Is there a way to solve this ?

Body:
This is working.
You've to remove the possible special chars after using toLowerCase. You could use replace(/[^\w\s]/gi, '')

Fiddle

function isPalindrome(str){
  var charArr = str.toLowerCase().replace(/[^\w\s]/gi, '').split(""); //toLowerCase --> remove special characters --> split the string

  charArr.forEach( char => {
    console.log(char);
  })
  console.log(charArr.length)
}

isPalindrome("İris");


问:
Google Cloud SQL import - ERROR: HTTPError 403: The client is not authorized to make this request
I trying to import a database stored in the Cloud Storage using the command:

```<code>gcloud sql instances import instance-name gs://connect-to-the-cloud-sql.appspot.com/my-cloud-sql-instance-backup
</code>```

But, I am getting error:

```<code>ERROR: (gcloud.sql.instances.import) HTTPError 403: The client is not authorized to make this request.
</code>```

I've already logged in using:

```<code>gcloud auth login
</code>```

答: Make sure the instance-name is correct. I had the same error, it went away as soon as I corrected the instance-name. </p>

Body:
I trying to import a database stored in the Cloud Storage using the command:

gcloud sql instances import instance-name gs://connect-to-the-cloud-sql.appspot.com/my-cloud-sql-instance-backup

But, I am getting error:

ERROR: (gcloud.sql.instances.import) HTTPError 403: The client is not authorized to make this request.

I've already logged in using:

gcloud auth login


答:
What you need here, is standalone ng-model option. Also, I would simplify ngModel and innerHtml bindings

```<code>    <input type="text"
        id="{{indexMessage}}-{{indexReply}}-reply-text"
        [(ngModel)]="reply.text"
        [ngModelOptions]="{standalone: true}"
        name="{{indexMessage}}-{{indexReply}}-reply-text" />
    <span [innerHtml]="reply.text"></span>
</code>```

Another option would be using ngFor trackBy as it was suggested by @yurzui, in that case standalone is not needed.

You also have an issue with Reply.id. As a temporary workaround you may try following approach:

```<code>let maxId = 0;
export class Reply {
    constructor(public id: number = 0, public text: string  = '') {
        this.id = this.id || ++maxId;
    }
}
</code>```

Title: Remove item in *ngFor from *ngFor with Angular

Body:
I would like to remove item in *ngFor from *ngFor.

When I removed the reply 'test2',

and after I added an other reply, the 'test3' became empty.

<hello name="{{ name }}"></hello>

<form #form="ngForm" (ngSubmit)="submit()" ngNativeValidate class="mt-4">

          Id
          Text
          Action

            <input type="text"
            id="{{indexContent}}-{{indexMessage}}-{{indexReply}}-reply-text"
            [(ngModel)]=content.messages[indexMessage].replies[indexReply].text
            name="[[indexContent]]-[{{indexMessage}}]-[{{indexReply}}]-reply-text">

            Remove Reply

        Add Reply

  <button type="submit" class="btn btn-primary">Save</button>
</form>

And my message model with different function to add reply, remove reply

message.model.ts

import { Reply } from "./reply";

export class Message {

    constructor(public id: number         = 0,
                public text: string       = '',
                public replies: any[]     = []) {
    }

    public setModel(obj) {
        Object.assign(this, obj);
    }

    addReply(new_reply) {
        this.replies.push(new_reply);
    }

    addNewReply() {
        let new_reply = new Reply();

        this.replies.push(new_reply);
    }

    removeReply(reply) {
      this.replies.splice(this.replies.indexOf(reply), 1);
    }
}

I reproduce my problem just here: Remove object from array in *ngFor in Angular

https://stackblitz.com/edit/angular-clmi7d

Body:
What you need here, is standalone ng-model option. Also, I would simplify ngModel and innerHtml bindings

    <input type="text"
        id="{{indexMessage}}-{{indexReply}}-reply-text"
        [(ngModel)]="reply.text"
        [ngModelOptions]="{standalone: true}"
        name="{{indexMessage}}-{{indexReply}}-reply-text" />
    <span [innerHtml]="reply.text"></span>

Another option would be using ngFor trackBy as it was suggested by @yurzui, in that case standalone is not needed.

You also have an issue with Reply.id. As a temporary workaround you may try following approach:

let maxId = 0;
export class Reply {
    constructor(public id: number = 0, public text: string  = '') {
        this.id = this.id || ++maxId;
    }
}


问:
pandas CategoricalDtype: __new__() takes 1 positional argument but 2 were given
I'm reading the pandas documentation, and by following the first example on CategoricalIndex - MultiIndex / Advanced Indexing I've got an error that seems to come from the CategoricalDtype class.

Here is the code (the example in the documentation):

```<code>>>> import pandas as pd
>>> import numpy as np
>>> from pandas.api.types import CategoricalDtype
>>> df = pd.DataFrame({'A': np.arange(6),'B': list('aabbca')})
>>> df
   A  B
0  0  a
1  1  a
2  2  b
3  3  b
4  4  c
5  5  a

>>> df['B'] = df['B'].astype(CategoricalDtype(list('cab')))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __new__() takes 1 positional argument but 2 were given
</code>```

Just to check, I typed in my console the example given in pandas documentation - pandas.api.types.CategoricalDtype but the error persists:

```<code>>>> t = CategoricalDtype(categories=['b', 'a'], ordered=True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __new__() got an unexpected keyword argument 'categories'
>>> pd.Series(['a', 'b', 'a', 'c'], dtype=t)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 't' is not defined
</code>```

Could it be that there is a problem with the CategoricalDtype class or am I missing something?

答:
This will work properly in Pandas 0.21+.

For older versions we can do either:

```<code>In [201]: df['B'].astype('category')
Out[201]:
0    a
1    a
2    b
3    b
4    c
5    a
Name: B, dtype: category
Categories (3, object): [a, b, c]
</code>```

or:

```<code>In [202]: pd.Categorical(df['B'], categories=list('cab'))
Out[202]:
[a, a, b, b, c, a]
Categories (3, object): [c, a, b]
</code>```

Body:
I'm reading the pandas documentation, and by following the first example on CategoricalIndex - MultiIndex / Advanced Indexing I've got an error that seems to come from the CategoricalDtype class.

Here is the code (the example in the documentation):

>>> import pandas as pd
>>> import numpy as np
>>> from pandas.api.types import CategoricalDtype
>>> df = pd.DataFrame({'A': np.arange(6),'B': list('aabbca')})
>>> df
   A  B
0  0  a
1  1  a
2  2  b
3  3  b
4  4  c
5  5  a

>>> df['B'] = df['B'].astype(CategoricalDtype(list('cab')))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __new__() takes 1 positional argument but 2 were given

Just to check, I typed in my console the example given in pandas documentation - pandas.api.types.CategoricalDtype but the error persists:

>>> t = CategoricalDtype(categories=['b', 'a'], ordered=True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __new__() got an unexpected keyword argument 'categories'
>>> pd.Series(['a', 'b', 'a', 'c'], dtype=t)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 't' is not defined

Could it be that there is a problem with the CategoricalDtype class or am I missing something?

Body:
This will work properly in Pandas 0.21+.

For older versions we can do either:

In [201]: df['B'].astype('category')
Out[201]:
0    a
1    a
2    b
3    b
4    c
5    a
Name: B, dtype: category
Categories (3, object): [a, b, c]

or:

In [202]: pd.Categorical(df['B'], categories=list('cab'))
Out[202]:
[a, a, b, b, c, a]
Categories (3, object): [c, a, b]


问:
Saving existing file: empty value attribute is removed
I have a config file like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <add key="key1" value="value1" />
    <add key="key2" value="" />
    ...
  </appSettings>
  ...
</configuration>
</code>```

I read the config, change the value of key1 and save the config

```<code>System.Configuration.Configuration appConfig = ConfigurationManager.OpenExeConfiguration(Configuration.ConfigFile.Replace(".config", string.Empty));
appConfig.AppSettings.Settings["key1].Value = "newvalue1";
appConfig.Save(ConfigurationSaveMode.Minimal);
</code>```

After this I get the following result:

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <add key="key1" value="newvalue1" />
    <add key="key2"/>
    ...
  </appSettings>
  ...
</configuration>
</code>```

Why is the 'empty' value attribute removed for key "key2"?
When I try it with

```<code>appConfig.Save(ConfigurationSaveMode.Modified);
</code>```

, the attribute is not removed. But I want to know why it's removed in the first case?

Thanks

答:
```<code><add key="key2" value="" />
</code>```

and

```<code><add key="key2" />
</code>```

are both functionally equal.  The value of key2 with or without that tag is a null string variable which is equivalent to the empty string.

Edit to reflect comment:  Simply assign key2 the empty string in the same statement.

```<code>System.Configuration.Configuration appConfig =  ConfigurationManager.OpenExeConfiguration(Configuration.ConfigFile.Replace(".config", string.Empty));
appConfig.AppSettings.Settings["key1"].Value = "newvalue1";
appConfig.AppSettings.Settings["key2"].Value = "";
appConfig.Save(ConfigurationSaveMode.Minimal);
</code>```

Second Edit for 2nd comment:

Well, you haven't provided enough information then.  All of my answers answer your question.  The two values from the first answer are functionally equivalent.  Therefore, if you wish to see if the "key2" value = "" then you could simply run the following

```<code>if(appConfig.AppSettings.Settings["key2"] == null){
    //If this hits, that means <add key="key2" value="" />
}
</code>```

Please research how to ask a good question and adjust your question to reflect what you are really trying to ask.

Body:
I have a config file like this:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <add key="key1" value="value1" />
    <add key="key2" value="" />
    ...
  </appSettings>
  ...
</configuration>

I read the config, change the value of key1 and save the config

System.Configuration.Configuration appConfig = ConfigurationManager.OpenExeConfiguration(Configuration.ConfigFile.Replace(".config", string.Empty));
appConfig.AppSettings.Settings["key1].Value = "newvalue1";
appConfig.Save(ConfigurationSaveMode.Minimal);

After this I get the following result:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <add key="key1" value="newvalue1" />
    <add key="key2"/>
    ...
  </appSettings>
  ...
</configuration>

Why is the 'empty' value attribute removed for key "key2"?
When I try it with

appConfig.Save(ConfigurationSaveMode.Modified);

, the attribute is not removed. But I want to know why it's removed in the first case?

Thanks

Body:
<add key="key2" value="" />

and

<add key="key2" />

are both functionally equal.  The value of key2 with or without that tag is a null string variable which is equivalent to the empty string.

Edit to reflect comment:  Simply assign key2 the empty string in the same statement.

System.Configuration.Configuration appConfig =  ConfigurationManager.OpenExeConfiguration(Configuration.ConfigFile.Replace(".config", string.Empty));
appConfig.AppSettings.Settings["key1"].Value = "newvalue1";
appConfig.AppSettings.Settings["key2"].Value = "";
appConfig.Save(ConfigurationSaveMode.Minimal);

Second Edit for 2nd comment:

Well, you haven't provided enough information then.  All of my answers answer your question.  The two values from the first answer are functionally equivalent.  Therefore, if you wish to see if the "key2" value = "" then you could simply run the following

if(appConfig.AppSettings.Settings["key2"] == null){
    //If this hits, that means <add key="key2" value="" />
}

Please research how to ask a good question and adjust your question to reflect what you are really trying to ask.


问:
Installing paramiko
I am trying to install paramiko with python 2.7 but pip install fails because cryptography requires python 3 and above:

```<code>error in cryptography setup command: Invalid environment marker: python_version < '3'
    Complete output from command python setup.py egg_info:
    error in cryptography setup command: Invalid environment marker: python_version < '3'
</code>```

i manually installed cryptography for 2.7 and still can't install paramiko using both pip and a downloaded .tar file like "paramiko-2.0.2.tar" giving me the same error

any idea how can i install this module?

thank you

答:
Not sure if this is fix for the situation, but I was also facing same issue while installing paramiko yesterday, so I checked my development environment and installed same version of those packages. In my development environment I had below versions installed,
cryptography = 1.9
paramiko = 2.2.1
It worked for me, let me know if it doesn't work for you.
NOTE : install cryptography 1.9 manually, otherwise while installing paramiko 2.2.1 you'll get the same error.</p>

Title: Installing paramiko

Body:
I am trying to install paramiko with python 2.7 but pip install fails because cryptography requires python 3 and above:

error in cryptography setup command: Invalid environment marker: python_version < '3'
    Complete output from command python setup.py egg_info:
    error in cryptography setup command: Invalid environment marker: python_version < '3'

i manually installed cryptography for 2.7 and still can't install paramiko using both pip and a downloaded .tar file like "paramiko-2.0.2.tar" giving me the same error

any idea how can i install this module?

thank you


问:
base64 binary decode 32 bit array
I got an array which is 32 bit, big endian unsigned integers, basically in plain text is like this [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]

That 32bit endian array itself is encoded in binary base64 AAAAAQAAAAIAAAADAAAABAAAAAUAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEA==

Initially, if I receive this from heaven, now how can I decode/unpack everything to that understandable plain text representation in JavaScript.

In ruby I can simply use Base64.decode and String#Unpack

```<code>encoded_string = 'AAAAAQAAAAIAAAADAAAABAAAAAUAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEA=='

decoded_string = Base64.strict_decode64(encoded_string)
  => "\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x05\x00\x00\x00\x06\x00\x00\x00\a\x00\x00\x00\b\x00\x00\x00\t\x00\x00\x00\n\x00\x00\x00\v\x00\x00\x00\f\x00\x00\x00\r\x00\x00\x00\x0E\x00\x00\x00\x0F\x00\x00\x00\x10"

decoded_string.unpack('N*') #32-bit unsigned, network (big-endian) byte order
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
</code>```

Is there an equivalent of this simple step in JavaScript?

答:
Okay after some rigorous search I found this library specific to such purpose - https://www.npmjs.com/package/binary

Also provides other encodings

```<code>encoded_string = 'AAAAAQAAAAIAAAADAAAABAAAAAUAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEA=='
let buffer = new Buffer(encoded_string, 'base64');
let arrayList = [];
let binaryList = binary.parse(buffer);
for (var i = 0; i <(buffer.length / 4); i++) {
    arrayList.push(binaryList.word32bu('a').vars.a);
};
</code>```

Title: base64 binary decode 32 bit array

Body:
I got an array which is 32 bit, big endian unsigned integers, basically in plain text is like this [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]

That 32bit endian array itself is encoded in binary base64 AAAAAQAAAAIAAAADAAAABAAAAAUAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEA==

Initially, if I receive this from heaven, now how can I decode/unpack everything to that understandable plain text representation in JavaScript.

In ruby I can simply use Base64.decode and String#Unpack

encoded_string = 'AAAAAQAAAAIAAAADAAAABAAAAAUAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEA=='

decoded_string = Base64.strict_decode64(encoded_string)
  => "\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x05\x00\x00\x00\x06\x00\x00\x00\a\x00\x00\x00\b\x00\x00\x00\t\x00\x00\x00\n\x00\x00\x00\v\x00\x00\x00\f\x00\x00\x00\r\x00\x00\x00\x0E\x00\x00\x00\x0F\x00\x00\x00\x10"

decoded_string.unpack('N*') #32-bit unsigned, network (big-endian) byte order
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]

Is there an equivalent of this simple step in JavaScript?

Body:
Okay after some rigorous search I found this library specific to such purpose - https://www.npmjs.com/package/binary

Also provides other encodings

encoded_string = 'AAAAAQAAAAIAAAADAAAABAAAAAUAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEA=='
let buffer = new Buffer(encoded_string, 'base64');
let arrayList = [];
let binaryList = binary.parse(buffer);
for (var i = 0; i <(buffer.length / 4); i++) {
    arrayList.push(binaryList.word32bu('a').vars.a);
};


问:
How patches are created in Dictionary learning
How do we calculate image patches of a gray image. How is the size of the patch calculated? How many patches are needed to be calculated? Please explain and if possible give some links.</p>

答: You can choose the patch size as you want. The only thing that is important is that your patch size of the patch offing process agrees with the patch size of your dictionary atoms. You could Ebene have whole images as atoms and no patches. However, with patches you get more “versatile” atoms, meaning that you can perform a much more detailed linear combination, when you have a sparse code. I suggest to watch some videos on YouTube (just search for sparse coding dictionary learning). You don’t need to calculate the patch size.</p>


问:
SQL Simple Join with two tables, but one is random
I am stuck with this. I have a simple set-up with two tables. One table is holding emailaddresses one table is holding vouchercodes. I want to join them in a third table, so that each emailaddress has one random vouchercode.

Unfortunatly I am stuck with this as there are no identic Ids to match both values. What I have so far brings no result:

```<code>Select
A.Email
B.CouponCode
FROM Emailaddresses as A
JOIN CouponCodes as B
on A.Email = B.CouponCode
</code>```

A hint would be great as search did not bring me any further yet.

Edit -

```<code>Table A (Addresses)
-------------------
Column A         | Column B
-------------------------
email1@gmail.com  True
email2@gmail.com
email3@gmail.com  True
email4@gmail.com

Table B (Voucher)
-------------------
ABCD1234
ABCD5678
ABCD9876
ABCD5432

Table C
-------------------------
column A | column B
-------------------------

email1@gmail.com  ABCD1234
email2@gmail.com  ABCD5678
email3@gmail.com  ABCD9876
email4@gmail.com  ABCD5432
</code>```

Sample Data:

答:
You want to randomly join records, one email with one coupon each. So create random row numbers and join on these:</p>

```<code>select
  e.email,
  c.couponcode
from (select t.*, row_number() over (order by newid()) as rn from emailaddresses t) e
join (select t.*, row_number() over (order by newid()) as rn from CouponCodes t) c
  on c.rn = e.rn;
</code>```

Body:
I am stuck with this. I have a simple set-up with two tables. One table is holding emailaddresses one table is holding vouchercodes. I want to join them in a third table, so that each emailaddress has one random vouchercode.

Unfortunatly I am stuck with this as there are no identic Ids to match both values. What I have so far brings no result:

Select
A.Email
B.CouponCode
FROM Emailaddresses as A
JOIN CouponCodes as B
on A.Email = B.CouponCode

A hint would be great as search did not bring me any further yet.

Edit -

Table A (Addresses)
-------------------
Column A         | Column B
-------------------------
email1@gmail.com  True
email2@gmail.com
email3@gmail.com  True
email4@gmail.com

Table B (Voucher)
-------------------
ABCD1234
ABCD5678
ABCD9876
ABCD5432

Table C
-------------------------
column A | column B
-------------------------

email1@gmail.com  ABCD1234
email2@gmail.com  ABCD5678
email3@gmail.com  ABCD9876
email4@gmail.com  ABCD5432

Sample Data:

Body:
You want to randomly join records, one email with one coupon each. So create random row numbers and join on these:

select
  e.email,
  c.couponcode
from (select t.*, row_number() over (order by newid()) as rn from emailaddresses t) e
join (select t.*, row_number() over (order by newid()) as rn from CouponCodes t) c
  on c.rn = e.rn;


问:
Get foreign key without requesting the whole object
I have a model Foo which have a ForeignKey to the User model.

Later, I need to grab all the User's id and put then on a list

```<code>foos = Foo.objects.filter(...)

l = [ f.user.id for f in foos ]
</code>```

But when I do that, django grabs the whole User instance from the DB instead of giving me just the numeric user's id, which exist in each Foo row.

How can I get all the ids without querying each user or using a select_related?

Thanks

答:
Use queryset's values() function, which will return a list of dictionaries containing name/value pairs for each attribute passed as parameters:

```<code>>>> Foo.objects.all().values('user__id')
[{'user__id': 1}, {'user__id' 2}, {'user__id': 3}]
</code>```

The ORM will then be able to optimize the SQL query to only return the required fields, instead of doing a "SELECT *".

OwnerDisplayName: Tiago

Body:
I have a model Foo which have a ForeignKey to the User model.

Later, I need to grab all the User's id and put then on a list

foos = Foo.objects.filter(...)

l = [ f.user.id for f in foos ]

But when I do that, django grabs the whole User instance from the DB instead of giving me just the numeric user's id, which exist in each Foo row.

How can I get all the ids without querying each user or using a select_related?

Thanks

LastEditorDisplayName: Fabian Steeg

Body:
Use queryset's values() function, which will return a list of dictionaries containing name/value pairs for each attribute passed as parameters:

>>> Foo.objects.all().values('user__id')
[{'user__id': 1}, {'user__id' 2}, {'user__id': 3}]

The ORM will then be able to optimize the SQL query to only return the required fields, instead of doing a "SELECT *".

OwnerDisplayName: Daniel