问:
UNIQUE constraint failed: sqlite database : android
I am trying to insert values in table. But there is only one value inserted. I am getting an error in log cat when I am trying to insert new values.

Log cat shows :

```<code>abort at 13 in [INSERT INTO event(totalminutesfrom,dayofweek,title,location,totalminutesto,id) VALUES (?,?,?,?,?,?)]: UNIQUE constraint failed: event.id
01-24 11:34:39.764 7763-7763/com.example.siddhi.timetablelayout E/SQLiteDatabase: Error inserting totalminutesfrom=694 dayofweek=null title=qxs location=Eded & Mariz totalminutesto=0 id=0
01-24 11:34:39.764 7763-7763/com.example.siddhi.timetablelayout E/SQLiteDatabase: android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: event.id (code 1555)
01-24 11:34:39.764 7763-7763/com.example.siddhi.timetablelayout E/SQLiteDatabase:     at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
01-24 11:34:39.764 7763-7763/com.example.siddhi.timetablelayout E/SQLiteDatabase:     at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:782)
01-24 11:34:39.764 7763-7763/com.example.siddhi.timetablelayout E/SQLiteDatabase:     at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
01-24 11:34:39.764 7763-7763/com.example.siddhi.timetablelayout E/SQLiteDatabase:     at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
01-24 11:34:39.764 7763-7763/com.example.siddhi.timetablelayout E/SQLiteDatabase:     at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1471)
01-24 11:34:39.764 7763-7763/com.example.siddhi.timetablelayout E/SQLiteDatabase:     at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
01-24 11:34:39.764 7763-7763/com.example.siddhi.timetablelayout E/SQLiteDatabase:     at com.example.siddhi.timetablelayout.EventTableHelper.addEvent(EventTableHelper.java:76)
01-24 11:34:39.764 7763-7763/com.example.siddhi.timetablelayout E/SQLiteDatabase:     at com.example.siddhi.timetablelayout.AddEventActivity$5.onClick(AddEventActivity.java:217)
</code>```

Its showing error on these two lines while inserting row.

```<code>db.insert(TABLE, null, values);

   db.addEvent(new EventData(eventTitle,dayOfWeek,totalMinutesFrom, totalMinutesTo,location));
</code>```

EventTableHelper

```<code>public class EventTableHelper extends SQLiteOpenHelper {

    private static final String TABLE = "event";
    private static final String KEY_ID = "id";
    private static final String KEY_TITLE = "title";
    private static final String KEY_LOCATION = "location";
    private static final String KEY_DAY_OF_WEEK = "dayofweek";
    private static final String KEY_TOTAL_MINUTES_FROM = "totalminutesfrom";
    private static final String KEY_TOTAL_MINUTES_TO = "totalminutesto";

    public EventTableHelper(Context context) {
        super(context, Constants.DATABASE_NAME, null, Constants.DATABASE_VERSION);
        //3rd argument to be passed is CursorFactory instance
    }

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        //createTable(db);
    }

    public void createTable(SQLiteDatabase db){
        String CREATE_EVENTS_TABLE = "CREATE TABLE " + TABLE + "("
                + KEY_ID + " INTEGER PRIMARY KEY," + KEY_TITLE + " TEXT,"
                + KEY_DAY_OF_WEEK +"TEXT" + KEY_TOTAL_MINUTES_FROM +"INTEGER"
                + KEY_TOTAL_MINUTES_TO + "INTEGER" +  KEY_LOCATION + "TEXT" +  ")";

        db.execSQL(CREATE_EVENTS_TABLE);

    }
    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
       // db.execSQL("DROP TABLE IF EXISTS " + TABLE);

      //  createTable(db);

        // Create tables again
        //onCreate(db);
    }

    // code to add the new contact
    public void addEvent(EventData event) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_ID, event.getId());
        values.put(KEY_TITLE,event.getTitle()); // Contact Name
        values.put(KEY_DAY_OF_WEEK,event.getDayofWeek());
        values.put(KEY_TOTAL_MINUTES_FROM,event.getFromMinutes());
        values.put(KEY_TOTAL_MINUTES_TO,event.getToMinutes());
        values.put(KEY_LOCATION,event.getLocation());
        // Inserting Row
        db.insert(TABLE, null, values);
        //2nd argument is String containing nullColumnHack
        db.close(); // Closing database connection
    }

    // code to get the single contact
   EventData getEvent(int id) {
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE, new String[] { KEY_ID,
                        KEY_TITLE, KEY_DAY_OF_WEEK, KEY_TOTAL_MINUTES_FROM,KEY_TOTAL_MINUTES_TO,KEY_LOCATION }, KEY_ID + "=?",
                new String[] { String.valueOf(id) }, null, null, null, null);
        if (cursor != null)
            cursor.moveToFirst();
       EventData eventData = new EventData(Integer.parseInt(cursor.getString(0)),cursor.getString(1), cursor.getString(2),
               cursor.getInt(3),cursor.getInt(4),cursor.getString(5));

        return eventData;
    }

    // code to get all contacts in a list view
    public List<EventData> getAllEvents() {
        List<EventData> conList = new ArrayList<EventData>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {

                EventData event = new EventData();

                event.setId(Integer.parseInt(cursor.getString(0)));
                event.setTitle(cursor.getString(1));
                event.setDayofWeek(cursor.getString(2));
                event.setFromMinutes(cursor.getInt(3));
                event.setToMinutes(cursor.getInt(4));
                event.setLocation(cursor.getString(5));
                // Adding contact to list
                conList.add(event);
            } while (cursor.moveToNext());
        }

        // return contact list
        return conList;
    }
}
</code>```

How to solve this??

答:
I originally put the new unique constraint infant of the old one. Instead make sure you're current unique column is first:</p>

```<code>CREATE TABLE TEST (client_id TEXT unique, remote_id INT unique)
</code>```

Body:
I am trying to insert values in table. But there is only one value inserted. I am getting an error in log cat when I am trying to insert new values.

Log cat shows :

abort at 13 in [INSERT INTO event(totalminutesfrom,dayofweek,title,location,totalminutesto,id) VALUES (?,?,?,?,?,?)]: UNIQUE constraint failed: event.id
01-24 11:34:39.764 7763-7763/com.example.siddhi.timetablelayout E/SQLiteDatabase: Error inserting totalminutesfrom=694 dayofweek=null title=qxs location=Eded & Mariz totalminutesto=0 id=0
01-24 11:34:39.764 7763-7763/com.example.siddhi.timetablelayout E/SQLiteDatabase: android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: event.id (code 1555)
01-24 11:34:39.764 7763-7763/com.example.siddhi.timetablelayout E/SQLiteDatabase:     at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
01-24 11:34:39.764 7763-7763/com.example.siddhi.timetablelayout E/SQLiteDatabase:     at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:782)
01-24 11:34:39.764 7763-7763/com.example.siddhi.timetablelayout E/SQLiteDatabase:     at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
01-24 11:34:39.764 7763-7763/com.example.siddhi.timetablelayout E/SQLiteDatabase:     at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
01-24 11:34:39.764 7763-7763/com.example.siddhi.timetablelayout E/SQLiteDatabase:     at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1471)
01-24 11:34:39.764 7763-7763/com.example.siddhi.timetablelayout E/SQLiteDatabase:     at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
01-24 11:34:39.764 7763-7763/com.example.siddhi.timetablelayout E/SQLiteDatabase:     at com.example.siddhi.timetablelayout.EventTableHelper.addEvent(EventTableHelper.java:76)
01-24 11:34:39.764 7763-7763/com.example.siddhi.timetablelayout E/SQLiteDatabase:     at com.example.siddhi.timetablelayout.AddEventActivity$5.onClick(AddEventActivity.java:217)

Its showing error on these two lines while inserting row.

db.insert(TABLE, null, values);

   db.addEvent(new EventData(eventTitle,dayOfWeek,totalMinutesFrom, totalMinutesTo,location));

EventTableHelper

public class EventTableHelper extends SQLiteOpenHelper {

    private static final String TABLE = "event";
    private static final String KEY_ID = "id";
    private static final String KEY_TITLE = "title";
    private static final String KEY_LOCATION = "location";
    private static final String KEY_DAY_OF_WEEK = "dayofweek";
    private static final String KEY_TOTAL_MINUTES_FROM = "totalminutesfrom";
    private static final String KEY_TOTAL_MINUTES_TO = "totalminutesto";

    public EventTableHelper(Context context) {
        super(context, Constants.DATABASE_NAME, null, Constants.DATABASE_VERSION);
        //3rd argument to be passed is CursorFactory instance
    }

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        //createTable(db);
    }

    public void createTable(SQLiteDatabase db){
        String CREATE_EVENTS_TABLE = "CREATE TABLE " + TABLE + "("
                + KEY_ID + " INTEGER PRIMARY KEY," + KEY_TITLE + " TEXT,"
                + KEY_DAY_OF_WEEK +"TEXT" + KEY_TOTAL_MINUTES_FROM +"INTEGER"
                + KEY_TOTAL_MINUTES_TO + "INTEGER" +  KEY_LOCATION + "TEXT" +  ")";

        db.execSQL(CREATE_EVENTS_TABLE);

    }
    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
       // db.execSQL("DROP TABLE IF EXISTS " + TABLE);

      //  createTable(db);

        // Create tables again
        //onCreate(db);
    }

    // code to add the new contact
    public void addEvent(EventData event) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_ID, event.getId());
        values.put(KEY_TITLE,event.getTitle()); // Contact Name
        values.put(KEY_DAY_OF_WEEK,event.getDayofWeek());
        values.put(KEY_TOTAL_MINUTES_FROM,event.getFromMinutes());
        values.put(KEY_TOTAL_MINUTES_TO,event.getToMinutes());
        values.put(KEY_LOCATION,event.getLocation());
        // Inserting Row
        db.insert(TABLE, null, values);
        //2nd argument is String containing nullColumnHack
        db.close(); // Closing database connection
    }

    // code to get the single contact
   EventData getEvent(int id) {
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE, new String[] { KEY_ID,
                        KEY_TITLE, KEY_DAY_OF_WEEK, KEY_TOTAL_MINUTES_FROM,KEY_TOTAL_MINUTES_TO,KEY_LOCATION }, KEY_ID + "=?",
                new String[] { String.valueOf(id) }, null, null, null, null);
        if (cursor != null)
            cursor.moveToFirst();
       EventData eventData = new EventData(Integer.parseInt(cursor.getString(0)),cursor.getString(1), cursor.getString(2),
               cursor.getInt(3),cursor.getInt(4),cursor.getString(5));

        return eventData;
    }

    // code to get all contacts in a list view
    public List<EventData> getAllEvents() {
        List<EventData> conList = new ArrayList<EventData>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {

                EventData event = new EventData();

                event.setId(Integer.parseInt(cursor.getString(0)));
                event.setTitle(cursor.getString(1));
                event.setDayofWeek(cursor.getString(2));
                event.setFromMinutes(cursor.getInt(3));
                event.setToMinutes(cursor.getInt(4));
                event.setLocation(cursor.getString(5));
                // Adding contact to list
                conList.add(event);
            } while (cursor.moveToNext());
        }

        // return contact list
        return conList;
    }
}

