问:
Custom property binding @Input not working
I am creating custom property in one component which I want to access in another component through @Input() but its not working getting nothing in the second component not even displaying the initial value of result(custom property), I am not getting any error in console, I have also searched solutions online, find some, but can't get it to work.

Please help me out, Here is my code.

Demo Plunker created by a user in the comments.

property-binding-component.ts (Child)

```<code>import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-property-binding',
  template: `
      {{result}} //value working here
  `,
  styles: []
})
export class PropertyBindingComponent{
   @Input() result: number = 5000;
}
</code>```

UPDATED
databindings-components.ts(parent)

```<code>import { Component} from '@angular/core';

@Component({
  selector: 'app-databindings',
  templateUrl: './databindings.component.html',
  styleUrls: ['./databindings.component.css']
})
export class DatabindingsComponent {
}
</code>```

databindings-component.html (Parent)

```<code><app-property-binding [result]="300">   </app-property-binding>
//not working here not event showing the value `5000`
</code>```

app.module.ts

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { DatabindingsComponent } from './databindings/databindings.component';
import { PropertyBindingComponent } from './databindings/property-binding.component';

@NgModule({
  declarations: [AppComponent, DatabindingsComponent, PropertyBindingComponent ],
  imports: [
  BrowserModule,
  FormsModule,
  HttpModule
 ],
  providers: [],
  bootstrap: [AppComponent]
 })
 export class AppModule { }
</code>```

Thanks

答:
The Plunker demo works fine. I'm guessing a reason:

Check your local setup.

Check "app.module.ts" file and see if there are any typos in import and declarations parts.

Check your spelling for "property-binding-component.ts" file (What you typed in your question), which should be "property-binding.component.ts".

Check your "databindings-component.html" file, and double check whether the selector name matches or not. (Since you can't even see the "5000").

Body:
I am creating custom property in one component which I want to access in another component through @Input() but its not working getting nothing in the second component not even displaying the initial value of result(custom property), I am not getting any error in console, I have also searched solutions online, find some, but can't get it to work.

Please help me out, Here is my code.

Demo Plunker created by a user in the comments.

property-binding-component.ts (Child)

import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-property-binding',
  template: `
      {{result}} //value working here
  `,
  styles: []
})
export class PropertyBindingComponent{
   @Input() result: number = 5000;
}

UPDATED
databindings-components.ts(parent)

import { Component} from '@angular/core';

@Component({
  selector: 'app-databindings',
  templateUrl: './databindings.component.html',
  styleUrls: ['./databindings.component.css']
})
export class DatabindingsComponent {
}

databindings-component.html (Parent)

<app-property-binding [result]="300">   </app-property-binding>
//not working here not event showing the value `5000`

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { DatabindingsComponent } from './databindings/databindings.component';
import { PropertyBindingComponent } from './databindings/property-binding.component';

@NgModule({
  declarations: [AppComponent, DatabindingsComponent, PropertyBindingComponent ],
  imports: [
  BrowserModule,
  FormsModule,
  HttpModule
 ],
  providers: [],
  bootstrap: [AppComponent]
 })
 export class AppModule { }

Thanks


来源: stackexchange

问:
Spring : binding object with and without @ModelAttribute
I am new in Spring and registering a user.I did like this.

```<code>@RequestMapping("/register")
    public String register(@ModelAttribute User user,BindingResult result){
       if(!result.hasErrors()){
         userSerive.register(user);
       }
     return "welcome";
}
</code>```

This worked fine,but problem here is I don't need this user object in my welcome.jsp page,so why make model object heavier.So I tried without @ModelAttribute, this also works for me like below.

```<code>@RequestMapping("/register")
    public String register(User user,BindingResult result){
       if(!result.hasErrors()){
         userSerive.register(user);
       }
     return "welcome";
}
</code>```

So I just want to know what are pros & cons of both and which is the best practice if I really don't need user object in jsp. Is @ModelAttribute does any other thing apart from adding object to Model,which spring implicit binding not does.Is @ModelAttribute safer way of binding or else?

I want to categories my query in following 4 type of request.what would be difference  with and without @ModelAttribute if I need not to send data in view and my request is any of-

query string ie form data in GET

request payload or body ie form data in POST

json data in ajaxified GET requst

json data in POST requst- I guess this would not be bind in any of both. @RequestBody is required.

答:
This question is very useful, but I don't see the reply here answer the question properly.

I read through more threads in stackoverflow, and found this one very useful:
https://stackoverflow.com/a/26916920/1542363

For myself how to decide which one to use, if I only need the binding and do not want to store the parameter object in model, then don't use @ModelAttribute.

ContentLicense: CC BY-SA 3.0

Body:
I am new in Spring and registering a user.I did like this.

@RequestMapping("/register")
    public String register(@ModelAttribute User user,BindingResult result){
       if(!result.hasErrors()){
         userSerive.register(user);
       }
     return "welcome";
}

This worked fine,but problem here is I don't need this user object in my welcome.jsp page,so why make model object heavier.So I tried without @ModelAttribute, this also works for me like below.

@RequestMapping("/register")
    public String register(User user,BindingResult result){
       if(!result.hasErrors()){
         userSerive.register(user);
       }
     return "welcome";
}

So I just want to know what are pros & cons of both and which is the best practice if I really don't need user object in jsp. Is @ModelAttribute does any other thing apart from adding object to Model,which spring implicit binding not does.Is @ModelAttribute safer way of binding or else?

I want to categories my query in following 4 type of request.what would be difference  with and without @ModelAttribute if I need not to send data in view and my request is any of-

query string ie form data in GET

request payload or body ie form data in POST

json data in ajaxified GET requst

json data in POST requst- I guess this would not be bind in any of both. @RequestBody is required.


问:
NullPointerException When trying to get string element from array
I have an array of strings called "CONSOLES" and a method "getConsoleName", when I try to get the name by index ID, i get a "NullPointerException"

I just want to get the name by using index...

for example:

```<code>   String myconsole = getConsoleName(0); // myConsole will be "PC"
</code>```

this is my code:

```<code>   public static String[] CONSOLES = {
    "PC",
    "PS4",
    "XBOX ONE",
    "PS VITA"
};

public static String getConsoleName(int ID)
{
    String rtext = "unknown";
    try {
        rtext = CONSOLES[ID];
    } catch (Exception e) {
        System.err.println(e);
    }
    return rtext;
}
</code>```

I hope you understood me

答:
Better code would be -
You need to check first if the ID is less than the length of the CONSOLES array

```<code>   public static String getConsoleName(int ID)
   {
        return (ID < CONSOLES.length ? CONSOLES[ID] : "unknown");
   }
</code>```

If the code is throwing NullPointerException, please paste the logs showing more details on which line

Body:
I have an array of strings called "CONSOLES" and a method "getConsoleName", when I try to get the name by index ID, i get a "NullPointerException"

I just want to get the name by using index...

for example:

   String myconsole = getConsoleName(0); // myConsole will be "PC"

this is my code:

   public static String[] CONSOLES = {
    "PC",
    "PS4",
    "XBOX ONE",
    "PS VITA"
};

public static String getConsoleName(int ID)
{
    String rtext = "unknown";
    try {
        rtext = CONSOLES[ID];
    } catch (Exception e) {
        System.err.println(e);
    }
    return rtext;
}

I hope you understood me

Body:
Better code would be -
You need to check first if the ID is less than the length of the CONSOLES array

   public static String getConsoleName(int ID)
   {
        return (ID < CONSOLES.length ? CONSOLES[ID] : "unknown");
   }

If the code is throwing NullPointerException, please paste the logs showing more details on which line


问:
How to wait until thread is completed in android
I have this method updatePosts() that needs to run inside of a thread. it looks like this

```<code>public void updatePosts(){
    new Thread(){
        public void run(){
            posts.addAll(pholder.fetchPosts());
            System.out.println("size of posts is " + posts.size());

            // UI elements should be accessed only in
            // the primary thread, so we must use the
            // handler here.

        }
    }.start();
}
</code>```

It is literally updating the List called "posts". I have this in my onCreate. The problem is, since it is running in a separate thread, it does not complete before my ImageAdapter needs to use the "posts" List.

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    updatePosts();
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    GridView gridview = (GridView) findViewById(R.id.gridview);
    gridview.setAdapter(new ImageAdapter(this, posts));

    gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v,
                                int position, long id) {
            Toast.makeText(MainActivity.this, "" + position,
                    Toast.LENGTH_SHORT).show();
        }
    });

}
</code>```

What options do I have to ensure that the updatePosts can finish before the ImageAdapter get created?

答:
I think you need to use Handler.

```<code>private ImageAdapter mAdapter;
private MyHandler mHandler;
private List<YourData> posts;
@Override
protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
 setSupportActionBar(toolbar);

 GridView gridview = (GridView) findViewById(R.id.gridview);
 mAdapter = new ImageAdapter(this, posts)；
 gridview.setAdapter(mAdapter);
 gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View v,
                            int position, long id) {
        Toast.makeText(MainActivity.this, "" + position,
                Toast.LENGTH_SHORT).show();
    }
 });
 mHandler = new MyHandler(this);
 updatePosts();
}
public void updatePosts(){
new Thread(){
    public void run(){
        posts.addAll(pholder.fetchPosts());
        System.out.println("size of posts is " + posts.size());
        if (mHandler != null) {
          mHandler.sendMessage(mHandler.obtainMessage(1));
         }
        // UI elements should be accessed only in
        // the primary thread, so we must use the
        // handler here.

    }
}.start();
}
private static class MyHandler extend Handler{
 private WeakReference<Your Activity name> outer;
 public MyHandler(Your Activity name activity){
     outer = new WeakReference<>(activity);
 }
 @Override
 public void handleMessage(Message msg){
     switch(msg.what){
         case 1:
             if(outer.get()!=null){
                 outer.get().mAdapter.refresh(outer.get().posts);
             }
         break;
         default:break;
     }
 }
}
</code>```

And in your ImageAdapter,you need add a method:

```<code> public void refresh(List<YourData> dataSet){
  this.dataSet = dataSet;
  notifyDataSetChanged();
}
</code>```

Body:
I have this method updatePosts() that needs to run inside of a thread. it looks like this

public void updatePosts(){
    new Thread(){
        public void run(){
            posts.addAll(pholder.fetchPosts());
            System.out.println("size of posts is " + posts.size());

            // UI elements should be accessed only in
            // the primary thread, so we must use the
            // handler here.

        }
    }.start();
}

It is literally updating the List called "posts". I have this in my onCreate. The problem is, since it is running in a separate thread, it does not complete before my ImageAdapter needs to use the "posts" List.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    updatePosts();
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    GridView gridview = (GridView) findViewById(R.id.gridview);
    gridview.setAdapter(new ImageAdapter(this, posts));

    gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v,
                                int position, long id) {
            Toast.makeText(MainActivity.this, "" + position,
                    Toast.LENGTH_SHORT).show();
        }
    });

}

What options do I have to ensure that the updatePosts can finish before the ImageAdapter get created?

Body:
I think you need to use Handler.

