问:
Uncaught TypeError: col_class.split is not a function
```<code>$('#addcol-inner').click(function() {
    var sum = 0;0
    var collection = $('#white').find('.ui-sortable-handle');
    collection.each(function(k,v){
        var class_item = $(v).attr('class');
        var col_class = class_item.search('');
        var col_number = col_class.split('-')[2];
        sum += col_number;
        if(sum > 12){

            return false;
    }
</code>```

I dont know whats is wrong, i wont sum the number of col class
this is HTML

```<code><div id="white" class="column-container clearfix ui-sortable">
    <div class="column-cell ui-sortable-handle col-md-12" data-post-content-id="3801" data-active-mode="text">
</code>```

答:
search() returns the integer index of the match, hence col_class is an integer value which has no split() method.

That line itself is redundant and can be removed as you're searching for an empty string. Also col_number will be a string, so presumably you'll need to use parseInt() to get the sum as an integer.

Update

Now that you've added your HTML, the issue is that the column number you're trying to access is the last element in the resulting array, not the second. Hence you need to amend the logic which retrieves that value. Try this:

$('#addcol-inner').click(function() {
  var sum = 0; // note that the second 0 is redundant

  $('#white').find('.ui-sortable-handle').each(function() {
    var class_item = $(this).prop('class').split('-');
    var col_number = class_item[class_item.length - 1];
    sum += parseInt(col_number, 10);
    if (sum > 12) {
      return false;
    }
  })

  console.log(sum);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="white" class="column-container clearfix ui-sortable">
  <div class="column-cell ui-sortable-handle col-md-12" data-post-content-id="3801" data-active-mode="text"></div>
</div>

<button id="addcol-inner">Click me</button></code>```

Body:
$('#addcol-inner').click(function() {
    var sum = 0;0
    var collection = $('#white').find('.ui-sortable-handle');
    collection.each(function(k,v){
        var class_item = $(v).attr('class');
        var col_class = class_item.search('');
        var col_number = col_class.split('-')[2];
        sum += col_number;
        if(sum > 12){

            return false;
    }

I dont know whats is wrong, i wont sum the number of col class
this is HTML

Body:
search() returns the integer index of the match, hence col_class is an integer value which has no split() method.

That line itself is redundant and can be removed as you're searching for an empty string. Also col_number will be a string, so presumably you'll need to use parseInt() to get the sum as an integer.

Update

Now that you've added your HTML, the issue is that the column number you're trying to access is the last element in the resulting array, not the second. Hence you need to amend the logic which retrieves that value. Try this:

$('#addcol-inner').click(function() {
  var sum = 0; // note that the second 0 is redundant

  $('#white').find('.ui-sortable-handle').each(function() {
    var class_item = $(this).prop('class').split('-');
    var col_number = class_item[class_item.length - 1];
    sum += parseInt(col_number, 10);
    if (sum > 12) {
      return false;
    }
  })

  console.log(sum);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="white" class="column-container clearfix ui-sortable">
  <div class="column-cell ui-sortable-handle col-md-12" data-post-content-id="3801" data-active-mode="text"></div>
</div>

<button id="addcol-inner">Click me</button>


来源: stackexchange

问:
Pandas equivalent of SQL case when statement to create new variable
I have this df:

```<code>data = np.array([[np.nan, 0], [2, 0], [np.nan, 1]])
df = pd.DataFrame(data=data, columns = ['a', 'b'])
</code>```

which looks like this:

```<code>     a    b
    --------
0   NaN  0.0
1   2.0  0.0
2   NaN  1.0
</code>```

My goal is to create a third column "c" that has a value of 1 when column "a" is equal to NaN and column "b" is equal to 0. "c" would be 0 otherwise. The simple SQL case statement would be:

```<code>(CASE WHEN a IS NULL AND b = 0 THEN 1 ELSE 0 END) AS C
</code>```

The desired output is this:

```<code>     a    b   c
    -----------
0   NaN  0.0  1
1   2.0  0.0  0
2   NaN  1.0  0
</code>```

My (wrong) try:

```<code>df['c'] = np.where(df['a']==np.nan & df['b'] == 0, 1, 0)
</code>```

Many thx.

答:
You're almost there, instead use np.where(df['a'].isnull() & (df['b'] == 0), 1, 0) for null check.

Alternatively,

```<code>In [258]: df['c'] = (df['a'].isnull() & (df['b'] == 0)).astype(int)

In [259]: df
Out[259]:
     a    b  c
0  NaN  0.0  1
1  2.0  0.0  0
2  NaN  1.0  0
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have this df:

data = np.array([[np.nan, 0], [2, 0], [np.nan, 1]])
df = pd.DataFrame(data=data, columns = ['a', 'b'])

which looks like this:

     a    b
    --------
0   NaN  0.0
1   2.0  0.0
2   NaN  1.0

My goal is to create a third column "c" that has a value of 1 when column "a" is equal to NaN and column "b" is equal to 0. "c" would be 0 otherwise. The simple SQL case statement would be:

(CASE WHEN a IS NULL AND b = 0 THEN 1 ELSE 0 END) AS C

The desired output is this:

     a    b   c
    -----------
0   NaN  0.0  1
1   2.0  0.0  0
2   NaN  1.0  0

My (wrong) try:

df['c'] = np.where(df['a']==np.nan & df['b'] == 0, 1, 0)

Many thx.

Body:
You're almost there, instead use np.where(df['a'].isnull() & (df['b'] == 0), 1, 0) for null check.

Alternatively,

In [258]: df['c'] = (df['a'].isnull() & (df['b'] == 0)).astype(int)

In [259]: df
Out[259]:
     a    b  c
0  NaN  0.0  1
1  2.0  0.0  0
2  NaN  1.0  0


问:
Transpose data in a primeng datatable/typescript
I have an array of place which has these fields.(continent and country)

```<code> places = [
           { "continent":"Europe", "country": "UK" },
           { "continent":"North America", "country": "US" },
           { "continent":"Asia", "country": "Philippines" },
           { "continent":"Africa", "country": "Egypt" }
          ];
</code>```

If I plot it in a primeng datatable it something like this.

What I want is to transpose the data. I want the datatable to  be shown in the datatable in such that the continent row will become the header and the country will be the fields. Want I want is something like this.

I created a plunkr for this. http://plnkr.co/edit/KX1pCw?p=preview

答:
Modified your plunkr to work here .

html -

```<code><p-dataTable [value]="places" sortMode="single" reorderableColumns="true" [globalFilter]="gb" scrollable="true" scrollHeight="350px">
  <p-column *ngFor="let col of cols" [field]="col.field" [header]="col.header" [sortable]="true" [style]="{'width': '200px'}">
  </p-column>
</p-dataTable>
</code>```

app.component.ts -

```<code>export class AppComponent {
  places_rawdata =
          [
           { "continent":"Europe", "country": "UK" },
           { "continent":"North America", "country": "US" },
           { "continent":"Asia", "country": "Philippines" },
           { "continent":"Africa", "country": "Egypt" }
          ];

  places: any [] = [];
  cols:any[]=[];

  ngOnInit() {
    let temp: any = {};
    this.places=[];
    this.places_rawdata.forEach(
     (place,index) => {
       let s : string = 'country' + index;
       temp[s]= place.country
       this.cols.push({field: s, header: place.continent})
    });
    this.places = [...this.places,temp];
    console.log(this.places);
  }
}
</code>```

Body:
I have an array of place which has these fields.(continent and country)

 places = [
           { "continent":"Europe", "country": "UK" },
           { "continent":"North America", "country": "US" },
           { "continent":"Asia", "country": "Philippines" },
           { "continent":"Africa", "country": "Egypt" }
          ];

If I plot it in a primeng datatable it something like this.

What I want is to transpose the data. I want the datatable to  be shown in the datatable in such that the continent row will become the header and the country will be the fields. Want I want is something like this.

I created a plunkr for this. http://plnkr.co/edit/KX1pCw?p=preview

Body:
Modified your plunkr to work here .

html -

<p-dataTable [value]="places" sortMode="single" reorderableColumns="true" [globalFilter]="gb" scrollable="true" scrollHeight="350px">
  <p-column *ngFor="let col of cols" [field]="col.field" [header]="col.header" [sortable]="true" [style]="{'width': '200px'}">
  </p-column>
</p-dataTable>

app.component.ts -

export class AppComponent {
  places_rawdata =
          [
           { "continent":"Europe", "country": "UK" },
           { "continent":"North America", "country": "US" },
           { "continent":"Asia", "country": "Philippines" },
           { "continent":"Africa", "country": "Egypt" }
          ];

  places: any [] = [];
  cols:any[]=[];

  ngOnInit() {
    let temp: any = {};
    this.places=[];
    this.places_rawdata.forEach(
     (place,index) => {
       let s : string = 'country' + index;
       temp[s]= place.country
       this.cols.push({field: s, header: place.continent})
    });
    this.places = [...this.places,temp];
    console.log(this.places);
  }
}


问:
IOS video over video merge with circle cropping
Iam making an app which does a basic video processing .
Ive successfully managed to merge to video (video over video) .

how can I crop the up-left small video into a circle ?

答:
If You want to export that video You need to:

Create CALayer which would be the parent of Your video layers

Add two CALayers as sublayers of parent layer

Create a CAShapeLayer circle and mask the video layer you want

Create AVMutableVideoComopsition and setup it (frameDuration, renderSize, instructions, ... etc)

Create an AVVideoCompositionCoreAnimationTool instance with init(postProcessingAsVideoLayers:in:) method

Assign it to AVMutableVideoComopsition's animationTool property

Export it with AVAssetExportSession (with setting AVMutableVideoComopsition to property videoCompostion of export session)

This is only for post processing not for preview.

For preview You can try to create two AVPlayerLayers with masking one of them, if this doesn't work You can create a custom video compositor and render each frame as you wish


问:
How to disable Hibernate logs in Eclipse?
I am new to hibernate , I am doing project in Eclipse. When I log in to my application it displays to many log messages in console which I dont need, the log message is something like this,

```<code>97 [http-bio-8080-exec-9] INFO org.hibernate.annotations.common.Version - Hibernate Commons Annotations 3.2.0.Final
102 [http-bio-8080-exec-9] INFO org.hibernate.cfg.Environment - Hibernate 3.6.10.Final
103 [http-bio-8080-exec-9] INFO org.hibernate.cfg.Environment - hibernate.properties not found
105 [http-bio-8080-exec-9] INFO org.hibernate.cfg.Environment - Bytecode provider name : javassist
108 [http-bio-8080-exec-9] INFO org.hibernate.cfg.Environment - using JDK 1.4 java.sql.Timestamp handling
165 [http-bio-8080-exec-9] INFO org.hibernate.cfg.Configuration - configuring from resource: /hibernate.cfg.xml
165 [http-bio-8080-exec-9] INFO org.hibernate.cfg.Configuration - Configuration resource: /hibernate.cfg.xml
220 [http-bio-8080-exec-9] INFO org.hibernate.cfg.Configuration - Configured SessionFactory: null
262 [http-bio-8080-exec-9] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: com.aurodisplay.its.beans.UserRegisterBean
296 [http-bio-8080-exec-9] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity com.aurodisplay.its.beans.UserRegisterBean on table users
334 [http-bio-8080-exec-9] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: com.aurodisplay.its.beans.AdminInfoBean
334 [http-bio-8080-exec-9] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity com.aurodisplay.its.beans.AdminInfoBean on table admin_info
337 [http-bio-8080-exec-9] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: com.aurodisplay.its.beans.LatitudeBean
337 [http-bio-8080-exec-9] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity com.aurodisplay.its.beans.LatitudeBean on table latlng
</code>```

My hibernate.cfg.xml

```<code><!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
</code>```

```<code><session-factory>

    <!-- Database connection settings -->
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="connection.url">jdbc:mysql://localhost:3306/its_serverdb</property>
    <property name="connection.username">root</property>
    <property name="connection.password">root</property>

    <!-- JDBC connection pool (use the built-in) -->
    <property name="connection.pool_size">10</property>

    <!-- SQL dialect -->
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

    <!-- Disable the second-level cache  -->
    <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

    <!-- Echo all executed SQL to stdout -->
    <property name="show_sql">true</property>

    <property name="hibernate.connection.zeroDateTimeBehavior">convertToNull</property>
  <property name="hibernate.connection.release_mode">on_close</property>
     // next are mappings
</code>```

I have integrated Log4j , Here is my Log4j.xml file

```<code><?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration debug="true" xmlns:log4j='http://jakarta.apache.org/log4j/'>

<appender name="console" class="org.apache.log4j.ConsoleAppender">
    <layout class="org.apache.log4j.PatternLayout">
    <param name="ConversionPattern" value="[%d{dd-MM-yyyy HH:mm:ss}] [%c{1}] %-5p :%L - %m%n" />
    </layout>
</appender>

<appender name="file" class="org.apache.log4j.RollingFileAppender">
    <param name="append" value="false" />
    <param name="maxFileSize" value="10MB" />
    <param name="maxBackupIndex" value="10" />
    <param name="file" value="${catalina.home}/logs/ITS_Server.log" />
    <layout class="org.apache.log4j.PatternLayout">
    <param name="ConversionPattern" value="[%d{dd-MM-yyyy HH:mm:ss}] [%c{1}] %-5p:%L - %m%n" />
    </layout>
</appender>

<category name="org.hibernate">
    <priority value="DEBUG" />
</category>

<category name="java.sql">
    <priority value="debug" />
</category>

<logger name="org.hibernate">
    <level value="info"/>
</logger>

<root>
    <level value="DEBUG" />
    <appender-ref ref="console" />
    <appender-ref ref="file" />

  </root>

 </log4j:configuration>
</code>```

How can I disable it. When I google about it, somany solutions are using Log4j I dont know what is it and what is it for. can I do disable logs without Log4j if possible please tell me how .It would be greate help. Thank you.

答:
Old post, but usefull :

First, you can use log4j configuration file (add this to your pom.xml)

```<code><dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>
</code>```

Finally, to disable logging, put in src/main/resources/log4j.properties file

```<code>log4j.rootLogger=OFF
</code>```

Body:
I am new to hibernate , I am doing project in Eclipse. When I log in to my application it displays to many log messages in console which I dont need, the log message is something like this,

97 [http-bio-8080-exec-9] INFO org.hibernate.annotations.common.Version - Hibernate Commons Annotations 3.2.0.Final
102 [http-bio-8080-exec-9] INFO org.hibernate.cfg.Environment - Hibernate 3.6.10.Final
103 [http-bio-8080-exec-9] INFO org.hibernate.cfg.Environment - hibernate.properties not found
105 [http-bio-8080-exec-9] INFO org.hibernate.cfg.Environment - Bytecode provider name : javassist
108 [http-bio-8080-exec-9] INFO org.hibernate.cfg.Environment - using JDK 1.4 java.sql.Timestamp handling
165 [http-bio-8080-exec-9] INFO org.hibernate.cfg.Configuration - configuring from resource: /hibernate.cfg.xml
165 [http-bio-8080-exec-9] INFO org.hibernate.cfg.Configuration - Configuration resource: /hibernate.cfg.xml
220 [http-bio-8080-exec-9] INFO org.hibernate.cfg.Configuration - Configured SessionFactory: null
262 [http-bio-8080-exec-9] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: com.aurodisplay.its.beans.UserRegisterBean
296 [http-bio-8080-exec-9] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity com.aurodisplay.its.beans.UserRegisterBean on table users
334 [http-bio-8080-exec-9] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: com.aurodisplay.its.beans.AdminInfoBean
334 [http-bio-8080-exec-9] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity com.aurodisplay.its.beans.AdminInfoBean on table admin_info
337 [http-bio-8080-exec-9] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: com.aurodisplay.its.beans.LatitudeBean
337 [http-bio-8080-exec-9] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity com.aurodisplay.its.beans.LatitudeBean on table latlng

My hibernate.cfg.xml

<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<session-factory>

    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="connection.url">jdbc:mysql://localhost:3306/its_serverdb</property>
    <property name="connection.username">root</property>
    <property name="connection.password">root</property>

    <property name="connection.pool_size">10</property>

    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

    <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

    <property name="show_sql">true</property>

    <property name="hibernate.connection.zeroDateTimeBehavior">convertToNull</property>
  <property name="hibernate.connection.release_mode">on_close</property>
     // next are mappings

I have integrated Log4j , Here is my Log4j.xml file

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration debug="true" xmlns:log4j='http://jakarta.apache.org/log4j/'>

<appender name="console" class="org.apache.log4j.ConsoleAppender">
    <layout class="org.apache.log4j.PatternLayout">
    <param name="ConversionPattern" value="[%d{dd-MM-yyyy HH:mm:ss}] [%c{1}] %-5p :%L - %m%n" />
    </layout>
</appender>

<appender name="file" class="org.apache.log4j.RollingFileAppender">
    <param name="append" value="false" />
    <param name="maxFileSize" value="10MB" />
    <param name="maxBackupIndex" value="10" />
    <param name="file" value="${catalina.home}/logs/ITS_Server.log" />
    <layout class="org.apache.log4j.PatternLayout">
    <param name="ConversionPattern" value="[%d{dd-MM-yyyy HH:mm:ss}] [%c{1}] %-5p:%L - %m%n" />
    </layout>
</appender>

<category name="org.hibernate">
    <priority value="DEBUG" />
</category>

<category name="java.sql">
    <priority value="debug" />
</category>

<logger name="org.hibernate">
    <level value="info"/>
</logger>

<root>
    <level value="DEBUG" />
    <appender-ref ref="console" />
    <appender-ref ref="file" />

  </root>

 </log4j:configuration>

How can I disable it. When I google about it, somany solutions are using Log4j I dont know what is it and what is it for. can I do disable logs without Log4j if possible please tell me how .It would be greate help. Thank you.

Body:
Old post, but usefull :

First, you can use log4j configuration file (add this to your pom.xml)

<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

Finally, to disable logging, put in src/main/resources/log4j.properties file

log4j.rootLogger=OFF


问:
return to top of treeview when clicking tree node in the bottom in the GWT app
I recently start to work on the source codes written in GWT. I do not have any knowledge on GWT at all. There is a tree view, which is working well in IE and FireFox, however it does not work in Chrome. When clicking a certain node, it return to the top of the tree in the Chrome. Actually, that treeview resides in the scroll box, it goes up to top of the scroll box when clicking node in the bottom. What would be the clue of this issue? Any clue I can investigate into would be welcomed :)</p>

答:
I had the same issue you are facing - if you are talking about the Tree from GXT. You can solve it when you override the focus method to do nothing</p>

```<code>@Override
public void focus() {
    //override to fix focus issue
}
</code>```

Body:
I had the same issue you are facing - if you are talking about the Tree from GXT. You can solve it when you override the focus method to do nothing

@Override
public void focus() {
    //override to fix focus issue
}


问:
How to remove specific item from local storage array?
I'm building  a 'to do list' , The user appends new notes to the list after clicking .

I  saved all the appended data in the local storage.

Now i want to remove the clicked note from the array and save it back to the local storage.
I have this code:

```<code>    **//Here i get the note**
    var getNote = JSON.parse(localStorage.getItem("savedNotes")) || [];
         $("#notes-section").append(getNote);

    **//Here i set the note**
         getNote.push(note);
      localStorage.setItem("savedNotes", JSON.stringify(getNote));

 **//Here i want to remove the note from the array**
    $(document).on('click', '.pin', function() {
$(this).parent().css({opacity: 1.0, visibility: "visible"}).animate({opacity: 0}, 2000);

  for(var i =0 ; i < getNote.length; i++ ){

     getNote.splice(i,1);

       localStorage.setItem("savedNotes", JSON.stringify(getNote));
    }

});
</code>```

答:
As stated in comments you need to provide only relevant code, but just to clear things out here, the way to go here is:

To have an empty array of notes.

Add this array to localStorage via localStorage.setItem("savedNotes", JSON.stringify(notes)).

Every time you add a note you will need to: parse this array back from localStorage with notes = JSON.parse(localStorage.getItem("savedNotes")).

Then push the new note into this array via notes.push(note).

Then set this item again with localStorage.setItem("savedNotes",
JSON.stringify(notes)), it will update your existing item in the localStorage.

It all relies on Storage.getItem() and Storage.setItem() methods.

And to remove a note from the array you need to do the same thing, expect that you will search for this note in the parsed array and remove it.

Body:
I'm building  a 'to do list' , The user appends new notes to the list after clicking .

I  saved all the appended data in the local storage.

Now i want to remove the clicked note from the array and save it back to the local storage.
I have this code:

    **//Here i get the note**
    var getNote = JSON.parse(localStorage.getItem("savedNotes")) || [];
         $("#notes-section").append(getNote);

    **//Here i set the note**
         getNote.push(note);
      localStorage.setItem("savedNotes", JSON.stringify(getNote));

 **//Here i want to remove the note from the array**
    $(document).on('click', '.pin', function() {
$(this).parent().css({opacity: 1.0, visibility: "visible"}).animate({opacity: 0}, 2000);

  for(var i =0 ; i < getNote.length; i++ ){

     getNote.splice(i,1);

       localStorage.setItem("savedNotes", JSON.stringify(getNote));
    }

});


问:
Python readability through descriptive naming
I have been using Python for about a year now, coming from a mostly Java background. I found Python quite easy to learn because of its focus on readability and simple design. The thing I don't understand about python is why for a language that focuses so heavily on readability, it often uses very non-descriptive names for modules, functions, constants etc.. One thing I like about Java is its very descriptive class/attribute/method names (I like objective-C even more for this reason). It seems python programmers in general seem to have taken a C type approach to naming where they use as short names as possible for everything. I know everyone wants to do as little typing as possible but I like a lot of programmers spend the majority of my time reading code rather that writing it so I find the choice between short non-descriptive names and long descriptive names, an easy one to make. (I like longer descriptive names xD)

A few examples, just looking at some modules in the standard library,

sched — Event scheduler, Could this have been EventScheduler?

asyncore — Asynchronous socket handler, AsynchronousSocketHandler?

imghdr — Determine the type of an image, DetermineImageType?

Pickle?

I know this isn't a huge issue but I find myself more often than not having to look up the meaning of any new (or forgotten) module I come across when in other languages like Objective-C or Java I can get this meaning straight away from the modules/functions/attributes definition.
On another note, people tend to write code similar to the way the standard library is written so you can be sure that if the standard library uses non-descriptive names the average developer will use even more non-descriptive names.

I was just wondering does anyone know why this is?

答:
I guess there's a balance to be struck between being descriptive and concise, and Python's scripting background makes it somewhat more concise than Java (because us hobbyists are too lazy for all that typing ;-) ). At the risk of sounding like a fanboy, Python tries to walk the line between the descriptive-but-long (Java), and the short-but-tricky (*cough*Perl).