How to solve this??

Body:
I originally put the new unique constraint infant of the old one. Instead make sure you're current unique column is first:

CREATE TABLE TEST (client_id TEXT unique, remote_id INT unique)


来源: stackexchange

问:
length function not giving output
$select.Length is not giving output. Please find code below:

```<code>clear
$filePath = "c:\temp\result.txt"
$select = Select-String -Pattern "Final result:" -Path 'C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Log\Summary.txt' #| Out-File c:\pattern.txt
$select1 = Select-String -Pattern "Final result:" -Path 'C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Log\Summary.txt' | Out-File D:\temp\pattern.txt
Write-Host($select.Length)

if ($select.Length -gt 0) {
    Write-Host 'Contains String'
    $select2 = Select-String -Pattern "Passed" -Path 'D:\temp\pattern.txt'

    if ($select2.Length -gt 0) {
        #Out-File C:\temp\result.txt $filePath -Append
        New-Item $filePath -ItemType file
        'Success' | Out-File -FilePath $filePath -Append
    } else {
        New-Item $filePath -ItemType file
        'Failed' | Out-File -FilePath $filePath -Append
    }
} else {
    Write-Host 'Does not contain String'
}
</code>```

Ideally it should generate file with success as text in result.txt, but it's not working. I'm not getting any error.

答:
$select does not contain type [String], which I assume is what you expect to have the property Length. Instead, use $select.Line.Length, where $select.Line is the matched line. Repeat for $select2

$select1 - don't pipe to out file at the same time as assigning variable.  I think below gets you what you want and avoids that.

```<code>$select = Select-String -Pattern "Final result:" -Path 'C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Log\Summary.txt'

# This outputs the matching line only
$select.Line |Out-File D:\temp\pattern.txt
</code>```

ContentLicense: CC BY-SA 3.0

Title: length function not giving output

Body:
$select.Length is not giving output. Please find code below:

clear
$filePath = "c:\temp\result.txt"
$select = Select-String -Pattern "Final result:" -Path 'C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Log\Summary.txt' #| Out-File c:\pattern.txt
$select1 = Select-String -Pattern "Final result:" -Path 'C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Log\Summary.txt' | Out-File D:\temp\pattern.txt
Write-Host($select.Length)

if ($select.Length -gt 0) {
    Write-Host 'Contains String'
    $select2 = Select-String -Pattern "Passed" -Path 'D:\temp\pattern.txt'

    if ($select2.Length -gt 0) {
        #Out-File C:\temp\result.txt $filePath -Append
        New-Item $filePath -ItemType file
        'Success' | Out-File -FilePath $filePath -Append
    } else {
        New-Item $filePath -ItemType file
        'Failed' | Out-File -FilePath $filePath -Append
    }
} else {
    Write-Host 'Does not contain String'
}

Ideally it should generate file with success as text in result.txt, but it's not working. I'm not getting any error.

Body:
$select does not contain type [String], which I assume is what you expect to have the property Length. Instead, use $select.Line.Length, where $select.Line is the matched line. Repeat for $select2

$select1 - don't pipe to out file at the same time as assigning variable.  I think below gets you what you want and avoids that.

$select = Select-String -Pattern "Final result:" -Path 'C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Log\Summary.txt'

# This outputs the matching line only
$select.Line |Out-File D:\temp\pattern.txt


问:
Presenting a UIViewController with background transparent in swift 3.0
I am presenting a viewController with transparent background. But the components on that viewController is invisible when it is presented. A blank viewController is seen.I have given alpha value and black background color.
This is my code when  i call the transparent viewController

```<code>if indexPath.row==0
{
   let modalViewController = PopUpViewController()
    modalViewController.modalPresentationStyle = .overCurrentContext
    present(modalViewController, animated: true, completion: nil)
 }
</code>```

But there is a orange color UIView present on this Controller which is invisible Thanks in advance

答:
You can take two view one as outerView (Transparent black) and  innerView( OrangeView) , note that both view are in same hierarchy. (as in screen shot)

Default View of viewController background color should be clearColor.

OuterView should having transparent black background.

On Segue presentation property in Attribute inspector of Segue should be Over Full Screen as shown in image.

it will show on running.

Body:
I am presenting a viewController with transparent background. But the components on that viewController is invisible when it is presented. A blank viewController is seen.I have given alpha value and black background color.
This is my code when  i call the transparent viewController

if indexPath.row==0
{
   let modalViewController = PopUpViewController()
    modalViewController.modalPresentationStyle = .overCurrentContext
    present(modalViewController, animated: true, completion: nil)
 }

But there is a orange color UIView present on this Controller which is invisible Thanks in advance


问:
vis.js network: nodes z-index
Is there an equivalent of the CSS z-index for vis.js nodes?

Suppose that I have 2 kinds of nodes (in a graph with physics disabled): Circles and rectangles. I would like the rectangles to always be displayed over the circles when they are overlapping.

答:
Kind of a late reply but the short answer is: no

See this issue: https://github.com/almende/vis/issues/3146

Title: vis.js network: nodes z-index


问:
How do i extract some data in string? using PHP
I have a string of URL format.

It is this.
"http://test.com/foo/bar/detail.php?key=KEY&other=x"

What I need is to extract "KEY" from URL.

It is similar this.

```<code>$foo = $_GET['key'];
</code>```

But what I have is a string of URL format.

How do i extract KEY this string?

答:
You can use parse_url(): http://php.net/manual/en/function.parse-url.php And parse-str http://php.net/manual/en/function.parse-str.php

```<code>$string = "http://test.com/foo/bar/detail.php?key=KEY&other=x";
$query = parse_url($url, PHP_URL_QUERY);
$variable = parse_str($query, $output);
echo $output['key'];
</code>```

Body:
I have a string of URL format.

It is this.
"http://test.com/foo/bar/detail.php?key=KEY&other=x"

What I need is to extract "KEY" from URL.

It is similar this.

$foo = $_GET['key'];

But what I have is a string of URL format.

How do i extract KEY this string?

Body:
You can use parse_url(): http://php.net/manual/en/function.parse-url.php And parse-str http://php.net/manual/en/function.parse-str.php

$string = "http://test.com/foo/bar/detail.php?key=KEY&other=x";
$query = parse_url($url, PHP_URL_QUERY);
$variable = parse_str($query, $output);
echo $output['key'];


问:
Using reserved keywords as object key with spread operators
Say I have an object that looks like this

```<code>const props = {
    delete: function() {
        // stuffs
    },
    hello: 'hello',
    other: 'other',
}
</code>```

Now say I use spread operators and do something like this

```<code>const {hello, ...otherStuffs} = props;
</code>```

Then for otherStuffs, I still get an object that is a copy of props but except for the hello key.

But what if I do not want the delete key of the object ? I can not do the same as done above because apparently delete is a reserved keyword.

```<code>const {delete, ...otherStuffs} = props; // error here
</code>```

I can however still filter the keys from the object that are not equal to 'delete' and get my object but is there a way to do this using spread operators ?

答:
You can do it by aliasing the delete property of props. You can try this

const props = {
    delete: function() {
        console.log("delete");
    },
    hello: 'hello',
    other: 'other',
}

const {"delete": del, ...otherStuffs} = props;
del();```

Reference: Invalid JavaScript identifier as a property name

Body:
Say I have an object that looks like this

const props = {
    delete: function() {
        // stuffs
    },
    hello: 'hello',
    other: 'other',
}

Now say I use spread operators and do something like this

const {hello, ...otherStuffs} = props;

Then for otherStuffs, I still get an object that is a copy of props but except for the hello key.

But what if I do not want the delete key of the object ? I can not do the same as done above because apparently delete is a reserved keyword.

const {delete, ...otherStuffs} = props; // error here

I can however still filter the keys from the object that are not equal to 'delete' and get my object but is there a way to do this using spread operators ?

Body:
You can do it by aliasing the delete property of props. You can try this

const props = {
    delete: function() {
        console.log("delete");
    },
    hello: 'hello',
    other: 'other',
}

const {"delete": del, ...otherStuffs} = props;
del();

Reference: Invalid JavaScript identifier as a property name


问:
Display specific categories on a wordpress post loop
I'm actually using risewp theme (not the pro version). In the homepage I need to show posts from "novita" categories in the "Scopri tutte le novità", and the "escursioni" posts in the "Le prossime escursioni" section.
Actually it seems that both the parts show all the categories.

How can I do that? I already tried the other solutions posted here, but nothing worked. Thanks!

Site:  http://provasiti100.altervista.org/

答:
Get Posts for specific category using function get_posts

https://developer.wordpress.org/reference/functions/get_posts/

and create Short_code for that and use it in the site to display data.

You can also specify dynamic shotcode with attribute like category name;

https://developer.wordpress.org/reference/functions/add_shortcode/

Example:
[featured_post cat_name="novita"]


问:
Apache JKmanager Activation Status is not updating
I have changed the Activation Status of JKManager node1 from Activate to Deactivate and once after access the application URL and login the status of the JKManager gets changed to activate status.And i couldn't find any errors in Apache logs.Does is there  any other configuration required?

My application is using  Server Version: Apache/2.2.15 (Win32) mod_jk/1.2.265,mod-jk and Jboss Application Server Version 6.And below is the configured worker.properties file

```<code>worker.list=workerlist
# Set properties for node1
worker.node1.type=ajp13
worker.node1.host=xxxx
worker.node1.port=xx
worker.node1.lbfactor=4

# Set properties for node2
worker.node2.type=ajp13
worker.node2.host=xxxx
worker.node2.port=xx
worker.node2.lbfactor=4

# Set properties for workerlist(lb)
worker.workerlist.type=lb
worker.workerlist.balance_workers=node1,node2
worker.workerlist.sticky_session=1

