问:
Pointer instantly 0x0
i have this code. the pointer turns 0x0 immediately before using it. short before, it had the correct address.

```<code>TreeViewColumn *col;
col = preview->get_column(pcFolder); /* col = 0x7fff5fc404a0 */
col->set_resizable(true);            /* col = 0x0 */
</code>```

i use Gtkmm 2.4, but it returns the expected value, it just turns 0x0. whats wrong?

gdb proof:

```<code>151             col = preview->get_column(pcFolder); /* col = 0x7fff5fc404a0 */
(gdb) print col
$1 = ('Gtk::TreeViewColumn' *) 0x7fff5fc404a0
(gdb) print *col
warning: can't find linker symbol for virtual table for `Gtk::TreeViewColumn' value
$2 = {
  <Gtk::Object> = {
    <Glib::Object> = {
      <Glib::ObjectBase> = <invalid address>,
      members of Glib::Object:
      _vptr$Object = 0x7fff5fc06a20,
      static object_class_ = {<No data fields>}
    },
    members of Gtk::Object:
    static object_class_ = {<No data fields>},
    referenced_ = 21,
    gobject_disposed_ = 60
  },
  members of Gtk::TreeViewColumn:
  static treeviewcolumn_class_ = {<No data fields>}
}
(gdb) next
152             col->set_resizable(true);            /* col = 0x0 */
(gdb) print col
$3 = ('Gtk::TreeViewColumn' *) 0x0
(gdb) print *col
Cannot access memory at address 0x0
(gdb) next

Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x0000000000000000
0x00000001000edc68 in Gtk::TreeViewColumn::set_resizable ()
</code>```

i have no idea what causes this phenomenon. do you have?

Solution:
reading the documentation. the function returning pcFolder counts from 1, get_column() from 0.

答:
The function call:

```<code>preview->get_column(pcFolder);
</code>```

returns NULL.

When gdb shows the current code line, it hasn't been executed until you type next.

You probably pass an index that is larger than the number of columns in preview. Try:

```<code>p pcFolder
p preview->get_columns().size()
</code>```

Title: Pointer instantly 0x0

Body:
i have this code. the pointer turns 0x0 immediately before using it. short before, it had the correct address.

TreeViewColumn *col;
col = preview->get_column(pcFolder); /* col = 0x7fff5fc404a0 */
col->set_resizable(true);            /* col = 0x0 */

i use Gtkmm 2.4, but it returns the expected value, it just turns 0x0. whats wrong?

gdb proof:

151             col = preview->get_column(pcFolder); /* col = 0x7fff5fc404a0 */
(gdb) print col
$1 = ('Gtk::TreeViewColumn' *) 0x7fff5fc404a0
(gdb) print *col
warning: can't find linker symbol for virtual table for `Gtk::TreeViewColumn' value
$2 = {
  <Gtk::Object> = {
    <Glib::Object> = {
      <Glib::ObjectBase> = <invalid address>,
      members of Glib::Object:
      _vptr$Object = 0x7fff5fc06a20,
      static object_class_ = {<No data fields>}
    },
    members of Gtk::Object:
    static object_class_ = {<No data fields>},
    referenced_ = 21,
    gobject_disposed_ = 60
  },
  members of Gtk::TreeViewColumn:
  static treeviewcolumn_class_ = {<No data fields>}
}
(gdb) next
152             col->set_resizable(true);            /* col = 0x0 */
(gdb) print col
$3 = ('Gtk::TreeViewColumn' *) 0x0
(gdb) print *col
Cannot access memory at address 0x0
(gdb) next

Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x0000000000000000
0x00000001000edc68 in Gtk::TreeViewColumn::set_resizable ()

i have no idea what causes this phenomenon. do you have?

Solution:
reading the documentation. the function returning pcFolder counts from 1, get_column() from 0.

Body:
The function call:

preview->get_column(pcFolder);

returns NULL.

When gdb shows the current code line, it hasn't been executed until you type next.

You probably pass an index that is larger than the number of columns in preview. Try:

p pcFolder
p preview->get_columns().size()


来源: stackexchange

问:
scipy.misc.imshow RuntimeError('Could not execute image view')
I am testing scipy.misc.imshow and I got RuntimeError: Could not execute image viewer.

I am using Python3.4 and running it on CentOS 7.

```<code>import scipy.misc
img = scipy.misc.imread('Data/cat.jpg')
assert len(img.shape) == 3
img_resized = scipy.misc.imresize(img, (224, 224))
img_answer = (img_resized/255.0).astype('float32')
scipy.misc.imshow(img_answer)
</code>```

And I got an error:

```<code>sh: see: command not found
Traceback (most recent call last):
  File "/usr/local/pycharm/helpers/pydev/pydev_run_in_console.py", line 71, in <module>
    globals = run_file(file, None, None)
  File "/usr/local/pycharm/helpers/pydev/pydev_run_in_console.py", line 31, in run_file
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "/usr/local/pycharm/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "/root/PycharmProjects/myVQA/testgood.py", line 6, in <module>
    scipy.misc.imshow(img_answer)
  File "/usr/lib64/python3.4/site-packages/scipy/misc/pilutil.py", line 442, in imshow
    raise RuntimeError('Could not execute image viewer.')
RuntimeError: Could not execute image viewer.
</code>```

It says that the see command is not found. Where is the see command installed on CentOS7? How can I fix the problem?

I tried to add SCIPY_PIL_IMAGE_VIEWER=/bin/eog to /etc/profile
but it seems to be no help.

答:
You can use matplotlib.pyplot as an alternative to using SciPy's imshow method.

```<code>import scipy.misc
img = scipy.misc.imread('Data/cat.jpg')
assert len(img.shape) == 3
img_resized = scipy.misc.imresize(img, (224, 224))
img_answer = (img_resized/255.0).astype('float32')

import matplotlib.pyplot as plt
plt.imshow(np.uint8(img_tinted))
plt.show()
</code>```

 =>

P.S. If we directly plot the image as plt.imshow(img_tinted), then it might sometimes give weird results if the data presented to it is not in the form of unit8. Hence, to prevent this we explicitly cast np.uint8 to the image such as plt.imshow(np.uint8(img_tinted))

The following images show output in the absence of np.uint8

ContentLicense: CC BY-SA 3.0

Body:
I am testing scipy.misc.imshow and I got RuntimeError: Could not execute image viewer.

I am using Python3.4 and running it on CentOS 7.

import scipy.misc
img = scipy.misc.imread('Data/cat.jpg')
assert len(img.shape) == 3
img_resized = scipy.misc.imresize(img, (224, 224))
img_answer = (img_resized/255.0).astype('float32')
scipy.misc.imshow(img_answer)

And I got an error:

sh: see: command not found
Traceback (most recent call last):
  File "/usr/local/pycharm/helpers/pydev/pydev_run_in_console.py", line 71, in <module>
    globals = run_file(file, None, None)
  File "/usr/local/pycharm/helpers/pydev/pydev_run_in_console.py", line 31, in run_file
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "/usr/local/pycharm/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "/root/PycharmProjects/myVQA/testgood.py", line 6, in <module>
    scipy.misc.imshow(img_answer)
  File "/usr/lib64/python3.4/site-packages/scipy/misc/pilutil.py", line 442, in imshow
    raise RuntimeError('Could not execute image viewer.')
RuntimeError: Could not execute image viewer.

It says that the see command is not found. Where is the see command installed on CentOS7? How can I fix the problem?

I tried to add SCIPY_PIL_IMAGE_VIEWER=/bin/eog to /etc/profile
but it seems to be no help.

Body:
You can use matplotlib.pyplot as an alternative to using SciPy's imshow method.

import scipy.misc
img = scipy.misc.imread('Data/cat.jpg')
assert len(img.shape) == 3
img_resized = scipy.misc.imresize(img, (224, 224))
img_answer = (img_resized/255.0).astype('float32')

import matplotlib.pyplot as plt
plt.imshow(np.uint8(img_tinted))
plt.show()

 =>

P.S. If we directly plot the image as plt.imshow(img_tinted), then it might sometimes give weird results if the data presented to it is not in the form of unit8. Hence, to prevent this we explicitly cast np.uint8 to the image such as plt.imshow(np.uint8(img_tinted))

The following images show output in the absence of np.uint8


问:
How To Pass Object From *ngFor Select Options To (change) function Angular 2
I have a *ngFor select option list that I am using to pass options to functions. I cannot figure out how to pass the actual object (not value) through to the function I'm calling.

```<code><h1>
  {{title}}
  <form name="qrForm">
   <h2>Item Number</h2>
   <input type="number" name="myitem" [(ngModel)]="itemno"
(blur)="getItemsList(scriptno)">
  <h2>Date of birth</h2>
  <input type="date" name="dob" [(ngModel)]="dateofbirth" (blur)="getItemsList(itemno, dateofbirth)">
  <div *ngIf="showDeliveryTypes" name="deliverytypes">
  <h3>Delivery Method</h3>
  <select #select [(ngModel)]="current" (change)="validateDeliveryTypes(select.value)" name="deliveryoptions">
    <option *ngFor="let item of qrData.DeliveryTypes" [value]="item.DeliveryTypeId">{{item.DeliveryTypeName}}</option>

  </select>
  </div>
 </form>
</h1>
</code>```

In the (change)="validateDeliveryTypes()" function I'm getting the item.DeliveryTypeId value (which is what you would expect). But, how can I get the "item" object so I can access all the properties on that object and not just the DeliveryTypeId?

Any help greatly appreciated. Still learning Angular 2.

答:
You can find it by the selected DeliveryTypeId inside validateDeliveryTypes method using Array.prototype.find

```<code>...
public validateDeliveryTypes(){
   let selectedItem = this.qrData.DeliveryTypes.find((item)=> item.DeliveryTypeId===this.current);
   //rest of your code here
}
...
</code>```

Body:
I have a *ngFor select option list that I am using to pass options to functions. I cannot figure out how to pass the actual object (not value) through to the function I'm calling.

  {{title}}
  <form name="qrForm">

Item Number

   <input type="number" name="myitem" [(ngModel)]="itemno"
(blur)="getItemsList(scriptno)">

Date of birth

  <input type="date" name="dob" [(ngModel)]="dateofbirth" (blur)="getItemsList(itemno, dateofbirth)">

Delivery Method

  <select #select [(ngModel)]="current" (change)="validateDeliveryTypes(select.value)" name="deliveryoptions">
    <option *ngFor="let item of qrData.DeliveryTypes" [value]="item.DeliveryTypeId">{{item.DeliveryTypeName}}</option>

  </select>

 </form>

In the (change)="validateDeliveryTypes()" function I'm getting the item.DeliveryTypeId value (which is what you would expect). But, how can I get the "item" object so I can access all the properties on that object and not just the DeliveryTypeId?

Any help greatly appreciated. Still learning Angular 2.

Body:
You can find it by the selected DeliveryTypeId inside validateDeliveryTypes method using Array.prototype.find

...
public validateDeliveryTypes(){
   let selectedItem = this.qrData.DeliveryTypes.find((item)=> item.DeliveryTypeId===this.current);
   //rest of your code here
}
...