Things that are used often and easily understood can be short, so we have a str type rather than an AsciiString or UnicodeString (Python2/3 respectively). More specialised functions, like urllib.urlencode or random.normalvariate get longer names.

The core language is generally kept simple (e.g. there is no character type, only one-character strings). The idea that there's only "one right way to do it", along with duck typing, mean that there's no need for names like do_something_with_type_a. And, while it's just an excuse, there is clear documentation for anything that's not obvious.

As for itertools? The module name doesn't really matter, it's just a grouping of functions. Some of the functions are clearer (chain, cycle, repeat), some less so (islice, izip). I suppose we assume that concepts like "zipping" and "slicing" are straightforward once you're familiar with Python.

sched/asyncore/imghdr: All admittedly brief and undescriptive, but I've never seen any of them used. They probably date back to the days of 8-character filenames, and updating them has never been a priority.

pickle: Quirky, but you really only have to look it up once, then it's obvious. You couldn't really call it "serializer", because it's for a specific serialisation, not a generic framework.

ContentLicense: CC BY-SA 2.5


问:
Spring MVC - JSON infinite recursion
I have bi-directional relationship like this...

Person.java

```<code> public class Person{

    @JsonIgnore
    @OneToMany(targetEntity=PersonOrganization.class, cascade=CascadeType.ALL,
        fetch=FetchType.EAGER, mappedBy="person")
    private Set<PeopleOrg> organization;
    .....
 }
</code>```