worker.list=jkstatus
worker.jkstatus.type=status
</code>```

答: The issue is due to Jboss Application server(Server.xml) and Apache Server(V_host) are configured with same port and we have changed the Port of JBOSS in server.xml which resolved the issue.Thanks </p>

Body:
I have changed the Activation Status of JKManager node1 from Activate to Deactivate and once after access the application URL and login the status of the JKManager gets changed to activate status.And i couldn't find any errors in Apache logs.Does is there  any other configuration required?

My application is using  Server Version: Apache/2.2.15 (Win32) mod_jk/1.2.265,mod-jk and Jboss Application Server Version 6.And below is the configured worker.properties file

worker.list=workerlist
# Set properties for node1
worker.node1.type=ajp13
worker.node1.host=xxxx
worker.node1.port=xx
worker.node1.lbfactor=4

# Set properties for node2
worker.node2.type=ajp13
worker.node2.host=xxxx
worker.node2.port=xx
worker.node2.lbfactor=4

# Set properties for workerlist(lb)
worker.workerlist.type=lb
worker.workerlist.balance_workers=node1,node2
worker.workerlist.sticky_session=1

worker.list=jkstatus
worker.jkstatus.type=status


问:
hasManyThrough - Not returning the right data
I have an intermediate table titled

app_services

It consists of the following columns :

app_service_id (PK)

app_id (FK)

service_id (FK)

The final table is the services table :

Services

service_id (PK)

service_name

service_icon

I am trying a hasManyThrough on app_services. But it's returning the wrong results..

For app_id = 1 it has the service id's of 1 & 3. But it is returning back the service_id's pf 1 & 4.

In my app_model I am defining the relationship as follows :

```<code>public function services()
{
    return $this->hasManyThrough(
        'App\Service', 'App\AppService',
        'service_id', 'service_id', 'app_id'
    );
}
</code>```

Now that looks right to me? Would someone mine checking if it's correct or not.

Thank You!

答:
```<code>public function services()
{
    return $this->belongsToMany('App\Service');
}
</code>```

Now, with such declaration of relationships Laravel “assumes” that pivot table name obeys the rules and is app_service.But, if it’s actually different (for example, it’s plural), you can provide it as a second parameter:

```<code> public function services()
  {
        return $this->belongsToMany('App\Service','app_services');
  }
</code>```

'app_services' is an intermediate table name

Moreover, you can specify the actual field names of that pivot table, if they are different than default app_id and service_id. Then just add two more parameters – first, the current model field, and then the field of the model being joined

```<code>public function services()
{
        return $this->belongsToMany('App\Service','app_services','app_id','service_id');
}
</code>```

Now,using this relationship you can retrieved data

```<code>$app = App::find($app_id);
$app->services();
</code>```

Body:
I have an intermediate table titled

app_services

It consists of the following columns :

app_service_id (PK)

app_id (FK)

service_id (FK)

The final table is the services table :

Services

service_id (PK)

service_name

service_icon

I am trying a hasManyThrough on app_services. But it's returning the wrong results..

For app_id = 1 it has the service id's of 1 & 3. But it is returning back the service_id's pf 1 & 4.

In my app_model I am defining the relationship as follows :

public function services()
{
    return $this->hasManyThrough(
        'App\Service', 'App\AppService',
        'service_id', 'service_id', 'app_id'
    );
}

Now that looks right to me? Would someone mine checking if it's correct or not.

Thank You!

Body:
public function services()
{
    return $this->belongsToMany('App\Service');
}

Now, with such declaration of relationships Laravel “assumes” that pivot table name obeys the rules and is app_service.But, if it’s actually different (for example, it’s plural), you can provide it as a second parameter:

 public function services()
  {
        return $this->belongsToMany('App\Service','app_services');
  }

'app_services' is an intermediate table name

Moreover, you can specify the actual field names of that pivot table, if they are different than default app_id and service_id. Then just add two more parameters – first, the current model field, and then the field of the model being joined

public function services()
{
        return $this->belongsToMany('App\Service','app_services','app_id','service_id');
}

Now,using this relationship you can retrieved data

$app = App::find($app_id);
$app->services();


问:
Stream OpenCV frame to HTML in Python
I am trying to read a video from a URL in opencv(Python) and then process it frame by frame and then send it to an HTML page.

But I am only getting the first frame, after that the program gives the following error

This is my main file (main.py)

```<code>from flask import Flask, render_template, Response
from camera import VideoCamera
import pdb
app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

def gen(camera):
    while True:
        frame = camera.get_frame()
        yield (b'--frame\r\n'
                b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')

@app.route('/video_feed')
def video_feed():
    return Response(gen(VideoCamera()),
                    mimetype='multipart/x-mixed-replace; boundary=frame')

if __name__ == '__main__':
    app.run(host='127.0.0.1', debug=True)
</code>```

And this is the camera.py file:

```<code>    import cv2
    import urllib
    import pdb
    import numpy as np

    face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
    #https://github.com/Itseez/opencv/blob/master/data/haarcascades/haarcascade_eye.xml
    eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')

    class VideoCamera(object):
        def __init__(self):
            # Using OpenCV to capture from device 0. If you have trouble capturing
            # from a webcam, comment the line below out and use a video file
            # instead.
            self.video = urllib.urlopen('http://192.168.10.12:8080/video')   #cv2.VideoCapture(0)
            # If you decide to use video.mp4, you must have this file in the folder
            # as the main.py.
            # self.video = cv2.VideoCapture('video.mp4')

        def __del__(self):
            self.video.release()

        def get_frame(self):

            bytes=''
            while True:
                # pdb.set_trace()
                bytes+=self.video.read(1024)
                a = bytes.find('\xff\xd8')
                b = bytes.find('\xff\xd9')
                if a!=-1 and b!=-1:
                    jpg = bytes[a:b+2]
                    bytes= bytes[b+2:]

                    img = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8),cv2.IMREAD_COLOR)
                    # pdb.set_trace()
                    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
                    faces = face_cascade.detectMultiScale(gray, 1.3, 5)
                    for (x,y,w,h) in faces:
                        cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
                        roi_gray = gray[y:y+h, x:x+w]
                        roi_color = img[y:y+h, x:x+w]

                    ret, jpeg = cv2.imencode('.jpg', img)
                    return jpeg.tobytes()
</code>```

I only get the first frame( Shown below):

答: Use small size for reading bytes in .read() function.</p>

Title: Stream OpenCV frame to HTML in Python

Body:
I am trying to read a video from a URL in opencv(Python) and then process it frame by frame and then send it to an HTML page.

But I am only getting the first frame, after that the program gives the following error

This is my main file (main.py)

from flask import Flask, render_template, Response
from camera import VideoCamera
import pdb
app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

def gen(camera):
    while True:
        frame = camera.get_frame()
        yield (b'--frame\r\n'
                b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')

@app.route('/video_feed')
def video_feed():
    return Response(gen(VideoCamera()),
                    mimetype='multipart/x-mixed-replace; boundary=frame')

if __name__ == '__main__':
    app.run(host='127.0.0.1', debug=True)

And this is the camera.py file:

    import cv2
    import urllib
    import pdb
    import numpy as np

    face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
    #https://github.com/Itseez/opencv/blob/master/data/haarcascades/haarcascade_eye.xml
    eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')

    class VideoCamera(object):
        def __init__(self):
            # Using OpenCV to capture from device 0. If you have trouble capturing
            # from a webcam, comment the line below out and use a video file
            # instead.
            self.video = urllib.urlopen('http://192.168.10.12:8080/video')   #cv2.VideoCapture(0)
            # If you decide to use video.mp4, you must have this file in the folder
            # as the main.py.
            # self.video = cv2.VideoCapture('video.mp4')

        def __del__(self):
            self.video.release()

        def get_frame(self):

            bytes=''
            while True:
                # pdb.set_trace()
                bytes+=self.video.read(1024)
                a = bytes.find('\xff\xd8')
                b = bytes.find('\xff\xd9')
                if a!=-1 and b!=-1:
                    jpg = bytes[a:b+2]
                    bytes= bytes[b+2:]

                    img = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8),cv2.IMREAD_COLOR)
                    # pdb.set_trace()
                    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
                    faces = face_cascade.detectMultiScale(gray, 1.3, 5)
                    for (x,y,w,h) in faces:
                        cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
                        roi_gray = gray[y:y+h, x:x+w]
                        roi_color = img[y:y+h, x:x+w]

                    ret, jpeg = cv2.imencode('.jpg', img)
                    return jpeg.tobytes()

I only get the first frame( Shown below):


问:
ASP.NET MVC 5 Plugin
Perdon me, this is not any problem, rather is asking help from you.

I am completely new to pluggable application.  I've not even think it before.

Currently I'm working in an SMS application which might have different gateways to send sms.

Among the gateways, right gateway is selected dynamically base on some criteria.

Different gateways require different url and data to send an SMS. i.e. -

```<code> //This is for one gateway
 xyz.com/SendTextMessage?Username=XX&Password=XX&From=XX&To=XX&Message=##

 //This is for one gateway
 abc.com?IN_MSG_ID=XX&MOBILENO=XX&BODY=XX&ORIGIN_PORT=XX
</code>```

For example, I need a plugin which is able to send sms -

```<code>void SendMessage()
{
     //Send via abc
}
</code>```

There may be another plugin which can send sms-

```<code>void SendMessage()
{
     //Send via xyz
}
</code>```

I can't figure out how I can prepare plugin for gateway without modifying the source code of main application.

May I have an idea from you?

答:
Please refer to some documentation about Factory Pattern. Here is one - https://www.tutorialspoint.com/design_pattern/factory_pattern.htm

Have an IMessageSender interface, which has a method SendMessage(), which takes a MessageObject parameter. MessageObject should have all the relevant details for sending the message. (From, To, Body etc)

Now, you can have different implementations of IMessageSender interface, each using its own gatway and other details.

```<code>ABCMessageSender : IMessageSender
{
   void SendMessage(MessageObject messageObject)
   {
      //Send via abc
   }
}