private ImageAdapter mAdapter;
private MyHandler mHandler;
private List<YourData> posts;
@Override
protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
 setSupportActionBar(toolbar);

 GridView gridview = (GridView) findViewById(R.id.gridview);
 mAdapter = new ImageAdapter(this, posts)；
 gridview.setAdapter(mAdapter);
 gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View v,
                            int position, long id) {
        Toast.makeText(MainActivity.this, "" + position,
                Toast.LENGTH_SHORT).show();
    }
 });
 mHandler = new MyHandler(this);
 updatePosts();
}
public void updatePosts(){
new Thread(){
    public void run(){
        posts.addAll(pholder.fetchPosts());
        System.out.println("size of posts is " + posts.size());
        if (mHandler != null) {
          mHandler.sendMessage(mHandler.obtainMessage(1));
         }
        // UI elements should be accessed only in
        // the primary thread, so we must use the
        // handler here.

    }
}.start();
}
private static class MyHandler extend Handler{
 private WeakReference<Your Activity name> outer;
 public MyHandler(Your Activity name activity){
     outer = new WeakReference<>(activity);
 }
 @Override
 public void handleMessage(Message msg){
     switch(msg.what){
         case 1:
             if(outer.get()!=null){
                 outer.get().mAdapter.refresh(outer.get().posts);
             }
         break;
         default:break;
     }
 }
}

And in your ImageAdapter,you need add a method:

 public void refresh(List<YourData> dataSet){
  this.dataSet = dataSet;
  notifyDataSetChanged();
}


问:
Parsing XML with cElementTree
I have been tasked with re-writing some old XML parsing code to Python and I stumbled into the joy that is cElementTree and I love it because I can do so much in so few lines.

My experience level with xpath is not that extensive and this question is more about drilling further down the structure.

I have this in test.xml

```<code><?xml version="1.0"?>
   <ownershipDocument>
     <issue>
         <ic>0000030305</ic>
         <iname>DUCOMM</iname>
         <its>DCP</its>
     </issue>
     <ndt>
         <ndtran>
             <tc>
                 <tft>4</tft>
                 <tc>P</tc>
                 <esi>0</esi>
             </tc>
         </ndtran>
         <ndtran>
             <tc>
                 <tft>4</tft>
                 <tc>P</tc>
                 <esi>0</esi>
             </tc>
          </ndtran>
     </ndt>
 </ownershipDocument>
</code>```

I wrote this script in Python :

```<code>import xml.etree.cElementTree as ET
tree = ET.parse('test.xml')
root = tree.getroot()
print root.tag
print root.attrib
for child in root:
    print(child.tag, child.attrib)

for issue in root.findall('issue'):
    ic = issue.find('ic').text
    iname= issue.find('iname').text
    print(ic,iname)
</code>```

This gives me :

```<code>ownershipDocument
{}
('issue', {})
('ndt', {})
('0000030305', 'DUCOMM')
</code>```

That successfully gets me the info I need in the "issue".

Problem is that I need to access multiple "ndtran" nodes ( in the "ndt" node ). While parsing I can extract the "tft", "tc" and "esi" values as groups but I need to iterate over each "tc" node, extract the "tft","tc","esi" values, insert them into a database and then move to the next "tc" node and do it again.

What I tried to use to iterate over each of these was this :

```<code>for tc in root.findall("./ndt/ndtran/tc"):
    tft = tc.find('tft').text
    tc = tc.find('tc').text
    esi = tc.find('esi').text
    print(tft,tc,esi)
</code>```

This almost gets me there ( I think ) but it does give me an error.

```<code>esi = tc.find('esi').text
AttributeError: 'int' object has no attribute 'text'
</code>```

I hope that makes sense. I believe what I am after is the DOM parsing methodology which is fine since these documents aren't that big.

I appreciate any advice or pointers in the right direction.

答:
You were replacing value of tc attribute to be string in the previous line :

```<code>for tc in root.findall("./ndt/ndtran/tc"):
    tft = tc.find('tft').text
    tc = tc.find('tc').text
   #^^ use different variable name here
    esi = tc.find('esi').text
         #^^ at this point, `tc` is no longer referencing the outer <tc> elements
</code>```

Interesting coincidence that string also has find() method which return int (-1) when the keyword is not found, hence the 'int' object has no attribute 'text' error.

Title: Parsing XML with cElementTree

Body:
I have been tasked with re-writing some old XML parsing code to Python and I stumbled into the joy that is cElementTree and I love it because I can do so much in so few lines.

My experience level with xpath is not that extensive and this question is more about drilling further down the structure.

I have this in test.xml

<?xml version="1.0"?>
   <ownershipDocument>
     <issue>
         <ic>0000030305</ic>
         <iname>DUCOMM</iname>
         <its>DCP</its>
     </issue>
     <ndt>
         <ndtran>
             <tc>
                 <tft>4</tft>
                 <tc>P</tc>
                 <esi>0</esi>
             </tc>
         </ndtran>
         <ndtran>
             <tc>
                 <tft>4</tft>
                 <tc>P</tc>
                 <esi>0</esi>
             </tc>
          </ndtran>
     </ndt>
 </ownershipDocument>

I wrote this script in Python :

import xml.etree.cElementTree as ET
tree = ET.parse('test.xml')
root = tree.getroot()
print root.tag
print root.attrib
for child in root:
    print(child.tag, child.attrib)

for issue in root.findall('issue'):
    ic = issue.find('ic').text
    iname= issue.find('iname').text
    print(ic,iname)

This gives me :

ownershipDocument
{}
('issue', {})
('ndt', {})
('0000030305', 'DUCOMM')

That successfully gets me the info I need in the "issue".

Problem is that I need to access multiple "ndtran" nodes ( in the "ndt" node ). While parsing I can extract the "tft", "tc" and "esi" values as groups but I need to iterate over each "tc" node, extract the "tft","tc","esi" values, insert them into a database and then move to the next "tc" node and do it again.

What I tried to use to iterate over each of these was this :

for tc in root.findall("./ndt/ndtran/tc"):
    tft = tc.find('tft').text
    tc = tc.find('tc').text
    esi = tc.find('esi').text
    print(tft,tc,esi)

This almost gets me there ( I think ) but it does give me an error.

esi = tc.find('esi').text
AttributeError: 'int' object has no attribute 'text'

I hope that makes sense. I believe what I am after is the DOM parsing methodology which is fine since these documents aren't that big.

I appreciate any advice or pointers in the right direction.

Body:
You were replacing value of tc attribute to be string in the previous line :

for tc in root.findall("./ndt/ndtran/tc"):
    tft = tc.find('tft').text
    tc = tc.find('tc').text
   #^^ use different variable name here
    esi = tc.find('esi').text
         #^^ at this point, `tc` is no longer referencing the outer <tc> elements

Interesting coincidence that string also has find() method which return int (-1) when the keyword is not found, hence the 'int' object has no attribute 'text' error.


问:
How to copy a very large table into another table in MYSQL?
I have a large table with 110M rows. I would like to copy some of the fields into a new table and here is a rough idea of how I am trying to do:

```<code>    DECLARE l_seenChangesTo DATETIME DEFAULT '1970-01-01 01:01:01';
    DECLARE l_migrationStartTime DATETIME;

    SELECT NOW() into l_migrationStartTime;

    -- See if we've run this migration before and if so, pick up from where we left off...
    IF EXISTS(SELECT seenChangesTo FROM migration_status WHERE client_user = CONCAT('this-migration-script-', user())) THEN
        SELECT seenChangesTo FROM migration_status WHERE client_user = CONCAT('this-migration-script-', user()) INTO l_seenChangesTo;
        SELECT NOW() as LogTime, CONCAT('Picking up from where we left off: ', l_seenChangesTo) as MigrationStatus;
    END IF;

    INSERT IGNORE INTO newTable
        (field1, field2, lastModified)
        SELECT o.column1 AS field1,
               o.column2 AS field2,
               o.lastModified
          FROM oldTable o
          WHERE
                o.lastModified >= l_seenChangesTo AND
                o.lastModified <= l_migrationStartTime;

    INSERT INTO migration_status (client_user,seenChangesTo)
        VALUES (CONCAT('this-migration-script-', user()), l_migrationStartTime)
        ON DUPLICATE KEY UPDATE seenChangesTo=l_migrationStartTime;
</code>```

Context:

```<code>CREATE TABLE IF NOT EXISTS `newTable` (
    `field1`     varchar(255) NOT NULL,
    `field2`      tinyint unsigned NOT NULL,
    `lastModified`        datetime NOT NULL,

    PRIMARY KEY (`field1`, `field2`),
    KEY `ix_field1` (`field1`),
    KEY `ix_lastModified` (`lastModified`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `oldTable` (
    `column1`     varchar(255) NOT NULL,
    `column2`      tinyint unsigned NOT NULL,
    `lastModified`        datetime NOT NULL,

    PRIMARY KEY (`column1`, `column2`),
    KEY `ix_column1` (`column1`),
    KEY `ix_lastModified` (`lastModified`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `migration_status` (
        `client_user` char(64) NOT NULL,
        `seenChangesTo` char(128) NOT NULL,

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

Note: I have a few more columns in oldTable. Both oldTable and newTable are in same DB schema using mysql.

What's the general strategy when copying a very table? Should I perform this migration in an iterative manner by copy say 50,000 rows at time.

答: The insert speed doing a migration like this iteratively is going to be dreadfully slow.  Why not SELECT oldTable INTO OUTFILE, then LOAD DATA INFILE ?

Body:
I have a large table with 110M rows. I would like to copy some of the fields into a new table and here is a rough idea of how I am trying to do:

    DECLARE l_seenChangesTo DATETIME DEFAULT '1970-01-01 01:01:01';
    DECLARE l_migrationStartTime DATETIME;

    SELECT NOW() into l_migrationStartTime;

    -- See if we've run this migration before and if so, pick up from where we left off...
    IF EXISTS(SELECT seenChangesTo FROM migration_status WHERE client_user = CONCAT('this-migration-script-', user())) THEN
        SELECT seenChangesTo FROM migration_status WHERE client_user = CONCAT('this-migration-script-', user()) INTO l_seenChangesTo;
        SELECT NOW() as LogTime, CONCAT('Picking up from where we left off: ', l_seenChangesTo) as MigrationStatus;
    END IF;

    INSERT IGNORE INTO newTable
        (field1, field2, lastModified)
        SELECT o.column1 AS field1,
               o.column2 AS field2,
               o.lastModified
          FROM oldTable o
          WHERE
                o.lastModified >= l_seenChangesTo AND
                o.lastModified <= l_migrationStartTime;

    INSERT INTO migration_status (client_user,seenChangesTo)
        VALUES (CONCAT('this-migration-script-', user()), l_migrationStartTime)
        ON DUPLICATE KEY UPDATE seenChangesTo=l_migrationStartTime;

Context:

CREATE TABLE IF NOT EXISTS `newTable` (
    `field1`     varchar(255) NOT NULL,
    `field2`      tinyint unsigned NOT NULL,
    `lastModified`        datetime NOT NULL,

    PRIMARY KEY (`field1`, `field2`),
    KEY `ix_field1` (`field1`),
    KEY `ix_lastModified` (`lastModified`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `oldTable` (
    `column1`     varchar(255) NOT NULL,
    `column2`      tinyint unsigned NOT NULL,
    `lastModified`        datetime NOT NULL,

    PRIMARY KEY (`column1`, `column2`),
    KEY `ix_column1` (`column1`),
    KEY `ix_lastModified` (`lastModified`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `migration_status` (
        `client_user` char(64) NOT NULL,
        `seenChangesTo` char(128) NOT NULL,

        PRIMARY KEY (`client_user`)
    );

Note: I have a few more columns in oldTable. Both oldTable and newTable are in same DB schema using mysql.

What's the general strategy when copying a very table? Should I perform this migration in an iterative manner by copy say 50,000 rows at time.


问:
How to override type properties in TypeScript
For example, I have

```<code>type Line = {
  start: Point;
  end: Point;
  color: string; //'cyan'/'aquablue'/...
}
</code>```

But now I want to create new line type on the base of Line, so that it stores color as number:

```<code>type HexColorLine = Point & {
  color: number;
}
</code>```

Now I expect the HexColorPoint type be equal to

```<code>{
  start: Point;
  end: Point;
  color: number;
}
</code>```

But it equals to

```<code>{
  start: Point;
  end: Point;
  color: string | number;
}
</code>```

Is there a way to override but not extend the prop type with some short syntax? Do i really have to define entirely new type for this?

答:
This is not supported at the moment. TypeScript would need a concept of subtraction types. Proposals exist https://github.com/Microsoft/TypeScript/issues/12215 and https://github.com/Microsoft/TypeScript/issues/4183

Fix

Create a base type :

```<code>type LineBase = {
  start: Point;
  end: Point;
}
type LineBase = LineBase & {
  color: string; //'cyan'/'aquablue'/...
}
</code>```

Body:
For example, I have

type Line = {
  start: Point;
  end: Point;
  color: string; //'cyan'/'aquablue'/...
}

But now I want to create new line type on the base of Line, so that it stores color as number:

type HexColorLine = Point & {
  color: number;
}

Now I expect the HexColorPoint type be equal to

{
  start: Point;
  end: Point;
  color: number;
}

But it equals to

{
  start: Point;
  end: Point;
  color: string | number;
}

Is there a way to override but not extend the prop type with some short syntax? Do i really have to define entirely new type for this?

Body:
This is not supported at the moment. TypeScript would need a concept of subtraction types. Proposals exist https://github.com/Microsoft/TypeScript/issues/12215 and https://github.com/Microsoft/TypeScript/issues/4183

Fix

Create a base type :

type LineBase = {
  start: Point;
  end: Point;
}
type LineBase = LineBase & {
  color: string; //'cyan'/'aquablue'/...
}


问:
GENERAL_NAME_free error when using Aerospike from Ruby
I am trying to create a simple shared library libfoo.so which opens a connection to Aerospike server using a single function, waits for 3 seconds and closes the connection. libfoo.so has a single function open_then_close(char* host, int port).

Then I want to invoke this function from Ruby using FFI:

```<code>require 'ffi'