PersonOrganization.java

```<code>  public class PersonOrganization{

    @JsonIgnore
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="PERSONID", nullable=false)
private Person person;
  }
</code>```

Even with @JsonIgnore annotation I am getting infinite recursion error when trying to retrieve Person records. I have tried new annotations in 1.6 version. @JsonBackReference and @JsonManagedReference. Even then I am getting infinite recursion..

With @JsonBackReference("person-organization") on Person and @JsonManagedReference("person-organization") on PersonOrganization

```<code>org.codehaus.jackson.map.JsonMappingException: Infinite recursion (StackOverflowError) (through reference chain: com.entity.Person["organization"]->org.hibernate.collection.PersistentSet[0]->com.entity.PersonOrganization["person"]->com.entity.Person["organization"]->org.hibernate.collection.PersistentSet[0]...
</code>```

Even If I interchange the annotations, I am still getting this exception.. Please let me know if there is something wrong with the mappings or the way I am using JSON annotations. Thanks

答:
Apparently since Jackson 1.6 you can use @JsonManagedReference and @JsonBackReference to effectively solve the infinite recursion problem.

I won't go into the details but this changing you classes to the below format should solve the problem.

```<code> public class Person{

    @OneToMany(targetEntity=PersonOrganization.class, cascade=CascadeType.ALL, fetch=FetchType.EAGER, mappedBy="person")
    @Column(nullable = true)
    @JsonManagedReference
    private Set<PeopleOrg> organization;
    .....
 }

public class PersonOrganization{

    @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinColumn(name="PERSONID")
    @JsonBackReference
    private Person person;
  }
</code>```

Basically Jackson converts Set<PeopleOrg> organization, the forward part of the reference a to json-like format using the marshalling process, it then looks for Person person, the back part of the reference and does not serialize it.

Credits - Kurt Bourbaki & More info - http://keenformatics.blogspot.co.ke/2013/08/how-to-solve-json-infinite-recursion.html

Title: Spring MVC - JSON infinite recursion

Body:
I have bi-directional relationship like this...

Person.java

 public class Person{

    @JsonIgnore
    @OneToMany(targetEntity=PersonOrganization.class, cascade=CascadeType.ALL,
        fetch=FetchType.EAGER, mappedBy="person")
    private Set<PeopleOrg> organization;
    .....
 }

PersonOrganization.java

  public class PersonOrganization{

    @JsonIgnore
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="PERSONID", nullable=false)
private Person person;
  }

Even with @JsonIgnore annotation I am getting infinite recursion error when trying to retrieve Person records. I have tried new annotations in 1.6 version. @JsonBackReference and @JsonManagedReference. Even then I am getting infinite recursion..

With @JsonBackReference("person-organization") on Person and @JsonManagedReference("person-organization") on PersonOrganization

org.codehaus.jackson.map.JsonMappingException: Infinite recursion (StackOverflowError) (through reference chain: com.entity.Person["organization"]->org.hibernate.collection.PersistentSet[0]->com.entity.PersonOrganization["person"]->com.entity.Person["organization"]->org.hibernate.collection.PersistentSet[0]...

Even If I interchange the annotations, I am still getting this exception.. Please let me know if there is something wrong with the mappings or the way I am using JSON annotations. Thanks

Body:
Apparently since Jackson 1.6 you can use @JsonManagedReference and @JsonBackReference to effectively solve the infinite recursion problem.

I won't go into the details but this changing you classes to the below format should solve the problem.

 public class Person{

    @OneToMany(targetEntity=PersonOrganization.class, cascade=CascadeType.ALL, fetch=FetchType.EAGER, mappedBy="person")
    @Column(nullable = true)
    @JsonManagedReference
    private Set<PeopleOrg> organization;
    .....
 }

public class PersonOrganization{

    @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinColumn(name="PERSONID")
    @JsonBackReference
    private Person person;
  }

Basically Jackson converts Set<PeopleOrg> organization, the forward part of the reference a to json-like format using the marshalling process, it then looks for Person person, the back part of the reference and does not serialize it.

Credits - Kurt Bourbaki & More info - http://keenformatics.blogspot.co.ke/2013/08/how-to-solve-json-infinite-recursion.html


问:
How to get the CommandArgument of an ImageButton inside a Repeater
I have a repeater which structured like this

```<code><asp:Repeater ID="RpAccBind" runat="server" OnItemDataBound="RpAccBind_ItemDataBound">
    <ItemTemplate>
        <tr id="acsryRow" runat="server">
            <td data-th="Product">
                <div class="prodImgMain">
                    <img src="../instrumentimages/<%# Eval("ProductImage") %>" alt="<%# Eval("ProductName")%>" />
                </div>
            </td>

            <td data-th="Description">
                <div class="prodDescriptionContainer">
                    <ul>
                        <li>
                            <span class="prdRow"><%# Eval("ProductName") %></span>
                        </li>
                    </ul>
                </div>
                <div class="quantityIconWrap form-group">
                    <span class="number-wrapper">

                        <asp:TextBox Text='<%# Eval("Quantity") %>' ID="txtqty" CssClass="form-control" runat="server" size="3" Width="50" onkeyup="this.value=this.value.replace(/[^0-9]/g,'');" OnTextChanged="txtQtyTextChanged" AutoPostBack="true"></asp:TextBox>

                    </span>
                    <span>

                        <asp:ImageButton ID="lnkAscRemove" runat="server" class="btn" OnClick="lnkRemoveClick" CommandArgument='<%# Eval("ProductId")%>' ImageUrl="../images/deleteIcon.png"></asp:ImageButton>
                    </span>
                </div>
            </td>

            <td data-th="Amount" style="padding-right: 5%;">
                <div class="amountColMain">
                    <ul>
                        <li><span><strong><span id="litConPrice" runat="server">$<%# Eval("ConsumerPrice") %></span></strong></span></li>

                    </ul>
                </div>
            </td>
            <td></td>
        </tr>

    </ItemTemplate>
    <FooterTemplate>
    </FooterTemplate>
</asp:Repeater>
</code>```

Now, whenever the txtQty is 0, i want to have the productid in respect of the imagebutton clicked. Right Now, i am using something like

```<code>long productId = Convert.ToInt64(((ImageButton)((RepeaterItem)txtQty.Parent).FindControl("lnkAscRemove")).CommandArgument);
</code>```

It is giving me an error of unable to cast HtmlTableCell to RepeaterItem

Any Kind of help will be appreciated. Thanks in advance

答:
To use CommandName and CommandArgument, you need to use a Command event, not a Click.

```<code><asp:ImageButton ID="lnkAscRemove" runat="server" OnCommand="lnkAscRemove_Command"
    CommandArgument='<%# Eval("ProductId")%>'
</code>```

Code behind

```<code>protected void lnkAscRemove_Command(object sender, CommandEventArgs e)
{
    Label1.Text = e.CommandArgument.ToString();
}
</code>```

Update

If you want to get the ProductId from a TextBox, you could add it as a custom property and then read it in code behind.

```<code><asp:TextBox Text='<%# Eval("ProductId") %>' ID="txtqty" runat="server" AutoPostBack="true"
    OnTextChanged="txtqty_TextChanged" ProductId='<%# Eval("ProductId") %>'></asp:TextBox>
</code>```

Code behind

```<code>protected void txtqty_TextChanged(object sender, EventArgs e)
{
    TextBox tb = sender as TextBox;
    Label1.Text = tb.Attributes["ProductId"];
}
</code>```

Body:
I have a repeater which structured like this

<asp:Repeater ID="RpAccBind" runat="server" OnItemDataBound="RpAccBind_ItemDataBound">
    <ItemTemplate>

                    <img src="../instrumentimages/<%# Eval("ProductImage") %>" alt="<%# Eval("ProductName")%>" />

                            <%# Eval("ProductName") %>

                        <asp:TextBox Text='<%# Eval("Quantity") %>' ID="txtqty" CssClass="form-control" runat="server" size="3" Width="50" onkeyup="this.value=this.value.replace(/[^0-9]/g,'');" OnTextChanged="txtQtyTextChanged" AutoPostBack="true"></asp:TextBox>

                        <asp:ImageButton ID="lnkAscRemove" runat="server" class="btn" OnClick="lnkRemoveClick" CommandArgument='<%# Eval("ProductId")%>' ImageUrl="../images/deleteIcon.png"></asp:ImageButton>

$<%# Eval("ConsumerPrice") %>

    </ItemTemplate>
    <FooterTemplate>
    </FooterTemplate>
</asp:Repeater>

Now, whenever the txtQty is 0, i want to have the productid in respect of the imagebutton clicked. Right Now, i am using something like

long productId = Convert.ToInt64(((ImageButton)((RepeaterItem)txtQty.Parent).FindControl("lnkAscRemove")).CommandArgument);

It is giving me an error of unable to cast HtmlTableCell to RepeaterItem

Any Kind of help will be appreciated. Thanks in advance

Body:
To use CommandName and CommandArgument, you need to use a Command event, not a Click.

<asp:ImageButton ID="lnkAscRemove" runat="server" OnCommand="lnkAscRemove_Command"
    CommandArgument='<%# Eval("ProductId")%>'

Code behind

protected void lnkAscRemove_Command(object sender, CommandEventArgs e)
{
    Label1.Text = e.CommandArgument.ToString();
}

Update

If you want to get the ProductId from a TextBox, you could add it as a custom property and then read it in code behind.

<asp:TextBox Text='<%# Eval("ProductId") %>' ID="txtqty" runat="server" AutoPostBack="true"
    OnTextChanged="txtqty_TextChanged" ProductId='<%# Eval("ProductId") %>'></asp:TextBox>

Code behind

protected void txtqty_TextChanged(object sender, EventArgs e)
{
    TextBox tb = sender as TextBox;
    Label1.Text = tb.Attributes["ProductId"];
}


问:
How can I check if the Launcher/Home screen is currently displayed
I am working on a widget that is fetching and displaying some data.
The refresh rate is custom.

What I would like to do, is only fetch data when the widget is displayed (when the launcher is on top).

Is there a way to check if the launcher is displayed?

答:
There's almost certainly no way of doing this, unless of course the homescreen has some API for requesting this information. Your best bet is probably listening for screen turn ons/turnoffs.

But even so, just pick a conservative refresh rate and let your users modify it.


问:
How to programmatically create a Fragment Google Map
```<code>layContent = (LinearLayout) findViewById(R.id.ll_survey_list);

  TextView textQuestion;

            textQuestion = new TextView(this);
            textQuestion.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
            textQuestion.setTextColor(Color.parseColor("#000000"));
            textQuestion.setPadding(8,35,3,0);
            textQuestion.setVisibility(View.VISIBLE);
            textQuestion.setText(surveyS.get(s));
            layContent.addView(textQuestion);
</code>```

I have already made a textview programmatically and I want to make one programmatically for fragment google map like Textview. How can I do that ?

```<code><fragment
           android:id="@+id/map"
           android:name="com.google.android.gms.maps.MapFragment"
           android:layout_width="match_parent"
           android:layout_height="200dp"
           android:layout_centerHorizontal="true"
           android:visibility="gone"/>
</code>```

My question is this Googlemap will array in layContent

答:
FragmentManager fragmentManager = getFragmentManager ();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction ();
fragmentTransaction.add (R.id.myFrame, myFrag);
fragmentTransaction.commit ();

check this link: https://www.intertech.com/Blog/programmatically-working-with-android-fragments/

Body:
layContent = (LinearLayout) findViewById(R.id.ll_survey_list);

  TextView textQuestion;

            textQuestion = new TextView(this);
            textQuestion.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
            textQuestion.setTextColor(Color.parseColor("#000000"));
            textQuestion.setPadding(8,35,3,0);
            textQuestion.setVisibility(View.VISIBLE);
            textQuestion.setText(surveyS.get(s));
            layContent.addView(textQuestion);

I have already made a textview programmatically and I want to make one programmatically for fragment google map like Textview. How can I do that ?

<fragment
           android:id="@+id/map"
           android:name="com.google.android.gms.maps.MapFragment"
           android:layout_width="match_parent"
           android:layout_height="200dp"
           android:layout_centerHorizontal="true"
           android:visibility="gone"/>

My question is this Googlemap will array in layContent


问:
How can I write to the console in PHP?
Is it possible write a string or log into the console?

What I mean

Just like in JSP, if we print something like system.out.println("some"), it will be there at the console, not at a page.

答:
I was looking for a way to debug code in a WordPress plugin that I was developing and came across this post.

I took the bits of code that are most applicable to me from other responses and combined these into a function that I can use for debugging WordPress. The function is:

```<code>function debug_log($object=null, $label=null, $priority=1) {
    $priority = $priority<1? 1: $priority;
    $message = json_encode($object, JSON_PRETTY_PRINT);
    $label = "Debug" . ($label ? " ($label): " : ': ');
    echo "<script>console.log('" . str_repeat("-", $priority-1) . $label . "', " . $message . ");</script>";
}
</code>```

Usage is as follows:

```<code>$txt = 'This is a test string';
$sample_array = array('cat', 'dog', 'pig', 'ant', 'fly');
debug_log($txt, '', 7);
debug_log($sample_array);
</code>```

If this function is used with WordPress development, the function should be placed in the functions.php file of the child theme and can then be called anywhere in the code.

ContentLicense: CC BY-SA 4.0

Title: How can I write to the console in PHP?

Body:
I was looking for a way to debug code in a WordPress plugin that I was developing and came across this post.

I took the bits of code that are most applicable to me from other responses and combined these into a function that I can use for debugging WordPress. The function is:

function debug_log($object=null, $label=null, $priority=1) {
    $priority = $priority<1? 1: $priority;
    $message = json_encode($object, JSON_PRETTY_PRINT);
    $label = "Debug" . ($label ? " ($label): " : ': ');
    echo "<script>console.log('" . str_repeat("-", $priority-1) . $label . "', " . $message . ");</script>";
}

Usage is as follows:

$txt = 'This is a test string';
$sample_array = array('cat', 'dog', 'pig', 'ant', 'fly');
debug_log($txt, '', 7);
debug_log($sample_array);

If this function is used with WordPress development, the function should be placed in the functions.php file of the child theme and can then be called anywhere in the code.


问:
Why is git marking two separate deleted lines as conflict?
I have a file with this content:

```<code>line 1
line 2
line 3
line 4
</code>```

commited on branch A.

From this, I create a branch B and delete the third line in a commit.
I checkout branch A and delete the second line in another commit.

When I merge branch B in branch A, I get a conflict in that file like this:

```<code>line 1
<<<<<<< HEAD
line 2
=======
line 3
>>>>>>> B
line 4
</code>```

1) Why is there a conflict if there wasn't the same line modified?
2) Why is it showing like that instead of:

```<code>line 1
<<<<<<< HEAD
=======
>>>>>>> B
line 4
</code>```

that more clearly shows that those lines were deleted?

答:
In order to make sure it doesn't destroy anything, any decent diff program also keeps track of at least two lines of context: one above and one below the added/modified/deleted lines.

When you delete line 3 on branch B, in fact, you modify the block of lines 2-4. Similar, on branch A you modify the block of lines 1-3.

These two blocks overlap and they introduce different changes. Git cannot tell for sure how to merge these changes, that's why it marks them as a conflict.

The content of the file on branch B is:

```<code>line 1
line 2
line 4
</code>```

but on the current branch (branch A) is:

```<code>line 1
line 3
line 4
</code>```

Which one is the "correct" version? What do you expect to get after the merge? Git cannot tell. I cannot tell. Only you can tell.

How to read the conflicting area as reported by Git:

```<code>line 1
<<<<<<< HEAD
line 2
=======
line 3
>>>>>>> B
line 4
</code>```

In plain English, the block above says: "between line 1 and line 4, there is line 2 on the current branch but line 3 on branch B".

The block you suggest:

```<code>line 1
<<<<<<< HEAD
=======
>>>>>>> B
line 4
</code>```

means: on both branches, there is nothing between line 1 and line 4. And this is not true.

You will never encounter such a block in a diff. It basically means there is no conflict between the compared versions of the file.

Body:
I have a file with this content:

line 1
line 2
line 3
line 4

commited on branch A.

From this, I create a branch B and delete the third line in a commit.
I checkout branch A and delete the second line in another commit.

When I merge branch B in branch A, I get a conflict in that file like this:

line 1
<<<<<<>>>>>> B
line 4

1) Why is there a conflict if there wasn't the same line modified?
2) Why is it showing like that instead of:

line 1
<<<<<<>>>>>> B
line 4

that more clearly shows that those lines were deleted?

Body:
In order to make sure it doesn't destroy anything, any decent diff program also keeps track of at least two lines of context: one above and one below the added/modified/deleted lines.

When you delete line 3 on branch B, in fact, you modify the block of lines 2-4. Similar, on branch A you modify the block of lines 1-3.

These two blocks overlap and they introduce different changes. Git cannot tell for sure how to merge these changes, that's why it marks them as a conflict.

The content of the file on branch B is:

line 1
line 2
line 4

but on the current branch (branch A) is:

line 1
line 3
line 4

Which one is the "correct" version? What do you expect to get after the merge? Git cannot tell. I cannot tell. Only you can tell.

How to read the conflicting area as reported by Git:

line 1
<<<<<<< HEAD
line 2
=======
line 3
>>>>>>> B
line 4

In plain English, the block above says: "between line 1 and line 4, there is line 2 on the current branch but line 3 on branch B".

The block you suggest:

line 1
<<<<<<< HEAD
=======
>>>>>>> B
line 4

means: on both branches, there is nothing between line 1 and line 4. And this is not true.

You will never encounter such a block in a diff. It basically means there is no conflict between the compared versions of the file.


问:
Regex match line Z only if preceded by line X but not if preceded by line Y
Let me preface this by saying that the text is fed in line by line.  Lookahead will NOT work.

So for the following I should be running two separate regex searches.

This is about as far as I got with the regex before my brain hurt:

Case 1:

```<code>(?<!Case 2.)[\s\S]*?This line should match\.
</code>```

Case 2:

```<code>(?<!Case 1.)[\s\S]*?This line should match\.
</code>```

The first regex search should return a successful match for every line which matches the text: "This line should match." after the line "Case 1." but before the line "Case 2." (bracketed [ ] here for clarity)

The second regex search should return a successful match for every line which matches the text: `"This line should match." after the line "Case 2." but before the line "Start of new sequence." (parenthetical ( ) here for clarity)

In the actual text the parenthesis and brackets are not there and the two different sets of lines are textually identical.

Text being searched:

```<code>Start of new sequence.
Random line(s).
Case 1.
Random line(s).
[This line should match.]
Random line(s).
[This line should match.]
Random line(s).
Case 2.
Random line(s).
(This line should match.)
Random line(s).
(This line should match.)
Random line(s).

Start of new sequence.
Random line(s).
Case 1.
Random line(s).
[This line should match.]
Random line(s).
[This line should match.]
Random line(s).
Case 2.
Random line(s).
(This line should match.)
Random line(s).
(This line should match.)
</code>```

答:
How can you imagine a conditional match before (or after) a pattern you still don't have?

So if you receive the line, then you can match the pattern (with lookahead or any other construction).

Using lookahead I simply propose:

```<code>(?<=Case 1\.).*?(\[This line should match.\]).*?(?=Case 2\.)
</code>```

and

```<code>(?<=Case 2\.).*?(\(This line should match.\)).*?(?=Start of new sequence\.)
</code>```

This do the job for your example.

Body:
Let me preface this by saying that the text is fed in line by line.  Lookahead will NOT work.

So for the following I should be running two separate regex searches.

This is about as far as I got with the regex before my brain hurt:

Case 1:

(?<!Case 2.)[\s\S]*?This line should match\.

Case 2:

(?<!Case 1.)[\s\S]*?This line should match\.

The first regex search should return a successful match for every line which matches the text: "This line should match." after the line "Case 1." but before the line "Case 2." (bracketed [ ] here for clarity)

The second regex search should return a successful match for every line which matches the text: `"This line should match." after the line "Case 2." but before the line "Start of new sequence." (parenthetical ( ) here for clarity)

In the actual text the parenthesis and brackets are not there and the two different sets of lines are textually identical.

Text being searched:

Start of new sequence.
Random line(s).
Case 1.
Random line(s).
[This line should match.]
Random line(s).
[This line should match.]
Random line(s).
Case 2.
Random line(s).
(This line should match.)
Random line(s).
(This line should match.)
Random line(s).