XYZMessageSender : IMessageSender
{
   void SendMessage(MessageObject messageObject)
   {
      //Send via xyz
   }
}
</code>```

Now, you create a factory interface and a factory class

```<code>public interface IMessageSenderFactory
{
    IMessageSender getMessageSender(MessageObject messageObject);
}
</code>```

and then have an implementation for that interface

```<code>public class MessageSenderFactory : IMessageSenderFactory  {

   //use getMessageSender method to get object of type MessageSender
   public IMessageSender getMessageSender(MessageObject messageObject){

  if(messageObject == null){
     return null;
  }
  if(messageObject.From.equalsIgnoreCase("Some condition")){
     return new ABCMessageSender();

  } else if(messageObject.Rate.equalsIgnoreCase("Some other condition")){
     return new XYZMessageSender();

  } //else if(some other condition){
     //return some other message sender
  //}

  return null;
}
}
</code>```

In the end, use the factory method above to get the appropriate instance of IMessageSender and invoke SendMessage() on it. If you use any of the dependency injection patterns, you can inject IMessageSenderFactory into your controller (or any other consuming class) and use it from there.

Title: ASP.NET MVC 5 Plugin

Body:
Perdon me, this is not any problem, rather is asking help from you.

I am completely new to pluggable application.  I've not even think it before.

Currently I'm working in an SMS application which might have different gateways to send sms.

Among the gateways, right gateway is selected dynamically base on some criteria.

Different gateways require different url and data to send an SMS. i.e. -

 //This is for one gateway
 xyz.com/SendTextMessage?Username=XX&Password=XX&From=XX&To=XX&Message=##

 //This is for one gateway
 abc.com?IN_MSG_ID=XX&MOBILENO=XX&BODY=XX&ORIGIN_PORT=XX

For example, I need a plugin which is able to send sms -

void SendMessage()
{
     //Send via abc
}

There may be another plugin which can send sms-

void SendMessage()
{
     //Send via xyz
}

I can't figure out how I can prepare plugin for gateway without modifying the source code of main application.

May I have an idea from you?

Body:
Please refer to some documentation about Factory Pattern. Here is one - https://www.tutorialspoint.com/design_pattern/factory_pattern.htm

Have an IMessageSender interface, which has a method SendMessage(), which takes a MessageObject parameter. MessageObject should have all the relevant details for sending the message. (From, To, Body etc)

Now, you can have different implementations of IMessageSender interface, each using its own gatway and other details.

ABCMessageSender : IMessageSender
{
   void SendMessage(MessageObject messageObject)
   {
      //Send via abc
   }
}

XYZMessageSender : IMessageSender
{
   void SendMessage(MessageObject messageObject)
   {
      //Send via xyz
   }
}

Now, you create a factory interface and a factory class

public interface IMessageSenderFactory
{
    IMessageSender getMessageSender(MessageObject messageObject);
}

and then have an implementation for that interface

public class MessageSenderFactory : IMessageSenderFactory  {

   //use getMessageSender method to get object of type MessageSender
   public IMessageSender getMessageSender(MessageObject messageObject){

  if(messageObject == null){
     return null;
  }
  if(messageObject.From.equalsIgnoreCase("Some condition")){
     return new ABCMessageSender();

  } else if(messageObject.Rate.equalsIgnoreCase("Some other condition")){
     return new XYZMessageSender();

  } //else if(some other condition){
     //return some other message sender
  //}

  return null;
}
}

In the end, use the factory method above to get the appropriate instance of IMessageSender and invoke SendMessage() on it. If you use any of the dependency injection patterns, you can inject IMessageSenderFactory into your controller (or any other consuming class) and use it from there.


问:
CakePHP 3 : Association property name clashes with field of same name of table
I am using CakePHP 3.2. I have two tables service_requests and coupon_history

service_requests table

```<code>CREATE TABLE `service_requests` (
  `id` char(36) NOT NULL,
  `request_id` bigint(20) NOT NULL,
  `user_id` char(36) NOT NULL,
  `user_address_id` char(36) NOT NULL,
  `service_id` char(36) NOT NULL,
  `service_area_id` char(36) NOT NULL,
  `coupon_used` int(11) NOT NULL DEFAULT '0' COMMENT '0: Not Applied; 1: Applied',
  `coupon_used_id` char(36) NOT NULL,
  `status_code` int(11) NOT NULL,
  `status` varchar(50) NOT NULL,
  `created` datetime NOT NULL,
  `modified` datetime NOT NULL
)
</code>```

coupon_history table

```<code>CREATE TABLE `coupon_history` (
  `id` char(36) NOT NULL,
  `user_id` char(36) NOT NULL,
  `coupon_id` char(36) NOT NULL,
  `service_request_id` char(36) DEFAULT NULL,
  `created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `modified` datetime NOT NULL
)
</code>```

When I bake service_requests table by

```<code>bin/cake bake all service_requests
</code>```

It Warning Error as

```<code>Association property name "coupon_used" clashes with field of same name of table "service_requests". You should explicitly specify the "propertyName" option. in [/var/www/html/flitfix/admin2/vendor/cakephp/cakephp/src/ORM/Association.php, line 445]

2016-07-01 07:17:32 Warning: Warning (512): Association property name "coupon_used" clashes with field of same name of table "service_requests". You should explicitly specify the "propertyName" option. in [/var/www/html/flitfix/admin2/vendor/cakephp/cakephp/src/ORM/Association.php, line 445]
Trace:
Cake\Error\BaseErrorHandler::handleError() - CORE/src/Error/BaseErrorHandler.php, line 146
Cake\ORM\Association::property() - CORE/src/ORM/Association.php, line 445
Bake\Utility\Model\AssociationFilter::filterAssociations() - ROOT/vendor/cakephp/bake/src/Utility/Model/AssociationFilter.php, line 94
Bake\Shell\Task\TemplateTask::_filteredAssociations() - ROOT/vendor/cakephp/bake/src/Shell/Task/TemplateTask.php, line 465
Bake\Shell\Task\TemplateTask::_loadController() - ROOT/vendor/cakephp/bake/src/Shell/Task/TemplateTask.php, line 295
Bake\Shell\Task\TemplateTask::main() - ROOT/vendor/cakephp/bake/src/Shell/Task/TemplateTask.php, line 147
Bake\Shell\BakeShell::Bake\Shell\{closure}() - ROOT/vendor/cakephp/bake/src/Shell/BakeShell.php, line 252
Cake\Collection\Collection::each() - CORE/src/Collection/CollectionTrait.php, line 51
Bake\Shell\BakeShell::all() - ROOT/vendor/cakephp/bake/src/Shell/BakeShell.php, line 253
Cake\Console\Shell::runCommand() - CORE/src/Console/Shell.php, line 444
Cake\Console\ShellDispatcher::_dispatch() - CORE/src/Console/ShellDispatcher.php, line 221
Cake\Console\ShellDispatcher::dispatch() - CORE/src/Console/ShellDispatcher.php, line 181
Cake\Console\ShellDispatcher::run() - CORE/src/Console/ShellDispatcher.php, line 127
[main] - ROOT/bin/cake.php, line 33
</code>```

Previously there was coupon_used table which I renamed to coupon_history and deleted all controller, model and template named coupon_used and trying to bake again coupon_history but it gives error.
I tried with a new project created by composer but in that too same error is there.

答:
Please refer below link. Property name to be defined like this.

```<code>$this->belongsTo('ProductPrices', [
    'foreignKey' => 'product_price_id',
    'className'  => 'ProductPrices',
    'propertyName' => 'prod_price'
]);
</code>```

http://www.cloudypoint.com/Tutorials/discussion/cake-framework-solved-cakephp-3-querybuilder-for-associative-data/

Body:
I am using CakePHP 3.2. I have two tables service_requests and coupon_history

service_requests table

CREATE TABLE `service_requests` (
  `id` char(36) NOT NULL,
  `request_id` bigint(20) NOT NULL,
  `user_id` char(36) NOT NULL,
  `user_address_id` char(36) NOT NULL,
  `service_id` char(36) NOT NULL,
  `service_area_id` char(36) NOT NULL,
  `coupon_used` int(11) NOT NULL DEFAULT '0' COMMENT '0: Not Applied; 1: Applied',
  `coupon_used_id` char(36) NOT NULL,
  `status_code` int(11) NOT NULL,
  `status` varchar(50) NOT NULL,
  `created` datetime NOT NULL,
  `modified` datetime NOT NULL
)

coupon_history table

CREATE TABLE `coupon_history` (
  `id` char(36) NOT NULL,
  `user_id` char(36) NOT NULL,
  `coupon_id` char(36) NOT NULL,
  `service_request_id` char(36) DEFAULT NULL,
  `created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `modified` datetime NOT NULL
)

When I bake service_requests table by

bin/cake bake all service_requests

It Warning Error as

Association property name "coupon_used" clashes with field of same name of table "service_requests". You should explicitly specify the "propertyName" option. in [/var/www/html/flitfix/admin2/vendor/cakephp/cakephp/src/ORM/Association.php, line 445]

2016-07-01 07:17:32 Warning: Warning (512): Association property name "coupon_used" clashes with field of same name of table "service_requests". You should explicitly specify the "propertyName" option. in [/var/www/html/flitfix/admin2/vendor/cakephp/cakephp/src/ORM/Association.php, line 445]
Trace:
Cake\Error\BaseErrorHandler::handleError() - CORE/src/Error/BaseErrorHandler.php, line 146
Cake\ORM\Association::property() - CORE/src/ORM/Association.php, line 445
Bake\Utility\Model\AssociationFilter::filterAssociations() - ROOT/vendor/cakephp/bake/src/Utility/Model/AssociationFilter.php, line 94
Bake\Shell\Task\TemplateTask::_filteredAssociations() - ROOT/vendor/cakephp/bake/src/Shell/Task/TemplateTask.php, line 465
Bake\Shell\Task\TemplateTask::_loadController() - ROOT/vendor/cakephp/bake/src/Shell/Task/TemplateTask.php, line 295
Bake\Shell\Task\TemplateTask::main() - ROOT/vendor/cakephp/bake/src/Shell/Task/TemplateTask.php, line 147
Bake\Shell\BakeShell::Bake\Shell\{closure}() - ROOT/vendor/cakephp/bake/src/Shell/BakeShell.php, line 252
Cake\Collection\Collection::each() - CORE/src/Collection/CollectionTrait.php, line 51
Bake\Shell\BakeShell::all() - ROOT/vendor/cakephp/bake/src/Shell/BakeShell.php, line 253
Cake\Console\Shell::runCommand() - CORE/src/Console/Shell.php, line 444
Cake\Console\ShellDispatcher::_dispatch() - CORE/src/Console/ShellDispatcher.php, line 221
Cake\Console\ShellDispatcher::dispatch() - CORE/src/Console/ShellDispatcher.php, line 181
Cake\Console\ShellDispatcher::run() - CORE/src/Console/ShellDispatcher.php, line 127
[main] - ROOT/bin/cake.php, line 33

Previously there was coupon_used table which I renamed to coupon_history and deleted all controller, model and template named coupon_used and trying to bake again coupon_history but it gives error.
I tried with a new project created by composer but in that too same error is there.

Body:
Please refer below link. Property name to be defined like this.

$this->belongsTo('ProductPrices', [
    'foreignKey' => 'product_price_id',
    'className'  => 'ProductPrices',
    'propertyName' => 'prod_price'
]);

http://www.cloudypoint.com/Tutorials/discussion/cake-framework-solved-cakephp-3-querybuilder-for-associative-data/


问:
Adding one ui file into another
Suppose i have designer files with there respective classes say form.ui , form.h , form.cpp and myclass.ui , myclass.h , myclass,cpp . Now what i want is 2 different things .
Now i have a widget and a layout in the myclass.ui file and i now using addLayout function i add the form.ui file into it . Now i want it so that whole of the form.ui file content should come into small layout space by self adjusting . But that is not happening . So how could i achieve that

答:
QUILoader is your solution but maybe not the best, specially if you have custom actions & functions for your form.ui in your form.h & form.cpp. The easiest way its to promote a widget inside your widget and then make it not visible. When you have to show it, you can just change the hidden state.

In another case, you can create it dynamically and manage the memory by yourself.

Title: Adding one ui file into another


问:
I need a background program C++
I have created this program:

```<code>//Includes....
int main()
{
   ifstream readfile("File.txt");
   string str;
   while(1)
   {
      getline(readfile,str);
      system("cls");
      Sleep(10000);
   }
}
</code>```

It's just a program that reads every 10 seconds a line from the file "File.txt"

I want to make it work on background,how can I do that?

答: The proper way is to use a Windows service, there is enough information on Google on how to do this.</p>

OwnerDisplayName: Tal

LastEditorDisplayName: peSHIr

ContentLicense: CC BY-SA 2.5

Title: I need a background program C++

Body:
I have created this program:

//Includes....
int main()
{
   ifstream readfile("File.txt");
   string str;
   while(1)
   {
      getline(readfile,str);
      system("cls");
      Sleep(10000);
   }
}

It's just a program that reads every 10 seconds a line from the file "File.txt"

I want to make it work on background,how can I do that?

OwnerDisplayName: TomWij


问:
Invalid Resx file. Could not load type error why?
I'm getting designer error on code:

The Component i'm willing to define a List of properties for:

```<code>using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;

namespace TestProjectForProperty.Test
{
    public class MyTreeView : TreeView
    {
        private List<TypeDescriptorBase> _descriptorsAvailable = new List<TypeDescriptorBase>();

        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public List<TypeDescriptorBase> DescriptorsAvailable
        {
            get { return _descriptorsAvailable; }
            set { _descriptorsAvailable = value; }
        }
    }
}
</code>```

The Descriptor itself:

```<code>using System;

namespace TestProjectForProperty.Test
{
    [Serializable]
    public class TypeDescriptorBase
    {
        public string Name { get; set; }

        public override string ToString()
        {
            return Name;
        }
    }
}
</code>```

I am getting the following error if i try to use the component for example on a form and add any items on the property sheet or in the component's constructor to the DescriptorsAvailable property

Error 1   Invalid Resx file. Could not load type
  System.Collections.Generic.List`1[[TestProjectForProperty.Test.TypeDescriptorBase,
  TestProjectForProperty, Version=1.0.0.0, Culture=neutral,
  PublicKeyToken=null]], mscorlib, Version=4.0.0.0, Culture=neutral,
  PublicKeyToken=b77a5c561934e089 which is used in the .RESX file.
  Ensure that the necessary references have been added to your project.
  Line 134, position 5. ...\visual studio
  2010\Projects\TestProjectForProperty\TestProjectForProperty\Form1.resx    134 5   TestProjectForProperty

In the Resx file there is data field with base64 encoded stuff inside when this error is present.

I have been searching for an answer, but the best i got is to restart everything, it didn't help me, do you guys have any suggestions? I'm using .net 4 client and visual studio 2010

答:
For me, this error occured when I used a custom class as a property for the user control. When I switched from property to traditional get- and set- methods, the error disappeared. I guess this is because properties are already compiled at design-time, so when you build the whole project, a new version of the custom class is compiled which is separate from the one of the control, and the reference is broken.

For me, with the custom class Inventory, all I had to do was to switch from this property-based approach:

```<code>public Inventory Resources {get;set;}
</code>```

to this method-based approach:

```<code>private Inventory resources;
public Inventory getResources() { return resources; }
public void setResources(Inventory newResources) { resources = newResources; }
</code>```

I hope this helps someone, as I've been spending some hours on figuring it out.

Body:
I'm getting designer error on code:

The Component i'm willing to define a List of properties for:

using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;

namespace TestProjectForProperty.Test
{
    public class MyTreeView : TreeView
    {
        private List<TypeDescriptorBase> _descriptorsAvailable = new List<TypeDescriptorBase>();

        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public List<TypeDescriptorBase> DescriptorsAvailable
        {
            get { return _descriptorsAvailable; }
            set { _descriptorsAvailable = value; }
        }
    }
}

The Descriptor itself:

using System;

namespace TestProjectForProperty.Test
{
    [Serializable]
    public class TypeDescriptorBase
    {
        public string Name { get; set; }

        public override string ToString()
        {
            return Name;
        }
    }
}

I am getting the following error if i try to use the component for example on a form and add any items on the property sheet or in the component's constructor to the DescriptorsAvailable property

Error 1   Invalid Resx file. Could not load type
  System.Collections.Generic.List`1[[TestProjectForProperty.Test.TypeDescriptorBase,
  TestProjectForProperty, Version=1.0.0.0, Culture=neutral,
  PublicKeyToken=null]], mscorlib, Version=4.0.0.0, Culture=neutral,
  PublicKeyToken=b77a5c561934e089 which is used in the .RESX file.
  Ensure that the necessary references have been added to your project.
  Line 134, position 5. ...\visual studio
  2010\Projects\TestProjectForProperty\TestProjectForProperty\Form1.resx    134 5   TestProjectForProperty

In the Resx file there is data field with base64 encoded stuff inside when this error is present.

I have been searching for an answer, but the best i got is to restart everything, it didn't help me, do you guys have any suggestions? I'm using .net 4 client and visual studio 2010

Body:
For me, this error occured when I used a custom class as a property for the user control. When I switched from property to traditional get- and set- methods, the error disappeared. I guess this is because properties are already compiled at design-time, so when you build the whole project, a new version of the custom class is compiled which is separate from the one of the control, and the reference is broken.

For me, with the custom class Inventory, all I had to do was to switch from this property-based approach:

public Inventory Resources {get;set;}

to this method-based approach:

private Inventory resources;
public Inventory getResources() { return resources; }
public void setResources(Inventory newResources) { resources = newResources; }

I hope this helps someone, as I've been spending some hours on figuring it out.


问:
Neo4jClient - How to check if property exists
I'm having trouble converting the following Cypher query to the Neo4jClient syntax.

MATCH n
WHERE NOT (HAS (n.User)) OR n.User = "username"
RETURN n

This is what I currently have with the addition of some relationship logic and the omission of the HAS logic

```<code>var results = Client.Cypher
               .OptionalMatch("(result)-[connection:Connection]-(result2)")
               .Where((Result result) => result.User == username)
               .Return((result, connection, result2) => new Neo4jResultSingle()
               {
                   SearchedNode = result.As<Node<Result>>(),
                   RelationshipConnection = connection.As<RelationshipInstance<Connection>>(),
                   Relationship = connection.As<RelationshipInstance<ConnectionRelationship>>(),
                   RelationshipedNode = result2.As<Node<Result>>()
               }).Results.ToList();
</code>```

答:
HAS was superseded by EXISTS()

From the latest docs: Property existence checking

```<code>MATCH (n) WHERE EXISTS(n.User) RETURN n
</code>```

for opposite match add NOT before

```<code>MATCH (n) WHERE NOT EXISTS(n.User) RETURN n
</code>```

Body:
I'm having trouble converting the following Cypher query to the Neo4jClient syntax.

MATCH n
WHERE NOT (HAS (n.User)) OR n.User = "username"
RETURN n

This is what I currently have with the addition of some relationship logic and the omission of the HAS logic

var results = Client.Cypher
               .OptionalMatch("(result)-[connection:Connection]-(result2)")
               .Where((Result result) => result.User == username)
               .Return((result, connection, result2) => new Neo4jResultSingle()
               {
                   SearchedNode = result.As<Node<Result>>(),
                   RelationshipConnection = connection.As<RelationshipInstance<Connection>>(),
                   Relationship = connection.As<RelationshipInstance<ConnectionRelationship>>(),
                   RelationshipedNode = result2.As<Node<Result>>()
               }).Results.ToList();

Body:
HAS was superseded by EXISTS()

From the latest docs: Property existence checking

MATCH (n) WHERE EXISTS(n.User) RETURN n

for opposite match add NOT before

MATCH (n) WHERE NOT EXISTS(n.User) RETURN n


问:
python incorrectly calculates number
So, this was in my exam paper and I was really confused

```<code>def num_input():
    num1 = input("num1: ")
    num2 = input("num2: ")
    num1 = int(num2)*2.5
    num2 = int(num1)*1.5
    print("num1:", num1, "num2:", num2)

num_input()
</code>```

say that num1 = 60, and num2 = 18, shouldn't the new numbers be:

```<code>num1: 45
num2: 90
</code>```

but why is the output:

```<code>num1: 45
num2: 67.5
</code>```

?

答:
Well, when you calculate

```<code>num1 = int(num2)*2.5
</code>```

the value of 'int(num2)*2.5' is assigned to num1. At this stage, num1 has a new value which is the evaluation of the above result and its not 60 anymore.

Change your code to this instead:

```<code>def num_input():
    num1 = input("num1: ")
    num2 = input("num2: ")
    value1 = int(num2)*2.5
    value2 = int(num1)*1.5
    print("num1:", value1, "num2:", value2)

num_input()
</code>```

Title: python incorrectly calculates number

Body:
So, this was in my exam paper and I was really confused

def num_input():
    num1 = input("num1: ")
    num2 = input("num2: ")
    num1 = int(num2)*2.5
    num2 = int(num1)*1.5
    print("num1:", num1, "num2:", num2)

num_input()

say that num1 = 60, and num2 = 18, shouldn't the new numbers be:

num1: 45
num2: 90

but why is the output:

num1: 45
num2: 67.5

?

Body:
Well, when you calculate

num1 = int(num2)*2.5

the value of 'int(num2)*2.5' is assigned to num1. At this stage, num1 has a new value which is the evaluation of the above result and its not 60 anymore.

Change your code to this instead:

def num_input():
    num1 = input("num1: ")
    num2 = input("num2: ")
    value1 = int(num2)*2.5
    value2 = int(num1)*1.5
    print("num1:", value1, "num2:", value2)

num_input()


问:
Bind drag function to object in Tkinter UI
I'm trying to write a solitaire playing program - mainly to explore how to use a mouse to move objects in a GUI using Tkinter. I find the following code allows the user to move a card around a window with the mouse:

```<code>from tkinter import *
window = Tk()
window.state('zoomed')
window.configure(bg = 'green4')

def drag(event):
    card.place(x=event.x_root, y=event.y_root,anchor=CENTER)

card = Canvas(window, width=74, height=97, bg='blue')
card.place(x=300, y=600,anchor=CENTER)
card.bind("<B1-Motion>", drag)

window.mainloop()
</code>```

However if I add another card, as in:

```<code>another_card = Canvas(window, width=74, height=97, bg='red')
another_card.place(x=600, y=600,anchor=CENTER)
another_card.bind("<B1-Motion>", drag)
</code>```

Clicking this card will only move the first card. When I try to modify the drag function, as in:

```<code>def drag(event, card):
    card.place(x=event.x_root, y=event.y_root,anchor=CENTER)
</code>```

and

```<code>another_card.bind("<B1-Motion>", drag(event, another_card))
</code>```

I get 'too many arguments' or "name 'event' is not defined" errors. As I am eventually going to have up to 52 cards on the screen I can't write a separate drag function for each one. Is it possible to write a generic 'drag' code that could be bound to any object ?

PS in this example I have just used a blank canvas. However I have gifs for 52 playing cards that I will (hopefully) be moving around the GUI in the game itself.

答:
The problem is that you are hardcoding a reference to the first card in your drag() function.

```<code>from tkinter import *
window = Tk()
window.state('zoomed')
window.configure(bg = 'green4')

def drag(event):
    event.widget.place(x=event.x_root, y=event.y_root,anchor=CENTER)

card = Canvas(window, width=74, height=97, bg='blue')
card.place(x=300, y=600,anchor=CENTER)
card.bind("<B1-Motion>", drag)

another_card = Canvas(window, width=74, height=97, bg='red')
another_card.place(x=600, y=600,anchor=CENTER)
another_card.bind("<B1-Motion>", drag)

window.mainloop()
</code>```

By using event.widget, you always get the widget (Canvas) that generated the event.

Body:
I'm trying to write a solitaire playing program - mainly to explore how to use a mouse to move objects in a GUI using Tkinter. I find the following code allows the user to move a card around a window with the mouse:

from tkinter import *
window = Tk()
window.state('zoomed')
window.configure(bg = 'green4')

def drag(event):
    card.place(x=event.x_root, y=event.y_root,anchor=CENTER)

card = Canvas(window, width=74, height=97, bg='blue')
card.place(x=300, y=600,anchor=CENTER)
card.bind("<B1-Motion>", drag)

window.mainloop()

However if I add another card, as in:

another_card = Canvas(window, width=74, height=97, bg='red')
another_card.place(x=600, y=600,anchor=CENTER)
another_card.bind("<B1-Motion>", drag)

Clicking this card will only move the first card. When I try to modify the drag function, as in:

def drag(event, card):
    card.place(x=event.x_root, y=event.y_root,anchor=CENTER)

and

another_card.bind("<B1-Motion>", drag(event, another_card))

I get 'too many arguments' or "name 'event' is not defined" errors. As I am eventually going to have up to 52 cards on the screen I can't write a separate drag function for each one. Is it possible to write a generic 'drag' code that could be bound to any object ?

PS in this example I have just used a blank canvas. However I have gifs for 52 playing cards that I will (hopefully) be moving around the GUI in the game itself.

Body:
The problem is that you are hardcoding a reference to the first card in your drag() function.

from tkinter import *
window = Tk()
window.state('zoomed')
window.configure(bg = 'green4')

def drag(event):
    event.widget.place(x=event.x_root, y=event.y_root,anchor=CENTER)

card = Canvas(window, width=74, height=97, bg='blue')
card.place(x=300, y=600,anchor=CENTER)
card.bind("<B1-Motion>", drag)

another_card = Canvas(window, width=74, height=97, bg='red')
another_card.place(x=600, y=600,anchor=CENTER)
another_card.bind("<B1-Motion>", drag)

window.mainloop()

By using event.widget, you always get the widget (Canvas) that generated the event.

ContentLicense: CC BY-SA 4.0


问:
Javascript regex insensitive turkish character issue
i'm using regex for filtering some contents.

```<code>var word = new RegExp(filterWord,"gi");// "gi" means Global and insensitive
content = content.replace(word, "");//removes "word" from content
</code>```

This code works properly but when regex get uppercase "İ" it dont replace word.

ex:
if

```<code>filterWord = istanbul
</code>```

and

```<code>content = "İstanbul";
</code>```

Above code not working properly , if i write istanbul to İstanbul ,it is working but this time it is not insensitive , how can i solve this problem ?

答:
you can express lower and upper cases in a bracket

/[İi]stanbul/i

you can see from here

Body:
i'm using regex for filtering some contents.

var word = new RegExp(filterWord,"gi");// "gi" means Global and insensitive
content = content.replace(word, "");//removes "word" from content

This code works properly but when regex get uppercase "İ" it dont replace word.

ex:
if

filterWord = istanbul

and

content = "İstanbul";

Above code not working properly , if i write istanbul to İstanbul ,it is working but this time it is not insensitive , how can i solve this problem ?


问:
Regular expression: if three letters are included
I've got a number of word:
hello, poison, world, search, echo ...
And I've got some letters e, h, o
Now I need to find all words that includes this letters. Like search, echo for e, h, o

I can search this way:

```<code>words = %w[hello poison world search echo]
matched = words.select do |w|
  %w[e,h,o].all?{ |l| w =~ /#{l}/ }
end
</code>```

The problem is that if letters are o, o, o, or l, b, l this search will return true for words like open or boil, but I need to search words that includes three of o or two of l and one b

upd:

```<code>leters = "abc"
words.select{ |w| w.count(letters) >= 3 }
</code>```

upd 2

Bad solution, example:

```<code>"lllllll".count("lua") #=> 5
</code>```

答:
Are you sure you want a regexp? Strings support counting values in them, you could use that feature. Something like this: </p>

```<code>words = ["pool", "tool", "troll", "lot"]
letters = "olo"

#find how many of each letter we need
counts = {}
letters.each { |v| counts[v] = letters.count(v) }

#See if a given work matches all the counts
# accumulated above
res = words.select do |w|
  counts.keys.inject(true) do |match, letter|
      match && (w.count(letter) == counts[letter])
  end
end
</code>```

Body:
I've got a number of word:
hello, poison, world, search, echo ...
And I've got some letters e, h, o
Now I need to find all words that includes this letters. Like search, echo for e, h, o

I can search this way:

words = %w[hello poison world search echo]
matched = words.select do |w|
  %w[e,h,o].all?{ |l| w =~ /#{l}/ }
end

The problem is that if letters are o, o, o, or l, b, l this search will return true for words like open or boil, but I need to search words that includes three of o or two of l and one b

upd:

leters = "abc"
words.select{ |w| w.count(letters) >= 3 }

upd 2

Bad solution, example:

"lllllll".count("lua") #=> 5

Body:
Are you sure you want a regexp? Strings support counting values in them, you could use that feature. Something like this:

words = ["pool", "tool", "troll", "lot"]
letters = "olo"

#find how many of each letter we need
counts = {}
letters.each { |v| counts[v] = letters.count(v) }

#See if a given work matches all the counts
# accumulated above
res = words.select do |w|
  counts.keys.inject(true) do |match, letter|
      match && (w.count(letter) == counts[letter])
  end
end


问:
Javascript regex matching syntax not working
I would like to test a string to ensure it has the following pattern:

```<code>asas/asas2/asas
</code>```

The charatcers in between the slashes can be letters, digits or both.

I have a working example here, although i'm sure it could be improved.

Regex Example

But when tested in jsfiddle it doesn't work

Jsfiddle Example

```<code>var str = 'dfdfdf/dfdf/dfdf';
var patt = new RegExp("/(^\w+\/\w+\/\w+$)/g");
var res = patt.test(str);
alert(res);
</code>```

The above code example always returns false.

答:
Please try this code:

```<code>var str = 'dfdfdf/dfdf/dfdf';
var patt = new RegExp(/(^\w+\/\w+\/\w+$)/g);
var res = patt.test(str);
alert(res);
console.log(res);
</code>```

Thanks

Body:
I would like to test a string to ensure it has the following pattern:

asas/asas2/asas

The charatcers in between the slashes can be letters, digits or both.

I have a working example here, although i'm sure it could be improved.

Regex Example

But when tested in jsfiddle it doesn't work

Jsfiddle Example

var str = 'dfdfdf/dfdf/dfdf';
var patt = new RegExp("/(^\w+\/\w+\/\w+$)/g");
var res = patt.test(str);
alert(res);

The above code example always returns false.

Body:
Please try this code:

var str = 'dfdfdf/dfdf/dfdf';
var patt = new RegExp(/(^\w+\/\w+\/\w+$)/g);
var res = patt.test(str);
alert(res);
console.log(res);

Thanks


问:
Does Android really exist on other platforms than ARM?
I want to port an aplication written in C++ to android. Converting the application from C++ to Java will take a lot of work that I would prefer to use on making the application better for that platform instead of fixing convertion bugs and solving refactoring problems.

The NDK seems a good route to take but actually I don't want to miss a platform(if it is a considerable % of the market) just because the NDK doesn't or won't support it.

Android claims to support MIPS, ARM, X86 and others ... but actually all the implementations I have seen are only on ARM (or arm compatible).
I checked that on this site:
http://www.pdadb.net/

Would it be a bad desision to use the NDK?

Are there any non ARM devices that run or will run Android?

Where can I find more information about this?

Thanks in advance!

答:
The documentation gives the following:</p>

```<code>The latest release of the NDK supports these ARM instruction sets:

ARMv5TE (including Thumb-1 instructions)
ARMv7-A (including Thumb-2 and VFPv3-D16 instructions, with optional support for     NEON/VFPv3-D32 instructions)

Future releases of the NDK will also support:

x86 instructions (see CPU-ARCH-ABIS.HTML for more information)
</code>```

Body:
The documentation gives the following:

The latest release of the NDK supports these ARM instruction sets:

ARMv5TE (including Thumb-1 instructions)
ARMv7-A (including Thumb-2 and VFPv3-D16 instructions, with optional support for     NEON/VFPv3-D32 instructions)

Future releases of the NDK will also support:

x86 instructions (see CPU-ARCH-ABIS.HTML for more information)


问:
PopupWindow how to change icon and background programmatically?
Have is xml file for PopupWindow:

How to programmatically replace the icon and Backgroud in this xml?

答:
You can change the background by using
  LinearLayout ll=(LinearLayout) findViewById(R.id.linear);
ll.setBackground(...);```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>ImageView i=popUpwindow.findViewById(R.id.image1);

i.setImageResource(id here);
or
i.setImageDrawable(Drawable here);</code>```

Body:
You can change the background by using
  LinearLayout ll=(LinearLayout) findViewById(R.id.linear);
ll.setBackground(...);

ImageView i=popUpwindow.findViewById(R.id.image1);

i.setImageResource(id here);
or
i.setImageDrawable(Drawable here);


问:
Error creating topic in Apache Kafka
When using the command:

/usr/local/kafka/bin/kafka-topics.sh --create --zookeeper localhost:2181
  --replication-factor 1 --partitions 1 --topic test

I get the following error:

```<code>Unrecognized option: --create
Error: Could not create the Java Virtual Machine
Error: A fatal exception has occurred. Program will exit.
</code>```

I am following the instructions in the Kafka: The Definitive Guide book.

Thanks in advance.

答:
You should check whether you have downloaded the correct (compiled) version.

This may happen if you are trying to run the script in the source code version.

Title: Error creating topic in Apache Kafka

Body:
When using the command:

/usr/local/kafka/bin/kafka-topics.sh --create --zookeeper localhost:2181
  --replication-factor 1 --partitions 1 --topic test

I get the following error:

Unrecognized option: --create
Error: Could not create the Java Virtual Machine
Error: A fatal exception has occurred. Program will exit.

I am following the instructions in the Kafka: The Definitive Guide book.

Thanks in advance.


问:
3 div's middle div take up remaining width
Alright guys, I've been busting my balls over this one.

I've got three divs; left, middle, right. All 100% height. The left and right div have a fixed width of 150px. Now I want the middle div to take up the remaining space.

Example: Here

CSS:

```<code>#left {
    height:100%;
    width:150px;
    float:left;
    background:red;
    z-index:999;
}
#middle {
    height:100%;
    width:100%;
    background:yellow;
    margin-left:-150px;
    margin-right:-150px;
}
#right {
    float:right;
    height:100%;
    width:150px;
    background:red;
    z-index:998;
}
</code>```

答:
If you don't want to use table cells and don't want to give your outer boxes a fixed width (instead let their width be determined by their content, you can use the overflow-hidden and float method)

The bad thing about this method is you have to adhere to having overflow hidden on your divs and also you have to arrange your divs in a backwards way (see below)

DEMO

HTML

```<code><div class='container'>

    <div class='third-box'>Third</div>

    <div class='first-second'>
        <div class='first-box'>First</div>
        <div class='second-box'>Second</div>
    </div>