问:
Ironpython with pycharm: Drawing and Forms
This is probably a very noob question. I am trying to get some basic code from sharpdevelop into Pycharm. The code basically just draws a window and place some fields and buttons using Windows forms. I've set the interprter in Pycharm to be Ironpython. There seems to be something wrong with the import statements. When I run the following (Which is just a copy paste from code that is perfectly working in sharpdevelop):

```<code>import System.Drawing
import System.Windows.Forms

class MainForm(Form):
    def __init__(self):
    self.InitializeComponent()

def InitializeComponent(self):
    self._checkBox1 = System.Windows.Forms.CheckBox()
    self._comboBox1 = System.Windows.Forms.ComboBox()
    self._label1 = System.Windows.Forms.Label()
    #rest of code ...
</code>```

I get the following message

ImportError: No module named Drawing

答:
You will need to add a reference to the DLLs. It's three lines:

```<code>import clr
clr.AddReference("System.Drawing")
clr.AddReference("System.Windows.Forms")
</code>```

SharpDevelop takes care of adding the references in Program.py (the file that runs). It imports the MainForm class, instantiates it, and displays the form.

Since I am assuming this is the file you run, you will need to add the references within the same file.

Body:
This is probably a very noob question. I am trying to get some basic code from sharpdevelop into Pycharm. The code basically just draws a window and place some fields and buttons using Windows forms. I've set the interprter in Pycharm to be Ironpython. There seems to be something wrong with the import statements. When I run the following (Which is just a copy paste from code that is perfectly working in sharpdevelop):

import System.Drawing
import System.Windows.Forms

class MainForm(Form):
    def __init__(self):
    self.InitializeComponent()

def InitializeComponent(self):
    self._checkBox1 = System.Windows.Forms.CheckBox()
    self._comboBox1 = System.Windows.Forms.ComboBox()
    self._label1 = System.Windows.Forms.Label()
    #rest of code ...

I get the following message

ImportError: No module named Drawing

Body:
You will need to add a reference to the DLLs. It's three lines:

import clr
clr.AddReference("System.Drawing")
clr.AddReference("System.Windows.Forms")

SharpDevelop takes care of adding the references in Program.py (the file that runs). It imports the MainForm class, instantiates it, and displays the form.

Since I am assuming this is the file you run, you will need to add the references within the same file.


问:
What is the best JAX-RS library?
I've been trying to choose which technology to use for a REST application and have found 4 candidates:

Jersey - jersey.java.net

Apache Wink - incubator.apache.org/wink

RESTlet - www.restlet.org

RESTeasy - jboss.org/resteasy

but haven't been able to differentiate between the four and choose one
so, which is best? the criteria s being:

a.  Stability \ maturity

b. Security

c. Ease of use

d. Support

Thanks!

答:
Rather than comparing I can give a definite picture about Jersey on your concerns. Firstly I am using Jersey for some time now (from its inception actually). The reason I still stick to Jersey is -

It is a matured project with a lot of test case and has been around for some time. I hardly found issues with Jersey and find it quite stable. I would say the project and its community are both matured enough to use it in production.

We are using Spring Security 2/3 with Jersey so I guess anything could be used on it.

To be honest I stick to JAX-RS stuffs as much as possible so I think its as easy as JAX-RS is. The only additional stuffs I use specific to Jersey is form data multipart, jersey client and jersey apache client. These are easy enough that I write a generic restful client for resources and a jersey client using client side HTTP Caching using HTTP Cache 4J. So I would say its pretty easy. Plus there are plenty (for my cases) tutorials, books, examples, blog posts, I hardly ever remember being stuck with anything.

Well, one of the primary reasons for me to never thinking of moving away from Jersey is its support. Paul Sandoz, the project lead of Jersey is just awesome support personnel in the mailing lists. I have rarely seen a topic in the mailing list where Paul does not help. In addition there are other members in the mailing list who are very eager to help out. The mailing list support is very good. The release cycle is short ensuring that bug fixes are available in short time.

All in all I am pretty happy with Jersey.

ContentLicense: CC BY-SA 4.0

Title: What is the best JAX-RS library?


问:
C# OleDb OUT parameter fails when calling oracle procedure
I'm calling a procedure which has an OUT parameter (of CURSOR Type). It seems I'm missing something because I get error: "wrong number or types of arguments...". My code is as follows:

```<code> public static DataTable SearchClient()
    {
        try
        {
            using (OleDbCommand cmd = new OleDbCommand(packetName + ".select_A1001310"))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add("io_cursor", OracleType.Cursor).Direction = ParameterDirection.Output;

                SqlManager sqlManager = new SqlManager();
                return sqlManager.GetDataTable(cmd);
            }
        }
        catch (Exception ex)
        {
            ex.ToString();
            System.Console.WriteLine(ex);
            //TODO; Handle exception
        }
        return null;
    }
</code>```

PROCEDURE:

```<code>TYPE lcursor_data IS REF CURSOR;
PROCEDURE select_A1001310(io_cursor OUT lcursor_data)
      AS
      BEGIN
        OPEN io_cursor FOR
        --
          SELECT client_id
            FROM a1001310
           WHERE status = 'A';
        --
      EXCEPTION
        WHEN OTHERS THEN
          IF io_cursor%ISOPEN THEN
            CLOSE io_cursor;
          END IF;
        --REVIRE: EXCEPTION HANDLER
      END select_A1001310;
</code>```

Any ideas?

UPDATE:
If I change my code, to use OracleClient instead of OleDb, it works. Is there a way to include a Cursor Type parameter using oleDb instead of OracleClient? The OracleClient code approach is as follows

```<code>public static DataTable SearchClient()
{
    string connection = ConfigurationManager.ConnectionStrings["DBConnection_Oracle"].ToString();
    string procedure = packetName + ".p_search_client";

    OracleParameter[] parameters = new OracleParameter[1];
    parameters[0] = new OracleParameter("io_cursor", OracleType.Cursor, 4000, ParameterDirection.Output, true, 0, 0, "", DataRowVersion.Current, String.Empty);

    DataTable dt = new DataTable();
    dt = DataManager_Oracle.GetDataTable_(connection, procedure, parameters);
    return dt;
}
</code>```

答:
If your stored procedure returns a rowset then, PLSQLRSet must be set to TRUE in your web.config</p>

```<code><connectionStrings>
        <add name="DBConnection" connectionString="Provider=MSDAORA.1;Data Source=DB;User Id=user;Password=pass;enlist=false;PLSQLRSet=true;OLE DB Services = -4" providerName="Oracle.DataAccess"/>
</connectionStrings>
</code>```

Body:
I'm calling a procedure which has an OUT parameter (of CURSOR Type). It seems I'm missing something because I get error: "wrong number or types of arguments...". My code is as follows:

 public static DataTable SearchClient()
    {
        try
        {
            using (OleDbCommand cmd = new OleDbCommand(packetName + ".select_A1001310"))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add("io_cursor", OracleType.Cursor).Direction = ParameterDirection.Output;

                SqlManager sqlManager = new SqlManager();
                return sqlManager.GetDataTable(cmd);
            }
        }
        catch (Exception ex)
        {
            ex.ToString();
            System.Console.WriteLine(ex);
            //TODO; Handle exception
        }
        return null;
    }

PROCEDURE:

TYPE lcursor_data IS REF CURSOR;
PROCEDURE select_A1001310(io_cursor OUT lcursor_data)
      AS
      BEGIN
        OPEN io_cursor FOR
        --
          SELECT client_id
            FROM a1001310
           WHERE status = 'A';
        --
      EXCEPTION
        WHEN OTHERS THEN
          IF io_cursor%ISOPEN THEN
            CLOSE io_cursor;
          END IF;
        --REVIRE: EXCEPTION HANDLER
      END select_A1001310;

Any ideas?

UPDATE:
If I change my code, to use OracleClient instead of OleDb, it works. Is there a way to include a Cursor Type parameter using oleDb instead of OracleClient? The OracleClient code approach is as follows

public static DataTable SearchClient()
{
    string connection = ConfigurationManager.ConnectionStrings["DBConnection_Oracle"].ToString();
    string procedure = packetName + ".p_search_client";

    OracleParameter[] parameters = new OracleParameter[1];
    parameters[0] = new OracleParameter("io_cursor", OracleType.Cursor, 4000, ParameterDirection.Output, true, 0, 0, "", DataRowVersion.Current, String.Empty);

    DataTable dt = new DataTable();
    dt = DataManager_Oracle.GetDataTable_(connection, procedure, parameters);
    return dt;
}

Body:
If your stored procedure returns a rowset then, PLSQLRSet must be set to TRUE in your web.config

<connectionStrings>
        <add name="DBConnection" connectionString="Provider=MSDAORA.1;Data Source=DB;User Id=user;Password=pass;enlist=false;PLSQLRSet=true;OLE DB Services = -4" providerName="Oracle.DataAccess"/>
</connectionStrings>


问:
IntentService Error: No default Constructor
I am a newbie to Android, and I am trying to use the IntentService but I get an error that it has no default constructor.
I tried restarting the Android Studio it doesn't work.

package com.example.hitesh.kuchbhi;

import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.TaskStackBuilder;
import android.support.v7.app.NotificationCompat;

import java.util.TreeSet;

public class DisplayNotification extends IntentService {
    public DisplayNotification(String name) {
        super("DisplayNotification");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        // my code which even after deleting gives the same error
    }
```
<p>log cat error</p>
```E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.hitesh.kuchbhi, PID: 28899
                  java.lang.RuntimeException: Unable to instantiate service com.example.hitesh.kuchbhi.DisplayNotification: java.lang.InstantiationException: class com.example.hitesh.kuchbhi.DisplayNotification has no zero argument constructor
                      at android.app.ActivityThread.handleCreateService(ActivityThread.java:2728)
                      at android.app.ActivityThread.access$1800(ActivityThread.java:144)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1368)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:135)
                      at android.app.ActivityThread.main(ActivityThread.java:5233)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at java.lang.reflect.Method.invoke(Method.java:372)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:898)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)

