问:
HighCharts: Display total value below the legend title
I am able to display the legend and legend title in angular2-highcharts.
I am planning to display the total count below the legend title ( here below city), but couldn't able to find out how.
Also I am not sure why % is displayed along with the value in the legend values.

My label formatter is:

```<code>  labelFormatter: function () {
      return '<div class="legend-label-md row" style=" border-bottom:1px solid black; margin-bottom: 5px"><span class="col-md-10">' + this.name +
             '</span><span class="col-md-2" >' + this.value +
              '%</span></div> ';
       }
</code>```

https://plnkr.co/edit/yzXLz7AIDoWa1Pzxxl4k?p=preview

答:
Each pie series point has total for the series, so you could update legend on load event of a chart to include the total from the series.

Demo: https://plnkr.co/edit/6JW1KmYE1Lr4pAIWCJTm?p=preview

template as:

```<code>template: `
    <chart  [options]="options" (load)="onLoad($event)">
    </chart>
`
</code>```

In class AppComponent:

```<code>    onLoad (e) {
                var chart = e.context,
                    total = chart.series[0].points[0].total;
                chart.update({
                    legend: {
                        title: {
                            text: 'City<br/><span style="font-size: 9px; color: #666; font-weight: normal">(Total: ' + total + ')</span>'
                        }
                    }
                })
              };
</code>```

Body:
I am able to display the legend and legend title in angular2-highcharts.
I am planning to display the total count below the legend title ( here below city), but couldn't able to find out how.
Also I am not sure why % is displayed along with the value in the legend values.

My label formatter is:

  labelFormatter: function () {
      return '
' + this.name +
             '' + this.value +
              '%
 ';
       }

https://plnkr.co/edit/yzXLz7AIDoWa1Pzxxl4k?p=preview

Body:
Each pie series point has total for the series, so you could update legend on load event of a chart to include the total from the series.

Demo: https://plnkr.co/edit/6JW1KmYE1Lr4pAIWCJTm?p=preview

template as:

template: `
    <chart  [options]="options" (load)="onLoad($event)">
    </chart>
`

In class AppComponent:

    onLoad (e) {
                var chart = e.context,
                    total = chart.series[0].points[0].total;
                chart.update({
                    legend: {
                        title: {
                            text: 'City<br/><span style="font-size: 9px; color: #666; font-weight: normal">(Total: ' + total + ')</span>'
                        }
                    }
                })
              };


来源: stackexchange

问:
SQL Server ODBC Driver not raising errors

This question is part in a series of bugs in the Microsoft ODBC
  driver:

ODBC driver fails to raise errors; but instead suppresses them

Reading columns out of order returns incorrect results

Cannot execute a stored procedure that is a SYNONYM

Microsoft has said they will not be fixing these bugs in their ODBC
  driver.

Background

If i have a sample table:

```<code>CREATE TABLE Wallet (
    WalletID int NOT NULL,
    Name varchar(50) NOT NULL
)
</code>```

i attempt to issue sql that inserts into the table without specifying a value to the NOT NULL WalletID column:

```<code>INSERT INTO Wallet (WalletID, Name) VALUES (1, 'Fan')
INSERT INTO Wallet (Name) VALUES ('Ardent Defender') --Constraint violation
</code>```

SQL Server gives an error:

(1 row(s) affected)

  Msg 515, Level 16, State 2, Line 2

  Cannot insert the value NULL into column 'WalletID', table 'Scratch.dbo.Wallet'; column does not allow nulls. INSERT fails.

  The statement has been terminated.

And that makes sense.

When connecting using ADO/OLEDB, and the SQL Server OLE DB Provider (SQLOLEDB):

Provider=SQLOLEDB;Data Source=hyperion;User ID=Contoso;Password=Trub4dor;

And i execute the the INSERT, the ADO/OLEDB/COM infrastructure returns a failure, which comes back to the high level language as an exception:

Cannot insert the value NULL into column 'WalletID', table 'Wallet'; column does not allow nulls. INSERT fails

And that all makes sense.

But try it with the ODBC driver

With the derprication of that native client OLE DB providers (and the MS recommendation that you do not use the native client ODBC drivers), i thought i would try my hand at using the SQL Server ODBC driver:

Provider=MSDASQL;Driver={SQL Server};Server={hyperion};UID={Contoso};PWD={Trub4dor};

Update - Undeprecated: Six years later, Microsoft has announced the un-deprecation of OLE DB support for SQL Server, and the creations of a third OLE DB driver for SQL Server: msoledbsql. (archive)

Previously, Microsoft announced deprecation of the Microsoft OLE DB Provider for SQL Server, part of the SQL Server Native Client (SNAC). At the time, this decision was made to try to provide more simplicity for the developer story around Windows native software development as we moved into the cloud era with Azure SQL Database, and to try to leverage the similarities of JDBC and ODBC for developers. However, during subsequent reviews it was determined that deprecation was a mistake because substantial scenarios within SQL Server still depend on OLE DB and changing those would break some existing customer scenarios.

With this in mind, we have decided to undeprecate OLE DB and release a new version by the first quarter of calendar year 2018 March 2018.

I issue my batch:

```<code>INSERT INTO Wallet (WalletID, Name) VALUES (1, 'Fan')
INSERT INTO Wallet (Name) VALUES ('Ardent Defender')
</code>```

I was surprised to learn that same SQL statement:

that triggers an INSERT FAILS error in SQL Server itself:

that results in a client side error when using the SQL Server OLE DB Provider

will silently fail when using the ODBC driver. The statement executes without any error being raised.

I was confused for about an hour when my SQL statements ran without error, but the rows would not appear in the database.

Silent Fail

Obviously a silent failure is no good.

And obviously i can just not use the SQL Server ODBC driver,

and continue to use the Microsoft OLE DB Provider for SQL Server provider.

But what is going on?

How do i tell the ADO-OLEDB-ODBC driver to report errors. Is it an ODBC connection string setting? Is it an MSDASQL connection string setting?

Sample Psuedocode

I'm actually using Delphi with ADO. But i'll transcode it into pseudo C# style code for easier conceptual understanding.

```<code>String commandText =
      "INSERT INTO Wallet (WalletID, Name) VALUES (1, 'Fan')"+CRLF+
      "INSERT INTO Wallet (Name) VALUES ('Ardent Defender')";

ADOConnection conn = new ADOConnection();
conn.ConnectionString = szConnectionString;
conn.Open();

HRESULT hr = conn.Execute(commandText, ref recordsAffected, [eoExecuteNoRecords]);
</code>```

In reality the checking of the HRESULT is handled by the language infrastructure and compiler magic - throwing a native language exception if it  FAILED.

答: The  WalletID int column is not set to auto-increment.

ContentLicense: CC BY-SA 3.0

Body:
This question is part in a series of bugs in the Microsoft ODBC
  driver:

ODBC driver fails to raise errors; but instead suppresses them

Reading columns out of order returns incorrect results

Cannot execute a stored procedure that is a SYNONYM

Microsoft has said they will not be fixing these bugs in their ODBC
  driver.

Background

If i have a sample table:

CREATE TABLE Wallet (
    WalletID int NOT NULL,
    Name varchar(50) NOT NULL
)

i attempt to issue sql that inserts into the table without specifying a value to the NOT NULL WalletID column:

INSERT INTO Wallet (WalletID, Name) VALUES (1, 'Fan')
INSERT INTO Wallet (Name) VALUES ('Ardent Defender') --Constraint violation

SQL Server gives an error:

(1 row(s) affected)

  Msg 515, Level 16, State 2, Line 2

  Cannot insert the value NULL into column 'WalletID', table 'Scratch.dbo.Wallet'; column does not allow nulls. INSERT fails.

  The statement has been terminated.

And that makes sense.

When connecting using ADO/OLEDB, and the SQL Server OLE DB Provider (SQLOLEDB):

Provider=SQLOLEDB;Data Source=hyperion;User ID=Contoso;Password=Trub4dor;

And i execute the the INSERT, the ADO/OLEDB/COM infrastructure returns a failure, which comes back to the high level language as an exception:

Cannot insert the value NULL into column 'WalletID', table 'Wallet'; column does not allow nulls. INSERT fails

And that all makes sense.

But try it with the ODBC driver

With the derprication of that native client OLE DB providers (and the MS recommendation that you do not use the native client ODBC drivers), i thought i would try my hand at using the SQL Server ODBC driver:

Provider=MSDASQL;Driver={SQL Server};Server={hyperion};UID={Contoso};PWD={Trub4dor};

Update - Undeprecated: Six years later, Microsoft has announced the un-deprecation of OLE DB support for SQL Server, and the creations of a third OLE DB driver for SQL Server: msoledbsql. (archive)

Previously, Microsoft announced deprecation of the Microsoft OLE DB Provider for SQL Server, part of the SQL Server Native Client (SNAC). At the time, this decision was made to try to provide more simplicity for the developer story around Windows native software development as we moved into the cloud era with Azure SQL Database, and to try to leverage the similarities of JDBC and ODBC for developers. However, during subsequent reviews it was determined that deprecation was a mistake because substantial scenarios within SQL Server still depend on OLE DB and changing those would break some existing customer scenarios.

With this in mind, we have decided to undeprecate OLE DB and release a new version by the first quarter of calendar year 2018 March 2018.

I issue my batch:

INSERT INTO Wallet (WalletID, Name) VALUES (1, 'Fan')
INSERT INTO Wallet (Name) VALUES ('Ardent Defender')

I was surprised to learn that same SQL statement:

that triggers an INSERT FAILS error in SQL Server itself:

that results in a client side error when using the SQL Server OLE DB Provider

will silently fail when using the ODBC driver. The statement executes without any error being raised.

I was confused for about an hour when my SQL statements ran without error, but the rows would not appear in the database.

Silent Fail

Obviously a silent failure is no good.

And obviously i can just not use the SQL Server ODBC driver,

and continue to use the Microsoft OLE DB Provider for SQL Server provider.

But what is going on?

How do i tell the ADO-OLEDB-ODBC driver to report errors. Is it an ODBC connection string setting? Is it an MSDASQL connection string setting?

Sample Psuedocode

I'm actually using Delphi with ADO. But i'll transcode it into pseudo C# style code for easier conceptual understanding.

String commandText =
      "INSERT INTO Wallet (WalletID, Name) VALUES (1, 'Fan')"+CRLF+
      "INSERT INTO Wallet (Name) VALUES ('Ardent Defender')";

ADOConnection conn = new ADOConnection();
conn.ConnectionString = szConnectionString;
conn.Open();

HRESULT hr = conn.Execute(commandText, ref recordsAffected, [eoExecuteNoRecords]);

In reality the checking of the HRESULT is handled by the language infrastructure and compiler magic - throwing a native language exception if it  FAILED.


问:
Oracle SQL Developer: Failure - Test failed: The Network Adapter could not establish the connection?

Problem

Please note that I changed details for security purposes. However, the problem remains intact.

I installed an Oracle 11g database on a server at location, say, herp-devDV.derp.edu.
Now I have another Oracle 11g database on a server at location, say, derp-db.derp.edu.