</div>
</code>```

CSS

```<code>.container {
     width: 400px;
}

.first-second {
    overflow: hidden;
}

.first-box {
    float: left;
    background-color: coral;
}

.second-box {
    overflow: hidden;
    background-color: aquamarine;
}

.third-box {
    float: right;
    background-color: salmon;
}
</code>```

Body:
Alright guys, I've been busting my balls over this one.

I've got three divs; left, middle, right. All 100% height. The left and right div have a fixed width of 150px. Now I want the middle div to take up the remaining space.

Example: Here

CSS:

#left {
    height:100%;
    width:150px;
    float:left;
    background:red;
    z-index:999;
}
#middle {
    height:100%;
    width:100%;
    background:yellow;
    margin-left:-150px;
    margin-right:-150px;
}
#right {
    float:right;
    height:100%;
    width:150px;
    background:red;
    z-index:998;
}

Body:
If you don't want to use table cells and don't want to give your outer boxes a fixed width (instead let their width be determined by their content, you can use the overflow-hidden and float method)

The bad thing about this method is you have to adhere to having overflow hidden on your divs and also you have to arrange your divs in a backwards way (see below)

DEMO

HTML

<div class='container'>

    <div class='third-box'>Third</div>

    <div class='first-second'>
        <div class='first-box'>First</div>
        <div class='second-box'>Second</div>
    </div>

</div>

CSS

.container {
     width: 400px;
}

.first-second {
    overflow: hidden;
}

.first-box {
    float: left;
    background-color: coral;
}

.second-box {
    overflow: hidden;
    background-color: aquamarine;
}

.third-box {
    float: right;
    background-color: salmon;
}


问:
How to read data one by one from excel sheet in node.js
I want to read some URLS from excel sheet and also some json payloads how to do it in node.js?</p>

答:
```<code>var spread_sheet = require('spread_sheet');