```

AndroidManifest file Screenshot

答:
See android developer guide for creating background services https://developer.android.com/training/run-background-service/create-service.html

From what I gather all you need to do is to create the intent service by creating a class that extends IntentService and within it, define a method that overrides onHandleIntent().

You need to remove the constructor you have defined for your DisplayNotification class or add a default constructor like so:

```<code>public DisplayNotification() {
    super("DisplayNotification");
}
</code>```

Body:
I am a newbie to Android, and I am trying to use the IntentService but I get an error that it has no default constructor.
I tried restarting the Android Studio it doesn't work.

package com.example.hitesh.kuchbhi;

import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.TaskStackBuilder;
import android.support.v7.app.NotificationCompat;

import java.util.TreeSet;

public class DisplayNotification extends IntentService {
    public DisplayNotification(String name) {
        super("DisplayNotification");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        // my code which even after deleting gives the same error
    }

log cat error

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.hitesh.kuchbhi, PID: 28899
                  java.lang.RuntimeException: Unable to instantiate service com.example.hitesh.kuchbhi.DisplayNotification: java.lang.InstantiationException: class com.example.hitesh.kuchbhi.DisplayNotification has no zero argument constructor
                      at android.app.ActivityThread.handleCreateService(ActivityThread.java:2728)
                      at android.app.ActivityThread.access$1800(ActivityThread.java:144)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1368)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:135)
                      at android.app.ActivityThread.main(ActivityThread.java:5233)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at java.lang.reflect.Method.invoke(Method.java:372)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:898)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)

AndroidManifest file Screenshot

Body:
See android developer guide for creating background services https://developer.android.com/training/run-background-service/create-service.html

From what I gather all you need to do is to create the intent service by creating a class that extends IntentService and within it, define a method that overrides onHandleIntent().

You need to remove the constructor you have defined for your DisplayNotification class or add a default constructor like so:

public DisplayNotification() {
    super("DisplayNotification");
}


问:
HTML5 Validation Pattern for example: 13-124132424
I'm looking to validate that the user entered either 13- or 14- followed by a long sequence of numbers on a form field.

This one doesn't work: (?:13|14)-[0-9]
This one worked with just 13- or 14- but without numbers after: (?:13|14)-

Example of what valid data should look like: 13-9327493743409

Thanks for your help!

答:
You just need to add a quantifier at the end:

```<code>pattern="(?:13|14)-[0-9]+"
</code>```

The [0-9]+ pattern matches one or more digits. The HTML5 pattern regex is anchored by default, ^ and $ are not necessary. If there can be 0+ digits after 13- or 14-, replace + with * (that matches zero or more occurrences of the quantified pattern).

input:valid {
  color: green;
}
input:invalid {
  color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form name="form1">
 <input pattern="(?:13|14)-[0-9]+" title=""/>
 <input type="Submit"/>
</form></code>```

Body:
You just need to add a quantifier at the end:

pattern="(?:13|14)-[0-9]+"

The [0-9]+ pattern matches one or more digits. The HTML5 pattern regex is anchored by default, ^ and $ are not necessary. If there can be 0+ digits after 13- or 14-, replace + with * (that matches zero or more occurrences of the quantified pattern).

input:valid {
  color: green;
}
input:invalid {
  color: red;
}

<form name="form1">
 <input pattern="(?:13|14)-[0-9]+" title=""/>
 <input type="Submit"/>
</form>


问:
Create a new dictionary with each iteration of loop
I am trying to extract positions and SNPs from a VCF file.  I have written the following so far. But how can I change the name of the dictionary so that I end up with one dictionary for each input file?

i.e.: python vcf_compare.py file1.vcf file2.vcf file3.vcf

```<code>import sys

import vcf

for variants in sys.argv[1:]:
    file1 = {}
    vcf_reader = vcf.Reader(open(variants))
    for record in vcf_reader:
        pos = record.POS
        alt = record.ALT
        ref= record.REF
        snps[pos]=ref,alt
</code>```

so for argv[1] a dictionary called file1 is created.  How can I make the dictionary change name to e.g. file two for the second iteration of the loop?

答:
Short answer: you can't. This is an incredibly frustrating fact to many early programmers. The fix: another dictionary! outside of your variants for loop, create another dictionary and use the filename as a key. Example (you can't just copy paste this, because I don't know how to use the vcf library):

```<code>import sys

import vcf

all_files = {}
for variants in sys.argv[1:]:
    #didn't see file1 used, and didn't see snps created
    #so figured file1 was snps...
    snps = {}
    vcf_reader = vcf.Reader(open(variants))
    for record in vcf_reader:
        pos = record.POS
        alt = record.ALT
        ref= record.REF
        snps[pos]=ref,alt
    all_files[variants] = snps
</code>```

I'm assuming here that variants is a filename in the form of a string. If not, replace the variants in all_files[variants] with the string you want to use as its key.

Body:
I am trying to extract positions and SNPs from a VCF file.  I have written the following so far. But how can I change the name of the dictionary so that I end up with one dictionary for each input file?

i.e.: python vcf_compare.py file1.vcf file2.vcf file3.vcf

import sys

import vcf

for variants in sys.argv[1:]:
    file1 = {}
    vcf_reader = vcf.Reader(open(variants))
    for record in vcf_reader:
        pos = record.POS
        alt = record.ALT
        ref= record.REF
        snps[pos]=ref,alt

so for argv[1] a dictionary called file1 is created.  How can I make the dictionary change name to e.g. file two for the second iteration of the loop?

Body:
Short answer: you can't. This is an incredibly frustrating fact to many early programmers. The fix: another dictionary! outside of your variants for loop, create another dictionary and use the filename as a key. Example (you can't just copy paste this, because I don't know how to use the vcf library):

import sys

import vcf

all_files = {}
for variants in sys.argv[1:]:
    #didn't see file1 used, and didn't see snps created
    #so figured file1 was snps...
    snps = {}
    vcf_reader = vcf.Reader(open(variants))
    for record in vcf_reader:
        pos = record.POS
        alt = record.ALT
        ref= record.REF
        snps[pos]=ref,alt
    all_files[variants] = snps

I'm assuming here that variants is a filename in the form of a string. If not, replace the variants in all_files[variants] with the string you want to use as its key.


问:
compute sum of columns in a nested list in R
How do we do column sums on elements of nested lists. I have a nested list of 10  each containing a sublist of 50 elements which are matrices with 4 columns with differing number of rows. Here is a simpler example. I need to add the columns across the lists. I need a vector of colsums.ll<-c(26, 66, 106, 146). I tried to do do.call("rbind",ll) to collapse the list into 1 dataframe and then apply colSums but was not successful. </p>

```<code>    l1<-matrix(c(1:8),nrow=2)
    l2<-matrix(c(1:16),nrow=4)
    l<-list(l1,l2)
    ll<-list(l,l)
     ll
    [[1]]
   [[1]][[1]]
        [,1] [,2] [,3] [,4]
  [1,]    1    3    5    7
  [2,]    2    4    6    8

   [[1]][[2]]
         [,1] [,2] [,3] [,4]
    [1,]    1    5    9   13
    [2,]    2    6   10   14
    [3,]    3    7   11   15
    [4,]    4    8   12   16

    [[2]]
    [[2]][[1]]
         [,1] [,2] [,3] [,4]
    [1,]    1    3    5    7
    [2,]    2    4    6    8

    [[2]][[2]]
        [,1] [,2] [,3] [,4]
    [1,]    1    5    9   13
    [2,]    2    6   10   14
    [3,]    3    7   11   15
    [4,]    4    8   12   16
</code>```

答:
Here's a purrr option:

```<code>library(purrr)

ll %>% flatten() %>%    # reduce depth to one level
    map(colSums) %>%    # get column sums of each element
    reduce(`+`)         # add respective colSums
#> [1]  26  66 106 146
</code>```

or reduce it to a single matrix first:

```<code>ll %>% flatten() %>% reduce(rbind) %>% colSums()
</code>```

or use invoke instead of reduce, which saves calls at the cost of slightly-less-beautiful syntax:

```<code>ll %>% flatten() %>% invoke(rbind, .) %>% colSums()
</code>```

All return the same thing.

Body:
How do we do column sums on elements of nested lists. I have a nested list of 10  each containing a sublist of 50 elements which are matrices with 4 columns with differing number of rows. Here is a simpler example. I need to add the columns across the lists. I need a vector of colsums.ll<-c(26, 66, 106, 146). I tried to do do.call("rbind",ll) to collapse the list into 1 dataframe and then apply colSums but was not successful.

    l1<-matrix(c(1:8),nrow=2)
    l2<-matrix(c(1:16),nrow=4)
    l<-list(l1,l2)
    ll<-list(l,l)
     ll
    [[1]]
   [[1]][[1]]
        [,1] [,2] [,3] [,4]
  [1,]    1    3    5    7
  [2,]    2    4    6    8

   [[1]][[2]]
         [,1] [,2] [,3] [,4]
    [1,]    1    5    9   13
    [2,]    2    6   10   14
    [3,]    3    7   11   15
    [4,]    4    8   12   16

    [[2]]
    [[2]][[1]]
         [,1] [,2] [,3] [,4]
    [1,]    1    3    5    7
    [2,]    2    4    6    8

    [[2]][[2]]
        [,1] [,2] [,3] [,4]
    [1,]    1    5    9   13
    [2,]    2    6   10   14
    [3,]    3    7   11   15
    [4,]    4    8   12   16

Body:
Here's a purrr option:

library(purrr)

ll %>% flatten() %>%    # reduce depth to one level
    map(colSums) %>%    # get column sums of each element
    reduce(`+`)         # add respective colSums
#> [1]  26  66 106 146

or reduce it to a single matrix first:

ll %>% flatten() %>% reduce(rbind) %>% colSums()

or use invoke instead of reduce, which saves calls at the cost of slightly-less-beautiful syntax:

ll %>% flatten() %>% invoke(rbind, .) %>% colSums()

All return the same thing.


问:
Capturing event of Windows LAN proxy settings change?
Is there a way to capture event for a LAN Proxy settings change in C# program/service? I would like to capture event when the user enables or disables the LAN proxy server or changes the address or the port of the proxy server.

I already tested with NetworkAddressChangedEventHandler but it doesn't seem to capture this event.

答: It is possible to listen events from Windows Registry (including change of Registry value) but apparently the Registry value of Software\Microsoft\Windows\CurrentVersion\Internet Settings is not being changed when the user changes the LAN proxy settings.</p>


问:
Do i have to use namespace to match xml documents?
Having a bit of trouble trying to get an xsd to match two documents:

XML Document 1:

```<code><?xml version="1.0" encoding="UTF-8"?>
<video contenttype="asf" fileextension=".wmv" hascontent="no" lang="en-GB" length="1800" pid="3678738364972" sid="">
    <lastmodified timestamp="1282678200000">
        Tue, 24 Aug 2010 19:30:00 +0000
    </lastmodified>
    <links/>
    <keywords/>
    <slides/>
    <copyright>
        Copyright owned by original broadcaster
    </copyright>
    <title>
        Friends
    </title>
    <comment>
        The One Where the Monkey Gets Away: Rachel accidentally lets Ross's pet monkey escape, then learns that her former best friend is engaged to marry her ex-fiancé.  [AD,S]
    </comment>
    <author>
        E4
    </author>
    <email/>
    <captioning/>
    <extendeddata>
        <data name="keepOriginal">
            0
        </data>
        <data name="keepTranscoded">
            0
        </data>
        <data name="realStartTime">
            1282677909
        </data>
        <data name="scheduledStartTime">
            1282678200
        </data>
        <data name="broadcastLength">
            1800
        </data>
        <data name="broadcastChannel">
            E4
        </data>
        <data name="paddingUsed">
            300000
        </data>
        <data name="transcodingSpec">
            -b 2.35M -a 128k --debug  --primary-format mp4 --podcast "-l 270 -b 600 -R 48 -B 64" --keep-files true
        </data>
        <data name="transcoding">
            succeeded
        </data>
        <data name="transcodingProfile">
            -b 2.35M -a 128k --debug  --primary-format mp4 --podcast "-l 270 -b 600 -R 48 -B 64" --keep-files true
        </data>
        <data name="transcoderDetails">
            ver 1.58.2.1, 2010-08-24  21:31:33 up 5 days, 11:24,  0 users,  load average: 3.08, 3.38, 2.67, OS20031 212.70.69.26
        </data>
        <data name="originalFilename">
            /var/lib/etvd/mpegts/E4/Friends (24-Aug-2010 20.30).emcast
        </data>
        <data name="originalRecordingTime">
            created 2010-08-24 , last modified 2010-08-24 : recording lasted 0s
        </data>
        <data name="primaryFormat">
            mp4
        </data>
        <data name="doXml">
            True
        </data>
        <data name="doFiles">
            True
        </data>
    </extendeddata>
    <categories>
        <category name="em:podcast">
            mp4
        </category>
    </categories>
</video>
</code>```