module Aerospike
  extend FFI::Library
  ffi_lib  "./libfoo.so", "libaerospike.so"
  attach_function :connect_then_close, [:string, :int], :int
end

puts Aerospike.connect_then_close("127.0.0.1", 3000)
</code>```

I tested foolib.so using a C program, it works fine. However when I try to run the above code I get the following error:

```<code>Could not open library '/usr/lib/libaerospike.so': /usr/lib/libaerospike.so: undefined symbol: GENERAL_NAME_free (LoadError)
</code>```

Additional info:

```<code>$ ldd /usr/lib/libaerospike.so
    linux-vdso.so.1 =>  (0x00007ffe413cb000)
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f2ec87a3000)
    /lib64/ld-linux-x86-64.so.2 (0x00005645069a7000)

$ nm -u /usr/lib/libaerospike.so | grep GENERAL_NAME_free
       U GENERAL_NAME_free
</code>```

Any idea what is wrong?

UPDATE

```<code>$ dpkg -l | grep libgcrypt
  ii  libgcrypt11:amd64       1.5.3-2ubuntu4.3        amd64        LGPL Crypto library - runtime library

$ locate libcrypto
  /lib/x86_64-linux-gnu/libcrypto.so.1.0.0
  /usr/lib/x86_64-linux-gnu/libcrypto.a
  /usr/lib/x86_64-linux-gnu/libcrypto.so
  /usr/lib/x86_64-linux-gnu/pkgconfig/libcrypto.pc
</code>```

This is how I compiled and created libfoo.so

```<code>$ gcc -Wall -c -fPIC foo.c -o foo.o -laerospike -lssl -lcrypto -lpthread -lm -lz
</code>```

Linking the wrong way:

```<code>$ gcc -shared -o libfoo.so foo.o
</code>```

答:
It looks like the symbol GENERAL_NAME_free is defined by OpenSSL's crypto library according to this man page and this OpenSSL forum post. So you are probably missing the libcrypto library.

But I'm curious, why you are using the Aerospike C client library for your Ruby program instead of using the Aerospike Ruby client? Is there some specific functionality in the C client that is missing from the Ruby client?

Body:
I am trying to create a simple shared library libfoo.so which opens a connection to Aerospike server using a single function, waits for 3 seconds and closes the connection. libfoo.so has a single function open_then_close(char* host, int port).

Then I want to invoke this function from Ruby using FFI:

require 'ffi'

module Aerospike
  extend FFI::Library
  ffi_lib  "./libfoo.so", "libaerospike.so"
  attach_function :connect_then_close, [:string, :int], :int
end

puts Aerospike.connect_then_close("127.0.0.1", 3000)

I tested foolib.so using a C program, it works fine. However when I try to run the above code I get the following error:

Could not open library '/usr/lib/libaerospike.so': /usr/lib/libaerospike.so: undefined symbol: GENERAL_NAME_free (LoadError)

Additional info:

$ ldd /usr/lib/libaerospike.so
    linux-vdso.so.1 =>  (0x00007ffe413cb000)
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f2ec87a3000)
    /lib64/ld-linux-x86-64.so.2 (0x00005645069a7000)

$ nm -u /usr/lib/libaerospike.so | grep GENERAL_NAME_free
       U GENERAL_NAME_free

Any idea what is wrong?

UPDATE

$ dpkg -l | grep libgcrypt
  ii  libgcrypt11:amd64       1.5.3-2ubuntu4.3        amd64        LGPL Crypto library - runtime library

$ locate libcrypto
  /lib/x86_64-linux-gnu/libcrypto.so.1.0.0
  /usr/lib/x86_64-linux-gnu/libcrypto.a
  /usr/lib/x86_64-linux-gnu/libcrypto.so
  /usr/lib/x86_64-linux-gnu/pkgconfig/libcrypto.pc

This is how I compiled and created libfoo.so

$ gcc -Wall -c -fPIC foo.c -o foo.o -laerospike -lssl -lcrypto -lpthread -lm -lz

Linking the wrong way:

$ gcc -shared -o libfoo.so foo.o


问:
How to zip a file while writing to it?
Does anyone know of a way to zip a stream that you are writing to? I'm trying to avoid writing the file to the disk, and was wondering if I can just compress data as you are writing it to the stream.

The use case behind this is that the raw file is going to be very large and we want to avoid having to write the entire thing unzipped onto the disk.

答: Wrap another OutputStream in a ZipOutputStream (or GZIPOutputStream), and call the write methods on the ZipOutputStream.

ContentLicense: CC BY-SA 2.5

Title: How to zip a file while writing to it?


问:
Typescript use shared library
When having different codebases how would I share code between them.
All code is in typescript and in continuous development.

I am looking for a simple solution.

Things I have tried:

1 using import statement with path to other project:

```<code>import { type } from '../../otherProj/src/type';
</code>```

does not work:

```<code>error TS2307: Cannot find module '../../otherProj/src/type'
</code>```

2 npm module

Installed locally using

```<code>npm i ../otherProj
</code>```

Is problematic as I always have to update the version of the library on each change or I have to manually uninstall / reinstall the library.

3 git submodule / subtree

Using a git submodule.

4 Softlink / Directory Junction

As we are on Windows we are right now using the mklink /D /J

Are there any other alternatives?

答:
2 npm module

Use npm link to link the module.

Docs

https://docs.npmjs.com/cli/link

Title: Typescript use shared library

Body:
When having different codebases how would I share code between them.
All code is in typescript and in continuous development.

I am looking for a simple solution.

Things I have tried:

1 using import statement with path to other project:

import { type } from '../../otherProj/src/type';

does not work:

error TS2307: Cannot find module '../../otherProj/src/type'

2 npm module

Installed locally using

npm i ../otherProj

Is problematic as I always have to update the version of the library on each change or I have to manually uninstall / reinstall the library.

3 git submodule / subtree

Using a git submodule.

4 Softlink / Directory Junction

As we are on Windows we are right now using the mklink /D /J

Are there any other alternatives?


问:
How should you structure HTML Label For attribute to work with screen readers and multiple forms
It is considered best-practice for label elements in HTML to use the for attribute to bind to an input element:

```<code><div>
  <label for="myinput">My Input Label</label>
  <input id="myinput" type="text" />
</div>
</code>```

Instead of

```<code><label>
  My input Label
  <input type="text" />
</label
</code>```

Due to accessibility & screen readers understanding the prior example better

Relevant 1

Relevant 2

However, Ids must (should) be unique for the entire document in html specification Relevant

Lets assume I want to make a form render on two different parts of my website. This means I cannot use the for attribute on the label because it requires an id to work correctly. How should I structure a form so that it can be duplicated in the document and still be understood by accessibility readers?

I am aware I could process the Ids on the label/input to guarantee they are unique. I am wondering if there is a solution that:

Plays nice with screen readers

Does not require for attribute on the label

答:
Unless you are supporting older screen reader / browser combinations you can wrap the label text and the field in one . The examples referenced in the WCAG document you linked are 10 versions or more old, and the IE bug that did not honor wrapped s went away in IE7 (I think, maybe earlier).

Be aware that there are potential styling differences depending on how you write your CSS as well as potential event bubbling issues depending on how you write your JS. But for pure HTML this is fine.

Remember that screen readers are not the only tools the benefit from the  element. Users with motor impairments benefit from the larger overall hit area. Users with low vision or cognitive impairments can benefit from browser default focus styles. On top of this, not all screen reader users are blind, so you want to make sure the experience for sighted users is analogous for those using screen readers.

So these should work for you (without knowing anything about the technology profile of your users):

```<code><label>
 First Name:
 <input type="text">
</label>
</code>```

and

```<code><label>
 <input type="checkbox">
 Yes, please spam me.