I entered the connection name, username, password, hostname, and service name in Oracle SQL developer for both herp-devDV.derp.edu and derp-db.derp.edu. I can connect to schema in derp-db.derp.edu, but not herp-devDV.derp.edu. It gives me this message:

```<code>Failure - Test failed: The Network Adapter could not establish the connection
</code>```

Details

I have the following information:

Port 1521 is not open for either server when I telnet

My listener is up and running for both.

I can access derp-db.derp.edu on Oracle SQL Developer.

Oracle client is on my local machine + Oracle SQL Developer

I can remote desktop to both servers

What I have done

Googled

Stackoverflow

Ran stop and start lnrctl commands

On herp-devDB.derp.edu I ran lsnrctl status

I received the following output

```<code>Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=IPC)(KEY=EXTPROC1521)))
STATUS of the LISTENER
------------------------
Alias                     LISTENER
Version                   TNSLSNR for 64-bit Windows: Version 11.2.0.1.0 - Production
Start Date                03-JUN-2014 13:37:22
Uptime                    6 days 0 hr. 53 min. 4 sec
Trace Level               off
Security                  ON: Local OS Authentication
SNMP                      OFF
Listener Parameter File   D:\oracle\product\11.2.0\dbhome_1\network\admin\listener.ora
Listener Log File         d:\oracle\diag\tnslsnr\HERP-DEVDB\listener\alert\log.xml
Listening Endpoints Summary...
  (DESCRIPTION=(ADDRESS=(PROTOCOL=ipc)(PIPENAME=\\.\pipe\EXTPROC1521ipc)))
  (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=HERP-DEVDB.derp.edu)(PORT=1521)))
Services Summary...
Service "CLRExtProc" has 1 instance(s).
  Instance "CLRExtProc", status UNKNOWN, has 1 handler(s) for this service...
Service "HERPDEVDBXDB" has 1 instance(s).
  Instance "herpdevdb", status READY, has 1 handler(s) for this service...
Service "herpdevdb" has 1 instance(s).
  Instance "herpdevdb", status READY, has 1 handler(s) for this service...
The command completed successfully
</code>```

I then check out my listener.ora and find

```<code>  SID_LIST_LISTENER =
  (SID_LIST =
    (SID_DESC =
      (SID_NAME = CLRExtProc)
      (ORACLE_HOME = D:\oracle\product\11.2.0\dbhome_1)
      (PROGRAM = extproc)
      (ENVS = "EXTPROC_DLLS=ONLY:D:\oracle\product\11.2.0\dbhome_1\bin\oraclr11.dll")
    )
  )

LISTENER =
  (DESCRIPTION_LIST =
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
      (ADDRESS = (PROTOCOL = TCP)(HOST = HERP-DEVDB.derp.edu)(PORT = 1521))
    )
  )
</code>```

At this point, I confess I am scratching my head as I don't see anything sticking out and telling me why this should not be working.

The only clue is when I check derp-db.derp.edu and run the command lsnrctl status. Please
see excerpt below:

```<code>Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=DERP-DB.edu)(PORT=1521)))
STATUS of the LISTENER
------------------------
Alias                     LISTENER
Version                   TNSLSNR for 64-bit Windows: Version 11.2.0.3.0 - Production
Start Date                18-MAY-2014 02:19:01
Uptime                    22 days 12 hr. 23 min. 18 sec
Trace Level               off
Security                  ON: Local OS Authentication
SNMP                      OFF
---etc----
</code>```

So I am still scratching my head. Why would derp-db be connecting to the DERP-DB.edu but herp-devDB is connecting to EXTPROC1521? How do I fix this? The listener.ora and other files between these two servers are almost identical except for the name of the instances.
Hmmm.

EDIT1: I changed the listener.ora in herp. This didn't fix it.

EDIT2: I cannot telnet into derp-db.derp.edu on port 1521. But I can still connect to it with SQL Developer? Wth?

EDIT3 I cannot telnet into herp-devdb.derp.edu on port 1521 either.

EDIT4 I cannot ping IP addresses of either server.

Anyway assistance would be greatly appreciated. Thanks

Regards,
Geeky

答:
only start listner then u can connect with database.
command run on editor:

lsnrctl start

its work fine.

Body:
Problem

Please note that I changed details for security purposes. However, the problem remains intact.

I installed an Oracle 11g database on a server at location, say, herp-devDV.derp.edu.
Now I have another Oracle 11g database on a server at location, say, derp-db.derp.edu.

I entered the connection name, username, password, hostname, and service name in Oracle SQL developer for both herp-devDV.derp.edu and derp-db.derp.edu. I can connect to schema in derp-db.derp.edu, but not herp-devDV.derp.edu. It gives me this message:

Failure - Test failed: The Network Adapter could not establish the connection

Details

I have the following information:

Port 1521 is not open for either server when I telnet

My listener is up and running for both.

I can access derp-db.derp.edu on Oracle SQL Developer.

Oracle client is on my local machine + Oracle SQL Developer

I can remote desktop to both servers

What I have done

Googled

Stackoverflow

Ran stop and start lnrctl commands

On herp-devDB.derp.edu I ran lsnrctl status

I received the following output

Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=IPC)(KEY=EXTPROC1521)))
STATUS of the LISTENER
------------------------
Alias                     LISTENER
Version                   TNSLSNR for 64-bit Windows: Version 11.2.0.1.0 - Production
Start Date                03-JUN-2014 13:37:22
Uptime                    6 days 0 hr. 53 min. 4 sec
Trace Level               off
Security                  ON: Local OS Authentication
SNMP                      OFF
Listener Parameter File   D:\oracle\product\11.2.0\dbhome_1\network\admin\listener.ora
Listener Log File         d:\oracle\diag\tnslsnr\HERP-DEVDB\listener\alert\log.xml
Listening Endpoints Summary...
  (DESCRIPTION=(ADDRESS=(PROTOCOL=ipc)(PIPENAME=\\.\pipe\EXTPROC1521ipc)))
  (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=HERP-DEVDB.derp.edu)(PORT=1521)))
Services Summary...
Service "CLRExtProc" has 1 instance(s).
  Instance "CLRExtProc", status UNKNOWN, has 1 handler(s) for this service...
Service "HERPDEVDBXDB" has 1 instance(s).
  Instance "herpdevdb", status READY, has 1 handler(s) for this service...
Service "herpdevdb" has 1 instance(s).
  Instance "herpdevdb", status READY, has 1 handler(s) for this service...
The command completed successfully

I then check out my listener.ora and find

  SID_LIST_LISTENER =
  (SID_LIST =
    (SID_DESC =
      (SID_NAME = CLRExtProc)
      (ORACLE_HOME = D:\oracle\product\11.2.0\dbhome_1)
      (PROGRAM = extproc)
      (ENVS = "EXTPROC_DLLS=ONLY:D:\oracle\product\11.2.0\dbhome_1\bin\oraclr11.dll")
    )
  )

LISTENER =
  (DESCRIPTION_LIST =
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
      (ADDRESS = (PROTOCOL = TCP)(HOST = HERP-DEVDB.derp.edu)(PORT = 1521))
    )
  )

At this point, I confess I am scratching my head as I don't see anything sticking out and telling me why this should not be working.

The only clue is when I check derp-db.derp.edu and run the command lsnrctl status. Please
see excerpt below:

Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=DERP-DB.edu)(PORT=1521)))
STATUS of the LISTENER
------------------------
Alias                     LISTENER
Version                   TNSLSNR for 64-bit Windows: Version 11.2.0.3.0 - Production
Start Date                18-MAY-2014 02:19:01
Uptime                    22 days 12 hr. 23 min. 18 sec
Trace Level               off
Security                  ON: Local OS Authentication
SNMP                      OFF
---etc----

So I am still scratching my head. Why would derp-db be connecting to the DERP-DB.edu but herp-devDB is connecting to EXTPROC1521? How do I fix this? The listener.ora and other files between these two servers are almost identical except for the name of the instances.
Hmmm.

EDIT1: I changed the listener.ora in herp. This didn't fix it.

EDIT2: I cannot telnet into derp-db.derp.edu on port 1521. But I can still connect to it with SQL Developer? Wth?

EDIT3 I cannot telnet into herp-devdb.derp.edu on port 1521 either.

EDIT4 I cannot ping IP addresses of either server.

Anyway assistance would be greatly appreciated. Thanks

Regards,
Geeky


问:
matching occurrence of opposite number in a list python
I have a list such has

```<code>results = [100, 100, -100, 100, -100, -100]
</code>```

I would like to figure out the first occurrence of the opposite number. so first 100 would be match with the first -100, the second 100 would be match with the second -100.

I would like to have position as output such has:

```<code>[0, 2], [1, 4], [3, 5]
</code>```

i.e : [0,2] represent the results[0] and  results[2]  where first occurrence of 100 is match with the first occurrence of -100

edit : you can assume there will always be the same amount of positive / negative and that the list will only contain 1 number

any help would be appricated

答:
```<code>pos = {}
for i,item in enumerate(results ):
    if item < 0: continue
    if item not in pos:
       pos[item] = []
    pos[item].append(i)

[ [pos[-item].pop(0), i] for i,item in enumerate(results ) if item < 0]

[[0, 2], [1, 4], [3, 5]]
</code>```

Body:
I have a list such has

results = [100, 100, -100, 100, -100, -100]

I would like to figure out the first occurrence of the opposite number. so first 100 would be match with the first -100, the second 100 would be match with the second -100.

I would like to have position as output such has:

[0, 2], [1, 4], [3, 5]

i.e : [0,2] represent the results[0] and  results[2]  where first occurrence of 100 is match with the first occurrence of -100

edit : you can assume there will always be the same amount of positive / negative and that the list will only contain 1 number

any help would be appricated


问:
My android app crashes on launch, and the stack trace doesn't show anything
I'm new to android development, and I'm trying to build a simple note taking app.

I've decided to use Realm instead of SQLite, but I couldn't figure out how to connect everything on the DB to my RecyclerView, so I found an example on their GitHub about creating Adapters for RecyclerViews that display data from a Realm DB.

I copied most of the code and edited it to suit my app, but now it crashes on launch, and I have no idea what's causing it because the stack trace doesn't show anything.

I've uploaded the app to this repo on GitHub for people to check it out and tell me what might be wrong.

答:
The exception is in the logs. Maybe you have a filter applied in the view?

The issue is that you are initializing Realm incorrectly.