XML Document 2:

```<code><?xml version="1.0" encoding="UTF-8"?>
<video xmlns="UploadXSD">
  <title>
    A vid with Pete
  </title>
  <description>
  Petes vid
  </description>
  <contributor>
    Pete
  </contributor>
  <subject>
    Cat 2
  </subject>
</video>
</code>```

Proposed XSD:

```<code><?xml version="1.0" encoding="utf-8"?>
<xs:schema id="UploadXSD"
    targetNamespace="UploadXSD"
    elementFormDefault="qualified"
    xmlns="http://tempuri.org/UploadXSD.xsd"
    xmlns:mstns="http://tempuri.org/UploadXSD.xsd"
    xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:element name="video">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="title" minOccurs="1" type="xs:string"></xs:element>
        <xs:element name="description" type="xs:string"></xs:element>
        <xs:element name="contributor" type="xs:string"></xs:element>
        <xs:element name="subject" type="xs:string"></xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>

</xs:schema>
</code>```

Is it possible to use c# to validate against both of the xml documents and NOT use a namespace? Because with the XML Document 1 (above) it is created by a third party system and it cannot generate the namespace...

Asked a few questions about xml in the last few days appreciate help am very new to this...

答:
I believe you do need to match namespace. I once faced a similar issue, where the XML document was out of my control (Adobe Smart Forms), and I wanted to validate it against my XSD.

To do this I cleaned the XML document before I validated, adjusting the namespace, and in my case removing alot of garbage that Adobe added. Sorry I don't have any code with me on how I did it.

ContentLicense: CC BY-SA 2.5

Body:
Having a bit of trouble trying to get an xsd to match two documents:

XML Document 1:

<?xml version="1.0" encoding="UTF-8"?>
<video contenttype="asf" fileextension=".wmv" hascontent="no" lang="en-GB" length="1800" pid="3678738364972" sid="">
    <lastmodified timestamp="1282678200000">
        Tue, 24 Aug 2010 19:30:00 +0000
    </lastmodified>
    <links/>
    <keywords/>
    <slides/>
    <copyright>
        Copyright owned by original broadcaster
    </copyright>
    <title>
        Friends
    </title>
    <comment>
        The One Where the Monkey Gets Away: Rachel accidentally lets Ross's pet monkey escape, then learns that her former best friend is engaged to marry her ex-fiancé.  [AD,S]
    </comment>
    <author>
        E4
    </author>
    <email/>
    <captioning/>
    <extendeddata>
        <data name="keepOriginal">
            0
        </data>
        <data name="keepTranscoded">
            0
        </data>
        <data name="realStartTime">
            1282677909
        </data>
        <data name="scheduledStartTime">
            1282678200
        </data>
        <data name="broadcastLength">
            1800
        </data>
        <data name="broadcastChannel">
            E4
        </data>
        <data name="paddingUsed">
            300000
        </data>
        <data name="transcodingSpec">
            -b 2.35M -a 128k --debug  --primary-format mp4 --podcast "-l 270 -b 600 -R 48 -B 64" --keep-files true
        </data>
        <data name="transcoding">
            succeeded
        </data>
        <data name="transcodingProfile">
            -b 2.35M -a 128k --debug  --primary-format mp4 --podcast "-l 270 -b 600 -R 48 -B 64" --keep-files true
        </data>
        <data name="transcoderDetails">
            ver 1.58.2.1, 2010-08-24  21:31:33 up 5 days, 11:24,  0 users,  load average: 3.08, 3.38, 2.67, OS20031 212.70.69.26
        </data>
        <data name="originalFilename">
            /var/lib/etvd/mpegts/E4/Friends (24-Aug-2010 20.30).emcast
        </data>
        <data name="originalRecordingTime">
            created 2010-08-24 , last modified 2010-08-24 : recording lasted 0s
        </data>
        <data name="primaryFormat">
            mp4
        </data>
        <data name="doXml">
            True
        </data>
        <data name="doFiles">
            True
        </data>
    </extendeddata>
    <categories>
        <category name="em:podcast">
            mp4
        </category>
    </categories>
</video>

XML Document 2:

<?xml version="1.0" encoding="UTF-8"?>
<video xmlns="UploadXSD">
  <title>
    A vid with Pete
  </title>
  <description>
  Petes vid
  </description>
  <contributor>
    Pete
  </contributor>
  <subject>
    Cat 2
  </subject>
</video>

Proposed XSD:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="UploadXSD"
    targetNamespace="UploadXSD"
    elementFormDefault="qualified"
    xmlns="http://tempuri.org/UploadXSD.xsd"
    xmlns:mstns="http://tempuri.org/UploadXSD.xsd"
    xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:element name="video">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="title" minOccurs="1" type="xs:string"></xs:element>
        <xs:element name="description" type="xs:string"></xs:element>
        <xs:element name="contributor" type="xs:string"></xs:element>
        <xs:element name="subject" type="xs:string"></xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>

</xs:schema>

Is it possible to use c# to validate against both of the xml documents and NOT use a namespace? Because with the XML Document 1 (above) it is created by a third party system and it cannot generate the namespace...

Asked a few questions about xml in the last few days appreciate help am very new to this...


问:
Laravel 5.2 split an application in two parts in order to have authentication and the rest separated
I have an application written in Laravel 5.2, I need to split this app in two parts, app A is responsible of the authentication and app B is responsible for the rest of the app.

Can someone guide me to make it working preserving data for policies?

答:
This is a late answer, I solved my problem with a SSO server implementation for the users and use this to log in the main Laravel app.

This can be possible using the Passport and Socialite official packages.


问:
Add string elements to Dynamic Array
Parsing a file and need to add students to a struct vector using an array for student names specific to that course line.

In my course.h file:

```<code>struct Course {
    std::string name;
    int enrollment;
    int maxEnrollment;

    std::string* students; ///< array of student names

    Course(std::string courseName, int maxEnrollmentPermitted);

    bool enroll(std::string studentName);

    void print(std::ostream& output);
};
</code>```

In my course.cpp file:

```<code>bool Course::enroll(std::string studentName) {
    this->students = new std::string[studentName];
    if (this->enrollment < this->maxEnrollment) {
        this->enrollment++;
        return true;
    }
    else {
        return false;
</code>```

In my source file:

```<code>void processEnrollmentRequests(istream& enrollmentRequestsFile, vector<Course>& courses) {
    // Read the requests, one at a time, serving each one
    string courseName;
    enrollmentRequestsFile >> courseName;

    while (enrollmentRequestsFile) {
        enrollmentRequestsFile >> ws;
        string studentName;
        getline(enrollmentRequestsFile, studentName);

        int pos = search(courses, courseName);
        if (pos >= 0) {
            // Found a matching course
            bool enrolled = courses[pos].enroll(studentName);
            if (enrolled) {
                cout << studentName << " has enrolled in " << courseName << endl;
            }
            else {
                // course is full
                cout << studentName << " cannot enroll in " << courseName << endl;
            }
        }
        else {
            // course does not exist
            cout << studentName << " cannot enroll in " << courseName << endl;
        }
        enrollmentRequestsFile >> courseName;
    }
}
        }
    }
</code>```

I cant seem to add the gathered studentName to the array using this->students = new std::string[studentName]. Getting an error that says must have integral or enumeration type.

答:
new SomeThing[size] is used to declare array. It makes no sense to use a string as the size.

Assuming the size of students is limited to maxEnrollment, you can use this:

```<code>if (this->enrollment < this->maxEnrollment) {
    this->students[this->enrollment++] = studentName;
    return true;
}
else {
    return false;
</code>```

Title: Add string elements to Dynamic Array

Body:
Parsing a file and need to add students to a struct vector using an array for student names specific to that course line.

In my course.h file:

struct Course {
    std::string name;
    int enrollment;
    int maxEnrollment;

    std::string* students; ///< array of student names

    Course(std::string courseName, int maxEnrollmentPermitted);

    bool enroll(std::string studentName);

    void print(std::ostream& output);
};

In my course.cpp file:

bool Course::enroll(std::string studentName) {
    this->students = new std::string[studentName];
    if (this->enrollment < this->maxEnrollment) {
        this->enrollment++;
        return true;
    }
    else {
        return false;

In my source file:

void processEnrollmentRequests(istream& enrollmentRequestsFile, vector<Course>& courses) {
    // Read the requests, one at a time, serving each one
    string courseName;
    enrollmentRequestsFile >> courseName;

    while (enrollmentRequestsFile) {
        enrollmentRequestsFile >> ws;
        string studentName;
        getline(enrollmentRequestsFile, studentName);

        int pos = search(courses, courseName);
        if (pos >= 0) {
            // Found a matching course
            bool enrolled = courses[pos].enroll(studentName);
            if (enrolled) {
                cout << studentName << " has enrolled in " << courseName << endl;
            }
            else {
                // course is full
                cout << studentName << " cannot enroll in " << courseName << endl;
            }
        }
        else {
            // course does not exist
            cout << studentName << " cannot enroll in " << courseName << endl;
        }
        enrollmentRequestsFile >> courseName;
    }
}
        }
    }

I cant seem to add the gathered studentName to the array using this->students = new std::string[studentName]. Getting an error that says must have integral or enumeration type.

Body:
new SomeThing[size] is used to declare array. It makes no sense to use a string as the size.

Assuming the size of students is limited to maxEnrollment, you can use this:

if (this->enrollment < this->maxEnrollment) {
    this->students[this->enrollment++] = studentName;
    return true;
}
else {
    return false;


问:
MYSQL delete all records except first and last for a given date
This gives me all the records for a particular switch and port. I would like to delete all except the first and last one for each day.</p>

```<code>/mysql -sN --user=root --password=notmypassword -e
"SELECT * FROM collector.fibre
WHERE fabric_switch_name = 'switch-1'
  AND port = '0'
  AND datatype = 'TxElements'
  AND (time > '2016-05-31 00:00:00' AND time < '2016-05-31 23:59:59') "
</code>```

Body:
This gives me all the records for a particular switch and port. I would like to delete all except the first and last one for each day.

/mysql -sN --user=root --password=notmypassword -e
"SELECT * FROM collector.fibre
WHERE fabric_switch_name = 'switch-1'
  AND port = '0'
  AND datatype = 'TxElements'
  AND (time > '2016-05-31 00:00:00' AND time < '2016-05-31 23:59:59') "

Body:
this query will extract all the record that should be deleted :

SELECT
  *
FROM
  collector.fibre  f
  INNER JOIN (
    -- create a special table   day   min_time  max_time
    select
      date(time) as 'day',
      min(time) as 'min_time',
      max(time) as 'max_time'
    from
      collector.fibre
     Where fabric_switch_name = 'switch-1'
    group by date(time)
  )  fd on date(f.time) = fd.day  -- join the two table to have a special table see example down
WHERE
  fabric_switch_name = 'switch-1'
  AND port = '0'
  AND datatype = 'TxElements'
  -- extract record witch the time is not
  -- the min or the max of that date
  AND (f.time <> fd.min_time and f.time <> fd.max_time)

let suppose this is your date

    1           2016-05-31 23:00:00
    2           2016-05-31 01:00:00
    3           2016-05-31 00:00:00
    4           2016-05-30 10:00:12
    5           2016-05-30 01:00:00
    6           2016-05-30 00:05:00

the result of join :

    1           2016-05-31 23:00:00         2016-05-31   2016-05-31 00:00:00  2016-05-31 23:00:00  -- this will not be selected in the result
    2           2016-05-31 01:00:00         2016-05-31   2016-05-31 00:00:00  2016-05-31 23:00:00  -- this will be selected because it's not min or max of that day
    3           2016-05-31 00:00:00         2016-05-31   2016-05-31 00:00:00  2016-05-31 23:00:00
    4           2016-05-30 10:00:00         2016-05-30   2016-05-30 00:05:00  2016-05-30 10:00:12
    5           2016-05-30 01:00:00         2016-05-30   2016-05-30 00:05:00  2016-05-30 10:00:12
    6           2016-05-30 00:00:00         2016-05-30   2016-05-30 00:05:00  2016-05-30 10:00:12


问:
Scraping JavaScript with Nokogiri
I have just begun using Nokogiri and have been able to successfully scape HTML pages. I am now attempting to scrape a certain page that is driven using a lot of JavaScript.

As an example to get me on my way - how could I scrape the decimal values from inside one of the blue boxes on this page?

答:
You can't scrape dynamic values using Nokogiri, as they aren't contained in the HTML itself, but added to the DOM later. Nokogiri can only parse the HTML data, it does not build a DOM or run the page.

In order to get values from the DOM, you would need to be able to build a DOM and process it according to standards. That would require actually simulating a web browser.

A simpler way to do this is to try to find out what API endpoints the page uses to retrieve the values it then displays and making requests to those endpoints yourself. However, this requires some knowledge of how the page works, and isn't easy to fully automate.

Long story short: You're gonna need a lot more than just Nokogiri to do this.

Title: Scraping JavaScript with Nokogiri


问:
Remove duplicates as well as original row
Removing duplicates is no problem, i am hitting an issue where i want to remove not only the duplicate but the original row that incurred the duplicate in a SELECT statement.

```<code>ItemNUMBER  ID    from_DATE   to_DATE   fancy_code
1           100   3/28/2015   4/10/2015    Z5111
2           100   4/18/2015   4/21/2015    Z5112
3           100   5/2/2015    5/5/2015     Z5111
4           100   5/31/2015   6/2/2015     Z5111
5           100   7/31/2015   8/16/2015    A400       --remove
6           100   7/31/2015   8/16/2015    A400       --remove
</code>```

Above is my table, and --remove is what the end goal is.  Any help would be much appreciated!

答:
If you reach to the repeated ItemNUMBER in the table, you can delete all of them by a simple WHERE clause.

In order to do that, you need to use an inner JOIN of the table itself, then by GROUP-ing BY the repeatable columns you'll reach to the the aim.

So the query can be similar to the following:

```<code>DELETE  theTable
WHERE   ItemNUMBER IN
(
    SELECT  t1.ItemNUMBER
    FROM    theTable t1
    JOIN    theTable t2 ON t1.ID = t2.ID AND t1.from_DATE = t2.from_DATE AND t1.to_DATE = t2.to_DATE AND t1.fancy_code = t2.fancy_code
    GROUP   BY t1.ItemNUMBER
    HAVING  COUNT(t1.ItemNUMBER) > 1
)
</code>```

Body:
Removing duplicates is no problem, i am hitting an issue where i want to remove not only the duplicate but the original row that incurred the duplicate in a SELECT statement.

ItemNUMBER  ID    from_DATE   to_DATE   fancy_code
1           100   3/28/2015   4/10/2015    Z5111
2           100   4/18/2015   4/21/2015    Z5112
3           100   5/2/2015    5/5/2015     Z5111
4           100   5/31/2015   6/2/2015     Z5111
5           100   7/31/2015   8/16/2015    A400       --remove
6           100   7/31/2015   8/16/2015    A400       --remove

Above is my table, and --remove is what the end goal is.  Any help would be much appreciated!

Body:
If you reach to the repeated ItemNUMBER in the table, you can delete all of them by a simple WHERE clause.

In order to do that, you need to use an inner JOIN of the table itself, then by GROUP-ing BY the repeatable columns you'll reach to the the aim.

So the query can be similar to the following:

DELETE  theTable
WHERE   ItemNUMBER IN
(
    SELECT  t1.ItemNUMBER
    FROM    theTable t1
    JOIN    theTable t2 ON t1.ID = t2.ID AND t1.from_DATE = t2.from_DATE AND t1.to_DATE = t2.to_DATE AND t1.fancy_code = t2.fancy_code
    GROUP   BY t1.ItemNUMBER
    HAVING  COUNT(t1.ItemNUMBER) > 1
)


问:
How can I hide the start of an element instead of the end when it get's overlapped?
I am trying to get a div element to hide the beginning of it's text opposed to the end. If this does not make sense, please see the fiddle -
 http://jsfiddle.net/L7zd8uyb/1/

As you reduce the width of the screen, 'paragraph' will hide behind the right-most div. Is it possible to reach this div and then start to hide 'some' behind the left-most div?

HTML:

```<code><div id="leftside">Left</div>
<div id="rightside">Right</div>

<div>
    <span>Some paragraph.</span>
</div>
</code>```

CSS:

```<code>#leftside {
  position: absolute;
  left: 0;
  width: 200px;
  background-color: red;
}

#rightside{
  position: absolute;
  right: 0;
  width: 150px;
  background-color: red;
}
span {
  margin-left: 200px;
}
</code>```

Note: The JSFiddle was simplified from the example provided in this question - How can I prevent HTML elements from overlapping or sliding under one another?

答:
Add these styles:

```<code>span {
  position: absolute;
  right: 150px;                  /* width of Right element */
  white-space: nowrap;           /* prevent wrapping */
  min-width: calc(100% - 350px); /* difference of Left and Right widths */
}

#leftside {
  z-index: 1;                   /* cover the middle element if needed */
}
</code>```

Fiddle

Body:
I am trying to get a div element to hide the beginning of it's text opposed to the end. If this does not make sense, please see the fiddle -
 http://jsfiddle.net/L7zd8uyb/1/

As you reduce the width of the screen, 'paragraph' will hide behind the right-most div. Is it possible to reach this div and then start to hide 'some' behind the left-most div?

HTML:

Left

Right

    Some paragraph.

CSS:

#leftside {
  position: absolute;
  left: 0;
  width: 200px;
  background-color: red;
}

#rightside{
  position: absolute;
  right: 0;
  width: 150px;
  background-color: red;
}
span {
  margin-left: 200px;
}

Note: The JSFiddle was simplified from the example provided in this question - How can I prevent HTML elements from overlapping or sliding under one another?

Body:
Add these styles:

span {
  position: absolute;
  right: 150px;                  /* width of Right element */
  white-space: nowrap;           /* prevent wrapping */
  min-width: calc(100% - 350px); /* difference of Left and Right widths */
}

#leftside {
  z-index: 1;                   /* cover the middle element if needed */
}

Fiddle


问:
How to get information in one HTML class, before another using Python and BeautifulSoup
On this website: https://www.theyworkforyou.com/mp/10001/diane_abbott/hackney_north_and_stoke_newington/votes

I'm trying to pull all of the text within each ul class "vote-description" entry, but only the text that comes prior to the a class tags - I.E, everything before

I have code that will pull everything from inside the entry, shown here:

```<code>import urllib2
from BeautifulSoup import *

response = urllib2.urlopen("https://www.theyworkforyou.com/mp/10001/diane_abbott/hackney_north_and_stoke_newington/votes")
html = response.read()
soup = BeautifulSoup(html)

desc = soup.findAll('ul',{'class':"vote-descriptions"})
for line in desc:
print line.findAll('li')
</code>```

How can I alter this code to exclude everything other than the part before the 'a' tag. For example, the first list entry found is:

```<code><li> Generally voted for equal <b>gay rights</b> <a class="vote-description__source" href="/mp/10001/diane_abbott/hackney_north_and_stoke_newington/divisions?policy=826">Show votes</a> <a class="vote-description__evidence" href="/mp/10001/diane_abbott/hackney_north_and_stoke_newington/divisions?policy=826">11 votes for, 1 vote against, 15 absences, between 1999–2014</a>
</li>
</code>```

But what I want to print is:

```<code>Generally voted for equal <b>gay rights</b>
</code>```

Any help would be much appreciated!

答:
Use contents BeautifulSoup Doc - .contents and .children

```<code>for line in desc:
    li_list = line.findAll('li')
    for li in li_list:
        print "%s%s" % (li.contents[0],li.b)
</code>```

Test

```<code>from bs4 import BeautifulSoup
html ="""<li> Generally voted for equal <b>gay rights</b> <a class="vote-description__source" href="/mp/10001/diane_abbott/hackney_north_and_stoke_newington/divisions?policy=826">Show votes</a> <a class="vote-description__evidence" href="/mp/10001/diane_abbott/hackney_north_and_stoke_newington/divisions?policy=826">11 votes for, 1 vote against, 15 absences, between 1999–2014</a></li>"""
soup = BeautifulSoup(html)
for line in soup.findAll('li'):
    print "%s%s" % (line.contents[0],line.b)
</code>```

Output

```<code>$ python test.py
Generally voted for equal  <b>gay rights</b>
</code>```

Body:
On this website: https://www.theyworkforyou.com/mp/10001/diane_abbott/hackney_north_and_stoke_newington/votes

I'm trying to pull all of the text within each ul class "vote-description" entry, but only the text that comes prior to the a class tags - I.E, everything before

I have code that will pull everything from inside the entry, shown here:

import urllib2
from BeautifulSoup import *

response = urllib2.urlopen("https://www.theyworkforyou.com/mp/10001/diane_abbott/hackney_north_and_stoke_newington/votes")
html = response.read()
soup = BeautifulSoup(html)

desc = soup.findAll('ul',{'class':"vote-descriptions"})
for line in desc:
print line.findAll('li')