</label>
</code>```

Body:
It is considered best-practice for label elements in HTML to use the for attribute to bind to an input element:

  My Input Label
  <input id="myinput" type="text" />

Instead of

  My input Label
  <input type="text" />
</label

Due to accessibility & screen readers understanding the prior example better

Relevant 1

Relevant 2

However, Ids must (should) be unique for the entire document in html specification Relevant

Lets assume I want to make a form render on two different parts of my website. This means I cannot use the for attribute on the label because it requires an id to work correctly. How should I structure a form so that it can be duplicated in the document and still be understood by accessibility readers?

I am aware I could process the Ids on the label/input to guarantee they are unique. I am wondering if there is a solution that:

Plays nice with screen readers

Does not require for attribute on the label

Body:
Unless you are supporting older screen reader / browser combinations you can wrap the label text and the field in one <label>. The examples referenced in the WCAG document you linked are 10 versions or more old, and the IE bug that did not honor wrapped <label>s went away in IE7 (I think, maybe earlier).

Be aware that there are potential styling differences depending on how you write your CSS as well as potential event bubbling issues depending on how you write your JS. But for pure HTML this is fine.

Remember that screen readers are not the only tools the benefit from the <label> element. Users with motor impairments benefit from the larger overall hit area. Users with low vision or cognitive impairments can benefit from browser default focus styles. On top of this, not all screen reader users are blind, so you want to make sure the experience for sighted users is analogous for those using screen readers.

So these should work for you (without knowing anything about the technology profile of your users):

<label>
 First Name:
 <input type="text">
</label>

and

<label>
 <input type="checkbox">
 Yes, please spam me.
</label>


问:
How do you make multiple radio buttons over an image responsive?
I have a picture of Hawaiian islands and I've placed 8 radio buttons with absolute position. But when I use the Chrome inspector to see if the image with the radio buttons are responsive, I see that they are not and the buttons don't stay on the spot on the image that were on full screen. Any suggestions?

CSS:

```<code>#radio1{
    position:absolute;
    top:58.9%;
    left:24.4%;
}

#radio2{
    position:absolute;
    top:57.5%;
    left:27.1%;
}

#radio3{
    position:absolute;
    top:63.2%;
    left:34.05%;
}

#radio4{
    position:absolute;
    top:66.8%;
    left:38%;
}

#radio5{
    position:absolute;
    top:68.9%;
    left:40.4%;
}

#radio6{
    position:absolute;
    top:69.7%;
    left:38.8%;
}

#radio7{
    position:absolute;
    top:73.1%;
    left:40.5%;
}

#radio8{
    position:absolute;
    top:78.8%;
    left:45.5%;
}

#third.form img{
    display:block;
    max-width: 100%;
    height: auto;
</code>```

HTML:

```<code><img src="map.png">
<label for="radio1"></label><input type="radio" name="radio" id="radio1" required><br>
<label for="radio2"></label><input type="radio" name="radio" id="radio2"><br>
<label for="radio3"></label><input type="radio" name="radio" id="radio3"><br>
<label for="radio4"></label><input type="radio" name="radio" id="radio4"><br>
<label for="radio5"></label><input type="radio" name="radio" id="radio5"><br>
<label for="radio6"></label><input type="radio" name="radio" id="radio6"><br>
<label for="radio7"></label><input type="radio" name="radio" id="radio7"><br>
<label for="radio8"></label><input type="radio" name="radio" id="radio8"><br>
</code>```

答:
First you need to use a container to wrap the radio button children, and you can set the island image as the background.

Then make use of the media queries to set the image size to achieve a responsive design.

.container {
  position: relative;
  background-image: url(http://hawaiian-words.com/hw/wp-content/uploads/2014/09/hawaii-island-road-map.jpg);
  background-size: cover;
  width: 884px;
  height: 927px;
}

#radio1 {
  position: absolute;
  top: 58.9%;
  left: 24.4%;
}

#radio2 {
  position: absolute;
  top: 57.5%;
  left: 27.1%;
}

#radio3 {
  position: absolute;
  top: 63.2%;
  left: 34.05%;
}

#radio4 {
  position: absolute;
  top: 66.8%;
  left: 38%;
}

#radio5 {
  position: absolute;
  top: 68.9%;
  left: 40.4%;
}

#radio6 {
  position: absolute;
  top: 69.7%;
  left: 38.8%;
}

#radio7 {
  position: absolute;
  top: 73.1%;
  left: 40.5%;
}

#radio8 {
  position: absolute;
  top: 78.8%;
  left: 45.5%;
}

#third.form img {
  display: block;
  max-width: 100%;
  height: auto;
}

@media screen and (max-width: 768px) {
  .container {
    width: 884px;
    height: 927px;
  }
}

@media (max-width: 768px) and (min-width: 480px) {
  .container {
    width: 663px;
    height: 695px;
  }
}
@media (max-width: 480px) {
  .container {
    width: 442px;
    height: 463px;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <label for="radio1"></label><input type="radio" name="radio" id="radio1" required><br>
  <label for="radio2"></label><input type="radio" name="radio" id="radio2"><br>
  <label for="radio3"></label><input type="radio" name="radio" id="radio3"><br>
  <label for="radio4"></label><input type="radio" name="radio" id="radio4"><br>
  <label for="radio5"></label><input type="radio" name="radio" id="radio5"><br>
  <label for="radio6"></label><input type="radio" name="radio" id="radio6"><br>
  <label for="radio7"></label><input type="radio" name="radio" id="radio7"><br>
  <label for="radio8"></label><input type="radio" name="radio" id="radio8"><br>
</div></code>```

Body:
I have a picture of Hawaiian islands and I've placed 8 radio buttons with absolute position. But when I use the Chrome inspector to see if the image with the radio buttons are responsive, I see that they are not and the buttons don't stay on the spot on the image that were on full screen. Any suggestions?

CSS:

#radio1{
    position:absolute;
    top:58.9%;
    left:24.4%;
}

#radio2{
    position:absolute;
    top:57.5%;
    left:27.1%;
}

#radio3{
    position:absolute;
    top:63.2%;
    left:34.05%;
}

#radio4{
    position:absolute;
    top:66.8%;
    left:38%;
}

#radio5{
    position:absolute;
    top:68.9%;
    left:40.4%;
}

#radio6{
    position:absolute;
    top:69.7%;
    left:38.8%;
}

#radio7{
    position:absolute;
    top:73.1%;
    left:40.5%;
}

#radio8{
    position:absolute;
    top:78.8%;
    left:45.5%;
}

#third.form img{
    display:block;
    max-width: 100%;
    height: auto;

HTML:

<input type="radio" name="radio" id="radio1" required>

<input type="radio" name="radio" id="radio2">

<input type="radio" name="radio" id="radio3">

<input type="radio" name="radio" id="radio4">

<input type="radio" name="radio" id="radio5">

<input type="radio" name="radio" id="radio6">

<input type="radio" name="radio" id="radio7">

<input type="radio" name="radio" id="radio8">

Body:
First you need to use a container to wrap the radio button children, and you can set the island image as the background.

Then make use of the media queries to set the image size to achieve a responsive design.

.container {
  position: relative;
  background-image: url(http://hawaiian-words.com/hw/wp-content/uploads/2014/09/hawaii-island-road-map.jpg);
  background-size: cover;
  width: 884px;
  height: 927px;
}

#radio1 {
  position: absolute;
  top: 58.9%;
  left: 24.4%;
}

#radio2 {
  position: absolute;
  top: 57.5%;
  left: 27.1%;
}

#radio3 {
  position: absolute;
  top: 63.2%;
  left: 34.05%;
}

#radio4 {
  position: absolute;
  top: 66.8%;
  left: 38%;
}

#radio5 {
  position: absolute;
  top: 68.9%;
  left: 40.4%;
}

#radio6 {
  position: absolute;
  top: 69.7%;
  left: 38.8%;
}

#radio7 {
  position: absolute;
  top: 73.1%;
  left: 40.5%;
}

#radio8 {
  position: absolute;
  top: 78.8%;
  left: 45.5%;
}

#third.form img {
  display: block;
  max-width: 100%;
  height: auto;
}

@media screen and (max-width: 768px) {
  .container {
    width: 884px;
    height: 927px;
  }
}

@media (max-width: 768px) and (min-width: 480px) {
  .container {
    width: 663px;
    height: 695px;
  }
}
@media (max-width: 480px) {
  .container {
    width: 442px;
    height: 463px;
  }
}

<div class="container">
  <label for="radio1"></label><input type="radio" name="radio" id="radio1" required><br>
  <label for="radio2"></label><input type="radio" name="radio" id="radio2"><br>
  <label for="radio3"></label><input type="radio" name="radio" id="radio3"><br>
  <label for="radio4"></label><input type="radio" name="radio" id="radio4"><br>
  <label for="radio5"></label><input type="radio" name="radio" id="radio5"><br>
  <label for="radio6"></label><input type="radio" name="radio" id="radio6"><br>
  <label for="radio7"></label><input type="radio" name="radio" id="radio7"><br>
  <label for="radio8"></label><input type="radio" name="radio" id="radio8"><br>
</div>


问:
Speeding Up Python Code Time
```<code>start = time.time()
import csv
f = open('Speed_Test.csv','r+')
coordReader = csv.reader(f, delimiter = ',')
count = -1
successful_trip = 0
trips = 0

for line in coordReader:
    successful_single = 0
    count += 1
    R = interval*0.30
    if count == 0:
        continue
    if 26 < float(line[0]) < 48.7537144 and 26 < float(line[2]) <   48.7537144 and -124.6521017 < float(line[1]) < -68 and -124.6521017 < float(line[3]) < -68:
        y2,x2,y1,x1 = convertCoordinates(float(line[0]),float(line[1]),float(line[2]),float(line[3]))
        coords_line,interval = main(y1,x1,y2,x2)

        for item in coords_line:
            loop_count = 0
            r = 0
            min_dist = 10000

            for i in range(len(df)):
                dist = math.sqrt((item[1]-df.iloc[i,0])**2 + (item[0]-df.iloc[i,1])**2)
                if dist < R:
                    loop_count += 1
                    if dist < min_dist:
                        min_dist = dist
                        r = i
            if loop_count != 0:
                successful_single += 1
                df.iloc[r,2] += 1

        trips += 1
        if successful_single == (len(coords_line)):
            successful_trip += 1

end = time.time()
print('Percent Successful:',successful_trip/trips)
print((end - start))
</code>```

I have this code and explaining it would be extremely time consuming but it doesn't run as fast as I need it to in order to be able to compute as much as I'd like. Is there anything anyone sees off the bat that I could do to speed the process up? Any suggestions would be greatly appreciated.

In essence it reads in 2 lat and long coordinates and changes them to a cartesian coordinate and then goes through every coordinate along the path from on origin coordinate to the destination coordinate in certain interval lengths depending on distance. As it is doing this though there is a data frame (df) with 300+ coordinate locations that it checks against each one of the trips intervals and sees if one is within radius R and then stores the shortest on.

答:
have you considered pooling and running these calculations in parallel ?

https://docs.python.org/2/library/multiprocessing.html

Your code also suggests the variable R,interval might create a dependency and requires a linear solution

Title: Speeding Up Python Code Time

Body:
start = time.time()
import csv
f = open('Speed_Test.csv','r+')
coordReader = csv.reader(f, delimiter = ',')
count = -1
successful_trip = 0
trips = 0