var row = "1,2,Jack,Pirate";  // If you want to add row.

var filePath = '/home/Pranjal/Desktop/test.xlsx';

var sheetName = "Sheet1";

var from_row  = 2;

var to_row = 6;

/*
spread_sheet.addRow(row,filePath,sheetName,function(err,result){

console.log(err,result)

})
*/

/*

spread_sheet.getRows(filePath,sheetName,from_row,to_row,function(err,result){

console.log(err,result)

*/
</code>```


问:
How to build a layout of single line and multi line labels in iOS autolayout?
I have an application in swift,and have encountered an autolayout issue. I've come up with the solution to it, but it doesn't seem to work as expected.

So, here's the issue:
I have two labels in a table view cell. The first one should only have one line, and the second one must have as many lines as needed and take up as much vertical space as needed. The first label should always be shown fully and, therefore, determine the position, the size, and the number of lines of the second label. Texts for both are set programmatically when drawing the cell, of course.

The solution seems to be pretty simple: Anchor the first label to the left, center it vertically, anchor the second label to the parent top, right, bottom and the right side of the first one. Set the number of lines to 0 for the second label. The editor shows no warnings or errors.

This is how it looks like:

In most cases it looks good, like on the picture below, but sometimes not (red arrows at the picture below):

The first label should have absolute priority and never be truncated, wrapped, or cut, but this happens. What am I doing wrong?

UPD: For the question to be more clear, the first label is so called 'margin label', it represents the margin and the indicator of the cell. This is done to imitate a tree structure. The second is, of course, the text itself. '>' is for the closed comment, 'v' is for the opened.

答: Increase the content compression resistance priority of the first label. If needed increase the horizontal content hugging priority of the second label.</p>


问:
Verify mock interactions within anonymous inner class
I am trying to test my ViewModel in my application, here is the constructor:

```<code>@Inject
public SearchUserViewModel(@Named("searchUser") UseCase searchUserUseCase) {
  this.searchUserUseCase = searchUserUseCase;
}
</code>```

In my test I create a SearchUserUseCase with mocks like this:

```<code>Observable error = Observable.error(new Throwable("Error"));
when(gitHubService.searchUser(MockFactory.TEST_USERNAME_ERROR)).thenReturn(error);