How can I alter this code to exclude everything other than the part before the 'a' tag. For example, the first list entry found is:

 Generally voted for equal gay rights Show votes 11 votes for, 1 vote against, 15 absences, between 1999–2014

But what I want to print is:

Generally voted for equal gay rights

Any help would be much appreciated!

Body:
Use contents BeautifulSoup Doc - .contents and .children

for line in desc:
    li_list = line.findAll('li')
    for li in li_list:
        print "%s%s" % (li.contents[0],li.b)

Test

from bs4 import BeautifulSoup
html ="""<li> Generally voted for equal <b>gay rights</b> <a class="vote-description__source" href="/mp/10001/diane_abbott/hackney_north_and_stoke_newington/divisions?policy=826">Show votes</a> <a class="vote-description__evidence" href="/mp/10001/diane_abbott/hackney_north_and_stoke_newington/divisions?policy=826">11 votes for, 1 vote against, 15 absences, between 1999&ndash;2014</a></li>"""
soup = BeautifulSoup(html)
for line in soup.findAll('li'):
    print "%s%s" % (line.contents[0],line.b)

Output

$ python test.py
Generally voted for equal  <b>gay rights</b>


问:
How to create a thumbnail image of html content stored in a database
If you were to convert this html content into a small thumbnail image , how would you do it?

P.S. I'm trying to do this to allow users on my site to browse through their posts(containing html elements (e.g. strong, i, img tag's).

答:
See here:

http://www.thumbalizr.com/index.php

They have a pretty decent simple API

Simple syntax to use the API:
  http://api.thumbalizr.com/?url=http://www.ford.de&width=250

Parameter:

Check http://api.thumbalizr.com for
  more details.

So you can simply have

Also see http://www.websnapr.com/ and their implementations page

Body:
See here:

http://www.thumbalizr.com/index.php

They have a pretty decent simple API

Simple syntax to use the API:
  http://api.thumbalizr.com/?url=http://www.ford.de&width=250

Parameter:

Check http://api.thumbalizr.com for
  more details.

So you can simply have <img src='http://api.thumbalizr.com/?url=http://www.yourdomain.com&width=250' />

Also see http://www.websnapr.com/ and their implementations page


问:
Call lifecycle methods on container component created with connect()
I would like to call componentDidMount() on the container component that is created by this connect()ed component:

```<code>import { View, Text } from 'react-native'
import { connect } from 'react-redux'
import { formStyles } from '../../style'
import { DimenInput } from '../dimenInput/DimenInput'
import { updateDimension } from '../../actions/updateDimension.action'
import React from 'react'
import { updateVolume } from '../../actions/updateDimension.action'
import calcVol from '../../calcVol'

const mapStateToProps = (state) => ({
  height1: state.get('height').get('height1').toString(),
  height2: state.get('height').get('height2').toString()
})

const updateHeight = (text, number) => (dispatch, getState) => {
  dispatch(updateDimension('height', text, number))
  let litres = calcVol(getState())
  dispatch(updateVolume(litres))
}

let Height = (props) => (
  <View style={formStyles.container}>
    <DimenInput
      value={props.height1}
      onChangeText={text => props.updateHeight(text, 1)}
    />
    <Text style={formStyles.text}>{'FT'}</Text>
    <DimenInput
      value={props.height2}
      onChangeText={text => props.updateHeight(text, 2)}
    />
    <Text style={formStyles.text}>{'IN'}</Text>
  </View>
)
Height.propTypes = {
  height1: React.PropTypes.string.isRequired,
  height2: React.PropTypes.string.isRequired,
  updateHeight: React.PropTypes.func.isRequired
}

Height = connect(
  mapStateToProps,
  { updateHeight }
)(Height)

export default Height
</code>```

Is it possible? I try to use connect() because it does some performance optimisations. Or do I just need to create the container component manually to add lifecycle methods?

The main aim of this is that I need to call a method on app startup. Not on component startup. So if there is another way to do that then I'm interested to know about it. There is a good way to do it with react router onEnter() however I do not have a react router as it is a single page app so no routes.

答:
If you want access to lifecycle methods of a React Component, you'll need to use an object extended from React.Component. You can achieve this by creating your component using React.createClass or ES6 class notation instead of using a functional component like you are dong now with your arrow function.

React top level API

```<code>var Height = React.createClass({
  componentDidMount: function(){
    //...
  }
});
</code>```

ES6 approach:

```<code>class Height extends React.Component {
  constructor(props) {
    //...
  }
  componentDidMount(){
     //...
  }
}
</code>```

Body:
I would like to call componentDidMount() on the container component that is created by this connect()ed component:

import { View, Text } from 'react-native'
import { connect } from 'react-redux'
import { formStyles } from '../../style'
import { DimenInput } from '../dimenInput/DimenInput'
import { updateDimension } from '../../actions/updateDimension.action'
import React from 'react'
import { updateVolume } from '../../actions/updateDimension.action'
import calcVol from '../../calcVol'

const mapStateToProps = (state) => ({
  height1: state.get('height').get('height1').toString(),
  height2: state.get('height').get('height2').toString()
})

const updateHeight = (text, number) => (dispatch, getState) => {
  dispatch(updateDimension('height', text, number))
  let litres = calcVol(getState())
  dispatch(updateVolume(litres))
}

let Height = (props) => (
  <View style={formStyles.container}>
    <DimenInput
      value={props.height1}
      onChangeText={text => props.updateHeight(text, 1)}
    />
    <Text style={formStyles.text}>{'FT'}</Text>
    <DimenInput
      value={props.height2}
      onChangeText={text => props.updateHeight(text, 2)}
    />
    <Text style={formStyles.text}>{'IN'}</Text>
  </View>
)
Height.propTypes = {
  height1: React.PropTypes.string.isRequired,
  height2: React.PropTypes.string.isRequired,
  updateHeight: React.PropTypes.func.isRequired
}

Height = connect(
  mapStateToProps,
  { updateHeight }
)(Height)

export default Height

Is it possible? I try to use connect() because it does some performance optimisations. Or do I just need to create the container component manually to add lifecycle methods?

The main aim of this is that I need to call a method on app startup. Not on component startup. So if there is another way to do that then I'm interested to know about it. There is a good way to do it with react router onEnter() however I do not have a react router as it is a single page app so no routes.

Body:
If you want access to lifecycle methods of a React Component, you'll need to use an object extended from React.Component. You can achieve this by creating your component using React.createClass or ES6 class notation instead of using a functional component like you are dong now with your arrow function.

React top level API

var Height = React.createClass({
  componentDidMount: function(){
    //...
  }
});

ES6 approach:

class Height extends React.Component {
  constructor(props) {
    //...
  }
  componentDidMount(){
     //...
  }
}


问:
Lazy paramater evaluation for a debug macro wrapped in a function
I am currently developing a small and simple logging library that acts as a Facade for the Boost.Log v2 C++ library.

My library is almost finished and I have successfully encapsulated Boost.Log, i.e.:

the API of my library is free of Boost.Log types, i.e. users do only have to deal with my types

the ABI of my library is free of Boost.Log types, i.e. dependencies do not have to link against Boost.Log.

There is one last thing I am not able to solve at the moment: Lazy parameter evaluation

I'll give a short usage example how Boost.Log behaves:

```<code>#include <chrono>
#include <thread>

#include <boost/log/core.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/trivial.hpp>

std::string time_costly_function(
    const std::chrono::seconds seconds = std::chrono::seconds{1}) {
  std::this_thread::sleep_for(seconds);
  return "DONE with time_costly_function";
}

int main() {
  boost::log::core::get()->set_filter(boost::log::trivial::severity >=
                                      boost::log::trivial::warning);
  BOOST_LOG_TRIVIAL(warning) << "This is evaluated: " << time_costly_function();
  BOOST_LOG_TRIVIAL(info) << "This is NOT evaluated: "
                          << time_costly_function();
}
</code>```

If you run the example above you can see that only the arguments for the first BOOST_LOG_TRIVIAL call are evaluated, i.e. time_costly_function() is only called once in total.

That is exactly the behavior that I want in my library, but as I mentioned I do not want that users have to deal with Boost.Log directly, but with my small Facade.

The following code illustrates the problem (very simplified to tackle down the actual problem):

```<code>#include <boost/log/core.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/trivial.hpp>

#include <chrono>
#include <thread>

std::string time_costly_function(
    const std::chrono::seconds seconds = std::chrono::seconds{1}) {
  std::this_thread::sleep_for(seconds);

  return "DONE with time_costly_function";
}

// Encapsulates Boost.Log. The API of my logging library does not know anything
// about Boost.Log (e.g. the Pimpl idiom is used).
//
// In reality this is a member function of a class in my library with the
// following signature:
//
// void log(const SeverityLevel level, const std::string& message) override;
//
void log(const std::string& message) { BOOST_LOG_TRIVIAL(warning) << message; }

// A custom logging macro.
//
// In reality this is a macro taking the object of a class with the member
// function illustrated above:
//
// FW_LOG(logger, level, message)
//
#define FW_LOG(message) log(message)

int main() {
  // TODO(wolters): This does not work, since everything is evaluated outside of
  // the Boost.Log macro(s). I want to call my macro as follows.
  //     FW_LOG(logger, level) << message << time_costly_function();
  // I.e. it should work like the Boost.Log macro(s) illustrated above.
  FW_LOG("foo" + time_costly_function());
}
</code>```

I identified the following problems in my code:

The function log may not take a std::string reference, since that will
always lead to an evaluation outside of that function.

The macro FW_LOG has to be rewritten in a manner that the following syntax is supported:
FW_LOG(logger, level) << message << time_costly_function();

I've thought about using streams and/or perfect forwarding using template functions, but I was unable to come up with a working solution (yet).

Requirements: The code has to be compilable using MSVC 12.0, Boost.Log 1.59.0. C+11 is allowed.

So my actual question is:

How do I have to rewrite the code in the second example (using both the macro and the function) to get the same behavior as in the first example?

答:
Something like</p>

```<code>#define FW_LOG(logger, level, message) \
    do { if (logger.check_level(level)) logger.log(message); while (false)
</code>```

Body:
I am currently developing a small and simple logging library that acts as a Facade for the Boost.Log v2 C++ library.

My library is almost finished and I have successfully encapsulated Boost.Log, i.e.:

the API of my library is free of Boost.Log types, i.e. users do only have to deal with my types

the ABI of my library is free of Boost.Log types, i.e. dependencies do not have to link against Boost.Log.

There is one last thing I am not able to solve at the moment: Lazy parameter evaluation

I'll give a short usage example how Boost.Log behaves:

#include <chrono>
#include <thread>

#include <boost/log/core.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/trivial.hpp>

std::string time_costly_function(
    const std::chrono::seconds seconds = std::chrono::seconds{1}) {
  std::this_thread::sleep_for(seconds);
  return "DONE with time_costly_function";
}

int main() {
  boost::log::core::get()->set_filter(boost::log::trivial::severity >=
                                      boost::log::trivial::warning);
  BOOST_LOG_TRIVIAL(warning) << "This is evaluated: " << time_costly_function();
  BOOST_LOG_TRIVIAL(info) << "This is NOT evaluated: "
                          << time_costly_function();
}