for line in coordReader:
    successful_single = 0
    count += 1
    R = interval*0.30
    if count == 0:
        continue
    if 26 < float(line[0]) < 48.7537144 and 26 < float(line[2]) <   48.7537144 and -124.6521017 < float(line[1]) < -68 and -124.6521017 < float(line[3]) < -68:
        y2,x2,y1,x1 = convertCoordinates(float(line[0]),float(line[1]),float(line[2]),float(line[3]))
        coords_line,interval = main(y1,x1,y2,x2)

        for item in coords_line:
            loop_count = 0
            r = 0
            min_dist = 10000

            for i in range(len(df)):
                dist = math.sqrt((item[1]-df.iloc[i,0])**2 + (item[0]-df.iloc[i,1])**2)
                if dist < R:
                    loop_count += 1
                    if dist < min_dist:
                        min_dist = dist
                        r = i
            if loop_count != 0:
                successful_single += 1
                df.iloc[r,2] += 1

        trips += 1
        if successful_single == (len(coords_line)):
            successful_trip += 1

end = time.time()
print('Percent Successful:',successful_trip/trips)
print((end - start))

I have this code and explaining it would be extremely time consuming but it doesn't run as fast as I need it to in order to be able to compute as much as I'd like. Is there anything anyone sees off the bat that I could do to speed the process up? Any suggestions would be greatly appreciated.

In essence it reads in 2 lat and long coordinates and changes them to a cartesian coordinate and then goes through every coordinate along the path from on origin coordinate to the destination coordinate in certain interval lengths depending on distance. As it is doing this though there is a data frame (df) with 300+ coordinate locations that it checks against each one of the trips intervals and sees if one is within radius R and then stores the shortest on.


问:
Magento - Checking if a module is installed?
I have a small piece of code in a template file that I ONLY want to run if a certain module is installed. I found the below code, which you can use to find if a module is active, but I want to know if a module is installed.

```<code>$modules = Mage::getConfig()->getNode('modules')->children();
$modulesArray = (array)$modules;

if($modulesArray['Mage_Paypal']->is('active')) {
    echo "Paypal module is active.";
} else {
    echo "Paypal module is not active.";
}
</code>```

I'm thinking I could maybe get a list of names of all the modules that are installed, and then use

```<code>if (stristr($modulelist, 'Name_Extension'))
</code>```

to show my code only if the referenced extension is installed.

Anyone any ideas how to do that? Or any better solutions?

答:
Another way to find if a module is installed but disabled is with:

```<code>if (Mage::getStoreConfigFlag('advanced/modules_disable_output/Mage_Paypal')) {
    echo "Paypal module is installed";
}
</code>```

Edit

Have just realised a version of this - using the little known ifconfig - could show a block only if another module is disabled. eg.

```<code><layout>
    <default>
        <reference name="content">
            <block ifconfig="advanced/modules_disable_output/Mage_Paypal" type="core/template" template="sorry/this/is/unavailable.phtml" />
        </reference>
    </default>
</layout>
</code>```

Body:
I have a small piece of code in a template file that I ONLY want to run if a certain module is installed. I found the below code, which you can use to find if a module is active, but I want to know if a module is installed.

$modules = Mage::getConfig()->getNode('modules')->children();
$modulesArray = (array)$modules;

if($modulesArray['Mage_Paypal']->is('active')) {
    echo "Paypal module is active.";
} else {
    echo "Paypal module is not active.";
}

I'm thinking I could maybe get a list of names of all the modules that are installed, and then use

if (stristr($modulelist, 'Name_Extension'))

to show my code only if the referenced extension is installed.

Anyone any ideas how to do that? Or any better solutions?

Body:
Another way to find if a module is installed but disabled is with:

if (Mage::getStoreConfigFlag('advanced/modules_disable_output/Mage_Paypal')) {
    echo "Paypal module is installed";
}

Edit

Have just realised a version of this - using the little known ifconfig - could show a block only if another module is disabled. eg.

<layout>
    <default>
        <reference name="content">
            <block ifconfig="advanced/modules_disable_output/Mage_Paypal" type="core/template" template="sorry/this/is/unavailable.phtml" />
        </reference>
    </default>
</layout>


问:
Java - How to initialize stack use another existing stack?
I already using Stack what using class type for TOKEN, and now I want to make and initialize new Stack using stack on first.

First I think C#'s code, like

Stack<Token> e_infixTokens = new Stack<Token>(infixTokens);

C#'s Stack constuctor use another stack to parameter, but I think JAVA doesn't. Am I right?

So, Here is begin part of my code,

```<code>private Stack<Token> infixTokens;
private Stack<Token> postfixTokens;

Formula(String formula){
    this.formula = formula;
    this.infixTokens = new Stack<>();
    this.postfixTokens = new Stack<>();
</code>```

And few lines under, I use this statement.

```<code>Stack<Token> e_infixTokens = new Stack<>(infixTokens);
</code>```

It occurs error. Error message is :

Stack() in Stack cannot be applied to Java.util.Stack

答:
One simple method is like this.

```<code>Stack<String> stackCopy = (Stack<String>) stack1.clone();
</code>```

This method is from java.util.Vector.clone(), so it's probably a fast  implementation.

Another one is like this, which is very slow after testing.

```<code>Stack<String> stackCopy = new Stack<String>();
for (String string : stack) {
    stackCopy2.add(string);
}
</code>```

The following snippet compares the performance of the two methods to initialize stack by another existing stack.

```<code>public static void main(String[] args) throws Exception {

    Stack<String> stack = new Stack<String>();
    for (int i = 0; i < 1000; i++) {
        stack.push("" + i);
    }

    {
        Stack<String> stackCopy = null;
        long time = System.currentTimeMillis();
        final int numIterations = 100000;
        for (int i = 0; i < numIterations; i++) {
            stackCopy = (Stack<String>) stack.clone();
        }
        System.out.println("stackCopy.get(0) 1 = " + stackCopy.get(0));

        long millis = System.currentTimeMillis() - time;
        System.out.println("Time taken for this: "
                + (millis > 100000 ? (millis / 1000) + " seconds." : millis + " milliseconds."));
    }
    {
        Stack<String> stackCopy = null;
        long time = System.currentTimeMillis();
        final int numIterations = 100000;
        for (int i = 0; i < numIterations; i++) {
            stackCopy = new Stack<String>();
            for (String string : stack) {
                stackCopy.add(string);
            }
        }
        System.out.println("stackCopy.get(0) 2 = " + stackCopy.get(0));

        long millis = System.currentTimeMillis() - time;
        System.out.println("Time taken for this: "
                + (millis > 100000 ? (millis / 1000) + " seconds." : millis + " milliseconds."));
    }
}
</code>```

The console result is as follows:

```<code>stackCopy.get(0) 1 = 0
Time taken for this: 70 milliseconds.
stackCopy.get(0) 2 = 0
Time taken for this: 4098 milliseconds.
</code>```

In addition, the speeds of calling 'add' and calling 'push' are similar in the second method.

Body:
I already using Stack what using class type for TOKEN, and now I want to make and initialize new Stack using stack on first.

First I think C#'s code, like

Stack<Token> e_infixTokens = new Stack<Token>(infixTokens);

C#'s Stack constuctor use another stack to parameter, but I think JAVA doesn't. Am I right?

So, Here is begin part of my code,

private Stack<Token> infixTokens;
private Stack<Token> postfixTokens;