```<code>03-31 15:56:54.403  8728  8728 E AndroidRuntime: java.lang.RuntimeException: Unable to create application com.odinuts.memo.app.MyApplication: java.lang.IllegalStateException: Call `Realm.init(Context)` before creating a RealmConfiguration
03-31 15:56:54.403  8728  8728 E AndroidRuntime:    at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5364)
03-31 15:56:54.403  8728  8728 E AndroidRuntime:    at android.app.ActivityThread.-wrap2(ActivityThread.java)
03-31 15:56:54.403  8728  8728 E AndroidRuntime:    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1528)
03-31 15:56:54.403  8728  8728 E AndroidRuntime:    at android.os.Handler.dispatchMessage(Handler.java:102)
03-31 15:56:54.403  8728  8728 E AndroidRuntime:    at android.os.Looper.loop(Looper.java:154)
03-31 15:56:54.403  8728  8728 E AndroidRuntime:    at android.app.ActivityThread.main(ActivityThread.java:6077)
03-31 15:56:54.403  8728  8728 E AndroidRuntime:    at java.lang.reflect.Method.invoke(Native Method)
03-31 15:56:54.403  8728  8728 E AndroidRuntime:    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
03-31 15:56:54.403  8728  8728 E AndroidRuntime:    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
03-31 15:56:54.403  8728  8728 E AndroidRuntime: Caused by: java.lang.IllegalStateException: Call `Realm.init(Context)` before creating a RealmConfiguration
03-31 15:56:54.403  8728  8728 E AndroidRuntime:    at io.realm.RealmConfiguration$Builder.<init>(RealmConfiguration.java:399)
03-31 15:56:54.403  8728  8728 E AndroidRuntime:    at io.realm.RealmConfiguration$Builder.<init>(RealmConfiguration.java:394)
03-31 15:56:54.403  8728  8728 E AndroidRuntime:    at com.odinuts.memo.app.MyApplication.onCreate(MyApplication.java:13)
03-31 15:56:54.403  8728  8728 E AndroidRuntime:    at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1024)
03-31 15:56:54.403  8728  8728 E AndroidRuntime:    at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5361)
03-31 15:56:54.403  8728  8728 E AndroidRuntime:    ... 8 more
</code>```

Edit: In Android Studio check your Android Monitor tab and make sure the following filters are correct

```<code>1) Process (this should be your app
2) Regex/selection (select your app, or no filters)
3) Log level (debug, info, error, etc)
4) Device (in case you have several)
</code>```

Body:
The exception is in the logs. Maybe you have a filter applied in the view?

The issue is that you are initializing Realm incorrectly.

03-31 15:56:54.403  8728  8728 E AndroidRuntime: java.lang.RuntimeException: Unable to create application com.odinuts.memo.app.MyApplication: java.lang.IllegalStateException: Call `Realm.init(Context)` before creating a RealmConfiguration
03-31 15:56:54.403  8728  8728 E AndroidRuntime:    at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5364)
03-31 15:56:54.403  8728  8728 E AndroidRuntime:    at android.app.ActivityThread.-wrap2(ActivityThread.java)
03-31 15:56:54.403  8728  8728 E AndroidRuntime:    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1528)
03-31 15:56:54.403  8728  8728 E AndroidRuntime:    at android.os.Handler.dispatchMessage(Handler.java:102)
03-31 15:56:54.403  8728  8728 E AndroidRuntime:    at android.os.Looper.loop(Looper.java:154)
03-31 15:56:54.403  8728  8728 E AndroidRuntime:    at android.app.ActivityThread.main(ActivityThread.java:6077)
03-31 15:56:54.403  8728  8728 E AndroidRuntime:    at java.lang.reflect.Method.invoke(Native Method)
03-31 15:56:54.403  8728  8728 E AndroidRuntime:    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
03-31 15:56:54.403  8728  8728 E AndroidRuntime:    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
03-31 15:56:54.403  8728  8728 E AndroidRuntime: Caused by: java.lang.IllegalStateException: Call `Realm.init(Context)` before creating a RealmConfiguration
03-31 15:56:54.403  8728  8728 E AndroidRuntime:    at io.realm.RealmConfiguration$Builder.<init>(RealmConfiguration.java:399)
03-31 15:56:54.403  8728  8728 E AndroidRuntime:    at io.realm.RealmConfiguration$Builder.<init>(RealmConfiguration.java:394)
03-31 15:56:54.403  8728  8728 E AndroidRuntime:    at com.odinuts.memo.app.MyApplication.onCreate(MyApplication.java:13)
03-31 15:56:54.403  8728  8728 E AndroidRuntime:    at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1024)
03-31 15:56:54.403  8728  8728 E AndroidRuntime:    at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5361)
03-31 15:56:54.403  8728  8728 E AndroidRuntime:    ... 8 more

Edit: In Android Studio check your Android Monitor tab and make sure the following filters are correct

1) Process (this should be your app
2) Regex/selection (select your app, or no filters)
3) Log level (debug, info, error, etc)
4) Device (in case you have several)


问:
Can you make the Tomcat 6 stdout.log file behave like a log4j DailyRollingFileAppender?
We are using the Windows installation of Tomcat 6.  By default, the log4j output for our app goes to the ${catalina.base}/logs/stdout_.log file.  This log file only rolls over when we restart Tomcat, and the file name always includes the date.

I would prefer it to behave like a DailyRollingFileAppender, where it renames the file when it rolls over... that way I can just open Notepad++ and see today's logs, since Notepad++ will remember that I opened that same file yesterday. :)

I know I can just create another appender in log4j, but I would end up with the stdout.log and another log file, and I'm afraid there would be a minor performance hit for logging to both files.  I've tried adding swallowOutput=true to my context.xml but I still get all logging in stdout.log.  Any ideas?

答:
The biggest performance hit is when preparing objects that you want to log (you know, when you do logger.info(" operating on " + myObject.toString + " bla bla bla" ) then doing myObject.toString() has the biggest cost). If you already have them than loggin to file is not a problem. And log4j is really well balanced and optimized, it uses buffers to write logs, so it do not make too frequent calls to file system.

Just create another appender, you will have a differentation from tomcat logs and your appilcation logs. How many logs do you have? A 1GB a day or more that you are afraid of performance loss? Don't assume anything before testing it. Just set-up, and do some kind of performance test.

OwnerDisplayName: Nick

ContentLicense: CC BY-SA 2.5


问:
repeat numbers in trial structure
How can I tell matlab to use numbers again ?

I have 10 Trials but only 8 numbers and I want to tell matlab to repeat the numbers in a randomized order. How can I do this?

numbers = {0 1 2 3 4 5 6 7 8};

答:
The Psychtoolbox function RandSel can be used for this:

```<code>numbers = 1:8;
trialNumbers = RandSel(numbers, 10);
</code>```

Note that because the selection is random, on a given run of 10 trials a given number might be repeated several times or not used at all.

Title: repeat numbers in trial structure

Body:
The Psychtoolbox function RandSel can be used for this:

numbers = 1:8;
trialNumbers = RandSel(numbers, 10);

Note that because the selection is random, on a given run of 10 trials a given number might be repeated several times or not used at all.


问:
Need help in xamarin form Design
I am making an app using Portable xamarin form (cross platform) having android and IOS project.

I am having designing issue.

Below is my code.

```<code><Grid ColumnSpacing="0" RowSpacing="0" >

    <Grid.RowDefinitions >
      <RowDefinition Height="Auto"></RowDefinition>
      <RowDefinition Height="Auto"></RowDefinition>
      <RowDefinition Height="Auto"></RowDefinition>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
      <ColumnDefinition Width="*"></ColumnDefinition>
    </Grid.ColumnDefinitions>

    <StackLayout Grid.Row="0" Grid.Column="0" Padding="20,30,20,0">
      <StackLayout VerticalOptions="StartAndExpand" HorizontalOptions="FillAndExpand" HeightRequest="30" BackgroundColor="#6E335E" Padding="10,0,10,0" >
        <Label Text="{ Binding CompanyName }" FontSize="18"  HorizontalOptions="Start" VerticalOptions="CenterAndExpand"  HorizontalTextAlignment="Center" TextColor="White" ></Label>

      </StackLayout>
    </StackLayout>

    <StackLayout VerticalOptions="FillAndExpand" Grid.Row="1" HeightRequest="130"  HorizontalOptions="FillAndExpand" Padding="20,0,20,0">
      <Image  Source="{ Binding LogoPath }" VerticalOptions="FillAndExpand"   HorizontalOptions="FillAndExpand" Aspect="AspectFill"></Image>

    </StackLayout>

    <StackLayout Grid.Row="2" Grid.Column="0" Padding="10,0,10,30" VerticalOptions="StartAndExpand" HorizontalOptions="FillAndExpand" >
      <Image  Source="image_bottom.png" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" Aspect="AspectFill"></Image>
    </StackLayout>

  </Grid>
</code>```

Below is the image Which describe how i want design

Please help me in designing issue.

Thanks in anvance

答:
Your stacklayout has a height of 130 so the row definition is only expanding to that point. You should set the definition to *, and the grid vertical options to fillandexpand so it will fillout the remainder of space.     </p>

```<code><Grid.RowDefinitions >
          <RowDefinition Height="Auto"></RowDefinition>
          <RowDefinition Height="*"></RowDefinition>
          <RowDefinition Height="Auto"></RowDefinition>
</Grid.RowDefinitions>
</code>```

Title: Need help in xamarin form Design

Body:
I am making an app using Portable xamarin form (cross platform) having android and IOS project.

I am having designing issue.

Below is my code.

<Grid ColumnSpacing="0" RowSpacing="0" >

    <Grid.RowDefinitions >
      <RowDefinition Height="Auto"></RowDefinition>
      <RowDefinition Height="Auto"></RowDefinition>
      <RowDefinition Height="Auto"></RowDefinition>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
      <ColumnDefinition Width="*"></ColumnDefinition>
    </Grid.ColumnDefinitions>

    <StackLayout Grid.Row="0" Grid.Column="0" Padding="20,30,20,0">
      <StackLayout VerticalOptions="StartAndExpand" HorizontalOptions="FillAndExpand" HeightRequest="30" BackgroundColor="#6E335E" Padding="10,0,10,0" >

      </StackLayout>
    </StackLayout>

    <StackLayout VerticalOptions="FillAndExpand" Grid.Row="1" HeightRequest="130"  HorizontalOptions="FillAndExpand" Padding="20,0,20,0">
      <Image  Source="{ Binding LogoPath }" VerticalOptions="FillAndExpand"   HorizontalOptions="FillAndExpand" Aspect="AspectFill"></Image>

    </StackLayout>

    <StackLayout Grid.Row="2" Grid.Column="0" Padding="10,0,10,30" VerticalOptions="StartAndExpand" HorizontalOptions="FillAndExpand" >
      <Image  Source="image_bottom.png" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" Aspect="AspectFill"></Image>
    </StackLayout>

  </Grid>

Below is the image Which describe how i want design

Please help me in designing issue.

Thanks in anvance

Body:
Your stacklayout has a height of 130 so the row definition is only expanding to that point. You should set the definition to *, and the grid vertical options to fillandexpand so it will fillout the remainder of space.

<Grid.RowDefinitions >
          <RowDefinition Height="Auto"></RowDefinition>
          <RowDefinition Height="*"></RowDefinition>
          <RowDefinition Height="Auto"></RowDefinition>
</Grid.RowDefinitions>