If you run the example above you can see that only the arguments for the first BOOST_LOG_TRIVIAL call are evaluated, i.e. time_costly_function() is only called once in total.

That is exactly the behavior that I want in my library, but as I mentioned I do not want that users have to deal with Boost.Log directly, but with my small Facade.

The following code illustrates the problem (very simplified to tackle down the actual problem):

#include <boost/log/core.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/trivial.hpp>

#include <chrono>
#include <thread>

std::string time_costly_function(
    const std::chrono::seconds seconds = std::chrono::seconds{1}) {
  std::this_thread::sleep_for(seconds);

  return "DONE with time_costly_function";
}

// Encapsulates Boost.Log. The API of my logging library does not know anything
// about Boost.Log (e.g. the Pimpl idiom is used).
//
// In reality this is a member function of a class in my library with the
// following signature:
//
// void log(const SeverityLevel level, const std::string& message) override;
//
void log(const std::string& message) { BOOST_LOG_TRIVIAL(warning) << message; }

// A custom logging macro.
//
// In reality this is a macro taking the object of a class with the member
// function illustrated above:
//
// FW_LOG(logger, level, message)
//
#define FW_LOG(message) log(message)

int main() {
  // TODO(wolters): This does not work, since everything is evaluated outside of
  // the Boost.Log macro(s). I want to call my macro as follows.
  //     FW_LOG(logger, level) << message << time_costly_function();
  // I.e. it should work like the Boost.Log macro(s) illustrated above.
  FW_LOG("foo" + time_costly_function());
}

I identified the following problems in my code:

The function log may not take a std::string reference, since that will
always lead to an evaluation outside of that function.

The macro FW_LOG has to be rewritten in a manner that the following syntax is supported:
FW_LOG(logger, level) << message << time_costly_function();

I've thought about using streams and/or perfect forwarding using template functions, but I was unable to come up with a working solution (yet).

Requirements: The code has to be compilable using MSVC 12.0, Boost.Log 1.59.0. C+11 is allowed.

So my actual question is:

How do I have to rewrite the code in the second example (using both the macro and the function) to get the same behavior as in the first example?

Body:
Something like