when(ObserverThread.getScheduler()).thenReturn(Schedulers.immediate());
when(SubscriberThread.getScheduler()).thenReturn(Schedulers.immediate());

searchUserUseCase = new SearchUserUseCase(gitHubService, SubscriberThread, ObserverThread);
</code>```

In my ViewModel class I have this snippet which I want to test:

```<code>public void onClickSearch(View view) {
  loadUsers();
}

private void loadUsers() {
  if (username == null) {
    fragmentListener.showMessage("Enter a username");
  } else {
    showProgressIndicator(true);
    searchUserUseCase.execute(new SearchUserSubscriber(), username);
  }
}

private final class SearchUserSubscriber extends DefaultSubscriber<SearchResponse> {

  @Override
  public void onCompleted() {
    showProgressIndicator(false);
  }

  @Override
  public void onError(Throwable e) {
    showProgressIndicator(false);
    fragmentListener.showMessage("Error loading users");
  }

  @Override
  public void onNext(SearchResponse searchResponse) {
    List<User> users = searchResponse.getUsers();
    if (users.isEmpty()) {
      fragmentListener.showMessage("No users found");
    } else {
      fragmentListener.addUsers(users);
    }
  }

}
</code>```

Finally in my test I have this:

```<code>@Test
public void shouldDisplayErrorMessageIfErrorWhenLoadingUsers() {
  SearchUserViewModel searchUserViewModel = new SearchUserViewModel(searchUserUseCase);
  searchUserViewModel.setFragmentListener(mockFragmentListener);
  searchUserViewModel.setUsername(MockFactory.TEST_USERNAME_ERROR);
  searchUserViewModel.onClickSearch(view);
  verify(mockFragmentListener).showMessage("Error loading users");
}
</code>```

I get this error from Mockito:

```<code>Wanted but not invoked:
fragmentListener.showMessage(
  "Error loading users"
);
</code>```

I am not sure if this is a good test, but I somehow want to test the SearchUserSubscriber one way or another. Thanks

Edit: I have found similar questions to this problem here: Can't verify mock method call from RxJava Subscriber (which still isn't answered) and here: Verify interactions in rxjava subscribers. The latter question is similar but does not execute the subscriber in a separate class (which happens in SearchUserUseCase here).

I also tried RobolectricGradleTestRunner instead of MockitoJunitRunner and changed to Schedulers.io() and AndroidSchedulers.mainThread(), but I still get the same error.

Tried mocking SearchUserUseCase instead of GitHubService (which feels cleaner), but I'm not sure on how to test the subscriber that way since that is passed as an argument to the void method execute() in UseCase.

```<code>public void execute(Subscriber useCaseSubscriber, String query) {
  subscription = buildUseCase(query)
    .observeOn(postExecutionThread.getScheduler())
    .subscribeOn(threadExecutor.getScheduler())
    .subscribe(useCaseSubscriber);
}
</code>```

And buildUseCase()

```<code>@Override
public Observable buildUseCase(String username) throws NullPointerException {
  if (username == null) {
    throw new NullPointerException("Query must not be null");
  }
  return getGitHubService().searchUser(username);
}
</code>```

答:
For me it worked out to add a Observable.Transformer<T, T> as followed:

```<code>void gatherData() {
    service.doSomeMagic()
      .compose(getSchedulerTransformer())
      .subscribe(view::displayValue);
}