问:
Angular : When to use "[]" in modules and controllers
I'm starting in Angular and i don't understand when to use or not [] when declaring (if it's called like this) modules and controllers.

So far, i understood that :

angular.module('app.prof', []).config(config); means i declare the module prof

while angular.module('app.prof').config(config); means i call it.

But i always end up having the [] in the controller and not in the module, and when i have two controllers i don't know what to do anymore.

I just want to understand Angular :(

Edit : adding more details

In my Angular project, i use the Fuse theme with a thing called Yeoman (if i understood well) so i never write

答:
You can declare a Module like this:

```<code> angular.module('myModule', []);
</code>```

Similarly,  you can declare a Controller like this:

```<code> angular.module('myModule')
    .controller('MyController', []);
</code>```

When you declare the controller, you're not using the empty array notation in the module, because you're defining a controller on an already existing module.

The empty array ([]) that you pass into the module or controller is a placeholder for dependencies you want to inject into your module or controller. See: AngularJS Depedency Injection.

Every AngularJS project has a 'top-level' or root module. This is the module that bootstraps your application together when you use it in accordance with an ng-app directive.

In your top-level module(s), you declare your dependencies to the other modules in your application. For example:

```<code>angular.module('root', ['childModule1', 'childModule2', 'childModule3']);
</code>```

In your controllers, you use dependency injection to inject services, functions, or AngularJS' built-in libraries (such as $http, $sce, or $q) For example:

```<code>angular.module('root')
    .controller('RootController', ['$window', '$location', 'myRootService']);
</code>```

Body:
You can declare a Module like this:

 angular.module('myModule', []);

Similarly,  you can declare a Controller like this:

 angular.module('myModule')
    .controller('MyController', []);

When you declare the controller, you're not using the empty array notation in the module, because you're defining a controller on an already existing module.

The empty array ([]) that you pass into the module or controller is a placeholder for dependencies you want to inject into your module or controller. See: AngularJS Depedency Injection.

Every AngularJS project has a 'top-level' or root module. This is the module that bootstraps your application together when you use it in accordance with an ng-app directive.

In your top-level module(s), you declare your dependencies to the other modules in your application. For example:

angular.module('root', ['childModule1', 'childModule2', 'childModule3']);

In your controllers, you use dependency injection to inject services, functions, or AngularJS' built-in libraries (such as $http, $sce, or $q) For example:

angular.module('root')
    .controller('RootController', ['$window', '$location', 'myRootService']);


问:
Composer list packages with installed version and latest version
As in the title, is there any command that can list installed packages and the latest version of those packages together?

edit:

```<code>php composer.phar show
</code>```

this show all available packages and also installed packages with installed version only

```<code>php composer.phar show [package]
</code>```

this can get both installed version and latest version, but it is inconvenience if many packages are installed

答:
Since Composer v1.1 (May 2016) you can run

composer outdated

ContentLicense: CC BY-SA 4.0

Body:
As in the title, is there any command that can list installed packages and the latest version of those packages together?

edit:

php composer.phar show

this show all available packages and also installed packages with installed version only

php composer.phar show [package]

this can get both installed version and latest version, but it is inconvenience if many packages are installed


问:
Creating and writing contents is not working in Excel using C#
I am trying to write into excel using below code snippet. But i am getting exception as in the sreenshot attached.

try
            {
                xlApp = new Microsoft.Office.Interop.Excel.Application();
                xlApp.Visible = false;
                workbook = xlApp.Workbooks.Add(1);
                worksheet = (Excel.Worksheet)workbook.Sheets[1];
                workbook.SaveAs(name);
                worksheet.Cells[count, "A"] = "Name";
                worksheet.Cells[count, "B"] = "Reports_to";
                worksheet.Cells[count, "C"] = "Title";
                worksheet.Cells[count, "D"] = "Department";
                count++;
            }
            catch (System.Exception exp)
            {
                MessageBox.Show("Excel Exception : " + exp.GetBaseException());
            }```
</div>
</div>
</p>

<p>I couldn't add screenshot as i dont have 10 reputation. My exception is as metioned below.</p>

<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>System.Runtime.InteropServices.COMException (0x800A03EC): Exception from HRESULT: 0x800A03EC

at Microsoft.Office.Interop.Excel.Workbooks.Add(Object Template)

at ReporterObj.FormExporter.InitializeExcel(String name) in d:\DJ\C# Pr

A first chance exception of type 'System.NullReferenceException' occurred in ReporterObj.exe ojects\ReporterImpExp\ReporterObj\Form1.cs:line 69</code>```

Appropriate suggesstion is appreciated.

Thank You.

答: i get this error only in chrome but not in IE after deployment on IIS. I have narrowed this down to authentication in IIS. If you disable forms authentication this error occurs otherwise works fine.</p>

Body:
I am trying to write into excel using below code snippet. But i am getting exception as in the sreenshot attached.

try
            {
                xlApp = new Microsoft.Office.Interop.Excel.Application();
                xlApp.Visible = false;
                workbook = xlApp.Workbooks.Add(1);
                worksheet = (Excel.Worksheet)workbook.Sheets[1];
                workbook.SaveAs(name);
                worksheet.Cells[count, "A"] = "Name";
                worksheet.Cells[count, "B"] = "Reports_to";
                worksheet.Cells[count, "C"] = "Title";
                worksheet.Cells[count, "D"] = "Department";
                count++;
            }
            catch (System.Exception exp)
            {
                MessageBox.Show("Excel Exception : " + exp.GetBaseException());
            }

I couldn't add screenshot as i dont have 10 reputation. My exception is as metioned below.

System.Runtime.InteropServices.COMException (0x800A03EC): Exception from HRESULT: 0x800A03EC

at Microsoft.Office.Interop.Excel.Workbooks.Add(Object Template)

at ReporterObj.FormExporter.InitializeExcel(String name) in d:\DJ\C# Pr

A first chance exception of type 'System.NullReferenceException' occurred in ReporterObj.exe ojects\ReporterImpExp\ReporterObj\Form1.cs:line 69

Appropriate suggesstion is appreciated.

Thank You.


问:
Input Type File Add File Path To A Span
I customized my input type="file" just like Facebook upload instead of textbox and a button(default input type="file") I make my input file a button only without the textbox where you can see the path of the file. I'am planning to add a span or a p tag next to my customized input file to show the path of the file.

How can I print the file path to my span tag when I choose a file?

html code

```<code><!doctype>
<html>
<head>
</head>

<body>

<div class="browse-wrap">
    <div class="title">Choose a file to upload</div>
    <input type="file" name="upload" class="upload" title="Choose a file to upload">
</div>
<span class="upload-path"></span>

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

css code

```<code>div.browse-wrap {
        top:0;
        left:0;
        margin:20px;
        cursor:pointer;
        overflow:hidden;
        padding:20px 60px;
        text-align:center;
        position:relative;
        background-color:#f6f7f8;
        border:solid 1px #d2d2d7;}
    div.title {
        color:#3b5998;
        font-size:14px;
        font-weight:bold;
        font-family:tahoma, arial, sans-serif;}
    input.upload {
        right:0;
        margin:0;
        bottom:0;
        padding:0;
        opacity:0;
        height:300px;
        outline:none;
        cursor:inherit;
        position:absolute;
        font-size:1000px !important;}
    span.upload-path {
        margin:20px;
        display:block;}
</code>```

Thanks!

答:
```<code>    .custom{
    position: relative;
    z-index: 1;
    border: 1px solid #ccc;
    cursor:pointer;
    width: 30%;
    height: 30px;
}

.custom::after{
    content: "Upload";
    position: absolute;
    right: 0px;
    background-color: rgba(51, 122, 183, 1);
    height: 65%;
    padding: 5px 10px;
    color: #fff;
    display: block;
    font-size: 18px;
    width: 50px;
    text-align: center;
    top: 0;

}

.custom .file-text{
    display: block;
    position: absolute;
    padding: 2px 20px;
    color: #f00;
    font-weight: bold;
    font-size: 20px;
}

.custom .file{
     display: inline;
     width: 100%;
     height: 100%;
     z-index: 9999;
     opacity: 0;
     cursor: pointer;
     padding: 0;
     position: relative;
}
</code>```

```
You must call a library jquery before code
    $(function () {
        $('.custom input[type="file"]').on("change", function() {

            $('.custom .file-text').text($(this).val());

        });
    });

```

```<code>    <!DOCTYPE html>
    <html>
       <head>
        </head>
       <body>
          <div class="custom">
             <span class="file-text">chosse file</span>
             <input type="file" class="file"></input>
          </div>
       </body>
    </html>
</code>```

Title: Input Type File Add File Path To A Span

Body:
I customized my input type="file" just like Facebook upload instead of textbox and a button(default input type="file") I make my input file a button only without the textbox where you can see the path of the file. I'am planning to add a span or a p tag next to my customized input file to show the path of the file.

How can I print the file path to my span tag when I choose a file?

html code

<!doctype>

Choose a file to upload

    <input type="file" name="upload" class="upload" title="Choose a file to upload">

css code

div.browse-wrap {
        top:0;
        left:0;
        margin:20px;
        cursor:pointer;
        overflow:hidden;
        padding:20px 60px;
        text-align:center;
        position:relative;
        background-color:#f6f7f8;
        border:solid 1px #d2d2d7;}
    div.title {
        color:#3b5998;
        font-size:14px;
        font-weight:bold;
        font-family:tahoma, arial, sans-serif;}
    input.upload {
        right:0;
        margin:0;
        bottom:0;
        padding:0;
        opacity:0;
        height:300px;
        outline:none;
        cursor:inherit;
        position:absolute;
        font-size:1000px !important;}
    span.upload-path {
        margin:20px;
        display:block;}

Thanks!

Body:
    .custom{
    position: relative;
    z-index: 1;
    border: 1px solid #ccc;
    cursor:pointer;
    width: 30%;
    height: 30px;
}

.custom::after{
    content: "Upload";
    position: absolute;
    right: 0px;
    background-color: rgba(51, 122, 183, 1);
    height: 65%;
    padding: 5px 10px;
    color: #fff;
    display: block;
    font-size: 18px;
    width: 50px;
    text-align: center;
    top: 0;

}

.custom .file-text{
    display: block;
    position: absolute;
    padding: 2px 20px;
    color: #f00;
    font-weight: bold;
    font-size: 20px;
}

.custom .file{
     display: inline;
     width: 100%;
     height: 100%;
     z-index: 9999;
     opacity: 0;
     cursor: pointer;
     padding: 0;
     position: relative;
}

You must call a library jquery before code
    $(function () {
        $('.custom input[type="file"]').on("change", function() {

            $('.custom .file-text').text($(this).val());

        });
    });

    <!DOCTYPE html>
    <html>
       <head>
        </head>
       <body>
          <div class="custom">
             <span class="file-text">chosse file</span>
             <input type="file" class="file"></input>
          </div>
       </body>
    </html>


问:
Class vs Struct for data only?
Is there any advantage over using a class over a struct in cases such as these?
(note: it will only hold variables, there will never be functions)

```<code>class Foo {
private:
   struct Pos { int x, y, z };
public:
   Pos Position;
};
</code>```

Versus:

```<code>struct Foo {
   struct Pos { int x, y, z } Pos;
};
</code>```

Similar questions:

When should you use a class vs a struct in C++?

What are the differences between struct and class in C++?

When should I use a struct instead of a class?

答: The only difference between a class and a struct is that struct members are public by default and class members are private by default.  So I say go with whichever one you like best.  I'm sure there are arguments to be made in terms of which one is more readable, but I really don't think it's a big deal.

OwnerDisplayName: Daniel

Title: Class vs Struct for data only?

Body:
Is there any advantage over using a class over a struct in cases such as these?
(note: it will only hold variables, there will never be functions)

class Foo {
private:
   struct Pos { int x, y, z };
public:
   Pos Position;
};

Versus:

struct Foo {
   struct Pos { int x, y, z } Pos;
};

Similar questions:

When should you use a class vs a struct in C++?

What are the differences between struct and class in C++?

When should I use a struct instead of a class?

LastEditorDisplayName: dmckee

OwnerDisplayName: Jason Baker


问:
@Scheduled & scheduler: What exactly does pool-size do?
I want to run several scheduled Tasks simultaneously.

When configuring spring to do so, I can supply a pool-size to the scheduler:

```<code><task:annotation-driven executor="myExecutor" scheduler="myScheduler"/>
<task:executor id="myExecutor" pool-size="32"/>
<task:scheduler id="myScheduler" pool-size="1000"/>
</code>```

But what exactly does the pool-size mean here?

Does it mean it can only store 1000 scheduled Methods or does it mean that only 1000 Methods can be processed at the same time?

tldr; If a @Scheduled(fixedDelay=60) annotated Method is NOT executed at the moment (meaning it's in between the delay), does it fill up the pool or not?

答:
It refers to the number of threads that can be pooled at once by the underlying ThreadPoolExecutor i.e. the notional number of methods that can be run at the same time.

The documentation on the task namespace goes into a lot of the detail you need.

I expect that 1000 threads is probably going to be far too many in most environments.

Body:
I want to run several scheduled Tasks simultaneously.

When configuring spring to do so, I can supply a pool-size to the scheduler:

<task:annotation-driven executor="myExecutor" scheduler="myScheduler"/>
<task:executor id="myExecutor" pool-size="32"/>
<task:scheduler id="myScheduler" pool-size="1000"/>

But what exactly does the pool-size mean here?

Does it mean it can only store 1000 scheduled Methods or does it mean that only 1000 Methods can be processed at the same time?

tldr; If a @Scheduled(fixedDelay=60) annotated Method is NOT executed at the moment (meaning it's in between the delay), does it fill up the pool or not?


问:
PYTHON: What is the fastest way of checking and editing an element in a structured array if it exists?
I have some issues with very large data sets. I need to find a solid and fast way to find/replace entries in my structured array. I am looking for an solution without looping of all entries. I know there are fast solutions for C but I do not know how to approach in python for that. I am also wonder if there is a numpy function for that very purpose!

I am using Python 2.7.13 and numpy 1.12.1!

TASK:
Set all positions of the orphans to the positions of the data_centrals by finding the haloid of the orphan from data_orphan in the list of the centrals in data_centrals.

```<code>import numpy as np

data =  Structured array:
    class:  ndarray
    shape:  (189258912,)

dt = [('hostid', '<u8'), ('z_pos', '<f8'), ('x_pos', '<f8'),
     ('y_pos', '<f8'), ('haloid', '<u8'), ('orphan', 'i1')]
</code>```

EDITED: A subsamples of data with 200 objects can be downloaded here! It structure is given by dt: first column--> hostid, second --> z_pos, etc. It can be copy/pasted as it is into a python shell or script ...

Below you can find the code for setting the positions.

QUESTION: Is there are smart way of searching for the haloids and setting the positions without looping over all entries of data_orphan?

```<code>data_centrals=data[np.where(data['haloid']==data['hostid'])] # (111958237,)

data_orphans=data[np.where(data['orphan']==2)]               # (61870681,)

a=0
while a<len(data_orphans):

    #check where in data_centrals the haloid of the orphan can be found
    position=np.where(data_centrals['haloid']==data_orphans['haloid'][a])

    #find the position of data_orphan['haloid'][a] in data
    position_data=np.where(data['hostid']==data_orphans['hostid'][a])

    #set the positions
    data['x_pos'][int(position_data[0])]=data_centrals['x_pos'][int(position[0])]
    data['y_pos'][int(position_data[0])]=data_centrals['y_pos'][int(position[0])]
    data['z_pos'][int(position_data[0])]=data_centrals['z_pos'][int(position[0])]

    a+=1
</code>```

答: If your data structure is a plain, unordered list or array then the answer is no. It will take linear time O(n) to find a specific element. If the list/array is ordered you can do a binary search in O(lg n) time. You may also consider alternative data structures like a balanced BST or python dictionary with better search times, but it depends on the structure of your data if such an approach is appropriate.</p>

Body:
I have some issues with very large data sets. I need to find a solid and fast way to find/replace entries in my structured array. I am looking for an solution without looping of all entries. I know there are fast solutions for C but I do not know how to approach in python for that. I am also wonder if there is a numpy function for that very purpose!

I am using Python 2.7.13 and numpy 1.12.1!

TASK:
Set all positions of the orphans to the positions of the data_centrals by finding the haloid of the orphan from data_orphan in the list of the centrals in data_centrals.

import numpy as np

data =  Structured array:
    class:  ndarray
    shape:  (189258912,)

dt = [('hostid', '<u8'), ('z_pos', '<f8'), ('x_pos', '<f8'),
     ('y_pos', '<f8'), ('haloid', '<u8'), ('orphan', 'i1')]

EDITED: A subsamples of data with 200 objects can be downloaded here! It structure is given by dt: first column--> hostid, second --> z_pos, etc. It can be copy/pasted as it is into a python shell or script ...

Below you can find the code for setting the positions.

QUESTION: Is there are smart way of searching for the haloids and setting the positions without looping over all entries of data_orphan?

data_centrals=data[np.where(data['haloid']==data['hostid'])] # (111958237,)

data_orphans=data[np.where(data['orphan']==2)]               # (61870681,)

a=0
while a<len(data_orphans):

    #check where in data_centrals the haloid of the orphan can be found
    position=np.where(data_centrals['haloid']==data_orphans['haloid'][a])

    #find the position of data_orphan['haloid'][a] in data
    position_data=np.where(data['hostid']==data_orphans['hostid'][a])

    #set the positions
    data['x_pos'][int(position_data[0])]=data_centrals['x_pos'][int(position[0])]
    data['y_pos'][int(position_data[0])]=data_centrals['y_pos'][int(position[0])]
    data['z_pos'][int(position_data[0])]=data_centrals['z_pos'][int(position[0])]

    a+=1


问:
Can I access a class without an __init__? - Python
I want to be able to print "hello harry" from a module. This is my module (called test23):

```<code>class tool:

    def handle(self,name):
        self.name = "hello " + name
</code>```

This is my script:

```<code>import test23

harry= test23.tool().handle(" harry")
print harry.name
</code>```

I can't seem to print "hello harry" inside my script idle. How would I go about doing this?

答:
handle doesn't return anything, so harry will be NoneType.
Do it in two times: first assign the instance, then call the method:

```<code>>>> class tool:
...   def hello(self,name):
...      self.name="hello "+name
...
>>> a=tool()
>>> a.hello('i')
>>> a.name
'hello i'
>>> b=tool().hello('b')
>>> b.name
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'name'
>>> type(b)
<type 'NoneType'>
</code>```

Body:
I want to be able to print "hello harry" from a module. This is my module (called test23):

class tool:

    def handle(self,name):
        self.name = "hello " + name

This is my script:

import test23

harry= test23.tool().handle(" harry")
print harry.name

I can't seem to print "hello harry" inside my script idle. How would I go about doing this?

Body:
handle doesn't return anything, so harry will be NoneType.
Do it in two times: first assign the instance, then call the method:

>>> class tool:
...   def hello(self,name):
...      self.name="hello "+name
...
>>> a=tool()
>>> a.hello('i')
>>> a.name
'hello i'
>>> b=tool().hello('b')
>>> b.name
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'name'
>>> type(b)
<type 'NoneType'>


问:
Remove all punctuation from string, except if it's between digits
I have a text that contains words and numbers. I'll give a representative example of the text:

```<code>string = "This is a 1example of the text. But, it only is 2.5 percent of all data"
</code>```

I'd like to convert it to something like:

```<code>"This is a  1 example of the text But it only is  2.5  percent of all data"
</code>```

So removing punctuation (can be . , or any other in string.punctuation) and also put a space between digits and words when it is concatenated. But keep the floats like 2.5 in my example.

I used the following code:

```<code>item = "This is a 1example of the text. But, it only is 2.5 percent of all data"
item = ' '.join(re.sub( r"([A-Z])", r" \1", item).split())
# This a start but not there yet !
#item = ' '.join([x.strip(string.punctuation) for x in item.split() if x not in string.digits])
item = ' '.join(re.split(r'(\d+)', item) )
print item
</code>```

The result is :

```<code> >> "This is a  1 example of the text. But, it only is  2 . 5  percent of all data"
</code>```

I'm almost there but can't figure out that last peace.

答:
You can use regex lookarounds like this:

```<code>(?<!\d)[.,;:](?!\d)
</code>```

Working demo

The idea is to have a character class gathering the punctuation you want to replace and use lookarounds to match punctuation that does not have digits around

```<code>regex = r"(?<!\d)[.,;:](?!\d)"

test_str = "This is a 1example of the text. But, it only is 2.5 percent of all data"

result = re.sub(regex, "", test_str, 0)
</code>```

Result is:

```<code>This is a 1example of the text But it only is 2.5 percent of all data
</code>```

Body:
I have a text that contains words and numbers. I'll give a representative example of the text:

string = "This is a 1example of the text. But, it only is 2.5 percent of all data"

I'd like to convert it to something like:

"This is a  1 example of the text But it only is  2.5  percent of all data"

So removing punctuation (can be . , or any other in string.punctuation) and also put a space between digits and words when it is concatenated. But keep the floats like 2.5 in my example.

I used the following code:

item = "This is a 1example of the text. But, it only is 2.5 percent of all data"
item = ' '.join(re.sub( r"([A-Z])", r" \1", item).split())
# This a start but not there yet !
#item = ' '.join([x.strip(string.punctuation) for x in item.split() if x not in string.digits])
item = ' '.join(re.split(r'(\d+)', item) )
print item

The result is :

 >> "This is a  1 example of the text. But, it only is  2 . 5  percent of all data"

I'm almost there but can't figure out that last peace.

Body:
You can use regex lookarounds like this:

(?<!\d)[.,;:](?!\d)

Working demo

The idea is to have a character class gathering the punctuation you want to replace and use lookarounds to match punctuation that does not have digits around

regex = r"(?<!\d)[.,;:](?!\d)"

test_str = "This is a 1example of the text. But, it only is 2.5 percent of all data"

result = re.sub(regex, "", test_str, 0)

Result is:

This is a 1example of the text But it only is 2.5 percent of all data


问:
Disable Button If Checkbox Is Unchecked In Angular JS
So I'm working on this web application. I have a list of categories, where if an item on the list is not checked, the "Save"and "Publish"buttons would be disabled. I understand ng-disabled = !(ng-model name)would do just that, but each time, I load the page, the buttons are disabled, but do not get enabled when I check an item on the list.

```<code><a ng-if="status() < 2" href="#" data-ng-click="publish(true)" class="btn btn-sm btn-block btn-success" ng-disabled="!cat.IsSelected">{{lbl.publish}}</a>
<a ng-if="status() == 2" href="#" data-ng-click="save()" class="btn btn-sm btn-block btn-primary" id="check_box" ng-disabled="!cat.IsSelected">
{{lbl.save}}
</a>
<span ng-if="status() < 2">
   <a href="#" ng-click="save()" class="btn btn-sm btn-block btn-primary"   id="check_box" ng-disabled="!cat.IsSelected">
    {{lbl.save}}
   </a>
</span>

<ul class="categories-list">
    <li ng-repeat="cat in lookups.CategoryList">
      <label><input type="checkbox" id="cat-{{cat.OptionValue}}" data-ng-model="cat.IsSelected"/> {{cat.OptionName}}</label>
    </li>
    <li ng-if="lookups.CategoryList.length == 0" class="item-empty">{{lbl.empty}}</li>
</ul>
</code>```

JS Code:

```<code>$scope.post.Categories = [];
if ($scope.lookups.CategoryList != null) {
    for (var i = 0; i < $scope.lookups.CategoryList.length; i++) {
        var cat = $scope.lookups.CategoryList[i];
        if (cat.IsSelected) {
            var catAdd = { "IsChecked": false, "Id": cat.OptionValue, "Title": cat.OptionName };
            $scope.post.Categories.push(catAdd);
        }
    }
}
</code>```

答:
UPDATE: made the fiddle more like the actual scenario.

Wrap your  tag in a button and put the ng-dissabled on that.

Here's a jsfiddle that demonstrates how I would do this: fiddle

```<code><div ng-app="test" ng-controller="myController">
  <button ng-click="save()" ng-disabled="!hasSelectedAnItem" class="btn btn-sm btn-block btn-primary">
    Save
  </button>
  <ul class="categories-list">
      <li ng-repeat="cat in items">
          <label><input type="checkbox" id="cat-{{cat.OptionValue}}" ng-model="cat.IsSelected" ng-change="canBeSaved()"/> {{cat.OptionName}}</label>
      </li>
  </ul>
</div>
</code>```

JS:

```<code>angular.module('test', [])

.controller('myController', ['$scope', function($scope) {
    $scope.hasSelectedAnItem = false;

   $scope.items = [
        {OptionValue: 123, OptionName: "Adam", IsSelected: true},
      {OptionValue: 234, OptionName: "Paul", IsSelected: false},
            {OptionValue: 345, OptionName: "Jason", IsSelected: true},
      {OptionValue: 464, OptionName: "Joe", IsSelected: false}
   ];

   $scope.canBeSaved = function() {

      var found = false;
        $scope.items.forEach(function(item) {
        if (item.IsSelected) {
            alert("Here");
            found = true;
        }
      });

      $scope.hasSelectedAnItem = found;
   }

   $scope.save = function() {
        alert($scope.cat.IsSelected);
   }

   $scope.canBeSaved();
}]);
</code>```

Body:
So I'm working on this web application. I have a list of categories, where if an item on the list is not checked, the "Save"and "Publish"buttons would be disabled. I understand ng-disabled = !(ng-model name)would do just that, but each time, I load the page, the buttons are disabled, but do not get enabled when I check an item on the list.

<a ng-if="status() < 2" href="#" data-ng-click="publish(true)" class="btn btn-sm btn-block btn-success" ng-disabled="!cat.IsSelected">{{lbl.publish}}

{{lbl.save}}

<span ng-if="status() < 2">

    {{lbl.save}}

      <input type="checkbox" id="cat-{{cat.OptionValue}}" data-ng-model="cat.IsSelected"/> {{cat.OptionName}}

{{lbl.empty}}

JS Code:

$scope.post.Categories = [];
if ($scope.lookups.CategoryList != null) {
    for (var i = 0; i < $scope.lookups.CategoryList.length; i++) {
        var cat = $scope.lookups.CategoryList[i];
        if (cat.IsSelected) {
            var catAdd = { "IsChecked": false, "Id": cat.OptionValue, "Title": cat.OptionName };
            $scope.post.Categories.push(catAdd);
        }
    }
}

Body:
UPDATE: made the fiddle more like the actual scenario.

Wrap your <a> tag in a button and put the ng-dissabled on that.

Here's a jsfiddle that demonstrates how I would do this: fiddle

<div ng-app="test" ng-controller="myController">
  <button ng-click="save()" ng-disabled="!hasSelectedAnItem" class="btn btn-sm btn-block btn-primary">
    Save
  </button>
  <ul class="categories-list">
      <li ng-repeat="cat in items">
          <label><input type="checkbox" id="cat-{{cat.OptionValue}}" ng-model="cat.IsSelected" ng-change="canBeSaved()"/> {{cat.OptionName}}</label>
      </li>
  </ul>
</div>

JS:

angular.module('test', [])

.controller('myController', ['$scope', function($scope) {
    $scope.hasSelectedAnItem = false;

   $scope.items = [
        {OptionValue: 123, OptionName: "Adam", IsSelected: true},
      {OptionValue: 234, OptionName: "Paul", IsSelected: false},
            {OptionValue: 345, OptionName: "Jason", IsSelected: true},
      {OptionValue: 464, OptionName: "Joe", IsSelected: false}
   ];

   $scope.canBeSaved = function() {

      var found = false;
        $scope.items.forEach(function(item) {
        if (item.IsSelected) {
            alert("Here");
            found = true;
        }
      });

      $scope.hasSelectedAnItem = found;
   }

   $scope.save = function() {
        alert($scope.cat.IsSelected);
   }

   $scope.canBeSaved();
}]);


问:
Tweaking Vim syntax file for character literals in Scheme
For those who love code, there is nothing worse than looking at ugly code. My current syntax highlighting file scheme.vim for the editor vim on debian does not seem to recognize some character literals which are perfectly legal (at least in guile or indeed scm). For example the character literal #\x0000 which refers to the hexadecimal unicode point 0x0000 is recognized as such and properly displayed, but if I use an octal representation #\000 or a name representation #\nul, then vim gives me this bright orange (I am guessing the intent is to highlight an error condition). Does anyone have a suggestion helping me to fix this?

答:
This is a more polished version of what came out of the comments:

The existing syntax file scheme.vim probably recognizes some names for character literals, for example#\newline, and this gives us a starting point of where to search:

```<code>syn match schemeCharacter "#\\newline"
</code>```

It is then just a matter of adding similar lines to the file with the new desired names...

```<code>syn match schemeCharacter "#\\linefeed"
...
</code>```

Now we know that the existing file properly formats character literals where the unicode point is expressed in hexadecimal form. Searching for other occurences of schemeCharacter we find:

```<code>syn match schemeCharacter "#\\x[0-9a-fA-F]\+"
</code>```

This really looks like a way of specifying a regex expression to match hex literals preceded by #\x. In order to add syntax recognition for character literals in octal format, we simply need to add another line of this type with the appropriate regex, this time allowing parsing of octal literals:

```<code>syn match schemeCharacter "#\\[0-7]\+"
</code>```

Note: according to the GNU guile manual, R7RS uses the literal #\escape instead of #\esc (or as well as?). If you want both literals to be recognized by the syntax file, you cannot simply put the line relating to 'escape' first. Maybe replace the line for 'esc' by:

```<code> syn match schemeCharacter "#\\esc[^a]"
</code>```

which indicates you will match any #\esc provided it is not followed by a.

Body:
This is a more polished version of what came out of the comments:

The existing syntax file scheme.vim probably recognizes some names for character literals, for example#\newline, and this gives us a starting point of where to search:

syn match schemeCharacter "#\\newline"

It is then just a matter of adding similar lines to the file with the new desired names...

syn match schemeCharacter "#\\linefeed"
...

Now we know that the existing file properly formats character literals where the unicode point is expressed in hexadecimal form. Searching for other occurences of schemeCharacter we find:

syn match schemeCharacter "#\\x[0-9a-fA-F]\+"

This really looks like a way of specifying a regex expression to match hex literals preceded by #\x. In order to add syntax recognition for character literals in octal format, we simply need to add another line of this type with the appropriate regex, this time allowing parsing of octal literals:

syn match schemeCharacter "#\\[0-7]\+"

Note: according to the GNU guile manual, R7RS uses the literal #\escape instead of #\esc (or as well as?). If you want both literals to be recognized by the syntax file, you cannot simply put the line relating to 'escape' first. Maybe replace the line for 'esc' by:

 syn match schemeCharacter "#\\esc[^a]"

which indicates you will match any #\esc provided it is not followed by a.


问:
Viewpager is pushed up when i push Toolbar
i have problem with toolbar When I push him up , viewpager go up to the top also , And leave space at the bottom (see picture ) Any solution to solve this problem.

this is my activity_main :

```<code><android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:background="#fafafb">
<android.support.design.widget.CoordinatorLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways|snap"
            android:elevation="5dp"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_below="@id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabMaxWidth="0dp"
            app:tabGravity="fill"
            app:tabMode="fixed"
            app:tabIndicatorHeight="2dp"
            android:elevation="10dp"/>
    </android.support.design.widget.AppBarLayout>
    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/tabs"
        android:background="#fafafb"
        android:layout_marginBottom="?attr/actionBarSize"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
</code>```

答:
Remove :

```<code>app:layout_behavior="@string/appbar_scrolling_view_behavior"
</code>```

From your ViewPager

The support library contains a special string resource @string/appbar_scrolling_view_behavior that maps to AppBarLayout.ScrollingViewBehavior, which is used to notify the AppBarLayout when scroll events occur on this particular view.

Read this for more Clarification

Body:
i have problem with toolbar When I push him up , viewpager go up to the top also , And leave space at the bottom (see picture ) Any solution to solve this problem.

this is my activity_main :

<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:background="#fafafb">
<android.support.design.widget.CoordinatorLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways|snap"
            android:elevation="5dp"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_below="@id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabMaxWidth="0dp"
            app:tabGravity="fill"
            app:tabMode="fixed"
            app:tabIndicatorHeight="2dp"
            android:elevation="10dp"/>
    </android.support.design.widget.AppBarLayout>
    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/tabs"
        android:background="#fafafb"
        android:layout_marginBottom="?attr/actionBarSize"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>

Body:
Remove :

app:layout_behavior="@string/appbar_scrolling_view_behavior"

From your ViewPager

The support library contains a special string resource @string/appbar_scrolling_view_behavior that maps to AppBarLayout.ScrollingViewBehavior, which is used to notify the AppBarLayout when scroll events occur on this particular view.

Read this for more Clarification


问:
Retrieving returned value from fetch inside render()?
I'm having a little trouble, I have JSON data which is being fetched, and then the data is rendered. However within the render I need to perform another fetch as the data I'm trying to render relies on the first JSON.

You can see I'm trying grab the returned value, but it comes as undefined.

So the fetch looks like this:

```<code>getFeaturedImage(thumbnail_json) {
    fetch(thumbnail_json)
      .then((response) => response.json())
      .then((responseData) => {
        return responseData.media_details.sizes.medium.source_url;
      })
      .done();
  }
</code>```

and the renderPost() is:

```<code>renderPosts() {
    contents = this.state.posts.map((post) => {
      let postDate = Moment(post.date).format('LLL');

      if ( post._links['wp:featuredmedia'] ) {
        console.log('has featured image');
        let thumbnail_json = post._links['wp:featuredmedia'][0].href;
        this.getFeaturedImage(thumbnail_json);
        console.log(this.getFeaturedImage(thumbnail_json)); // <----- UNDEFINED?
      } else {
        console.log('no featured image');
      }

      return (
        <View key={post.id} style={ postStyles.postContainer }>
          <Text style={postStyles.postTitle}>
            {post.title.rendered}
          </Text>
          <Text style={postStyles.postDate}>
            {postDate}
          </Text>
          <View style={ postStyles.excerptContainer }>
            <HTMLView stylesheet={htmlStyles}
              value={post.excerpt.rendered}
            />
          </View>
        </View>
      );
    });
    return (
      <ScrollView>
        <View style={baseStyles.container}>
          {contents}
        </View>
      </ScrollView>
    );
  }
</code>```

答:
Your function doesn't return anything currently, add a return in front of your fetch:

```<code>getFeaturedImage(thumbnail_json) {
  return fetch(thumbnail_json)
  .then((response) => response.json())
  .then((responseData) => {
    return responseData.media_details.sizes.medium.source_url;
  })
  .done();
</code>```

}

Body:
I'm having a little trouble, I have JSON data which is being fetched, and then the data is rendered. However within the render I need to perform another fetch as the data I'm trying to render relies on the first JSON.

You can see I'm trying grab the returned value, but it comes as undefined.

So the fetch looks like this:

getFeaturedImage(thumbnail_json) {
    fetch(thumbnail_json)
      .then((response) => response.json())
      .then((responseData) => {
        return responseData.media_details.sizes.medium.source_url;
      })
      .done();
  }

and the renderPost() is:

renderPosts() {
    contents = this.state.posts.map((post) => {
      let postDate = Moment(post.date).format('LLL');

      if ( post._links['wp:featuredmedia'] ) {
        console.log('has featured image');
        let thumbnail_json = post._links['wp:featuredmedia'][0].href;
        this.getFeaturedImage(thumbnail_json);
        console.log(this.getFeaturedImage(thumbnail_json)); // <----- UNDEFINED?
      } else {
        console.log('no featured image');
      }

      return (
        <View key={post.id} style={ postStyles.postContainer }>
          <Text style={postStyles.postTitle}>
            {post.title.rendered}
          </Text>
          <Text style={postStyles.postDate}>
            {postDate}
          </Text>
          <View style={ postStyles.excerptContainer }>
            <HTMLView stylesheet={htmlStyles}
              value={post.excerpt.rendered}
            />
          </View>
        </View>
      );
    });
    return (
      <ScrollView>
        <View style={baseStyles.container}>
          {contents}
        </View>
      </ScrollView>
    );
  }

Body:
Your function doesn't return anything currently, add a return in front of your fetch:

getFeaturedImage(thumbnail_json) {
  return fetch(thumbnail_json)
  .then((response) => response.json())
  .then((responseData) => {
    return responseData.media_details.sizes.medium.source_url;
  })
  .done();

}


问:
How to find out the minimum and maximum usable CPU and memory space left on a kubernetes node
I'm trying to deploy Magento on a GCE n1-standard-1 machine, but I keep getting the following error message.

```<code>pod (magento-magento-1486272877-zd34d) failed to fit in any node fit failure summary on nodes : Insufficient cpu (1)
</code>```

I'm using the official Magento helm chart, and I've configured the values.yml file to contain very low CPU requests: cpu: 25m

When I look at the node details on the kubernetes dashboard, I see that my CPU is already spinning at 0.728 (72.80%) while it's not even doing anything besides the system containers. Also see image below:

Does this mean I have 1 - 0.728 = 0.272m left for container requests? Then why is kubernetes still telling me that it has insufficient CPU when specifying 0.25m?

Thanks for your help.

答: I didn't see that the CPU limits were 0.248 according to the picture in my post, so I put cpu: 20m and it worked.

Body:
I'm trying to deploy Magento on a GCE n1-standard-1 machine, but I keep getting the following error message.

pod (magento-magento-1486272877-zd34d) failed to fit in any node fit failure summary on nodes : Insufficient cpu (1)

I'm using the official Magento helm chart, and I've configured the values.yml file to contain very low CPU requests: cpu: 25m

When I look at the node details on the kubernetes dashboard, I see that my CPU is already spinning at 0.728 (72.80%) while it's not even doing anything besides the system containers. Also see image below:

Does this mean I have 1 - 0.728 = 0.272m left for container requests? Then why is kubernetes still telling me that it has insufficient CPU when specifying 0.25m?

Thanks for your help.


问:
How to compute execution time in Nodejs ChildProcess.exec
We have an API request that logins our users, like this:

```<code>...

//lauches an API request

router.post("/trip/analyse",function(req,res){

    t0 = Date.now();

    shell = ("sudo /usr/bin/python /mypythonFile");

    child = exec(shell, function (error, stdout, stderr) {

      if (error) { //There is an error

        res.json({"Error" : true});

        console.log(Date.now() - t0);  // <-------- HERE, How to get this right ?

      }else{ //everything went fine

        res.json({"Error" : false});

        console.log(Date.now() - t0);  // <-------- HERE, How to get this right ?

      }

    });

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

I see that the printed execution time is not right, because when many users login at the same time, the "t0" value used for computing the executionTime ("Date.now() - t0") is not correctly computed. It uses the t0 values of a more recent call of this API request, and not the appropriate t0 value.

This is because the exec method is asynchronous and take time to execute.

How do I right properly the execution time ("Date.now() - t0"), where the original t0 variable is lost ?

答:
I only had to put

var t0 = Date.now();

And it worked !

Body:
We have an API request that logins our users, like this:

...

//lauches an API request

router.post("/trip/analyse",function(req,res){

    t0 = Date.now();

    shell = ("sudo /usr/bin/python /mypythonFile");

    child = exec(shell, function (error, stdout, stderr) {

      if (error) { //There is an error

        res.json({"Error" : true});

        console.log(Date.now() - t0);  // <-------- HERE, How to get this right ?

      }else{ //everything went fine

        res.json({"Error" : false});

        console.log(Date.now() - t0);  // <-------- HERE, How to get this right ?

      }

    });

});
...

I see that the printed execution time is not right, because when many users login at the same time, the "t0" value used for computing the executionTime ("Date.now() - t0") is not correctly computed. It uses the t0 values of a more recent call of this API request, and not the appropriate t0 value.

This is because the exec method is asynchronous and take time to execute.

How do I right properly the execution time ("Date.now() - t0"), where the original t0 variable is lost ?


问:
How to embed an icon (.ico) in a static library (Visual Studio)
Is there a way to embed resources (such as icons, dialogs) in a c++ (Win32 API) static library?
My purpose is to embed an icon in the static library in a way that functions that use LoadIcon will work as if it was a normal .exe so the main application can only link to the static library and include a header file, with no requirement to add other files such as .rc files, or .ico files, etc.
Clearly the main application who uses the static library doesn't have this resource so LoadIcon will fail, however I was wondering if there is a workaround to make it work. A static array with the icon data can work as long as the standard API calls (such as LoadIcon) will work.

To explain further, the person who will be using the static library will only have 2 files: .lib and .h and will not have any .rc file.

答:
I am posting an answer because after some research I found a way. Using my method, an icon can be used as an integral part of a static library and such library can be used by any type of application).
See also: https://www.codeproject.com/Articles/1275122/How-to-embed-resources-in-a-Static-Library

Icon is converted to a static array of BYTE. bin2c can be used for that.

Data is converted into a HICON handle. Here is how I have done that:

```<code>HICON GetIcon()
{
   DWORD dwTmp;
   int offset;
   HANDLE hFile;
   HICON hIcon = NULL;
   offset = LookupIconIdFromDirectoryEx(s_byIconData, TRUE, 0, 0, LR_DEFAULTCOLOR);
   if (offset != 0)
   {
      hIcon = CreateIconFromResourceEx(s_byIconData + offset, 0, TRUE, 0x00030000, 0, 0, LR_DEFAULTCOLOR | LR_DEFAULTSIZE);
   }
   return hIcon;
}
</code>```

GetIcon is used instead of LoadIcon.
Instead of calling:

m_hIcon = ::LoadIcon(hInstanceIcon, MAKEINTRESOURCE(pXMB->nIcon));

I call

```<code>m_hIcon = GetIcon()
</code>```

Body:
I am posting an answer because after some research I found a way. Using my method, an icon can be used as an integral part of a static library and such library can be used by any type of application).
See also: https://www.codeproject.com/Articles/1275122/How-to-embed-resources-in-a-Static-Library

Icon is converted to a static array of BYTE. bin2c can be used for that.

Data is converted into a HICON handle. Here is how I have done that:

HICON GetIcon()
{
   DWORD dwTmp;
   int offset;
   HANDLE hFile;
   HICON hIcon = NULL;
   offset = LookupIconIdFromDirectoryEx(s_byIconData, TRUE, 0, 0, LR_DEFAULTCOLOR);
   if (offset != 0)
   {
      hIcon = CreateIconFromResourceEx(s_byIconData + offset, 0, TRUE, 0x00030000, 0, 0, LR_DEFAULTCOLOR | LR_DEFAULTSIZE);
   }
   return hIcon;
}

GetIcon is used instead of LoadIcon.
Instead of calling:

m_hIcon = ::LoadIcon(hInstanceIcon, MAKEINTRESOURCE(pXMB->nIcon));

I call

m_hIcon = GetIcon()


问:
multiple IN conditions in JPQL
How can I express the following SQL in JPQL:

```<code>select * from table where
( ( table.col1 , table.col2) in
   (col1val1, col2val1),
   (col1val2, col2val2),
   (col1val3, col2val3)
)
</code>```

BTW: The above is valid Oracle SQL syntax

答:
Edit: Forget what follows, it's not correct. Left in to show thinking

I think you'd first have to split out the multi-dimensional statement into it's constituents:

```<code>select * from table
where table.col1 in (col1val1, col1val2, col1val3)
and table.col2 in (col2val1, col2val2, col2val3)
</code>```

which would translate in JPQL (assuming that "table" is mapped to an entity TableDto) like this:

```<code>select tableDto from TableDto tableDto
where tableDto.col1 in(col1val1, col1val2, col1val3)
and tableDto.col2 in(col2val1, col2val2, col2val3)
</code>```

The above is untested, but further information can be found in the JPQL reference documentation.

Title: multiple IN conditions in JPQL

Body:
How can I express the following SQL in JPQL:

select * from table where
( ( table.col1 , table.col2) in
   (col1val1, col2val1),
   (col1val2, col2val2),
   (col1val3, col2val3)
)

BTW: The above is valid Oracle SQL syntax

Body:
Edit: Forget what follows, it's not correct. Left in to show thinking

I think you'd first have to split out the multi-dimensional statement into it's constituents:

select * from table
where table.col1 in (col1val1, col1val2, col1val3)
and table.col2 in (col2val1, col2val2, col2val3)

which would translate in JPQL (assuming that "table" is mapped to an entity TableDto) like this:

select tableDto from TableDto tableDto
where tableDto.col1 in(col1val1, col1val2, col1val3)
and tableDto.col2 in(col2val1, col2val2, col2val3)

The above is untested, but further information can be found in the JPQL reference documentation.


问:
Sorting an array with multiple elements
I am making a to-do list in java for a class project. In the jList i display a date and a string that represent a date and what needs to be done on that day. I would also like to be able to sort these events by the dates on them, so the tasks that are due sooner appear first. I know how to sort a list of dates using bubble sort, but I do not know how to apply this to my list because each item contains a date AND a string. This is the code I have so far. Does anyone know how I will be able to sort the dates in order and keep the strings attached to their dates. Thanks. </p>

```<code>public class ToDoListManager {

    final int maxitems = 20;
    int items = 0;
    String[] toDoList = new String[20];
    Date[] Dates = new Date[20];

    String addItem(String toDo, Date date) {
        if (items == maxitems) {
            return ("No more Space");
        } else if (toDo.equalsIgnoreCase("") || (toDo == null) || (date == null)) {
            return ("All fields required");
        } else if (items < maxitems) {
            Dates[items] = date;
            SimpleDateFormat dt1 = new SimpleDateFormat("yyyy-MM-dd");
            toDoList[items] = "On " + dt1.format(date) + " " + toDo;
            items = items + 1;
            return (toDo + " Was Added to the List");
        }
        return null;
    }

    void Order(Date[] dates) {
        Date temp;
        boolean fixed = false;
        while (fixed == false) {
            fixed = true;
            for (int i = 0; i < dates.length - 1; i++) {
                if (dates[i].before(dates[i + 1])) {
                    temp = dates[i + 1];
                    dates[i + 1] = dates[i];
                    dates[i] = temp;
                    fixed = false;
                }
            }

        }
        System.out.println(dates);

    }

    String[] getItems() {
        String[] displayList = new String[items];
        for (int i = 0; i < items; i++) {
            displayList[i] = toDoList[i];

        }

        return displayList;

    }
}
</code>```

答:
This is roughly how I would structure your application. I have left out the order and getItems methods for brevity.

```<code>public class ToDoListManager {

    private static class ToDo
    {
        public final String text;
        public final Date   date;
        public ToDo(String text, Date date)
        {
            this.text = text;
            this.date = date;
        }
    }

    final int maxItems = 20;
    final List<ToDo> todos = new LinkedList<>();

    String addItem(String text, Date date) {
        if (todos.size() == maxItems) {
            return ("No more Space");
        } else if (text == null || text.equalsIgnoreCase("") || date == null) {
            return ("All fields required");
        } else if (todos.size() < maxItems) {

            final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            text = "On " + format.format(date) + " " + text;

            todos.add(new ToDo(text, date));

            return (text + " Was Added to the List");
        }
        return null;
    }
}
</code>```

You can see things become much simpler to work with once you ditch the primitive arrays in favour of Collections, and you start using classes.

Now to answer your question: rather than implement your own sort, use Collections.sort(todos).

In order to sort your list appropriately, you will need ToDo to implement Comparable<ToDo>. I'll leave this up to you to research and implement.

Title: Sorting an array with multiple elements

Body:
I am making a to-do list in java for a class project. In the jList i display a date and a string that represent a date and what needs to be done on that day. I would also like to be able to sort these events by the dates on them, so the tasks that are due sooner appear first. I know how to sort a list of dates using bubble sort, but I do not know how to apply this to my list because each item contains a date AND a string. This is the code I have so far. Does anyone know how I will be able to sort the dates in order and keep the strings attached to their dates. Thanks.

public class ToDoListManager {

    final int maxitems = 20;
    int items = 0;
    String[] toDoList = new String[20];
    Date[] Dates = new Date[20];

    String addItem(String toDo, Date date) {
        if (items == maxitems) {
            return ("No more Space");
        } else if (toDo.equalsIgnoreCase("") || (toDo == null) || (date == null)) {
            return ("All fields required");
        } else if (items < maxitems) {
            Dates[items] = date;
            SimpleDateFormat dt1 = new SimpleDateFormat("yyyy-MM-dd");
            toDoList[items] = "On " + dt1.format(date) + " " + toDo;
            items = items + 1;
            return (toDo + " Was Added to the List");
        }
        return null;
    }

    void Order(Date[] dates) {
        Date temp;
        boolean fixed = false;
        while (fixed == false) {
            fixed = true;
            for (int i = 0; i < dates.length - 1; i++) {
                if (dates[i].before(dates[i + 1])) {
                    temp = dates[i + 1];
                    dates[i + 1] = dates[i];
                    dates[i] = temp;
                    fixed = false;
                }
            }

        }
        System.out.println(dates);

    }

    String[] getItems() {
        String[] displayList = new String[items];
        for (int i = 0; i < items; i++) {
            displayList[i] = toDoList[i];

        }

        return displayList;

    }
}

Body:
This is roughly how I would structure your application. I have left out the order and getItems methods for brevity.

public class ToDoListManager {

    private static class ToDo
    {
        public final String text;
        public final Date   date;
        public ToDo(String text, Date date)
        {
            this.text = text;
            this.date = date;
        }
    }

    final int maxItems = 20;
    final List<ToDo> todos = new LinkedList<>();

    String addItem(String text, Date date) {
        if (todos.size() == maxItems) {
            return ("No more Space");
        } else if (text == null || text.equalsIgnoreCase("") || date == null) {
            return ("All fields required");
        } else if (todos.size() < maxItems) {

            final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            text = "On " + format.format(date) + " " + text;

            todos.add(new ToDo(text, date));

            return (text + " Was Added to the List");
        }
        return null;
    }
}

You can see things become much simpler to work with once you ditch the primitive arrays in favour of Collections, and you start using classes.

Now to answer your question: rather than implement your own sort, use Collections.sort(todos).

In order to sort your list appropriately, you will need ToDo to implement Comparable<ToDo>. I'll leave this up to you to research and implement.


问:
Restrict google map autocomplete
I want to restrict google to only 'address', '(cities)', '(regions)' et remove commercial market name.
According to the documentation

types

  Type:  Array
  The types of predictions to be returned. Four types are supported: >'establishment' for businesses, 'geocode' for addresses, '(regions)' for >administrative regions and '(cities)' for localities. If nothing is specified, >all types are returned.

But this code return nothing

```<code>var options = {
    types: ['address', '(cities)', '(regions)']
};

var autocomplete = new google.maps.places.Autocomplete(input, options);
autocomplete.bindTo('bounds', map);
</code>```

https://jsfiddle.net/7pa4x12L/1/

答:
You're suppose to specify only one type. As Add Autocomplete for places and addresses says:

In general only a single type is allowed.The exception is that you can
  safely mix the geocode and establishment types, but note that this
  will have the same effect as specifying no types

That's why if you check the sample code from Restrict the search to a specific country you can see that there's only one type specified.

```<code>var options = {
  types: ['(cities)'],
  componentRestrictions: {country: 'fr'}
};
</code>```

You can see more of this in the Autocomplete sample demo.

Title: Restrict google map autocomplete

Body:
I want to restrict google to only 'address', '(cities)', '(regions)' et remove commercial market name.
According to the documentation

types

  Type:  Array
  The types of predictions to be returned. Four types are supported: >'establishment' for businesses, 'geocode' for addresses, '(regions)' for >administrative regions and '(cities)' for localities. If nothing is specified, >all types are returned.

But this code return nothing

var options = {
    types: ['address', '(cities)', '(regions)']
};

var autocomplete = new google.maps.places.Autocomplete(input, options);
autocomplete.bindTo('bounds', map);

https://jsfiddle.net/7pa4x12L/1/

Body:
You're suppose to specify only one type. As Add Autocomplete for places and addresses says:

In general only a single type is allowed.The exception is that you can
  safely mix the geocode and establishment types, but note that this
  will have the same effect as specifying no types

That's why if you check the sample code from Restrict the search to a specific country you can see that there's only one type specified.

var options = {
  types: ['(cities)'],
  componentRestrictions: {country: 'fr'}
};

You can see more of this in the Autocomplete sample demo.


问:
Reading a config from a file
So i am trying to read from a text file and put it in a variable

in the text file there is

```<code>NAME= Bame
GAME= Fame
</code>```

I've heard of strsep/strtok but i'm still having issues and with this code i get Segmentation Fault 11

```<code>    #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

int main() {
char *token;
char *string;
char *tofree;
FILE *fp;
const char *file = "/tmp/test.txt";
fp = fopen(file, "r");
while(!feof(fp)) {
fgets(string, sizeof(string), fp);
token = strsep(&string, ",");
printf("%s", string);
}
fclose(fp);
exit(0);
}
</code>```

答:
The main problem is from this line:

```<code>fgets(string, sizeof(string), fp);
</code>```

The second parameter should be 'Maximum number of characters to be copied into str'. You should have initialised string to something before calling this function. If you look at the example in the link I gave, changing string to a character array will help you more forward.

```<code>char string[100];
....
fgets(string, 100, fp);
</code>```

Previously you were passing sizeof(string), however since string was actually a pointer type, you were passing the size of a pointer in bytes (either 4 or 8 depending on platform). string was also an unallocated pointer, so fgets would have been potentially writing to a random memory address.

Title: Reading a config from a file

Body:
So i am trying to read from a text file and put it in a variable

in the text file there is

NAME= Bame
GAME= Fame

I've heard of strsep/strtok but i'm still having issues and with this code i get Segmentation Fault 11

    #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

int main() {
char *token;
char *string;
char *tofree;
FILE *fp;
const char *file = "/tmp/test.txt";
fp = fopen(file, "r");
while(!feof(fp)) {
fgets(string, sizeof(string), fp);
token = strsep(&string, ",");
printf("%s", string);
}
fclose(fp);
exit(0);
}

Body:
The main problem is from this line:

fgets(string, sizeof(string), fp);

The second parameter should be 'Maximum number of characters to be copied into str'. You should have initialised string to something before calling this function. If you look at the example in the link I gave, changing string to a character array will help you more forward.

char string[100];
....
fgets(string, 100, fp);

Previously you were passing sizeof(string), however since string was actually a pointer type, you were passing the size of a pointer in bytes (either 4 or 8 depending on platform). string was also an unallocated pointer, so fgets would have been potentially writing to a random memory address.


问:
How to Display VS Code output window to side rather than below
In my VS Code set up I see the output/FSI frame below the main text editor pane like this:

whereas I would love it to appear to the right in the side-by-side view like it does on the images in this link: http://www.wintellect.com/devcenter/jwood/a-quick-look-at-f-in-visual-studio-code

Is there a config option I cannot find somewhere?

I tried Googling but drew a blank and cannot see anything obvious in the config options mentioned on the vs code site page describing the config options

答: This feature is not available yet in VS Code. However as of today (March 30, 2017) it's on 6 months roadmap so it should be done in a near feature.</p>


答:
I think this will do it.</p>

```<code>from test23 import tool

harry = tool()
harry.handle("harry")
print harry.name
</code>```

Title: Can I access a class without an __init__? - Python

Body:
I want to be able to print "hello harry" from a module. This is my module (called test23):

class tool:

    def handle(self,name):
        self.name = "hello " + name

This is my script:

import test23

harry= test23.tool().handle(" harry")
print harry.name

I can't seem to print "hello harry" inside my script idle. How would I go about doing this?

Body:
I think this will do it.

from test23 import tool

harry = tool()
harry.handle("harry")
print harry.name