Start of new sequence.
Random line(s).
Case 1.
Random line(s).
[This line should match.]
Random line(s).
[This line should match.]
Random line(s).
Case 2.
Random line(s).
(This line should match.)
Random line(s).
(This line should match.)

Body:
How can you imagine a conditional match before (or after) a pattern you still don't have?

So if you receive the line, then you can match the pattern (with lookahead or any other construction).

Using lookahead I simply propose:

(?<=Case 1\.).*?(\[This line should match.\]).*?(?=Case 2\.)

and

(?<=Case 2\.).*?(\(This line should match.\)).*?(?=Start of new sequence\.)

<a href="http://pythex.org/?regex=(%3F%3C%3DCase%202%5C.).*%3F(%5C(This%20line%20should%20match.%5C)).*%3F(%3F%3DStart%20of%20new%20sequence%5C.)&test_string=Start%20of%20new%20sequence.%0ARandom%20line(s).%0ACase%201.%0ARandom%20line(s).%0A%5BThis%20line%20should%20match.%5D%0ARandom%20line(s).%0A%5BThis%20line%20should%20match.%5D%0ARandom%20line(s).%0ACase%202.%0ARandom%20line(s).%0A(This%20line%20should%20match.)%0ARandom%20line(s).%0A(This%20line%20should%20match.)%0ARandom%20line(s).%0A%0AStart%20of%20new%20sequence.%0ARandom%20line(s).%0ACase%201.%0ARandom%20line(s).%0A%5BThis%20line%20should%20match.%5D%0ARandom%20line(s).%0A%5BThis%20line%20should%20match.%5D%0ARandom%20line(s).%0ACase%202.%0ARandom%20line(s).%0A(This%20line%20should%20match.)%0ARandom%20line(s).%0A(This%20line%20should%20match.)&ignorecase=0&multiline=0&dotall=1&verbose=0" rel="nofollow noreferrer">This do the job for your example.


问:
Google Apps Scripts, Distance Matrix URL not properly forming
The overall point of the app is to calculate and display the distance between two addresses defined by html inputs.The problem I am encountering is when the Calculate button is clicked it opens a new tab with a weird URL, "https://n-u3xjzi7wklp272w6mwu2e3jc3umixhe6rym5h7i-0lu-script.googleusercontent.com/userCodeAppPanel?origin=&destination=" which I'm guessing is actually supposed to be the distance matrix request url since the weird URL includes origin=&destination= but I definitely could be wrong.

Here is my Current Code:

```<code>    <!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <h2>Distance Between two Addresses</h2>
<form id="distance_form">
    <label>Origin: </label>
    <input id="origin" type="text" name="origin"/>
    <br/>
    <label>Destination: </label>
    <input id="destination" type="text" name="destination"/>
    <br/>
    <input type="submit" value="Calculate"/>
</form>
<div id="result">
</div>
  </body>

  <script>

$(function () {

  function calculateDistance(origin, destination) {
    var service = new google.maps.DistanceMatrixService();
    service.getDistanceMatrix(
    {
      origins: [origin],
      destinations: [destination],
      travelMode: google.maps.TravelMode.DRIVING,
      unitSystem: google.maps.UnitSystem.IMPERIAL,
      avoidHighways: false,
      avoidTolls: false
    }, callback);
  }

  function callback(response, status) {
    if (status != google.maps.DistanceMatrixStatus.OK) {
      $('#result').html(err);
    } else {
      var origin = response.originAddresses[0];
      var destination = response.destinationAddresses[0];
      if (response.rows[0].elements[0].status === "ZERO_RESULTS") {
        $('#result').html("Better get on a plane. There are no roads between "
                          + origin + " and " + destination);
      } else {
        var distance = response.rows[0].elements[0].distance;
        var distance_value = distance.value;
        var distance_text = distance.text;
        var miles = distance_text.substring(0, distance_text.length - 3);
        $('#result').html("It is " + miles + " miles from " + origin + " to " + destination);
      }
    }
  }

  $('#distance_form').submit(function(){

      var origin = $('#origin').val();
      var destination = $('#destination').val();
      var distance_text = calculateDistance(origin, destination);
  });

});

  </script>
  <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAxmrFQipNODQwlv57BHQxati2jR8_xWdA" async defer></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

</html>
</code>```

答:
The default behaviour on a form submission is to open a new page, which is what causes the strange URL in an Apps Script web app. You can turn this off by adding the following into the  of your HTML:</p>

```<code><script>

  function preventFormSubmit() {

    var forms = document.querySelectorAll('form')

    for (var i = 0; i < forms.length; i++) {
      forms[i].addEventListener('submit', function(event) {
        event.preventDefault()
      })
    }

  } // preventFormSubmit()

  window.addEventListener('load', preventFormSubmit)

</script>
</code>```

Body:
The overall point of the app is to calculate and display the distance between two addresses defined by html inputs.The problem I am encountering is when the Calculate button is clicked it opens a new tab with a weird URL, "https://n-u3xjzi7wklp272w6mwu2e3jc3umixhe6rym5h7i-0lu-script.googleusercontent.com/userCodeAppPanel?origin=&destination=" which I'm guessing is actually supposed to be the distance matrix request url since the weird URL includes origin=&destination= but I definitely could be wrong.

Here is my Current Code:

    <!DOCTYPE html>

    <base target="_top">

Distance Between two Addresses

<form id="distance_form">
    Origin:
    <input id="origin" type="text" name="origin"/>

    Destination:
    <input id="destination" type="text" name="destination"/>

    <input type="submit" value="Calculate"/>
</form>

Body:
The default behaviour on a form submission is to open a new page, which is what causes the strange URL in an Apps Script web app. You can turn this off by adding the following into the  of your HTML:

<script>

  function preventFormSubmit() {

    var forms = document.querySelectorAll('form')

    for (var i = 0; i < forms.length; i++) {
      forms[i].addEventListener('submit', function(event) {
        event.preventDefault()
      })
    }

  } // preventFormSubmit()

  window.addEventListener('load', preventFormSubmit)

</script>


问:
UNNotificationAction not showing in remote notification
I am implemetaing actionable remote notification but action button are not showing while notification come.

Payload

{"aps":{"alert":"Testing..
  (11)","badge":1,"sound":"default"},"category":"newnote"}

My Code

```<code> func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        self.configureUserNotifications()
        self.registerForRemoteNotification()

        return true
    }

func registerForRemoteNotification() {
    let center  = UNUserNotificationCenter.current()
    center.delegate = self
    center.requestAuthorization(options: [.sound, .alert, .badge]) { (granted, error) in
    if error == nil{
        UIApplication.shared.registerForRemoteNotifications()
    }
}

func configureUserNotifications() {
        let acceptAction = UNNotificationAction(identifier:
            "accept", title: "✅ Accept note", options: [])
        let rejectAction = UNNotificationAction(identifier:
            "reject", title: "❌ Reject note", options: [])
        let category =
            UNNotificationCategory(identifier: "newnote",
                                   actions: [acceptAction,rejectAction],
                                   intentIdentifiers: [],
                                   options: [])

        UNUserNotificationCenter.current()
            .setNotificationCategories([category])
    }

    func application(_ application: UIApplication,
                     didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("Registration for remote notifications failed")
        print(error.localizedDescription)
    }

    func application(_ application: UIApplication,
                     didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        print("Registered with device token: \(deviceToken.hexString)")
        self.deviceToken = deviceToken.hexString
    }

    //Called when a notification is delivered to a foreground app.

    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        print("User Info = ",notification.request.content.userInfo)
        completionHandler([.alert, .badge, .sound])
    }

    //Called to let your app know which action was selected by the user for a given notification.

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        print("User Info = ",response.notification.request.content.userInfo)
        print("Response received for \(response.actionIdentifier)")

        if response.actionIdentifier == "accept" {

        }
        else if response.actionIdentifier == "reject" {

        }
        completionHandler()
    }
</code>```

答:
I think if you move UNUserNotificationCenter.current()
            .setNotificationCategories([category]) to your registerForRemoteNotification function, the problem will resolve. Something like this:

```<code> if #available(iOS 8.0, *) {
        let settings: UIUserNotificationSettings =
            UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: Set([category]))
        application.registerUserNotificationSettings(settings)
        application.registerForRemoteNotifications()
    }
</code>```

Body:
I am implemetaing actionable remote notification but action button are not showing while notification come.

Payload

{"aps":{"alert":"Testing..
  (11)","badge":1,"sound":"default"},"category":"newnote"}

My Code

 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        self.configureUserNotifications()
        self.registerForRemoteNotification()

        return true
    }

func registerForRemoteNotification() {
    let center  = UNUserNotificationCenter.current()
    center.delegate = self
    center.requestAuthorization(options: [.sound, .alert, .badge]) { (granted, error) in
    if error == nil{
        UIApplication.shared.registerForRemoteNotifications()
    }
}

func configureUserNotifications() {
        let acceptAction = UNNotificationAction(identifier:
            "accept", title: "✅ Accept note", options: [])
        let rejectAction = UNNotificationAction(identifier:
            "reject", title: "❌ Reject note", options: [])
        let category =
            UNNotificationCategory(identifier: "newnote",
                                   actions: [acceptAction,rejectAction],
                                   intentIdentifiers: [],
                                   options: [])

        UNUserNotificationCenter.current()
            .setNotificationCategories([category])
    }

    func application(_ application: UIApplication,
                     didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("Registration for remote notifications failed")
        print(error.localizedDescription)
    }

    func application(_ application: UIApplication,
                     didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        print("Registered with device token: \(deviceToken.hexString)")
        self.deviceToken = deviceToken.hexString
    }

    //Called when a notification is delivered to a foreground app.

    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        print("User Info = ",notification.request.content.userInfo)
        completionHandler([.alert, .badge, .sound])
    }

    //Called to let your app know which action was selected by the user for a given notification.

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        print("User Info = ",response.notification.request.content.userInfo)
        print("Response received for \(response.actionIdentifier)")

        if response.actionIdentifier == "accept" {

        }
        else if response.actionIdentifier == "reject" {

        }
        completionHandler()
    }

Body:
I think if you move UNUserNotificationCenter.current()
            .setNotificationCategories([category]) to your registerForRemoteNotification function, the problem will resolve. Something like this:

 if #available(iOS 8.0, *) {
        let settings: UIUserNotificationSettings =
            UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: Set([category]))
        application.registerUserNotificationSettings(settings)
        application.registerForRemoteNotifications()
    }


问:
ReactJS: How to find dependencies, which still use PropTypes via main react package
I have changed my react application (based on meteorJS) to the prop-types package, but I'm still getting the warning Warning: Accessing PropTypes via the main React package is deprecated. Use the prop-types package from npm instead.

So I think there is any dependency which is still using the 'old' style. But how do I find this dependency?

This is what the console gives me:

```<code>modules.js?hash=49c6db2db08899db6ed5ab18f5681ac3bb3d8eab:13361 Warning: Accessing PropTypes via the main React package is deprecated. Use the prop-types package from npm instead.
printWarning @ modules.js?hash=49c6db2db08899db6ed5ab18f5681ac3bb3d8eab:13361
warning @ modules.js?hash=49c6db2db08899db6ed5ab18f5681ac3bb3d8eab:13385
get @ modules.js?hash=49c6db2db08899db6ed5ab18f5681ac3bb3d8eab:9932
PropTypes.js @ modules.js?hash=49c6db2db08899db6ed5ab18f5681ac3bb3d8eab:32612
fileEvaluate @ modules-runtime.js?hash=8587d188e038b75ecd27ed2469a52b269e38fb62:343
require @ modules-runtime.js?hash=8587d188e038b75ecd27ed2469a52b269e38fb62:238
index.js @ modules.js?hash=49c6db2db08899db6ed5ab18f5681ac3bb3d8eab:32381
fileEvaluate @ modules-runtime.js?hash=8587d188e038b75ecd27ed2469a52b269e38fb62:343
require @ modules-runtime.js?hash=8587d188e038b75ecd27ed2469a52b269e38fb62:238
main.js @ main.js:1
fileEvaluate @ modules-runtime.js?hash=8587d188e038b75ecd27ed2469a52b269e38fb62:343
require @ modules-runtime.js?hash=8587d188e038b75ecd27ed2469a52b269e38fb62:238
(anonymous) @ app.js?hash=bbc39e8f76f81774071d5c0341cfd78e2baf4ccc:25882
</code>```

答:
I have used simple text search on directory 'node_modules' to search for line that could have old style of importing PropTypes from 'react';

```<code>grep -R "PropTypes.*'react" node_modules/
</code>```

And with that tool, find the project that is causing warning messages from grep output.

Body:
I have changed my react application (based on meteorJS) to the prop-types package, but I'm still getting the warning Warning: Accessing PropTypes via the main React package is deprecated. Use the prop-types package from npm instead.

So I think there is any dependency which is still using the 'old' style. But how do I find this dependency?

This is what the console gives me:

modules.js?hash=49c6db2db08899db6ed5ab18f5681ac3bb3d8eab:13361 Warning: Accessing PropTypes via the main React package is deprecated. Use the prop-types package from npm instead.
printWarning @ modules.js?hash=49c6db2db08899db6ed5ab18f5681ac3bb3d8eab:13361
warning @ modules.js?hash=49c6db2db08899db6ed5ab18f5681ac3bb3d8eab:13385
get @ modules.js?hash=49c6db2db08899db6ed5ab18f5681ac3bb3d8eab:9932
PropTypes.js @ modules.js?hash=49c6db2db08899db6ed5ab18f5681ac3bb3d8eab:32612
fileEvaluate @ modules-runtime.js?hash=8587d188e038b75ecd27ed2469a52b269e38fb62:343
require @ modules-runtime.js?hash=8587d188e038b75ecd27ed2469a52b269e38fb62:238
index.js @ modules.js?hash=49c6db2db08899db6ed5ab18f5681ac3bb3d8eab:32381
fileEvaluate @ modules-runtime.js?hash=8587d188e038b75ecd27ed2469a52b269e38fb62:343
require @ modules-runtime.js?hash=8587d188e038b75ecd27ed2469a52b269e38fb62:238
main.js @ main.js:1
fileEvaluate @ modules-runtime.js?hash=8587d188e038b75ecd27ed2469a52b269e38fb62:343
require @ modules-runtime.js?hash=8587d188e038b75ecd27ed2469a52b269e38fb62:238
(anonymous) @ app.js?hash=bbc39e8f76f81774071d5c0341cfd78e2baf4ccc:25882

Body:
I have used simple text search on directory 'node_modules' to search for line that could have old style of importing PropTypes from 'react';

grep -R "PropTypes.*'react" node_modules/

And with that tool, find the project that is causing warning messages from grep output.


问:
Normal naming convention for a public static variable in a class?
My code looks like this:

```<code>public partial class App : Application
{
    public static PhrasesPage phrasesPage;
</code>```

Here's the class definition:

```<code>public partial class PhrasesPage
</code>```

Is the variable name normally written as phrasesPage or PhrasesPage?

答:
According to the guidelines:

public or protected instance fields are not allowed by the member design guidelines.

DO use PascalCasing [I think this is a typo and should be camel case] in field names.

✓ DO name fields using a noun, noun phrase, or adjective.

X DO NOT use a prefix for field names.

Those are guidelines so if you still want to go ahead and have a public field, use PascalCasing so in your case it would be PhrasesPage. Now whether that's a good name it or not is your decision.

Body:
My code looks like this:

public partial class App : Application
{
    public static PhrasesPage phrasesPage;

Here's the class definition:

public partial class PhrasesPage

Is the variable name normally written as phrasesPage or PhrasesPage?


问:
How do I save all locally created records in ember / ember data?
Currently, the Ember Data filter method has been deprecated. What's the best way to approach saving all new/updated records of a particular type?

You can call save() on a RecordArray so I have been doing:

this.get('store').peekAll('record-type').save() but I'm not sure if there's some better way to go about it.

答:
I would go with:

this.get('store').findAll('users').then((users) => {
  users
    .filterBy('dirtyType', 'created') // filter for unsaved records
    .invoke('save'); // call the save method on each model instance
});```

If you return the users object you get an array of promises that you could catch with Ember.RSVP.all(), to listen for when all the users have been saved.

Body:
I would go with:

this.get('store').findAll('users').then((users) => {
  users
    .filterBy('dirtyType', 'created') // filter for unsaved records
    .invoke('save'); // call the save method on each model instance
});

If you return the users object you get an array of promises that you could catch with Ember.RSVP.all(), to listen for when all the users have been saved.


问:
Make Python code faster
Is it possible to make this code run faster?

```<code>a,b=map(int,input().split())
c=list(map(int,input().split()))
d=list(map(int,input().split()))
e=list(map(int,input().split()))

happy=0

for i in c:
    if i in d:
        happy=happy+1
    elif i in e:
        happy=happy-1

print(happy)
</code>```

The code has to increment or decrement happy variable depending on if elements of c list are present in d or e lists. This code runs fine for small number of elements in c, d and e lists. But when there are many elements , the code execution is terminated due to timeout.

What can I do to make it run faster?

答:
You can avoid the loop.
The variable happy is essentially the difference between the number of elements found in d and the number of elements found in e.

Could there be duplicates in c?

If you want to count the same element only once, then you can use set, that implicitly remove duplicates:

```<code>set_c = set(c)
happy_match = set_c.intersect(d)
unhappy_match = set_c.intersect(e)

happy = len(happy) - len(unhappy_match)
</code>```

If you want to count each occurrence (including duplicates), then you can apply the same logic to lists:

```<code>happy_match = sum(1 if el in d else 0 for el in c)
unhappy_match = sum(1 if el in e else 0 for el in c)

happy = len(happy) - len(unhappy_match)
</code>```

Title: Make Python code faster

Body:
Is it possible to make this code run faster?

a,b=map(int,input().split())
c=list(map(int,input().split()))
d=list(map(int,input().split()))
e=list(map(int,input().split()))

happy=0

for i in c:
    if i in d:
        happy=happy+1
    elif i in e:
        happy=happy-1

print(happy)

The code has to increment or decrement happy variable depending on if elements of c list are present in d or e lists. This code runs fine for small number of elements in c, d and e lists. But when there are many elements , the code execution is terminated due to timeout.

What can I do to make it run faster?

Body:
You can avoid the loop.
The variable happy is essentially the difference between the number of elements found in d and the number of elements found in e.

Could there be duplicates in c?

If you want to count the same element only once, then you can use set, that implicitly remove duplicates:

set_c = set(c)
happy_match = set_c.intersect(d)
unhappy_match = set_c.intersect(e)

happy = len(happy) - len(unhappy_match)

If you want to count each occurrence (including duplicates), then you can apply the same logic to lists:

happy_match = sum(1 if el in d else 0 for el in c)
unhappy_match = sum(1 if el in e else 0 for el in c)

happy = len(happy) - len(unhappy_match)


问:
How to change the DisplayNameAttribute on runtime to use in a Property Grid C#
I am wondering how to change the DisplayNameAttribute on runtime,  I want the displayName to be Feet instead of Meters in my property grid when I do some conversions, is that possible?</p>

```<code>[DisplayName("Meters")]
public double Distance
  {
     get{return distance;}
  }
</code>```

答: If the displayname attribute already exists (like this situation) and you just want to change the name, you can use the propertydescriptor of this property. Just look through the attributes property until you find the attribute and change the value.</p>

Body:
I am wondering how to change the DisplayNameAttribute on runtime,  I want the displayName to be Feet instead of Meters in my property grid when I do some conversions, is that possible?

[DisplayName("Meters")]
public double Distance
  {
     get{return distance;}
  }


问:
Angular Routing is returning the path to html instead of the html
It's almost set up, except ui-view is loading the path to my html file instead of the html itself.

```<code>import angular from 'angular';
import angularMeteor from 'angular-meteor';
import template from './main.html';
import uiRouter from 'angular-ui-router';

import About from '../pages/about/about';

export default angular.module('main', [
  angularMeteor,
  uiRouter,
  About.name
])
  .component('main', {
    templateUrl: 'imports/main/main.html',
    controller: MainCtrl
  })
  .config(config);

function config($locationProvider, $urlRouterProvider) {
  'ngInject';

  $locationProvider.html5Mode(true);

  $urlRouterProvider.otherwise('/');
}
</code>```

Here's the about page javascript

```<code>class About {}

const name = 'about';

export default angular.module(name, [angularMeteor, uiRouter])
.component(name, {
  template,
  controllerAs: name,
  controller: About
})
.config(config);

function config($stateProvider) {
  'ngInject';

  $stateProvider
  .state('about', {
    url: '/about',
    template: '<about></about>'
  });
}
</code>```

So it will say /imports/pages/about/about.html instead of what's actually in the html file.

答:
I think you're not pointing to the file the right way.

Try to change the following:

```<code>$stateProvider
.state('about', {
url: '/about',
template: '<about></about>'
});
</code>```

into

```<code>$stateProvider
.state('about', {
url: '/about',
template: require('/imports/pages/about/about.html')
});
</code>```

Let me know if this works.

Body:
It's almost set up, except ui-view is loading the path to my html file instead of the html itself.

import angular from 'angular';
import angularMeteor from 'angular-meteor';
import template from './main.html';
import uiRouter from 'angular-ui-router';

import About from '../pages/about/about';

export default angular.module('main', [
  angularMeteor,
  uiRouter,
  About.name
])
  .component('main', {
    templateUrl: 'imports/main/main.html',
    controller: MainCtrl
  })
  .config(config);

function config($locationProvider, $urlRouterProvider) {
  'ngInject';

  $locationProvider.html5Mode(true);

  $urlRouterProvider.otherwise('/');
}

Here's the about page javascript

class About {}

const name = 'about';

export default angular.module(name, [angularMeteor, uiRouter])
.component(name, {
  template,
  controllerAs: name,
  controller: About
})
.config(config);

function config($stateProvider) {
  'ngInject';

  $stateProvider
  .state('about', {
    url: '/about',
    template: '<about></about>'
  });
}

So it will say /imports/pages/about/about.html instead of what's actually in the html file.

Body:
I think you're not pointing to the file the right way.

Try to change the following:

$stateProvider
.state('about', {
url: '/about',
template: '<about></about>'
});

into

$stateProvider
.state('about', {
url: '/about',
template: require('/imports/pages/about/about.html')
});

Let me know if this works.


答:
Change template to templateUrl</p>

```<code>templateUrl: 'imports/pages/about/about.html',
</code>```

Title: Angular Routing is returning the path to html instead of the html

Body:
Change template to templateUrl

templateUrl: 'imports/pages/about/about.html',


问:
Validating Rails Globalize Gem with Enum
When using the globalize gem with Active Record enums, I get an error, as if globalize doesn't know that the enum exists.

```<code>class Stuff < ActiveRecord::Base
  enum stuff_type: { one: 1, two: 2 }
  translates :name