Formula(String formula){
    this.formula = formula;
    this.infixTokens = new Stack<>();
    this.postfixTokens = new Stack<>();

And few lines under, I use this statement.

Stack<Token> e_infixTokens = new Stack<>(infixTokens);

It occurs error. Error message is :

Stack() in Stack cannot be applied to Java.util.Stack

Body:
One simple method is like this.

Stack<String> stackCopy = (Stack<String>) stack1.clone();

This method is from java.util.Vector.clone(), so it's probably a fast  implementation.

Another one is like this, which is very slow after testing.

Stack<String> stackCopy = new Stack<String>();
for (String string : stack) {
    stackCopy2.add(string);
}

The following snippet compares the performance of the two methods to initialize stack by another existing stack.

public static void main(String[] args) throws Exception {

    Stack<String> stack = new Stack<String>();
    for (int i = 0; i < 1000; i++) {
        stack.push("" + i);
    }

    {
        Stack<String> stackCopy = null;
        long time = System.currentTimeMillis();
        final int numIterations = 100000;
        for (int i = 0; i < numIterations; i++) {
            stackCopy = (Stack<String>) stack.clone();
        }
        System.out.println("stackCopy.get(0) 1 = " + stackCopy.get(0));

        long millis = System.currentTimeMillis() - time;
        System.out.println("Time taken for this: "
                + (millis > 100000 ? (millis / 1000) + " seconds." : millis + " milliseconds."));
    }
    {
        Stack<String> stackCopy = null;
        long time = System.currentTimeMillis();
        final int numIterations = 100000;
        for (int i = 0; i < numIterations; i++) {
            stackCopy = new Stack<String>();
            for (String string : stack) {
                stackCopy.add(string);
            }
        }
        System.out.println("stackCopy.get(0) 2 = " + stackCopy.get(0));

        long millis = System.currentTimeMillis() - time;
        System.out.println("Time taken for this: "
                + (millis > 100000 ? (millis / 1000) + " seconds." : millis + " milliseconds."));
    }
}

The console result is as follows:

stackCopy.get(0) 1 = 0
Time taken for this: 70 milliseconds.
stackCopy.get(0) 2 = 0
Time taken for this: 4098 milliseconds.

In addition, the speeds of calling 'add' and calling 'push' are similar in the second method.


问:
React Native In App Utils
I'm trying to set up payments for an iOS app using https://github.com/chirag04/react-native-in-app-utilsm, but I'm having a small problem which is that when I load NativeModules it does have the InAppUtils property so this returns undefined:

```<code>import { NativeModules } from 'react-native'
  const { InAppUtils } = NativeModules
...
  componentWillMount() {
    console.log(InAppUtils
}
</code>```

I installed using both rnpm install --save react-native-in-app-utils and npm install --save react-native-in-app-utils; react-native-link. In both cases it looks like the libraries are linked properly in Xcode.

Any ideas how I can check that the library is installed properly?

答: I installed with yarn add react-native-in-app-utils and it wasn't working, so I ran react-native link and rebuilt the app from XCode and it worked.

Title: React Native In App Utils

Body:
I'm trying to set up payments for an iOS app using https://github.com/chirag04/react-native-in-app-utilsm, but I'm having a small problem which is that when I load NativeModules it does have the InAppUtils property so this returns undefined:

import { NativeModules } from 'react-native'
  const { InAppUtils } = NativeModules
...
  componentWillMount() {
    console.log(InAppUtils
}

I installed using both rnpm install --save react-native-in-app-utils and npm install --save react-native-in-app-utils; react-native-link. In both cases it looks like the libraries are linked properly in Xcode.

Any ideas how I can check that the library is installed properly?


问:
convert relaxng file that include reference to another relax ng file to xsd
I am going to convert relaxng compact file to xsd.
So the command to user here would be:

```<code>java -jar tang.jar test.rng newtest.xsd
</code>```

My question here is as follow:
I have several rnc file in which some of them have the reference to another rnc file. For example I have test1.rnc as follow:

```<code>start= test
test =
  element test {
  (element ref {xsd:anyURL}?,
   element links {
     element link {
         attribute handle {text},
         attribute id {text}
      }*
   }?,
   element name { text }?,
   external "util/phone.rnc"?
}
</code>```

and in the util folder I have phone.rnc which is like this:

```<code>start = phone
phone =
   element phone {
     element number {
       element phonenumber {text }'
       element type { text }?
    },
  }
</code>```

So my question is that how can I convert them to xsd in a correct way?
I tried trang but got test.rnc:29:6: error: sorry, externalRef is not yet supported

答:
First run jing on the schema with the -s option to generate a “simplified“ version:

```<code>java -jar jing.jar -s -c test.rnc > test-simplified.rnc
</code>```

Then give that simplified schema as input to trang:

```<code>java -jar trang.jar test-simplified.rnc newtest.xsd
</code>```

If the version of jing you have doesn’t provide the -s option, then you need to either find and install a new version, or else just build a new version from the sources:

```<code>git clone https://github.com/relaxng/jing-trang.git
cd jing-trang
./ant
java -jar build/jing.jar
</code>```

The last command should emit something like this:

```<code>Jing version 20151127
usage: java com.thaiopensource.relaxng.util.Driver [-i] [-c] [-s] [-t] [-C catalogFile] [-e encoding] RNGFile XMLFile...
RELAX NG is a schema language for XML
See http://relaxng.org/ for more information.
</code>```

Body:
I am going to convert relaxng compact file to xsd.
So the command to user here would be:

java -jar tang.jar test.rng newtest.xsd

My question here is as follow:
I have several rnc file in which some of them have the reference to another rnc file. For example I have test1.rnc as follow:

start= test
test =
  element test {
  (element ref {xsd:anyURL}?,
   element links {
     element link {
         attribute handle {text},
         attribute id {text}
      }*
   }?,
   element name { text }?,
   external "util/phone.rnc"?
}

and in the util folder I have phone.rnc which is like this:

start = phone
phone =
   element phone {
     element number {
       element phonenumber {text }'
       element type { text }?
    },
  }

So my question is that how can I convert them to xsd in a correct way?
I tried trang but got test.rnc:29:6: error: sorry, externalRef is not yet supported

Body:
First run jing on the schema with the -s option to generate a “simplified“ version:

java -jar jing.jar -s -c test.rnc > test-simplified.rnc

Then give that simplified schema as input to trang:

java -jar trang.jar test-simplified.rnc newtest.xsd

If the version of jing you have doesn’t provide the -s option, then you need to either find and install a new version, or else just build a new version from the sources:

git clone https://github.com/relaxng/jing-trang.git
cd jing-trang
./ant
java -jar build/jing.jar

The last command should emit something like this:

Jing version 20151127
usage: java com.thaiopensource.relaxng.util.Driver [-i] [-c] [-s] [-t] [-C catalogFile] [-e encoding] RNGFile XMLFile...
RELAX NG is a schema language for XML
See http://relaxng.org/ for more information.


问:
How do you start a new line in a string/mtext
I am trying to get the text under Leadertext to display on separate lines. How do you show new line in VBA? so it comes out as

CB (Util)

E INV (Util)

```<code>  'Leader Text
    StartPoint(0) = points(6): StartPoint(1) = points(7): StartPoint(2) = points(8)
    LeaderTextWidth = 1
    LeaderText = ("CB " & Util & " E INV " & Util)
    Set LeaderAnnotation = ACAD.ActiveDocument.ModelSpace.AddMText(StartPoint, LeaderTextWidth, LeaderText)
</code>```

答:
Several ways. The VBA.Constants standard library module is your friend. MSDN describes them all.

vbNewLine represents a new line on the platform the code is running on:

```<code>LeaderText = ("CB " & Util & vbNewLine & " E INV " & Util)
</code>```

That's usually your ideal solution. However sometimes your code could be sending strings to a system with Unix-style new lines from both Windows and Mac machines, so you need to be more careful or specific. That's why other constants exist.

vbCrLf makes a Windows new line with ASCII characters 10 and 13:

```<code>LeaderText = ("CB " & Util & vbCrLf & " E INV " & Util)
</code>```

vbLf is ASCII 10, a line feed: vbLf is equivalent to Chr(10).

vbCr is ASCII 13, a carriage return: vbCr is equivalent to Chr(13).

Hence, this is also produces the exact same output (assuming Windows):

```<code>LeaderText = ("CB " & Util & vbCr & vbLf & " E INV " & Util)
</code>```

Or

```<code>LeaderText = ("CB " & Util & Chr(10) & Chr(13) & " E INV " & Util)
</code>```

Body:
I am trying to get the text under Leadertext to display on separate lines. How do you show new line in VBA? so it comes out as

CB (Util)

E INV (Util)

  'Leader Text
    StartPoint(0) = points(6): StartPoint(1) = points(7): StartPoint(2) = points(8)
    LeaderTextWidth = 1
    LeaderText = ("CB " & Util & " E INV " & Util)
    Set LeaderAnnotation = ACAD.ActiveDocument.ModelSpace.AddMText(StartPoint, LeaderTextWidth, LeaderText)

Body:
Several ways. The VBA.Constants standard library module is your friend. MSDN describes them all.

vbNewLine represents a new line on the platform the code is running on:

LeaderText = ("CB " & Util & vbNewLine & " E INV " & Util)

That's usually your ideal solution. However sometimes your code could be sending strings to a system with Unix-style new lines from both Windows and Mac machines, so you need to be more careful or specific. That's why other constants exist.

vbCrLf makes a Windows new line with ASCII characters 10 and 13:

LeaderText = ("CB " & Util & vbCrLf & " E INV " & Util)

vbLf is ASCII 10, a line feed: vbLf is equivalent to Chr(10).

vbCr is ASCII 13, a carriage return: vbCr is equivalent to Chr(13).

Hence, this is also produces the exact same output (assuming Windows):

LeaderText = ("CB " & Util & vbCr & vbLf & " E INV " & Util)

Or

LeaderText = ("CB " & Util & Chr(10) & Chr(13) & " E INV " & Util)


问:
Creating an array with large initial size in powershell
The only way I know to create an array in powershell is

$arr = @(1, 2, 3)

However, this creating method is not convenient if I want to create an array with large initial size such as 10000.

Because I don't want to write code like this

$arr = @(0, 0, 0, 0, 0, 0, ... ,0) # 10000 0s in this line of code

Writing code like the following is not efficient.

```<code>$arr = @()
for ($i = 1; $i -le 10000; $i++) {
  $arr += 0
}
</code>```

Because whenever += operator is executed, all of the elements in the old array would be copied into a newly created array.

What's the best way to create an array with large initial size in powershell?

答:
In PowerShell you are correct in that += will destroy the old array and create a new array with the new items.

For working with a large collection of items i would highly recommend using the ArrayList type from .NET as this is not a fixed size array so PowerShell will not destroy it every time you add an item to it and i've found this to work better in my projects.

Using ArrayList also means that you don't need to start with 10000 items. Because PowerShell won't need to recreate your array every time, you can start with 0 and then add each item as it's needed instead of starting with 10000.

So in your script i would create an empty ArrayList like so

```<code>[System.Collections.ArrayList]$arr = @()
</code>```

and then when you need to add something to it just call .Add() (You don't need to prepopulate the array with 10000 items, it will expand as you add items).

```<code>$arr.Add([int]0)
</code>```

Your example using an ArrayList:

```<code>[System.Collections.ArrayList]$arr = @()
for ($i = 1; $i -le 10000; $i++) {
    $arr.Add([int]0)
}
</code>```

Body:
The only way I know to create an array in powershell is

$arr = @(1, 2, 3)

However, this creating method is not convenient if I want to create an array with large initial size such as 10000.

Because I don't want to write code like this

$arr = @(0, 0, 0, 0, 0, 0, ... ,0) # 10000 0s in this line of code

Writing code like the following is not efficient.

$arr = @()
for ($i = 1; $i -le 10000; $i++) {
  $arr += 0
}

Because whenever += operator is executed, all of the elements in the old array would be copied into a newly created array.

What's the best way to create an array with large initial size in powershell?

Body:
In PowerShell you are correct in that += will destroy the old array and create a new array with the new items.

For working with a large collection of items i would highly recommend using the ArrayList type from .NET as this is not a fixed size array so PowerShell will not destroy it every time you add an item to it and i've found this to work better in my projects.

Using ArrayList also means that you don't need to start with 10000 items. Because PowerShell won't need to recreate your array every time, you can start with 0 and then add each item as it's needed instead of starting with 10000.

So in your script i would create an empty ArrayList like so

[System.Collections.ArrayList]$arr = @()

and then when you need to add something to it just call .Add() (You don't need to prepopulate the array with 10000 items, it will expand as you add items).

$arr.Add([int]0)

Your example using an ArrayList:

[System.Collections.ArrayList]$arr = @()
for ($i = 1; $i -le 10000; $i++) {
    $arr.Add([int]0)
}


问:
How to recognize names from a text using php
I want to extract name(firstnames and lastnames) from a text using php.
Example:
From text below I want to extract names(in this case Aline Wright and Jesse Wright)

Aline Wright is a cancer survivor,
  amputee and a newlywed.  Wednesday
  night she began to show signs she was
  having a stroke.

"I started feeling some left arm
  numbness and a facial droop," said
  Aline.

"It appeared to me that I was probably
  having a stroke."

That's when her husband of four days,
  Jesse Wright, put her in the car and
  rushed her to the Erlanger Medical
  Center. Wright knows an emergency. He
  is a nurse technician at Erlanger.

答:
If you want to do named entity recognition (NER) using PHP, you'll need to either call out to an external NER package or make use of an online natural language processing API.

APIs

NLP API are listed below. Complexity Intelligence and Alchemy API will probably be moderately easier to use for beginners than OpenCalais.

Complexity Intelligence - see the PHP named entity tagging sample code here.

Alchemy API - download their PHP SDK here.

OpenCalais - see the PHP sample code here.

No Code API - by using their api-calls provide text which u need to process. 10K free requests is quite enough for checking any hypothesis.

NER Packages

A few software packages you can use for NER are:

Stanford CoreNLP (Java)

LingPipe (Java)

NLTK (Python)

OpenNLP (Java)

YamCha (C++)

Of these, Stanford CoreNLP is probably a good place to start. Similar to many NLP APIs, it provides a complete processing pipeline for common tasks such as NER.

ContentLicense: CC BY-SA 4.0


问:
Kibana visualise count of not null of a field
I am using elastic search kibana for data visualisation.Suppose i have following json in elasticsearch

{
"name":"Aravind",
"dob":"12-2-17"
}
{
"name":"Aakask",
"dob":""
}
{
"name":"Rinu",
"dob":"14-2-17"
}
{
"name":"Alex",
"dob":"7-1-17"
}

I need to visualise total count of not null dob field.
In this example total dob = 3.Because one value for dob is empty(""), so no need to count that.
Any one tell me how to implement this with kibana?

答: Please look at null value documentation, there you will see that you can define in the mapping value that elastic could not be find, and then kibana don't be count it.</p>


问:
Calculate value based on amount of green against blue and red
A bit stuck on this one.

Here is my predicament:

A colour has 3 elements Red, Green and Blue (RGB).

All colours have a value from 0-255.

for example:

```<code>var red:int = 53;
var green:int = 150;
var blue:int = 28;
</code>```

My scoring system works that the greener the colour the higher score it will get out of 10.

so:

```<code>var red:int = 0;
var green:int = 255;
var blue:int = 0;
</code>```

Would receive the highest score(10) and:

```<code>var red:int = 255;
var green:int = 0;
var blue:int = 255;
</code>```

would receive the lowest score (0).

I need to produce an equation of some sort. Is Bayes' Theorum where I am meant to be?

really dont have a clue.

答:
I worked out a way to do this correctly.

please review the code below:

```<code>var color = parseInt(colorString);
var fitness:Number = 0;
var red:int = (color>> 16) & 0xFF;
var green:int = (color>> 8) & 0xFF;
var blue:int = color & 0xFF;
var greenPercentage = (green/255)*100;
var redAndBluePercentage = ((red+blue)/510)*100;
fitness = greenPercentage-redAndBluePercentage;
fitness = (fitness+100)/2;
trace(fitness);
</code>```

Maths works like this:
take your color separate it into Red, Green and Blue.

Take the percentage of green in the colour. (x/255)

take the percentage of red and blue in the colour (x/510)

subtract your red and blue percentage from your green.

add some maths to it to give you a possible score from 0-100.

```<code>colorFitness("0xFF00FF"); //Outputs 0
colorFitness("0x00FF00"); //Outputs 100
</code>```

Body:
A bit stuck on this one.

Here is my predicament:

A colour has 3 elements Red, Green and Blue (RGB).

All colours have a value from 0-255.

for example:

var red:int = 53;
var green:int = 150;
var blue:int = 28;

My scoring system works that the greener the colour the higher score it will get out of 10.

so:

var red:int = 0;
var green:int = 255;
var blue:int = 0;

Would receive the highest score(10) and:

var red:int = 255;
var green:int = 0;
var blue:int = 255;

would receive the lowest score (0).

I need to produce an equation of some sort. Is Bayes' Theorum where I am meant to be?

really dont have a clue.

Body:
I worked out a way to do this correctly.

please review the code below:

var color = parseInt(colorString);
var fitness:Number = 0;
var red:int = (color>> 16) & 0xFF;
var green:int = (color>> 8) & 0xFF;
var blue:int = color & 0xFF;
var greenPercentage = (green/255)*100;
var redAndBluePercentage = ((red+blue)/510)*100;
fitness = greenPercentage-redAndBluePercentage;
fitness = (fitness+100)/2;
trace(fitness);

Maths works like this:
take your color separate it into Red, Green and Blue.

Take the percentage of green in the colour. (x/255)

take the percentage of red and blue in the colour (x/510)

subtract your red and blue percentage from your green.

add some maths to it to give you a possible score from 0-100.

colorFitness("0xFF00FF"); //Outputs 0
colorFitness("0x00FF00"); //Outputs 100


问:
What's the best way to sort some items in a list in one way, and the rest, another way?
Say I do a search which returns a list of objects

```<code>{ age: 5, color: Yellow, eggs: 2 }
{ age: 3, color: White,  eggs: 5 }
{ age: 4, color: Brown,  eggs: 9 }
{ age: 2, color: Green,  eggs: 4 }
{ age: 3, color: Red,    eggs: 1 }
{ age: 1, color: Blue,   eggs: 6 }
</code>```

I would like to output them all, but in a particular order.
If age is 3, I want these items first, sorted on most amount of eggs.
Then I want the rest of the items sorted alphabetically on color.

So the sorted list would be

```<code>|   3's: eggs   |    rest: alphabetically on color    |
 White  -  Red  -  Blue  -  Brown  -  Green  -  Yellow
</code>```

What is the best way to do this sorting, preferably without creating temporary lists?

Can it be done using a single Comparator, or using streams maybe?

答:
You can do it with a single, kind of messy, Comparator. The idea is:

```<code>int compare(myType obj1, myType obj2)
{
    // first compare age
    if (obj1.age == 3)
    {
        if (obj2.age == 3)
        {
            // ages are both 3, so count eggs
            return obj1.eggs.compareTo(obj2.eggs);
        }
        // age 3 sorts before everything else
        return -1;
    }
    else if (obj2.age == 3)
    {
        // if obj2.age is 3, and obj1.age isn't 3,
        // then obj1 is greater than obj2
        return 1;
    }

    // compare color
    return obj1.color.compareTo(obj2.color);
}
</code>```

Please excuse any syntactical mistakes; my Java is a bit rusty.

Body:
Say I do a search which returns a list of objects

{ age: 5, color: Yellow, eggs: 2 }
{ age: 3, color: White,  eggs: 5 }
{ age: 4, color: Brown,  eggs: 9 }
{ age: 2, color: Green,  eggs: 4 }
{ age: 3, color: Red,    eggs: 1 }
{ age: 1, color: Blue,   eggs: 6 }

I would like to output them all, but in a particular order.
If age is 3, I want these items first, sorted on most amount of eggs.
Then I want the rest of the items sorted alphabetically on color.

So the sorted list would be

|   3's: eggs   |    rest: alphabetically on color    |
 White  -  Red  -  Blue  -  Brown  -  Green  -  Yellow

What is the best way to do this sorting, preferably without creating temporary lists?

Can it be done using a single Comparator, or using streams maybe?

Body:
You can do it with a single, kind of messy, Comparator. The idea is:

int compare(myType obj1, myType obj2)
{
    // first compare age
    if (obj1.age == 3)
    {
        if (obj2.age == 3)
        {
            // ages are both 3, so count eggs
            return obj1.eggs.compareTo(obj2.eggs);
        }
        // age 3 sorts before everything else
        return -1;
    }
    else if (obj2.age == 3)
    {
        // if obj2.age is 3, and obj1.age isn't 3,
        // then obj1 is greater than obj2
        return 1;
    }

    // compare color
    return obj1.color.compareTo(obj2.color);
}

Please excuse any syntactical mistakes; my Java is a bit rusty.


问:
NullPointerException When trying to get string element from array
I have an array of strings called "CONSOLES" and a method "getConsoleName", when I try to get the name by index ID, i get a "NullPointerException"

I just want to get the name by using index...

for example:

```<code>   String myconsole = getConsoleName(0); // myConsole will be "PC"
</code>```

this is my code:

```<code>   public static String[] CONSOLES = {
    "PC",
    "PS4",
    "XBOX ONE",
    "PS VITA"
};

public static String getConsoleName(int ID)
{
    String rtext = "unknown";
    try {
        rtext = CONSOLES[ID];
    } catch (Exception e) {
        System.err.println(e);
    }
    return rtext;
}
</code>```

I hope you understood me

答:
I just tested your code. Its working fine. no error I am getting output PC

```<code>public class StackOverFlow {
 public static String[] CONSOLES = {
            "PC",
            "PS4",
            "XBOX ONE",
            "PS VITA"
        };

 public static void main(String arg[]){

    System.out.println(getConsoleName(0));

}

public static String getConsoleName(int ID)
{
    String rtext = "unknown";
    try {
        rtext = CONSOLES[ID];
    } catch (Exception e) {
        System.err.println(e);
    }
    return rtext;
}
</code>```

}

If you are getting NullPointerException , please give complete code with main method to see where from it occurs.

Body:
I have an array of strings called "CONSOLES" and a method "getConsoleName", when I try to get the name by index ID, i get a "NullPointerException"

I just want to get the name by using index...

for example:

   String myconsole = getConsoleName(0); // myConsole will be "PC"

this is my code:

   public static String[] CONSOLES = {
    "PC",
    "PS4",
    "XBOX ONE",
    "PS VITA"
};

public static String getConsoleName(int ID)
{
    String rtext = "unknown";
    try {
        rtext = CONSOLES[ID];
    } catch (Exception e) {
        System.err.println(e);
    }
    return rtext;
}

I hope you understood me

Body:
I just tested your code. Its working fine. no error I am getting output PC

public class StackOverFlow {
 public static String[] CONSOLES = {
            "PC",
            "PS4",
            "XBOX ONE",
            "PS VITA"
        };

 public static void main(String arg[]){

    System.out.println(getConsoleName(0));

}

public static String getConsoleName(int ID)
{
    String rtext = "unknown";
    try {
        rtext = CONSOLES[ID];
    } catch (Exception e) {
        System.err.println(e);
    }
    return rtext;
}

}

If you are getting NullPointerException , please give complete code with main method to see where from it occurs.


问:
Convert Javascript regex to PHP regex?
I'm using the following regex from emailregex.com to validate emails on my site. It's working like a charm in JS but I'm unable to get it working within PHP.

/^(([^<>()[]\.,;:\s@"]+(.[^<>()[]\.,;:\s@"]+)*)|(".+"))@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/

The issue from what I'm seeing is the backslashes, when adding it in quotes it keeps trying to escape it. Regex101 shows that it is working, it's just a matter of how to get it into PHP.

Any help would be great, thanks!

PHP Code:

```<code>$emailRegex = "/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/"
</code>```

Title: Convert Javascript regex to PHP regex?

Body:
I'm using the following regex from emailregex.com to validate emails on my site. It's working like a charm in JS but I'm unable to get it working within PHP.

/^(([^<>()[]\.,;:\s@"]+(.[^<>()[]\.,;:\s@"]+)*)|(".+"))@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/

The issue from what I'm seeing is the backslashes, when adding it in quotes it keeps trying to escape it. Regex101 shows that it is working, it's just a matter of how to get it into PHP.

Any help would be great, thanks!

PHP Code:

$emailRegex = "/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/"

Body:
Use single quotes ' around regex text instead of double quotes "

  $emailRegex = '/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/';

Because you have used " in your regex,

Otherwise you need to escape " also by \"

Live demo : https://eval.in/763141


问:
Uploading an image to Flask server
I am struggling bit with Flask and uploading a file, here is my Flask code so far:

```<code>    @app.route('/api/user/update/', methods=['PUT'])
@auth.login_required
def update_user():
        # check if the post request has the file part
    user = User.query.filter_by(id=g.user.id,deleted=0).first()
    try:
        if 'uname' in request.args:
            user.username = request.args['uname']
        if 'password' in request.args:
            user.hash_password(request.args['password'])
        if 'lname' in request.args:
            user.lastname = request.args['lname']
        if 'fname' in request.args:
            user.firstname = request.args['fname']
        if 'address' in request.args:
            user.address = request.args['address']
        if 'preferance1' in request.args:
            user.pre1 = request.args['preferance1']
        if 'preferance2' in request.args:
            user.pre2 = request.args['preferance2']
        if 'preferance3' in request.args:
            user.pre3 = request.args['preferance3']
        if 'file' in request.files:
            file = request.files['file']
            filename = secure_filename(file.filename)
            filename.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            #print(filename)
            #print(url_for('upload_file', filename=filename))
            user.image_filename = filename
            user.image_url = url_for('upload_file', filename=filename)
        db.session.commit()
    except:
        print("Error")
        db.session.rollback()
        db.session.flush()
    return jsonify({'user':user.serialize})
</code>```

If I added anything as a file from Postman the request will failed and exception will be thrown. I am not sure why.

答: I think you should write file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) instead of filename.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)). The file is a File Storage object. And the filename is only a str.