private <T> Observable.Transformer<T, T> getSchedulerTransformer() {
    if (mTransformer == null) {
        mTransformer = (Observable.Transformer<T, T>) observable -> observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }

    return mTransformer;
}

void setSchedulerTransformer(Observable.Transformer<Observable<?>, Observable<?>> transformer) {
    mTransformer = transformer;
}
</code>```

And to set the Transformer. I just passed this:

```<code>setSchedulerTransformer(observable -> {
    if (observable instanceof Observable) {
        Observable observable1 = (Observable) observable;
        return observable1.subscribeOn(Schedulers.immediate())
                .observeOn(Schedulers.immediate());
    }
    return null;
});
</code>```

So just add a @Before method in your test and call presenter.setSchedulerTransformer and it should be able to test this. If you want more detail check this answer.

Body:
I am trying to test my ViewModel in my application, here is the constructor:

@Inject
public SearchUserViewModel(@Named("searchUser") UseCase searchUserUseCase) {
  this.searchUserUseCase = searchUserUseCase;
}

In my test I create a SearchUserUseCase with mocks like this:

Observable error = Observable.error(new Throwable("Error"));
when(gitHubService.searchUser(MockFactory.TEST_USERNAME_ERROR)).thenReturn(error);

when(ObserverThread.getScheduler()).thenReturn(Schedulers.immediate());
when(SubscriberThread.getScheduler()).thenReturn(Schedulers.immediate());

searchUserUseCase = new SearchUserUseCase(gitHubService, SubscriberThread, ObserverThread);

In my ViewModel class I have this snippet which I want to test:

public void onClickSearch(View view) {
  loadUsers();
}

private void loadUsers() {
  if (username == null) {
    fragmentListener.showMessage("Enter a username");
  } else {
    showProgressIndicator(true);
    searchUserUseCase.execute(new SearchUserSubscriber(), username);
  }
}

private final class SearchUserSubscriber extends DefaultSubscriber<SearchResponse> {

  @Override
  public void onCompleted() {
    showProgressIndicator(false);
  }

  @Override
  public void onError(Throwable e) {
    showProgressIndicator(false);
    fragmentListener.showMessage("Error loading users");
  }

  @Override
  public void onNext(SearchResponse searchResponse) {
    List<User> users = searchResponse.getUsers();
    if (users.isEmpty()) {
      fragmentListener.showMessage("No users found");
    } else {
      fragmentListener.addUsers(users);
    }
  }

}

Finally in my test I have this:

@Test
public void shouldDisplayErrorMessageIfErrorWhenLoadingUsers() {
  SearchUserViewModel searchUserViewModel = new SearchUserViewModel(searchUserUseCase);
  searchUserViewModel.setFragmentListener(mockFragmentListener);
  searchUserViewModel.setUsername(MockFactory.TEST_USERNAME_ERROR);
  searchUserViewModel.onClickSearch(view);
  verify(mockFragmentListener).showMessage("Error loading users");
}

I get this error from Mockito:

Wanted but not invoked:
fragmentListener.showMessage(
  "Error loading users"
);

I am not sure if this is a good test, but I somehow want to test the SearchUserSubscriber one way or another. Thanks

Edit: I have found similar questions to this problem here: Can't verify mock method call from RxJava Subscriber (which still isn't answered) and here: Verify interactions in rxjava subscribers. The latter question is similar but does not execute the subscriber in a separate class (which happens in SearchUserUseCase here).

I also tried RobolectricGradleTestRunner instead of MockitoJunitRunner and changed to Schedulers.io() and AndroidSchedulers.mainThread(), but I still get the same error.

Tried mocking SearchUserUseCase instead of GitHubService (which feels cleaner), but I'm not sure on how to test the subscriber that way since that is passed as an argument to the void method execute() in UseCase.

public void execute(Subscriber useCaseSubscriber, String query) {
  subscription = buildUseCase(query)
    .observeOn(postExecutionThread.getScheduler())
    .subscribeOn(threadExecutor.getScheduler())
    .subscribe(useCaseSubscriber);
}

And buildUseCase()

@Override
public Observable buildUseCase(String username) throws NullPointerException {
  if (username == null) {
    throw new NullPointerException("Query must not be null");
  }
  return getGitHubService().searchUser(username);
}

Body:
For me it worked out to add a Observable.Transformer<T, T> as followed:

void gatherData() {
    service.doSomeMagic()
      .compose(getSchedulerTransformer())
      .subscribe(view::displayValue);
}

private <T> Observable.Transformer<T, T> getSchedulerTransformer() {
    if (mTransformer == null) {
        mTransformer = (Observable.Transformer<T, T>) observable -> observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }

    return mTransformer;
}

void setSchedulerTransformer(Observable.Transformer<Observable<?>, Observable<?>> transformer) {
    mTransformer = transformer;
}

And to set the Transformer. I just passed this:

setSchedulerTransformer(observable -> {
    if (observable instanceof Observable) {
        Observable observable1 = (Observable) observable;
        return observable1.subscribeOn(Schedulers.immediate())
                .observeOn(Schedulers.immediate());
    }
    return null;
});

So just add a @Before method in your test and call presenter.setSchedulerTransformer and it should be able to test this. If you want more detail check this answer.


问:
Thread wait on file input pattern
What's the normal pattern for a thread to wait for file input in C# when it reaches end of file and
 needs to wait. Any particularly way of coding it, which is neat and elegant.

Thanks.
 Bob.

答: Not really a pattern but the FileSystemWatcher (http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx) might come in handy.

Title: Thread wait on file input pattern


问:
Any way to declare an array in-line?
Let's say I have a method m() that takes an array of Strings as an argument.  Is there a way I can just declare this array in-line when I make the call?  i.e. Instead of:

```<code>String[] strs = {"blah", "hey", "yo"};
m(strs);
</code>```

Can I just replace this with one line, and avoid declaring a named variable that I'm never going to use?

答:
You can create a method somewhere

```<code>public static <T> T[] toArray(T... ts) {
    return ts;
}
</code>```

then use it

```<code>m(toArray("blah", "hey", "yo"));
</code>```

for better look.

Title: Any way to declare an array in-line?

Body:
Let's say I have a method m() that takes an array of Strings as an argument.  Is there a way I can just declare this array in-line when I make the call?  i.e. Instead of:

String[] strs = {"blah", "hey", "yo"};
m(strs);

Can I just replace this with one line, and avoid declaring a named variable that I'm never going to use?

Body:
You can create a method somewhere

public static <T> T[] toArray(T... ts) {
    return ts;
}

then use it

m(toArray("blah", "hey", "yo"));

for better look.


问:
Index Error: list index out of range (Python), numbering correct
I am aware that this question has been asked multiple times before, however I have double checked the numbering and the error is still appearing. I was wondering whether there was anything else obvious I have missed.

```<code>with open('imagefile.csv', newline='') as csvfile:
    imagelog = csv.reader(csvfile, delimiter=',', quotechar='|')
    for row in imagelog:
        if row[0] == 'IMG' and row[2].endswith('.RAW'):
            gpsAndAtt.append({ 'label': 'IMG', 'timeMS': float(row[1]), 'file': row[2]})
</code>```

The error comes at the 4th line of the above code. However the .csv file as below, 3 columns. Or according to Python, 0,1,2

IMG,330985,033.RAW

  IMG,332985,034.JPG

  IMG,343985,035.RAW

The code is designed to strip out elements of the .csv for use with another file.

Thanks in advance.

EDIT

sorted empty lines issue in original question (poor formatting on stack)

答:
Not the "answer", since on the face of it, there should be no error, but where you have potentially erroneous input, you ought to have a "guard" on your returned 'row', since you are accessing row[2].
(By all means flag/display the offending row, for diagnostic purposes !)

Hence:

```<code>for row in imagelog:
  if len(row) >= 2:
      ...
</code>```

Body:
I am aware that this question has been asked multiple times before, however I have double checked the numbering and the error is still appearing. I was wondering whether there was anything else obvious I have missed.

with open('imagefile.csv', newline='') as csvfile:
    imagelog = csv.reader(csvfile, delimiter=',', quotechar='|')
    for row in imagelog:
        if row[0] == 'IMG' and row[2].endswith('.RAW'):
            gpsAndAtt.append({ 'label': 'IMG', 'timeMS': float(row[1]), 'file': row[2]})

The error comes at the 4th line of the above code. However the .csv file as below, 3 columns. Or according to Python, 0,1,2

IMG,330985,033.RAW

  IMG,332985,034.JPG

  IMG,343985,035.RAW

The code is designed to strip out elements of the .csv for use with another file.

Thanks in advance.

EDIT

sorted empty lines issue in original question (poor formatting on stack)

Body:
Not the "answer", since on the face of it, there should be no error, but where you have potentially erroneous input, you ought to have a "guard" on your returned 'row', since you are accessing row[2].
(By all means flag/display the offending row, for diagnostic purposes !)

Hence:

for row in imagelog:
  if len(row) >= 2:
      ...


问:
How to call an api from another api in expressjs?
I have an api like this:

```<code>app.get('/test', (req, res) => {
   console.log("this is test");
});
</code>```

and another api:

```<code>app.get('/check', (req, res) => {
   //I want to call "test" api without redirect to it.
});
</code>```

I want to call "test" api in "check" api without redirect to "test" api, just do the function in the "test" api.
Above is the example code. 'Cause I dont' want to rewrite function from "test" api to "check"

答:
Create a common middleware which need to executed for both the routes.

Below is the code snippet for the same:

```<code>app.get('/test', test);
app.get('/check', check, test);
</code>```

check and test are the middlewares which is used in common.

Body:
I have an api like this:

app.get('/test', (req, res) => {
   console.log("this is test");
});

and another api:

app.get('/check', (req, res) => {
   //I want to call "test" api without redirect to it.
});

I want to call "test" api in "check" api without redirect to "test" api, just do the function in the "test" api.
Above is the example code. 'Cause I dont' want to rewrite function from "test" api to "check"

Body:
Create a common middleware which need to executed for both the routes.

Below is the code snippet for the same:

app.get('/test', test);
app.get('/check', check, test);

check and test are the middlewares which is used in common.