  validates :name, presence: true, uniqueness { case_sensitive: false, scope: :stuff_type }

  default_scope do
    includes(:translations)
  end
end
</code>```

If I do:

```<code>s = Stuff.new(name: 'stuff')
s.one!
</code>```

I get an error as the following:

ActiveRecord::StatementInvalid: PG::InvalidTextRepresentation: ERROR:  invalid input syntax for integer: "one"

This happens because of the validation, cause it seems like globalize doesn't understand the enum.

Am I doing something wrong? How should I accomplish this?

答:
The solution was to create my own validation method!

Something like:

```<code>validate :name_by_type
def name_by_type
  max_occurrences = persisted? ? 1 : 0
  occurrences = Stuff.where(stuff_type: stuff_type, name: name).count
  errors['name'] << 'Name already in use' if occurrences > max_occurrences
end
</code>```

Body:
When using the globalize gem with Active Record enums, I get an error, as if globalize doesn't know that the enum exists.

class Stuff < ActiveRecord::Base
  enum stuff_type: { one: 1, two: 2 }
  translates :name

  validates :name, presence: true, uniqueness { case_sensitive: false, scope: :stuff_type }

  default_scope do
    includes(:translations)
  end
end

If I do:

s = Stuff.new(name: 'stuff')
s.one!

I get an error as the following:

ActiveRecord::StatementInvalid: PG::InvalidTextRepresentation: ERROR:  invalid input syntax for integer: "one"

This happens because of the validation, cause it seems like globalize doesn't understand the enum.

Am I doing something wrong? How should I accomplish this?

Body:
The solution was to create my own validation method!

Something like:

validate :name_by_type
def name_by_type
  max_occurrences = persisted? ? 1 : 0
  occurrences = Stuff.where(stuff_type: stuff_type, name: name).count
  errors['name'] << 'Name already in use' if occurrences > max_occurrences
end


问:
Common Dialog for selecting a SQL Server and getting login details?
My application needs to ask the user what SQL Server to connect to and what credentials to use for the connection, and I was wondering if there's a dialog box out there that somebody has already built - functioning like the OpenFileDialog that comes with the framework (in that you .Show it, then you can ask it which file was picked), but looking like the login box from SQL Management Studio.

Ideally, I'd .Show the dialog, and then once it finished, I could get a .ConnectionString property that returned the string associated with all the details they picked.

If once doesn't exist, I'd like to start the process to create it, because I imagine it would be helpful for people to just be able to drop on a form and have getting a database connection from the user taken care of.

答:
Not that I'm aware of, however it should be fairly simple to whip one up and you can use the SQL Server SMO objects which should have all the methods you need.

http://msdn.microsoft.com/en-us/library/ms162169.aspx


问:
Insert with on duplicate key update gives error 1064
I'm trying to use this query but whatever I do I cannot get it to work. I'm still very new to the on duplicate key update syntax, but I can't find anything wrong with it

```<code>INSERT INTO product_leverancier (product_id, leverancier_id, prijs)
SELECT i.product_id, i.leverancier_id, i.prijs FROM import_tbl i
ON DUPLICATE KEY UPDATE product_id=VALUES(product_id),
leverancier_id=VALUES(leverancier_id), prijs=VALUES(prijs)
</code>```

The error I get is this:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UPDATE product_id=VALUES(product_id), leverancier_id=VALUES(leverancier_id), pr' at line 2
  Error code 1064.

And whatever I change it's always the same error and error code.
Any idea what the problem is?

答:
Your syntax is a bit off, and I don't believe that VALUES is used when using a SELECT as the source of the insert.  Instead, use that source table for the update values:

```<code>INSERT INTO product_leverancier (product_id, leverancier_id, prijs)
SELECT i.product_id, i.leverancier_id, i.prijs
FROM import_tbl i
ON DUPLICATE KEY UPDATE
    product_id     = i.product_id,
    leverancier_id = i.leverancier_id,
    prijs          = i.prijs
</code>```

Note that the alias i is required when referring to the columns in the source table.

Here is a good reference question which delves deeper into the syntax of ON DUPLICATE KEY UPDATE when it is used with INSERT INTO ... SELECT:

INSERT INTO ... SELECT FROM ... ON DUPLICATE KEY UPDATE

Body:
I'm trying to use this query but whatever I do I cannot get it to work. I'm still very new to the on duplicate key update syntax, but I can't find anything wrong with it

INSERT INTO product_leverancier (product_id, leverancier_id, prijs)
SELECT i.product_id, i.leverancier_id, i.prijs FROM import_tbl i
ON DUPLICATE KEY UPDATE product_id=VALUES(product_id),
leverancier_id=VALUES(leverancier_id), prijs=VALUES(prijs)

The error I get is this:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UPDATE product_id=VALUES(product_id), leverancier_id=VALUES(leverancier_id), pr' at line 2
  Error code 1064.

And whatever I change it's always the same error and error code.
Any idea what the problem is?

Body:
Your syntax is a bit off, and I don't believe that VALUES is used when using a SELECT as the source of the insert.  Instead, use that source table for the update values:

INSERT INTO product_leverancier (product_id, leverancier_id, prijs)
SELECT i.product_id, i.leverancier_id, i.prijs
FROM import_tbl i
ON DUPLICATE KEY UPDATE
    product_id     = i.product_id,
    leverancier_id = i.leverancier_id,
    prijs          = i.prijs

Note that the alias i is required when referring to the columns in the source table.

Here is a good reference question which delves deeper into the syntax of ON DUPLICATE KEY UPDATE when it is used with INSERT INTO ... SELECT:

INSERT INTO ... SELECT FROM ... ON DUPLICATE KEY UPDATE


问:
Resetting template driven forms in angular 2 (models and validations both)
How do we reset the controls with validation states of Template driven forms in angular 2?
I know that controls can be reset by setting model values to which they are bound to. But what about the validation states(pristine, dirty etc..)?

I tried something like this:

```<code><form (ngSubmit)="onSubmit(playlistForm)" #playlistForm="ngForm">
// Some code here...
</form>
</code>```

And in controller,

```<code>onSubmit(playlistForm: any) {
// ...
  playlistForm.form.reset();
}
</code>```

But in above seems to actually redirect to the ''
And I get error below:

```<code>EXCEPTION: Error: Uncaught (in promise): Error: Cannot match any routes: ''
</code>```

So how do I do what I want?

答:
```<code><form (ngSubmit)="onSubmit(playlistForm)" #playlistForm="ngForm">
// Some code here...
</form>

onSubmit(playlistForm: ngForm) {
// ...
  playlistForm.form.reset();
}
</code>```

Body:
How do we reset the controls with validation states of Template driven forms in angular 2?
I know that controls can be reset by setting model values to which they are bound to. But what about the validation states(pristine, dirty etc..)?

I tried something like this:

<form (ngSubmit)="onSubmit(playlistForm)" #playlistForm="ngForm">
// Some code here...
</form>

And in controller,

onSubmit(playlistForm: any) {
// ...
  playlistForm.form.reset();
}

But in above seems to actually redirect to the ''
And I get error below:

EXCEPTION: Error: Uncaught (in promise): Error: Cannot match any routes: ''

So how do I do what I want?


问:
Errbot Dynamic Regex
I will generate the regex from a file or something and need it in the @re_botcmd

but i get the error: "not defined" is there a way do define a variable that re_botcmd is finding?

```<code>from errbot import BotPlugin, re_botcmd
from pathlib import Path
import re

class ModHelper(BotPlugin):
 """Help Mods Warning User and kick/ban them"""

 def activate(self):
     self.my_file = Path("./filter.txt")
     if not self.my_file.is_file():
         return

     self.filter = open('filter.txt', 'r')
     for self.tmp in self.filter:
         if not self['reg']:
             self['reg'] = '(',self.tmp,')'
         else:
             self['reg'] = self['reg'],'|(',self.tmp,')'

     return super().activate()

 @re_botcmd(pattern=self['reg'], prefixed=False, flags=re.IGNORECASE)
 def test_warn(self, msg, match):
      """Test"""
      return "Warn User"
</code>```

Error from Log file:

```<code>Errbot: File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
File "/home/errbot/errbot-root/plugins/err-modhelper/modhelper.py", line 5, in <module>
class ModHelper(BotPlugin):
File "/home/errbot/errbot-root/plugins/err-modhelper/modhelper.py", line 23, in ModHelper
@re_botcmd(pattern=self['reg'], prefixed=False, flags=re.IGNORECASE)
NameError: name 'self' is not defined
</code>```

Thanks ~

答:
Try somethin like this:</p>

```<code>class ModHelper(BotPlugin):
 """Help Mods Warning User and kick/ban them"""
 def __init__(self, reg=None):
    self.reg = reg

 def activate(self):
     self.my_file = Path("./filter.txt")
     if not self.my_file.is_file():
         return

     self.filter = open('filter.txt', 'r')
     for self.tmp in self.filter:
         if not self.reg:
             self.reg = '(',self.tmp,')'
         else:
             self.reg = self.reg,'|(',self.tmp,')'

     return super().activate()