Title: Uploading an image to Flask server

Body:
I am struggling bit with Flask and uploading a file, here is my Flask code so far:

    @app.route('/api/user/update/', methods=['PUT'])
@auth.login_required
def update_user():
        # check if the post request has the file part
    user = User.query.filter_by(id=g.user.id,deleted=0).first()
    try:
        if 'uname' in request.args:
            user.username = request.args['uname']
        if 'password' in request.args:
            user.hash_password(request.args['password'])
        if 'lname' in request.args:
            user.lastname = request.args['lname']
        if 'fname' in request.args:
            user.firstname = request.args['fname']
        if 'address' in request.args:
            user.address = request.args['address']
        if 'preferance1' in request.args:
            user.pre1 = request.args['preferance1']
        if 'preferance2' in request.args:
            user.pre2 = request.args['preferance2']
        if 'preferance3' in request.args:
            user.pre3 = request.args['preferance3']
        if 'file' in request.files:
            file = request.files['file']
            filename = secure_filename(file.filename)
            filename.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            #print(filename)
            #print(url_for('upload_file', filename=filename))
            user.image_filename = filename
            user.image_url = url_for('upload_file', filename=filename)
        db.session.commit()
    except:
        print("Error")
        db.session.rollback()
        db.session.flush()
    return jsonify({'user':user.serialize})