#define FW_LOG(logger, level, message) \
    do { if (logger.check_level(level)) logger.log(message); while (false)


问:
Array Unique for Array of Objects with exclude option for certain keys in Object
I have an Object Array with few fields.

I was able to get the Array unique for this Object Array using below code:

```<code>$aa = array_unique($dd,SORT_REGULAR);
</code>```

But what i am trying to achieve is, i want to exclude certain keys in object from "unique check". Lets say all object values are matching except "valid_from" and "valid_to" date fields.

Below is array structure:

```<code>Array
(
    [9948] => stdClass Object
        (
            [payrate] => 78.00000
            [valid_from] => 03/01/2017
            [valid_to] => 03/31/2017
        )

    [15133] => stdClass Object
        (
            [payrate] => 78.00000
            [valid_from] => 04/01/2017
            [valid_to] => 04/31/2017
        )

)
</code>```

So as per above case as my pay rate is same in both object, but as valid from and valid to are different it will be still considered different entries.

Is there anyway we can specify exclude certain fields out for Array Unique for Array of Objects.

答:
You can use array_filter with a custom callback to filter out some elements from an array.

All you have to do is to implement your filter logic. Here a simple example:

```<code><?php
$array = json_decode(
    '[{"name":"foo","count":2},{"name":"foo","count":10},{"name":"baz","count":5},{"name":"foobar","count":10}]'
);

$uniqueCheck = [];

$filtered = array_filter(
    $array,
    function ($element) use (&$uniqueCheck) {
        if (isset($uniqueCheck[$element->name])) {
            return false;
        }

        $uniqueCheck[$element->name] = true;

        return true;
    }
);

print_r($array);
print_r($filtered);
</code>```

This will produce:

```<code>Array
(
    [0] => stdClass Object
        (
            [name] => foo
            [count] => 2
        )

    [1] => stdClass Object
        (
            [name] => foo
            [count] => 10
        )

    [2] => stdClass Object
        (
            [name] => baz
            [count] => 5
        )

    [3] => stdClass Object
        (
            [name] => foobar
            [count] => 10
        )

)

Array
(
    [0] => stdClass Object
        (
            [name] => foo
            [count] => 2
        )

    [2] => stdClass Object
        (
            [name] => baz
            [count] => 5
        )

    [3] => stdClass Object
        (
            [name] => foobar
            [count] => 10
        )

)
</code>```

Edit: Changed $element->count based check to "unique $element->name check".

Body:
I have an Object Array with few fields.

I was able to get the Array unique for this Object Array using below code:

$aa = array_unique($dd,SORT_REGULAR);

But what i am trying to achieve is, i want to exclude certain keys in object from "unique check". Lets say all object values are matching except "valid_from" and "valid_to" date fields.

Below is array structure:

Array
(
    [9948] => stdClass Object
        (
            [payrate] => 78.00000
            [valid_from] => 03/01/2017
            [valid_to] => 03/31/2017
        )

    [15133] => stdClass Object
        (
            [payrate] => 78.00000
            [valid_from] => 04/01/2017
            [valid_to] => 04/31/2017
        )

)

So as per above case as my pay rate is same in both object, but as valid from and valid to are different it will be still considered different entries.

Is there anyway we can specify exclude certain fields out for Array Unique for Array of Objects.

Body:
You can use array_filter with a custom callback to filter out some elements from an array.

All you have to do is to implement your filter logic. Here a simple example:

<?php
$array = json_decode(
    '[{"name":"foo","count":2},{"name":"foo","count":10},{"name":"baz","count":5},{"name":"foobar","count":10}]'
);

$uniqueCheck = [];

$filtered = array_filter(
    $array,
    function ($element) use (&$uniqueCheck) {
        if (isset($uniqueCheck[$element->name])) {
            return false;
        }

        $uniqueCheck[$element->name] = true;

        return true;
    }
);

print_r($array);
print_r($filtered);

This will produce:

Array
(
    [0] => stdClass Object
        (
            [name] => foo
            [count] => 2
        )

    [1] => stdClass Object
        (
            [name] => foo
            [count] => 10
        )

    [2] => stdClass Object
        (
            [name] => baz
            [count] => 5
        )

    [3] => stdClass Object
        (
            [name] => foobar
            [count] => 10
        )

)

Array
(
    [0] => stdClass Object
        (
            [name] => foo
            [count] => 2
        )

    [2] => stdClass Object
        (
            [name] => baz
            [count] => 5
        )

    [3] => stdClass Object
        (
            [name] => foobar
            [count] => 10
        )

)

Edit: Changed $element->count based check to "unique $element->name check".


问:
set back button title text in iOS Xamarin
I want to set the BackButton Title text to ""(means empty). I am using below code to set the Title but it is not working.

Try 1 :

```<code>this.NavigationItem.BackBarButtonItem = new UIBarButtonItem("", UIBarButtonItemStyle.Plain, null);
</code>```

Try 2 :

```<code>this.NavigationItem.BackBarButtonItem.Title = "";
</code>```

it is give the object is not set to instance.

Is there any way to set the Back button title null in iOS.

Any Help Will be Appreciated.

答:
Try this

this.NavigationItem.SetLeftBarButtonItem(new UIBarButtonItem("text", UIBarButtonItemStyle.Plain , (sender, args) => { }), true);

Body:
I want to set the BackButton Title text to ""(means empty). I am using below code to set the Title but it is not working.

Try 1 :

this.NavigationItem.BackBarButtonItem = new UIBarButtonItem("", UIBarButtonItemStyle.Plain, null);

Try 2 :

this.NavigationItem.BackBarButtonItem.Title = "";

it is give the object is not set to instance.

Is there any way to set the Back button title null in iOS.

Any Help Will be Appreciated.


问:
NodeJS: Cannot call method 'push' of undefined
Greenhorn here trying to setup a basic nodejs program using events. My program seems to be fine but I am receiving an error that the push function is undefined. I was under the impression that this is a built-in function. Can someone point me in the right direction? Code is below.

//emitter.js file

function Emitter() {
  this.events = {};
}

Emitter.prototype.on = function(type, listener) {
  this.events = this.events[type] || [];
  this.events[type].push(listener);
}

Emitter.prototype.emit = function(type) {
  if (this.events[type]) {
    this.events[type].forEach(function(listener) {
      listener();
    });
  }
}

module.exports = Emitter;

// app.js file

var Emitter = require('./emitter');

var emtr = new Emitter();

emtr.on('greet', function() {
  console.log('Somewhere, someone said hello');
})

emtr.on('greet', function() {
  console.log('A second greeting occurred');
})

emtr.emit('greet');```

答:
You have a mistake in your Emitter.prototype.on() logic.

```<code>Emitter.prototype.on = function(type, listener) {
  this.events = this.events[type] || [];
  this.events[type].push(listener);
}
</code>```

In the above function this.events = this.events[type] || []; is incorrect because it is reassigning the entire events object to an array. Which means that the following line this.events[type].push(listener) won't be an array but undefined.

Just correct your function to properly assign this.events[type]

```<code>Emitter.prototype.on = function(type, listener) {
  this.events[type] = this.events[type] || [];
  this.events[type].push(listener);
}
</code>```

Body:
You have a mistake in your Emitter.prototype.on() logic.

Emitter.prototype.on = function(type, listener) {
  this.events = this.events[type] || [];
  this.events[type].push(listener);
}

In the above function this.events = this.events[type] || []; is incorrect because it is reassigning the entire events object to an array. Which means that the following line this.events[type].push(listener) won't be an array but undefined.

Just correct your function to properly assign this.events[type]

Emitter.prototype.on = function(type, listener) {
  this.events[type] = this.events[type] || [];
  this.events[type].push(listener);
}


问:
How can I use Linq with JSON to get all the Ids from this odd JSON?
I receive JSON from a web service that looks something like this:

```<code>{
   "RESULTS": {
      "1220": {
           "DDR_TYPE_ID": 7,
           "DDR_ID": 5199,
           "DDR_NAME": "Mesa Building"
      },
      "5455": {
           "DDR_TYPE_ID": 7,
           "DDR_ID": 417,
           "DDR_NAME": "Scottsdale Building"
      },
      "1462": {
           "DDR_TYPE_ID": 12,
           "DDR_ID": 3324,
           "DDR_NAME": "Gentry Building"
      }
   }
}
</code>```

I can't really serialize in my usual method because this isn't an array of the same objects thanks the the strange numbered keys.

All I need from this is a list of the DDR_ID values.

Is there a way to use Linq to JSON to get these values from this JSON?  Or is there a better way?

答:
If you want avoid using other objects:   </p>

```<code>using System;
using System.Linq;
using Newtonsoft.Json.Linq;

var jObject = JObject.Parse(json)["RESULTS"];
var result = jObject.Select(x => x.First["DDR_ID"]).Values<int>();
</code>```

Body:
I receive JSON from a web service that looks something like this:

{
   "RESULTS": {
      "1220": {
           "DDR_TYPE_ID": 7,
           "DDR_ID": 5199,
           "DDR_NAME": "Mesa Building"
      },
      "5455": {
           "DDR_TYPE_ID": 7,
           "DDR_ID": 417,
           "DDR_NAME": "Scottsdale Building"
      },
      "1462": {
           "DDR_TYPE_ID": 12,
           "DDR_ID": 3324,
           "DDR_NAME": "Gentry Building"
      }
   }
}

I can't really serialize in my usual method because this isn't an array of the same objects thanks the the strange numbered keys.

All I need from this is a list of the DDR_ID values.

Is there a way to use Linq to JSON to get these values from this JSON?  Or is there a better way?

Body:
If you want avoid using other objects:

using System;
using System.Linq;
using Newtonsoft.Json.Linq;

var jObject = JObject.Parse(json)["RESULTS"];
var result = jObject.Select(x => x.First["DDR_ID"]).Values<int>();


问:
Java bits to Integer
I have an application that is sending me 2 shorts one increments from 0 -> 32 -> 48 -> 16 then back to 0 and the second increments each time the first one hits 0. The second one goes up to a maximum of 65535 and then loops round back to 0. I'm guessing this is some bits that are encoded which can be made to create a single number?

How can I combine these two shorts into a single number that increments by 1 if they increment in the behaviour described above?

答:
```<code>0b0000_0000  0
0b0010_0000 32
0b0011_0000 48
0b0001_0000 16
</code>```

So you can increment a counter modulo 4, 0, 1, 2, 3, 0, 1, 2, ... and switch the two bits. Modulo 4 means & 0b11.

```<code>int x = 0;
for (int i = 0; i < 100; ++i) {
    System.out.printf("%04x%n", x);
    x = (x + 1) & 0xFFFF;
    x |= (x & 2) << 16;
    x |= ~((x & 2) ^ (x & 1)) << 17; // Or something like that
}
</code>```

I leave it to you to find the logic.

Title: Java bits to Integer

Body:
0b0000_0000  0
0b0010_0000 32
0b0011_0000 48
0b0001_0000 16

So you can increment a counter modulo 4, 0, 1, 2, 3, 0, 1, 2, ... and switch the two bits. Modulo 4 means & 0b11.

int x = 0;
for (int i = 0; i < 100; ++i) {
    System.out.printf("%04x%n", x);
    x = (x + 1) & 0xFFFF;
    x |= (x & 2) << 16;
    x |= ~((x & 2) ^ (x & 1)) << 17; // Or something like that
}

I leave it to you to find the logic.


问:
Passing data from child route to father route
I have a route structure like this:

```<code>        <Route path="/master" component={MasterPageLayout}>
            <IndexRoute path="/master/products" component={ProductsPage}/>
            <Route path="/master/customer/:id" component={CustomerDetailsPage}/>
            <Route path="/master/product/:id" component={ProductDetailsPage}/>
            <Route path="/master/price-table" component={PriceTablePage} />
        </Route>
        <Route path="/poc" component={DistribuitorPageLayout}>
            <IndexRoute path="/poc/inventory" component={InventoryPage}/>
        </Route>
</code>```

Inside the MasterPageLayout I have my header and my sidemenu (common to all the nested routes above him), the props.children is rendered inside those menus structures, but my header has a specific text for each route. How can I pass the text (and maybe some other data) from the child to the father?

答:
Passing data back up the tree is usually handled with callbacks.  As you only need to get the value once I'd recommend using one of the mounting lifecycle methods to call the callback.

As you've tagged react-redux, I'll give examples for both a React and Redux.  I don't believe the basic react example is actually suitable for your situation, as you are rendering props.children which makes passing the callback down more difficult, but I'll leave it in the answer in case it's useful to someone else.  The redux example should be applicable to your problem.

Basic React

You can pass a callback to the child that sets a value in the components state to use when rendering

```<code>class Child extends React.Component {
    componentWillMount() {
        this.props.setText("for example")
    }

    render() {
        return (
            <div>whatever</div>
        )
    }
}

class Parent extends React.Component {
    render() {
        return (
            <div>
                <Child setText={(text) => this.setState({text})} />
                {this.state.text}
            </div>
        )
    }
}
</code>```

React/Redux

You could dispatch an action to set the text when the child is mounted that sets a value in the store to render in the parent, e.g.

```<code>class ChildView extends React.Component {
    componentWillMount() {
        this.props.setText("for example")
    }

    render() {
        return (
            <div>whatever</div>
        )
    }
}

const mapDispatchToProps = (dispatch) => {
    return {
        setText: (text) => dispatch(setParentText(text))
    }
}

const Child = connect(null, mapDispatchToProps)(ChildView)

const ParentView = ({ text }) => {
    return (
        <div>
            <Child />
            {text}
        </div>
    )
}

const mapStateToProps = (state) => {
    return {
        text: state.parent.text
    }
}

const Parent = connect(mapStateToProps)(ParentView)
</code>```

I wont worry showing the action creator and the reducer/store setup.  If you're using redux you should be able to figure that bit out.

This approach will also work if Parent doesn't directly render Child, whether it is through props.children or extra layers are introduced.  In fact, Parent doesn't event need to be an ancestor of Child at all for this approach to work, as long as both are rendered on the same page.

Body:
I have a route structure like this:

        <Route path="/master" component={MasterPageLayout}>
            <IndexRoute path="/master/products" component={ProductsPage}/>
            <Route path="/master/customer/:id" component={CustomerDetailsPage}/>
            <Route path="/master/product/:id" component={ProductDetailsPage}/>
            <Route path="/master/price-table" component={PriceTablePage} />
        </Route>
        <Route path="/poc" component={DistribuitorPageLayout}>
            <IndexRoute path="/poc/inventory" component={InventoryPage}/>
        </Route>

Inside the MasterPageLayout I have my header and my sidemenu (common to all the nested routes above him), the props.children is rendered inside those menus structures, but my header has a specific text for each route. How can I pass the text (and maybe some other data) from the child to the father?

Body:
Passing data back up the tree is usually handled with callbacks.  As you only need to get the value once I'd recommend using one of the mounting lifecycle methods to call the callback.

As you've tagged react-redux, I'll give examples for both a React and Redux.  I don't believe the basic react example is actually suitable for your situation, as you are rendering props.children which makes passing the callback down more difficult, but I'll leave it in the answer in case it's useful to someone else.  The redux example should be applicable to your problem.

Basic React

You can pass a callback to the child that sets a value in the components state to use when rendering

class Child extends React.Component {
    componentWillMount() {
        this.props.setText("for example")
    }

    render() {
        return (
            <div>whatever</div>
        )
    }
}

class Parent extends React.Component {
    render() {
        return (
            <div>
                <Child setText={(text) => this.setState({text})} />
                {this.state.text}
            </div>
        )
    }
}

React/Redux

You could dispatch an action to set the text when the child is mounted that sets a value in the store to render in the parent, e.g.

class ChildView extends React.Component {
    componentWillMount() {
        this.props.setText("for example")
    }

    render() {
        return (
            <div>whatever</div>
        )
    }
}

const mapDispatchToProps = (dispatch) => {
    return {
        setText: (text) => dispatch(setParentText(text))
    }
}

const Child = connect(null, mapDispatchToProps)(ChildView)

const ParentView = ({ text }) => {
    return (
        <div>
            <Child />
            {text}
        </div>
    )
}

const mapStateToProps = (state) => {
    return {
        text: state.parent.text
    }
}

const Parent = connect(mapStateToProps)(ParentView)

I wont worry showing the action creator and the reducer/store setup.  If you're using redux you should be able to figure that bit out.

This approach will also work if Parent doesn't directly render Child, whether it is through props.children or extra layers are introduced.  In fact, Parent doesn't event need to be an ancestor of Child at all for this approach to work, as long as both are rendered on the same page.


问:
SQL Server 2008 Backup Transaction Logs
I understand that the transaction logs keep a record of historical transactions in order to facilitate a restore if needed. However do I need to keep creating transaction log backups for inactive databases that are hanging around on the server? No DDL statements are run against them and they are just used for reference. </p>

<p>I am just a bit worried that I might run out of log space if I get this wrong. </p>

答:
Have you considered changing the recovery model of your databases to the SIMPLE recovery model? Doing so would negate the need to backup the transaction log as it would be automatically re-used in the "unlikely" event that you need it to be.

I would still advise that regular FULL database backups be taken.

Also, if these database are indeed true read only databases then why not consider setting them to be so. This action would have the advantage of immediately highlighting any queries/users that are "still" issuing DML operations when you believe there to be none.

Other options for identifying queries that are performing more than just READ operations include running a Profiler Trace of activity on your database server and also an aggressive option would be to revoke all data modification rights from the relevant database Users.

Title: SQL Server 2008 Backup Transaction Logs

Body:
I understand that the transaction logs keep a record of historical transactions in order to facilitate a restore if needed. However do I need to keep creating transaction log backups for inactive databases that are hanging around on the server? No DDL statements are run against them and they are just used for reference.

I am just a bit worried that I might run out of log space if I get this wrong.


问:
Visualizing a feature/kernel produced by a CNN via an "optimal" input image using Keras
So I've been doing a lot of research regarding the visualization of CNN's and I can't seem to find a solution to what I'm trying to do, or at least to my understanding of the methodologies employed. A lot of it is pretty new and cutting edge, so I could just not be properly grasping the concepts.

Basically, I want to take a learned kernel/feature as trained by a CNN and essentially manufacture an "optimized" picture such that when the kernel is convolved with said picture, we have the highest convolutional sum possible.

If I'm not mistaken, this should exaggerate the features of that kernel on the image level rather than at the filter/kernel level, which seems to be what most have done in terms of visualizing these filters.

In case what I'm asking is not clear, here's an example (probably bad, but it'll get the point across.)

Assume we are using MNIST and I've created a CNN like so:

5x5 Conv with 10 kernels/Feature Maps

Relu

2x2 MaxPool 2 stride

Dense + Softmax

Let's say I've fully trained my model and now want to look at one of the 10 5x5 kernels it produced and get a better idea of what it's looking for. I want to manufacture a new 28x28 picture such that when convolved with this 5x5 kernel, the sum of the 28x28 convolution is maximized.

Are there techniques that already do something like this? I feel like everything I see involves either "unwinding" or "reversing" the neural net (https://arxiv.org/pdf/1311.2901.pdf), viewing the feature maps as pictures pass through (http://kvfrans.com/visualizing-features-from-a-convolutional-neural-network/), or just looking at the kernels themselves (https://www.youtube.com/watch?v=AgkfIQ4IGaM).

Is it even something useful to look at? I feel like this is the closest thing I've seen to what I'm requesting. https://arxiv.org/pdf/1312.6034.pdf

Any insight would be a huge help, thanks!

答: This is called activation maximization, and Keras even has an example of it available here. Note that the code in the post might be outdated for current Keras versions, but a updated version is available in the examples folder in Keras.</p>