 @re_botcmd(pattern=self.reg, prefixed=False, flags=re.IGNORECASE)
 def test_warn(self, msg, match):
      """Test"""
      return "Warn User"
</code>```

Title: Errbot Dynamic Regex

Body:
I will generate the regex from a file or something and need it in the @re_botcmd

but i get the error: "not defined" is there a way do define a variable that re_botcmd is finding?

from errbot import BotPlugin, re_botcmd
from pathlib import Path
import re

class ModHelper(BotPlugin):
 """Help Mods Warning User and kick/ban them"""

 def activate(self):
     self.my_file = Path("./filter.txt")
     if not self.my_file.is_file():
         return

     self.filter = open('filter.txt', 'r')
     for self.tmp in self.filter:
         if not self['reg']:
             self['reg'] = '(',self.tmp,')'
         else:
             self['reg'] = self['reg'],'|(',self.tmp,')'

     return super().activate()

 @re_botcmd(pattern=self['reg'], prefixed=False, flags=re.IGNORECASE)
 def test_warn(self, msg, match):
      """Test"""
      return "Warn User"

Error from Log file:

Errbot: File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
File "/home/errbot/errbot-root/plugins/err-modhelper/modhelper.py", line 5, in <module>
class ModHelper(BotPlugin):
File "/home/errbot/errbot-root/plugins/err-modhelper/modhelper.py", line 23, in ModHelper
@re_botcmd(pattern=self['reg'], prefixed=False, flags=re.IGNORECASE)
NameError: name 'self' is not defined

Thanks ~

Body:
Try somethin like this:

class ModHelper(BotPlugin):
 """Help Mods Warning User and kick/ban them"""
 def __init__(self, reg=None):
    self.reg = reg

 def activate(self):
     self.my_file = Path("./filter.txt")
     if not self.my_file.is_file():
         return

     self.filter = open('filter.txt', 'r')
     for self.tmp in self.filter:
         if not self.reg:
             self.reg = '(',self.tmp,')'
         else:
             self.reg = self.reg,'|(',self.tmp,')'

     return super().activate()

 @re_botcmd(pattern=self.reg, prefixed=False, flags=re.IGNORECASE)
 def test_warn(self, msg, match):
      """Test"""
      return "Warn User"


问:
Convert data with one column and multiple rows into multi column multi row data
I have an output of web scraped data in R which looks as follows

```<code>Name1
Email: email1@xyz.com
City/Town: Location1
Name2
Email: email2@abc.com
City/Town: Location2
Name3
Email: email3@pqr.com
City/Town: Location3
</code>```

Some names may not have email or location. I want convert above data into tabular format. The output should look like

```<code>Name      Email           City/Town
Name1   email1@xyz.com  Location1
Name2   email2@abc.com  Location2
Name3   email3@pqr.com  Location3
Name4                   Location4
Name5   email5@abc.com
</code>```

答:
Using dplyr and tidyr, tested on both data provided by @Jaap txt, and by @UweBlock txt1:

```<code>library(dplyr)
library(tidyr)

# data_frame(txt = txt1) %>%
data_frame(txt = txt) %>%
  mutate(txt = if_else(grepl(":", txt), txt, paste("Name:", txt)),
         rn = row_number()) %>%
  separate(txt, into = c("mytype", "mytext"), sep = ":") %>%
  spread(key = mytype, value = mytext) %>%
  select(-rn) %>%
  fill(Name) %>%
  group_by(Name) %>%
  fill(1:2, .direction = "down") %>%
  fill(1:2, .direction = "up") %>%
  unique() %>%
  ungroup() %>%
  select(3:1)

# # A tibble: 5 x 3
#     Name           Email `City/Town`
#    <chr>           <chr>       <chr>
# 1  Name1  email1@xyz.com   Location1
# 2  Name2  email2@abc.com   Location2
# 3  Name3  email3@pqr.com   Location3
# 4  Name4            <NA>   Location4
# 5  Name5  email5@abc.com        <NA>
</code>```

Notes:

See here why we need rn.

Hoping someone will suggest better/simpler code using only tidyverse.

Body:
I have an output of web scraped data in R which looks as follows

Name1
Email: email1@xyz.com
City/Town: Location1
Name2
Email: email2@abc.com
City/Town: Location2
Name3
Email: email3@pqr.com
City/Town: Location3

Some names may not have email or location. I want convert above data into tabular format. The output should look like

Name      Email           City/Town
Name1   email1@xyz.com  Location1
Name2   email2@abc.com  Location2
Name3   email3@pqr.com  Location3
Name4                   Location4
Name5   email5@abc.com

Body:
Using dplyr and tidyr, tested on both data provided by @Jaap txt, and by @UweBlock txt1:

library(dplyr)
library(tidyr)

# data_frame(txt = txt1) %>%
data_frame(txt = txt) %>%
  mutate(txt = if_else(grepl(":", txt), txt, paste("Name:", txt)),
         rn = row_number()) %>%
  separate(txt, into = c("mytype", "mytext"), sep = ":") %>%
  spread(key = mytype, value = mytext) %>%
  select(-rn) %>%
  fill(Name) %>%
  group_by(Name) %>%
  fill(1:2, .direction = "down") %>%
  fill(1:2, .direction = "up") %>%
  unique() %>%
  ungroup() %>%
  select(3:1)

# # A tibble: 5 x 3
#     Name           Email `City/Town`
#    <chr>           <chr>       <chr>
# 1  Name1  email1@xyz.com   Location1
# 2  Name2  email2@abc.com   Location2
# 3  Name3  email3@pqr.com   Location3
# 4  Name4            <NA>   Location4
# 5  Name5  email5@abc.com        <NA>

Notes:

See here why we need rn.

Hoping someone will suggest better/simpler code using only tidyverse.


问:
How can I use Stripe to delay charging a customer until a physical item is shipped?
I'm in the process of building an online marketplace which sells shippable goods. The site will be similar to Etsy, which will connect merchants with buyers.

I'd like to be able to charge a customer's card ONLY when an item is shipped by a merchant to avoid chargebacks and provide an Amazon-like payment experience. This will also help us avoid chargebacks and payment disputes in case a merchant is slow to ship or flakes out. In some cases, the goods will take more than 7 days to be custom manufactured and shipped out

Here's an example timeline:

1/1/2014 - Customer adds $75 worth of items to their cart and clicks "buy". Enters credit card info.

1/1/2014 - Customer's card is verified and a $75 temporary hold is placed on their card. Order is sent to merchant for fulfillment.

1/14/2014 - Merchant ships goods to customer and adds shipping tracking info

1/14/2014 - Customer's card is charged for the full amount and merchant receives $75 minus fees.

I plan to use Stripe Connect for payment processing, but am not sure how to delay capturing a payment for more than 7 days. Any thoughts? I don't want to aggregate the funds under my own account and use payouts since this will likely run afoul of money transmission laws. Any help would be appreciated!

EDIT: It looks like Quora has a similar question here , but the answers don't seem to deal with the case where a merchant ships out the item but the payment fails.

答:
<?php

require_once('stripe-php/init.php');
\Stripe\Stripe::setApiKey('your stripe key');
$token  = $_POST['stripeToken'];

$stripeinfo = \Stripe\Token::retrieve($token);

     $email = $stripeinfo->email;

   $customer = \Stripe\Customer::create(array(
    "source" => $token,
    "email" => $email)
);

?>```


问:
Can't run exes made with ocra -- FATAL ERROR: Failed to create process
I'm trying to package a Ruby program as an .exe on a Windows computer using OCRA. When I tried to use it to create the executable for my program, it threw a weird error at runtime. I tried it with a simple Hello World program, and the error persisted.

I put the following in helloworld.rb:

```<code>puts "Hello, World!"
</code>```

Then, I ran the file through OCRA:

```<code>H:\ocra test>ocra --no-dep-run helloworld.rb
=== Detected gem did_you_mean-1.1.0 (loaded, files)
===     14 files, 32780 bytes
=== Detected gem ocra-1.3.8 (loaded, files)
===     5 files, 291748 bytes
=== Including 59 encoding support files (3918740 bytes, use --no-enc to exclude)

=== Building helloworld.exe
=== Adding user-supplied source files
=== Adding ruby executable ruby.exe
=== Adding detected DLL C:/Ruby24-x64/bin/ruby_builtin_dlls/libgmp-10.dll
=== Adding detected DLL C:/Ruby24-x64/bin/ruby_builtin_dlls/libffi-6.dll
=== Adding library files
=== Compressing 7908093 bytes
=== Finished building helloworld.exe (1919669 bytes)
</code>```

However, when I tried to run this executable, I got the following message:

```<code>H:\ocra test>helloworld.exe
FATAL ERROR: Failed to create process (C:\Users\[username]\AppData\Local\Temp\ocr9C6D.tmp\bin\ruby.exe): 14001
</code>```

Note: This is not a duplicate of this person's question which has the same error message. I am unable to run the EXE on the computer that generated it, whereas the person who asked the linked question was having issues running it on other computers.

Here are the versions of Ruby and OCRA, both of which I believe are the latest version:

```<code>H:\ocra test>ruby --version
ruby 2.4.1p111 (2017-03-22 revision 58053) [x64-mingw32]
H:\ocra test>ocra --version
Ocra 1.3.8
</code>```

I'm on Windows 7 Professional 64 bit.

I also tried running it without the --no-dep-run flag, running the exe on my C: drive instead of H:, and running it in a command prompt with local administrator privileges. All gave the same error message.

How do I fix this?

答: There's now an updated Ocra 1.3.9 which fixes the issue.</p>

Body:
I'm trying to package a Ruby program as an .exe on a Windows computer using OCRA. When I tried to use it to create the executable for my program, it threw a weird error at runtime. I tried it with a simple Hello World program, and the error persisted.

I put the following in helloworld.rb:

puts "Hello, World!"

Then, I ran the file through OCRA:

H:\ocra test>ocra --no-dep-run helloworld.rb
=== Detected gem did_you_mean-1.1.0 (loaded, files)
===     14 files, 32780 bytes
=== Detected gem ocra-1.3.8 (loaded, files)
===     5 files, 291748 bytes
=== Including 59 encoding support files (3918740 bytes, use --no-enc to exclude)

=== Building helloworld.exe
=== Adding user-supplied source files
=== Adding ruby executable ruby.exe
=== Adding detected DLL C:/Ruby24-x64/bin/ruby_builtin_dlls/libgmp-10.dll
=== Adding detected DLL C:/Ruby24-x64/bin/ruby_builtin_dlls/libffi-6.dll
=== Adding library files
=== Compressing 7908093 bytes
=== Finished building helloworld.exe (1919669 bytes)

However, when I tried to run this executable, I got the following message:

H:\ocra test>helloworld.exe
FATAL ERROR: Failed to create process (C:\Users\[username]\AppData\Local\Temp\ocr9C6D.tmp\bin\ruby.exe): 14001

Note: This is not a duplicate of this person's question which has the same error message. I am unable to run the EXE on the computer that generated it, whereas the person who asked the linked question was having issues running it on other computers.

Here are the versions of Ruby and OCRA, both of which I believe are the latest version:

H:\ocra test>ruby --version
ruby 2.4.1p111 (2017-03-22 revision 58053) [x64-mingw32]
H:\ocra test>ocra --version
Ocra 1.3.8

I'm on Windows 7 Professional 64 bit.

I also tried running it without the --no-dep-run flag, running the exe on my C: drive instead of H:, and running it in a command prompt with local administrator privileges. All gave the same error message.

How do I fix this?


问:
Looking for a new language that supports both interpreted and native compilation modes
I currently program in Perl, Python, C#, C, C++, Java, and a few other languages, and I'm looking for a new language to use as a primary when doing personal projects.

My current criteria are:

can  be run as an interpreted language (i.e., run without having to wait to compile it);

can be compiled to native code;

are strongly typed (even if optionally);

support macros/templating/code morphing/wtf you want to call it;

has a decent number of libraries for it, or easily accessible to it;

Ideas?  Suggestions?

答: Scala? It does run scripts, although they are compiled (transparently) first. I'm not sure what you mean by code morphing etc, but it's pretty good for DSLs. It meets all your other requirements - compiled as much as Java is, strongly typed, and has a reasonable number of its own libraries as well as all of Java's. I'm still a beginner with it, but I like it so far.</p>


答:
Have you tried this?</p>

```<code>ON DUPLICATE KEY UPDATE
    product_leverancier.product_id = i.product_id,
    product_leverancier.leverancier_id = i.leverancier_id,
    product_leverancier.prijs = i.prijs
</code>```

Title: Insert with on duplicate key update gives error 1064

Body:
Have you tried this?

ON DUPLICATE KEY UPDATE
    product_leverancier.product_id = i.product_id,
    product_leverancier.leverancier_id = i.leverancier_id,
    product_leverancier.prijs = i.prijs