If I added anything as a file from Postman the request will failed and exception will be thrown. I am not sure why.


问:
npm can't find package.json
I'm trying to install the dependencies of some example: npm's express 2.5.8 that I've downloaded, but all of the apps throw the same error:

```<code>c:\node\stylus>npm install -d
npm info it worked if it ends with ok
npm info using npm@1.1.1
npm info using node@v0.6.11
npm ERR! Couldn't read dependencies.

npm ERR! Error: ENOENT, no such file or directory 'c:\node\stylus\package.json'
npm ERR! You may report this log at:
npm ERR!     <http://github.com/isaacs/npm/issues>
npm ERR! or email it to:
npm ERR!     <npm-@googlegroups.com>
npm ERR!
npm ERR! System Windows_NT 6.1.7600
npm ERR! command "C:\\Program Files (x86)\\nodejs\\\\node.exe" "C:\\Program File
s (x86)\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "-d"
npm ERR! cwd c:\node\stylus
npm ERR! node -v v0.6.11
npm ERR! npm -v 1.1.1
npm ERR! path c:\node\stylus\package.json
npm ERR! code ENOENT
npm ERR! message ENOENT, no such file or directory 'c:\node\stylus\package.json'

npm ERR! errno {}
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     c:\node\stylus\npm-debug.log
npm not ok
</code>```

The blockage appears to be:

no such file or directory 'c:\node\stylus\package.json

Did I miss a step that creates the package.json ?

I'm running:

Windows 7 64 bit

npm 1.1.1

node 6.11

express 2.5.8

答: I have run npm install -y to skip the question step for creating the missing file package.json, y means yes

Title: npm can't find package.json

Body:
I'm trying to install the dependencies of some example: npm's express 2.5.8 that I've downloaded, but all of the apps throw the same error:

c:\node\stylus>npm install -d
npm info it worked if it ends with ok
npm info using npm@1.1.1
npm info using node@v0.6.11
npm ERR! Couldn't read dependencies.

npm ERR! Error: ENOENT, no such file or directory 'c:\node\stylus\package.json'
npm ERR! You may report this log at:
npm ERR!     <http://github.com/isaacs/npm/issues>
npm ERR! or email it to:
npm ERR!     <npm-@googlegroups.com>
npm ERR!
npm ERR! System Windows_NT 6.1.7600
npm ERR! command "C:\\Program Files (x86)\\nodejs\\\\node.exe" "C:\\Program File
s (x86)\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "-d"
npm ERR! cwd c:\node\stylus
npm ERR! node -v v0.6.11
npm ERR! npm -v 1.1.1
npm ERR! path c:\node\stylus\package.json
npm ERR! code ENOENT
npm ERR! message ENOENT, no such file or directory 'c:\node\stylus\package.json'

npm ERR! errno {}
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     c:\node\stylus\npm-debug.log
npm not ok

The blockage appears to be:

no such file or directory 'c:\node\stylus\package.json

Did I miss a step that creates the package.json ?

I'm running:

Windows 7 64 bit

npm 1.1.1

node 6.11

express 2.5.8


问:
Why am I not getting a value from my getElementById()?
I want to take in a value from the URL, add it to a span tag on my slots.html so the user can read it, then pull that same value into another JS file to alter it as the game progresses. The Url code works fine and I get the appropriate value:

elId("wallet").textContent = (values["bank"]); which returns for example 1234.

Player Bank:
 which displays 1234 properly

but when I try to get the value from my html (var elWallet=elId("wallet");)to another JS page it returns  instead of 1234.

Could someone please explain to me what I am doing wrong, and how to improve my understanding of this. Any help would be appreciated!

EDIT: var elId = function(id) {return document.getElementById(id); } is the function I wrote to make writing document.get easier.

EDIT 2: Well I found the issue, talking through with a friend, thanks anyways for all the help.

答:
Could please try using innerHTML to get the values.

elWallet.innerHTML will return the value inside your span tag.

Update:
This works for me. may be you might have put wallet element after the script tag.

Player Bank: 1234

```<code><script>
var elId = function(id) {return document.getElementById(id); }
var elWallet=elId("wallet");
console.log(elWallet.textContent);
console.log(elWallet.innerHTML);

</script>
</body>
</html>
</code>```

Body:
Could please try using innerHTML to get the values.

elWallet.innerHTML will return the value inside your span tag.

Update:
This works for me. may be you might have put wallet element after the script tag.

Player Bank: 1234

<script>
var elId = function(id) {return document.getElementById(id); }
var elWallet=elId("wallet");
console.log(elWallet.textContent);
console.log(elWallet.innerHTML);

</script>
</body>
</html>


问:
Removing consecutive duplicates words out of text using Regex and displaying the new text
Hy,

I have the following code:

```<code>import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.regex.*;

/
public  class RegexSimple4
{

     public static void main(String[] args) {

          try {
              Scanner myfis = new Scanner(new File("D:\\myfis32.txt"));
              ArrayList <String> foundaz = new ArrayList<String>();
              ArrayList <String> noduplicates = new ArrayList<String>();

              while(myfis.hasNext()) {
                  String line = myfis.nextLine();
                  String delim = " ";
                  String [] words = line.split(delim);

                  for (String s : words) {
                      if (!s.isEmpty() && s != null) {
                          Pattern pi = Pattern.compile("[aA-zZ]*");
                          Matcher ma = pi.matcher(s);

                          if (ma.find()) {
                              foundaz.add(s);
                          }
                      }
                  }
              }

              if(foundaz.isEmpty()) {
                  System.out.println("No words have been found");
              }

              if(!foundaz.isEmpty()) {
                  int n = foundaz.size();
                  String plus = foundaz.get(0);
                  noduplicates.add(plus);
                  for(int i=1; i<n; i++) {
                      if ( !noduplicates.get(i-1) .equalsIgnoreCase(foundaz.get(i))) {
                          noduplicates.add(foundaz.get(i));
                      }
                  }

                  //System.out.print("Cuvantul/cuvintele \n"+i);

              }
              if(!foundaz.isEmpty()) {
                  System.out.print("Original text \n");
                  for(String s: foundaz) {
                      System.out.println(s);
                  }
              }
              if(!noduplicates.isEmpty()) {
                  System.out.print("Remove duplicates\n");
                  for(String s: noduplicates) {
                      System.out.println(s);
                  }
              }

          } catch(Exception ex) {
              System.out.println(ex);
          }
      }
  }
</code>```

With the purpose of removing consecutive duplicates from phrases. The code works only for a column of strings not for full length phrases.

For example my input should be:

Blah blah dog cat mice.
  Cat mice dog dog.

And the output

Blah dog cat mice.
  Cat mice dog.

Sincerly,

答:
Bellow code work fine

import java.util.Scanner;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class DuplicateRemoveEx {

```<code>public static void main(String[] args){

    String regex="(?i)\\b(\\w+)(\\b\\W+\\1\\b)+";
    Pattern p = Pattern.compile(regex,Pattern.CASE_INSENSITIVE);

    Scanner in = new Scanner(System.in);
    int numSentences = Integer.parseInt(in.nextLine());
    while(numSentences-- >0){
        String input = in.nextLine();
        Matcher m = p.matcher(input);
        while(m.find()){
            input=input.replaceAll(regex, "$1");
        }
        System.out.println(input);
    }
    in.close();
}
</code>```

}

Body:
Hy,

I have the following code:

import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.regex.*;

/
public  class RegexSimple4
{

     public static void main(String[] args) {

          try {
              Scanner myfis = new Scanner(new File("D:\\myfis32.txt"));
              ArrayList <String> foundaz = new ArrayList<String>();
              ArrayList <String> noduplicates = new ArrayList<String>();

              while(myfis.hasNext()) {
                  String line = myfis.nextLine();
                  String delim = " ";
                  String [] words = line.split(delim);

                  for (String s : words) {
                      if (!s.isEmpty() && s != null) {
                          Pattern pi = Pattern.compile("[aA-zZ]*");
                          Matcher ma = pi.matcher(s);

                          if (ma.find()) {
                              foundaz.add(s);
                          }
                      }
                  }
              }

              if(foundaz.isEmpty()) {
                  System.out.println("No words have been found");
              }

              if(!foundaz.isEmpty()) {
                  int n = foundaz.size();
                  String plus = foundaz.get(0);
                  noduplicates.add(plus);
                  for(int i=1; i<n; i++) {
                      if ( !noduplicates.get(i-1) .equalsIgnoreCase(foundaz.get(i))) {
                          noduplicates.add(foundaz.get(i));
                      }
                  }

                  //System.out.print("Cuvantul/cuvintele \n"+i);

              }
              if(!foundaz.isEmpty()) {
                  System.out.print("Original text \n");
                  for(String s: foundaz) {
                      System.out.println(s);
                  }
              }
              if(!noduplicates.isEmpty()) {
                  System.out.print("Remove duplicates\n");
                  for(String s: noduplicates) {
                      System.out.println(s);
                  }
              }

          } catch(Exception ex) {
              System.out.println(ex);
          }
      }
  }

With the purpose of removing consecutive duplicates from phrases. The code works only for a column of strings not for full length phrases.

For example my input should be:

Blah blah dog cat mice.
  Cat mice dog dog.

And the output

Blah dog cat mice.
  Cat mice dog.

Sincerly,

Body:
Bellow code work fine

import java.util.Scanner;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class DuplicateRemoveEx {

public static void main(String[] args){

    String regex="(?i)\\b(\\w+)(\\b\\W+\\1\\b)+";
    Pattern p = Pattern.compile(regex,Pattern.CASE_INSENSITIVE);

    Scanner in = new Scanner(System.in);
    int numSentences = Integer.parseInt(in.nextLine());
    while(numSentences-- >0){
        String input = in.nextLine();
        Matcher m = p.matcher(input);
        while(m.find()){
            input=input.replaceAll(regex, "$1");
        }
        System.out.println(input);
    }
    in.close();
}

}