问:
p_threads: Condition Variable Locking
Let's say I had 4 threads, a producer and three consumers, a single mutex and a single condition variable, every consumer runs the same function that does the below:

```<code>mutexlock(mutex)
signal[i] = 1;
while(signal[i] == 1) {
condwait(cond, mutex)
}
mutexunlock(mutex)
</code>```

And the producer does the below

```<code>if(signal == 1)
{
set 0 - atomically using CAS
mutexlock(mutex)
condbroadcast(cond)
mutexunlock(mutex)
}
</code>```

Let's say if more than one consumer were in that lock, wouldn't they fight for the cond variable? Should I create one for each thread or can p_thread condition variables be shared accross multiple threads without any race conditions?

答:
Semantic of pthread_cond_wait is to release acquired mutex and block on conditional variable. When signal arrives, block is released, then pthread_cond_wait acquires the lock on mutex.

So, in your case, when you use pthread_cond_broadcast all threads blocked on conditional will move past this point, but after that one of them will be granted lock on mutex. Which one? It depends on the order the scheduler wakes them up after being unblocked and the pthread implementation in case two or more threads try to acquire the lock at the some moment. It's safe to consider it's random.

If you replace pthread_cond_broadcast with pthread_cond_signal, the signal will be delivered to some threads. Yes, it is expected to be one, but sometimes more than one can be released from conditional variable. Still, the thread (or threads) to deliver signal to will be chosen by scheduler. And if more than one is waked up from cond waiting, they will fight for the mutex. As previously - you can consider the result as random.

Let's look into documentation:

If more than one thread is blocked on a condition variable, the scheduling policy shall determine the order in which threads are unblocked.

On a multi-processor, it may be impossible for an implementation of pthread_cond_signal() to avoid the unblocking of more than one thread blocked on a condition variable.

BTW, I am quite curious. There are several questions about conditional variables recently (are you guys all doing a project for your uni or what?) and in every question I have seen in last 24 hours I have seen a following pattern for signalling:

```<code>pthread_mutex_lock(&mutex);
pthread_cond_broadcast(&cond); /* or signal */
pthread_mutex_unlock(&mutex);
</code>```

when waiting threads have:

```<code>pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond,&mutex);
/* do something */
pthread_mutex_unlock(&mutex);
</code>```

What's the reason behind that?

Waiting threads wait on cond, mutex is released. So signalling thread acquires lock on mutex, signals other threads. In this very moment they - still being inside the pthread_cond_wait progress past the cond blockade, then they try to acquire the lock on mutex. And, of course, they cannot, because the lock is hold by signalling thread. Then, signalling thread releases mutex and waiting threads can finally process by acquiring - one by one - the mutex.

For signalling writer and waiting consumers this pattern should be as below.

For writer:

```<code>while(loop_condition) {
    prepare_data() /* it could be a long process */
    lock(&mutex);
    add_data_to_queue(); /* fast, inside critical section */
    unlock(&mutex);
    signal(&cond); /* or broadcast */
}
</code>```

For consumers:

```<code>while(consumer_loop_condition) {
    lock(&mutex);
    while(!data_ready_to_process()) {
        wait(&cond,&mutex);
    }
    fetch_data(); /* fast, still inside critical section */
    unlock(&mutex);
    if(got_data) {
        process_data(); /* could be a long process */
    }
}
</code>```

Please see also this answer for some more explanation on cond/mutexes and some example code to play with.

Title: p_threads: Condition Variable Locking

Body:
Let's say I had 4 threads, a producer and three consumers, a single mutex and a single condition variable, every consumer runs the same function that does the below:

mutexlock(mutex)
signal[i] = 1;
while(signal[i] == 1) {
condwait(cond, mutex)
}
mutexunlock(mutex)

And the producer does the below

if(signal == 1)
{
set 0 - atomically using CAS
mutexlock(mutex)
condbroadcast(cond)
mutexunlock(mutex)
}

Let's say if more than one consumer were in that lock, wouldn't they fight for the cond variable? Should I create one for each thread or can p_thread condition variables be shared accross multiple threads without any race conditions?

Body:
Semantic of pthread_cond_wait is to release acquired mutex and block on conditional variable. When signal arrives, block is released, then pthread_cond_wait acquires the lock on mutex.

So, in your case, when you use pthread_cond_broadcast all threads blocked on conditional will move past this point, but after that one of them will be granted lock on mutex. Which one? It depends on the order the scheduler wakes them up after being unblocked and the pthread implementation in case two or more threads try to acquire the lock at the some moment. It's safe to consider it's random.

If you replace pthread_cond_broadcast with pthread_cond_signal, the signal will be delivered to some threads. Yes, it is expected to be one, but sometimes more than one can be released from conditional variable. Still, the thread (or threads) to deliver signal to will be chosen by scheduler. And if more than one is waked up from cond waiting, they will fight for the mutex. As previously - you can consider the result as random.

Let's look into documentation:

If more than one thread is blocked on a condition variable, the scheduling policy shall determine the order in which threads are unblocked.

On a multi-processor, it may be impossible for an implementation of pthread_cond_signal() to avoid the unblocking of more than one thread blocked on a condition variable.

BTW, I am quite curious. There are several questions about conditional variables recently (are you guys all doing a project for your uni or what?) and in every question I have seen in last 24 hours I have seen a following pattern for signalling:

pthread_mutex_lock(&mutex);
pthread_cond_broadcast(&cond); /* or signal */
pthread_mutex_unlock(&mutex);

when waiting threads have:

pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond,&mutex);
/* do something */
pthread_mutex_unlock(&mutex);

What's the reason behind that?

Waiting threads wait on cond, mutex is released. So signalling thread acquires lock on mutex, signals other threads. In this very moment they - still being inside the pthread_cond_wait progress past the cond blockade, then they try to acquire the lock on mutex. And, of course, they cannot, because the lock is hold by signalling thread. Then, signalling thread releases mutex and waiting threads can finally process by acquiring - one by one - the mutex.

For signalling writer and waiting consumers this pattern should be as below.

For writer:

while(loop_condition) {
    prepare_data() /* it could be a long process */
    lock(&mutex);
    add_data_to_queue(); /* fast, inside critical section */
    unlock(&mutex);
    signal(&cond); /* or broadcast */
}

For consumers:

while(consumer_loop_condition) {
    lock(&mutex);
    while(!data_ready_to_process()) {
        wait(&cond,&mutex);
    }
    fetch_data(); /* fast, still inside critical section */
    unlock(&mutex);
    if(got_data) {
        process_data(); /* could be a long process */
    }
}

Please see also this answer for some more explanation on cond/mutexes and some example code to play with.


来源: stackexchange

问:
How to efficiently build a tree from a flat structure?
I have a bunch of objects in a flat structure. These objects have an ID and a ParentID property so they can be arranged in trees. They are in no particular order.
Each ParentID property does not necessarily matches with an ID in the structure. Therefore their could be several trees emerging from these objects.

How would you process these objects to create the resulting trees ?

I'm not so far from a solution but I'm sure it is far from optimal...

I need to create these trees to then insert Data into a database, in proper order.

There are no circular references. A Node is a RootNode when ParentID == null or when ParentID can't be found in the other objects

答:
Vague as the question seems to me, I would probably create a map from the ID to the actual object. In pseudo-java (I didn't check whether it works/compiles), it might be something like:

```<code>Map<ID, FlatObject> flatObjectMap = new HashMap<ID, FlatObject>();

for (FlatObject object: flatStructure) {
    flatObjectMap.put(object.ID, object);
}
</code>```

And to look up each parent:

```<code>private FlatObject getParent(FlatObject object) {
    getRealObject(object.ParentID);
}

private FlatObject getRealObject(ID objectID) {
    flatObjectMap.get(objectID);
}
</code>```

By reusing getRealObject(ID) and doing a map from object to a collection of objects (or their IDs), you get a parent->children map too.

OwnerDisplayName: Costo

ContentLicense: CC BY-SA 3.0

LastEditorDisplayName: Costo

Body:
Vague as the question seems to me, I would probably create a map from the ID to the actual object. In pseudo-java (I didn't check whether it works/compiles), it might be something like:

Map<ID, FlatObject> flatObjectMap = new HashMap<ID, FlatObject>();

for (FlatObject object: flatStructure) {
    flatObjectMap.put(object.ID, object);
}

And to look up each parent:

private FlatObject getParent(FlatObject object) {
    getRealObject(object.ParentID);
}

private FlatObject getRealObject(ID objectID) {
    flatObjectMap.get(objectID);
}

By reusing getRealObject(ID) and doing a map from object to a collection of objects (or their IDs), you get a parent->children map too.

OwnerDisplayName: wolfie

ContentLicense: CC BY-SA 2.5


问:
How do I convert a derived recursive data type to a base data type?
I have a class called nesteddict derived from collections.defaultdict that hold a nested set of dictionaries:

```<code>import collections

class nesteddict(collections.defaultdict):
    """Nested dictionary structure.

    Based on Stack Overflow question 635483
    """
    def __init__(self):
        collections.defaultdict.__init__(self, nesteddict)
        self.locked = False
</code>```

I would like to be able to perform an operation an instance that converts all of the nesteddict objects to python-native dict objects.

One way to do this is to have a method:

```<code>def todict(self):
    for (key,val) in self.iteritems():
        if isinstance(val,nesteddict):
            val.todict()
            self[key] = dict(val)
    self = dict(self)
</code>```

This is successful at replacing all the inner mapping objects with dict types, but the last statement in the method is obviously not going to work.

Here is an example:

```<code>In [93]: a = pyutils.nesteddict()

In [94]: a[1][1] = 'a'

In [95]: a[1][2] = 'b'

In [96]: a[2][1] = 'c'

In [97]: a[2][2] = 'd'

In [98]: print a
defaultdict(<class 'pyutils.nesteddict'>, {1: defaultdict(<class 'pyutils.nesteddict'>, {1: 'a', 2: 'b'}), 2: defaultdict(<class 'pyutils.nesteddict'>, {1: 'c', 2: 'd'})})

In [99]: a.todict()

In [100]: print a
defaultdict(<class 'pyutils.nesteddict'>, {1: {1: 'a', 2: 'b'}, 2: {1: 'c', 2: 'd'}})
</code>```

Is there a way to do this in python?  Have a method that converts its object to another type?  If not, what is a good alternative to this.  Note that the datatype in practice may be large, so it would be preferable not to just make a copy and then return it.

Thanks!

Uri

答: dict(a) will give you a default dict from any object that derives from defaultdict.  That is, assuming you havn't overridden the required special methods.

Body:
I have a class called nesteddict derived from collections.defaultdict that hold a nested set of dictionaries:

import collections

class nesteddict(collections.defaultdict):
    """Nested dictionary structure.

    Based on Stack Overflow question 635483
    """
    def __init__(self):
        collections.defaultdict.__init__(self, nesteddict)
        self.locked = False

I would like to be able to perform an operation an instance that converts all of the nesteddict objects to python-native dict objects.

One way to do this is to have a method:

def todict(self):
    for (key,val) in self.iteritems():
        if isinstance(val,nesteddict):
            val.todict()
            self[key] = dict(val)
    self = dict(self)

This is successful at replacing all the inner mapping objects with dict types, but the last statement in the method is obviously not going to work.

Here is an example:

In [93]: a = pyutils.nesteddict()

In [94]: a[1][1] = 'a'

In [95]: a[1][2] = 'b'

In [96]: a[2][1] = 'c'

In [97]: a[2][2] = 'd'

In [98]: print a
defaultdict(<class 'pyutils.nesteddict'>, {1: defaultdict(<class 'pyutils.nesteddict'>, {1: 'a', 2: 'b'}), 2: defaultdict(<class 'pyutils.nesteddict'>, {1: 'c', 2: 'd'})})

In [99]: a.todict()

In [100]: print a
defaultdict(<class 'pyutils.nesteddict'>, {1: {1: 'a', 2: 'b'}, 2: {1: 'c', 2: 'd'}})

Is there a way to do this in python?  Have a method that converts its object to another type?  If not, what is a good alternative to this.  Note that the datatype in practice may be large, so it would be preferable not to just make a copy and then return it.

Thanks!

Uri


问:
Groovy literal regex /\\/ is not compiling
I have a path in Windows:

```<code>assert f.toString() == 'C:\\path\\to\\some\\dir'
</code>```

I need to convert the backslashes \ to forward slashes /. Using Java syntax, I would write:

```<code>assert f.toString().replaceAll('\\\\', '/') == 'C:/path/to/some/dir'
</code>```

But I am studying Groovy, so I thought I would write a literal regular expression:

```<code>assert f.toString().replaceAll(/\\/, '/') == 'C:/path/to/some/dir'
</code>```

This throws a compilation error:

unexpected token: ) ==  at line: 4, column: 42

I started looking on the internet, and found several comments suggesting that this particular regex literal would not work, instead you would have to use a workaround like /\\+/. But this obviously changes the semantics of the regex.

I cannot really understand why /\\/ does not work. Maybe somebody does?

答:
The \ at the end of the slashy string ruins it.

The main point is that you need to separate the \ from the / trailing slashy string delimiter.

It can be done in several ways:

```<code>println(f.replaceAll('\\\\', '/'))   // Using a single-quoted string literal with 4 backslashes, Java style
println(f.replaceAll(/[\\]/, '/'))   // Wrapping the backslash with character class
println(f.replaceAll(/\\{1}/, '/'))  // Using a {1} limiting quantifier
println(f.replaceAll(/\\(?:)/, '/')) // Using an empty group after it
</code>```

See the Groovy demo.

However, you may use dollar slashy strings to use the backslash at the end of the string:

```<code>f.replaceAll($/\\/$, '/')
</code>```

See the demo and check this thread:

Slashy strings: backslash escapes end of line chars and slash, $ escapes interpolated variables/closures, can't have backslash as last character, empty string not allowed. Examples: def a_backslash_b = /a\b/; def a_slash_b = /a\/b/;

Dollar slashy strings: backslash escapes only EOL, $ escapes interpolated variables/closures and itself if required and slash if required, use $$ to have $ as last character or to have a $ before an identifier or curly brace or slash, use $/ to have a slash before a $, empty string not allowed. Examples: def a_backslash_b = $/a\b/$; def a_slash_b = $/a/b/$; def a_dollar_b = $/a$$b/$;

Body:
I have a path in Windows:

assert f.toString() == 'C:\\path\\to\\some\\dir'

I need to convert the backslashes \ to forward slashes /. Using Java syntax, I would write:

assert f.toString().replaceAll('\\\\', '/') == 'C:/path/to/some/dir'

But I am studying Groovy, so I thought I would write a literal regular expression:

assert f.toString().replaceAll(/\\/, '/') == 'C:/path/to/some/dir'

This throws a compilation error:

unexpected token: ) ==  at line: 4, column: 42

I started looking on the internet, and found several comments suggesting that this particular regex literal would not work, instead you would have to use a workaround like /\\+/. But this obviously changes the semantics of the regex.

I cannot really understand why /\\/ does not work. Maybe somebody does?

Body:
The \ at the end of the slashy string ruins it.

The main point is that you need to separate the \ from the / trailing slashy string delimiter.

It can be done in several ways:

println(f.replaceAll('\\\\', '/'))   // Using a single-quoted string literal with 4 backslashes, Java style
println(f.replaceAll(/[\\]/, '/'))   // Wrapping the backslash with character class
println(f.replaceAll(/\\{1}/, '/'))  // Using a {1} limiting quantifier
println(f.replaceAll(/\\(?:)/, '/')) // Using an empty group after it

See the Groovy demo.

However, you may use dollar slashy strings to use the backslash at the end of the string:

f.replaceAll($/\\/$, '/')

See the demo and check this thread:

Slashy strings: backslash escapes end of line chars and slash, $ escapes interpolated variables/closures, can't have backslash as last character, empty string not allowed. Examples: def a_backslash_b = /a\b/; def a_slash_b = /a\/b/;

Dollar slashy strings: backslash escapes only EOL, $ escapes interpolated variables/closures and itself if required and slash if required, use $$ to have $ as last character or to have a $ before an identifier or curly brace or slash, use $/ to have a slash before a $, empty string not allowed. Examples: def a_backslash_b = $/a\b/$; def a_slash_b = $/a/b/$; def a_dollar_b = $/a$$b/$;


问:
Android - SQlite check if value in row exists
This question is similar to this and this.

I have 4 columns in my database (id, name, surname, image). I only want to check if the name that is being entered already exists in "name" column.

here is my SQLiteOpenHelper:

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

public SQLiteHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
    super(context, name, factory, version);
}

public void queryData(String sql){
    SQLiteDatabase database = getWritableDatabase();
    database.execSQL(sql);
}

@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {

}

public void insertData(String name, String surname, byte[] image){
    SQLiteDatabase database = getWritableDatabase();
    String sql = "INSERT INTO STUDENTS VALUES (NULL, ?, ?, ?)";

    SQLiteStatement statement = database.compileStatement(sql);
    statement.clearBindings();

    statement.bindString(1, name);
    statement.bindString(2, surname);
    statement.bindBlob(3, image);

    statement.executeInsert();

}

@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

}

/*public void removeSingleContact(String name, String price, byte[] image) {

    SQLiteDatabase dbb = getWritableDatabase();
    dbb.delete(name, surname, image);

}*/

public Cursor getData(String sql){
    SQLiteDatabase database = getReadableDatabase();
    return database.rawQuery(sql, null);
}

}
</code>```

and this is how I add to SQlite;

```<code>public class AddEditStudent extends AppCompatActivity {

    public static SQLiteHelper sqLiteHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addedit_student);

        sqLiteHelper = new SQLiteHelper(this, "StudentsDB.sqlite", null, 1);

        sqLiteHelper.queryData("CREATE TABLE IF NOT EXISTS STUDENTS(Id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, surname VARCHAR, image BLOB)");

            btnAdd.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View view) {

                        if (edtName.getText().toString().trim().length() == 0) {
                            Toast.makeText(getApplicationContext(), "Please provide your students name", Toast.LENGTH_SHORT).show();

                        } else
                            try {

                                    //THIS IS WHERE I WANT TO CHECK---------

                                    sqLiteHelper.insertData(
                                            edtName.getText().toString().trim(),
                                            edtPrice.getText().toString().trim(),
                                            imageViewToByte(imageView)

                                    );

                                        Toast.makeText(getApplicationContext(), "Added successfully!", Toast.LENGTH_SHORT).show();

                                        finish();
                                    }

                                }
                            } catch (Exception e) {
                            e.printStackTrace();
                            }

                    }
                });
</code>```

EDIT----
Thank you for the help so far. I have 2 buttons, one for update and one for insert, the problem I am facing is how will I know what row to update without using an ID. I have a gridview that is being populated by cardviews, in the cardview there is a button to edit info, please see image.

https://i.stack.imgur.com/aFJTl.png

If I click on the exit sign I do;

```<code>holder.dit.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // Do something
                Intent editintent = new Intent(context, AddEditStudent.class);
                editintent.putExtra("studentname", finalHolder.txtName.getText().toString());
                editintent.putExtra("studentsurname", finalHolder.txtPrice.getText().toString());

                context.startActivity(editintent);
            }
        });
</code>```

then in AddEditStudent Class is where the insert and update is.

答:
Update you Insert Query

```<code>    String name = edtName.getText().toString().trim();
        String query = "Select * From STUDENTS where name = '"+name+"'";
        if(sqLiteHelper.getData(query).getCount()>0){
            Toast.makeText(getApplicationContext(), "Already Exist!", Toast.LENGTH_SHORT).show();
        }else{
            sqLiteHelper.insertData(
                    name,
                    edtPrice.getText().toString().trim(),
                    imageViewToByte(imageView)

            );
Toast.makeText(getApplicationContext(), "Added successfully!", Toast.LENGTH_SHORT).show();

        }
</code>```

Body:
This question is similar to this and this.

I have 4 columns in my database (id, name, surname, image). I only want to check if the name that is being entered already exists in "name" column.

here is my SQLiteOpenHelper:

public class SQLiteHelper extends SQLiteOpenHelper {

public SQLiteHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
    super(context, name, factory, version);
}

public void queryData(String sql){
    SQLiteDatabase database = getWritableDatabase();
    database.execSQL(sql);
}

@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {

}

public void insertData(String name, String surname, byte[] image){
    SQLiteDatabase database = getWritableDatabase();
    String sql = "INSERT INTO STUDENTS VALUES (NULL, ?, ?, ?)";

    SQLiteStatement statement = database.compileStatement(sql);
    statement.clearBindings();

    statement.bindString(1, name);
    statement.bindString(2, surname);
    statement.bindBlob(3, image);

    statement.executeInsert();

}

@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

}

/*public void removeSingleContact(String name, String price, byte[] image) {

    SQLiteDatabase dbb = getWritableDatabase();
    dbb.delete(name, surname, image);

}*/

public Cursor getData(String sql){
    SQLiteDatabase database = getReadableDatabase();
    return database.rawQuery(sql, null);
}

}

and this is how I add to SQlite;

public class AddEditStudent extends AppCompatActivity {

    public static SQLiteHelper sqLiteHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addedit_student);

        sqLiteHelper = new SQLiteHelper(this, "StudentsDB.sqlite", null, 1);

        sqLiteHelper.queryData("CREATE TABLE IF NOT EXISTS STUDENTS(Id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, surname VARCHAR, image BLOB)");

            btnAdd.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View view) {

                        if (edtName.getText().toString().trim().length() == 0) {
                            Toast.makeText(getApplicationContext(), "Please provide your students name", Toast.LENGTH_SHORT).show();

                        } else
                            try {

                                    //THIS IS WHERE I WANT TO CHECK---------

                                    sqLiteHelper.insertData(
                                            edtName.getText().toString().trim(),
                                            edtPrice.getText().toString().trim(),
                                            imageViewToByte(imageView)

                                    );

                                        Toast.makeText(getApplicationContext(), "Added successfully!", Toast.LENGTH_SHORT).show();

                                        finish();
                                    }

                                }
                            } catch (Exception e) {
                            e.printStackTrace();
                            }

                    }
                });

EDIT----
Thank you for the help so far. I have 2 buttons, one for update and one for insert, the problem I am facing is how will I know what row to update without using an ID. I have a gridview that is being populated by cardviews, in the cardview there is a button to edit info, please see image.

https://i.stack.imgur.com/aFJTl.png

If I click on the exit sign I do;

holder.dit.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // Do something
                Intent editintent = new Intent(context, AddEditStudent.class);
                editintent.putExtra("studentname", finalHolder.txtName.getText().toString());
                editintent.putExtra("studentsurname", finalHolder.txtPrice.getText().toString());

                context.startActivity(editintent);
            }
        });

then in AddEditStudent Class is where the insert and update is.

Body:
Update you Insert Query

    String name = edtName.getText().toString().trim();
        String query = "Select * From STUDENTS where name = '"+name+"'";
        if(sqLiteHelper.getData(query).getCount()>0){
            Toast.makeText(getApplicationContext(), "Already Exist!", Toast.LENGTH_SHORT).show();
        }else{
            sqLiteHelper.insertData(
                    name,
                    edtPrice.getText().toString().trim(),
                    imageViewToByte(imageView)

            );
Toast.makeText(getApplicationContext(), "Added successfully!", Toast.LENGTH_SHORT).show();

        }


问:
How should I use blobs in a Caffe Python layer, and when does their training take place?
I am creating a network using Caffe, for which I need to define my own layer. I would like to use the Python layer for this.

My layer will contain some learned parameters. From this answer, I am told that I will need to create a blob vector for this.

Is there any specification that this blob will need to follow, such
as constraints in dimensions, etc.? Irrespective of what my layer
does, can I create a blob of one dimension, and use any element, one
each, of the blob for any computation in the layer?

What does the diff of a blob mean? From what I understand, the diff of bottom is the gradient at the current layer, and top for the previous layer. However, what exactly is happening here?

When do these parameters get trained? Does this need to be done manually in the layer definition?

I have seen the examples in test_python_layer.py, but most of them do not have any parameters.

答:
You can add as many internal parameters as you wish, and these parameters (Blobs) may have whatever shape you want them to be.

To add Blobs (in your layer's class):

```<code>def setup(self, bottom, top):
  self.blobs.add_blob(2) # add two blobs
  self.blobs[0].reshape(3, 4)  # first blob is 2D
  self.blobs[0].data[...] = 0 # init
  self.blobs[1].reshape(10)  # second blob is 1D with 10 elements
  self.blobs[1].data[...] = 1 # init to 1
</code>```

What is the "meaning" of each parameter and how to organize them in self.blobs is entirely up to you.

How are trainable parameters being "trained"?

This is one of the cool things about caffe (and other DNN toolkits as well), you don't need to worry about it!

What do you need to do? All you need is to compute the gradient of the loss w.r.t the parameters and store it in self.blobs[i].diff. Once the gradients are updated, caffe's internals takes care of updating the parameters according to the gradients/learning rate/momentum/update policy etc.

So,

You must have a non-trivial backward method for your layer

```<code>backward(self, top, propagate_down, bottom):
  self.blobs[0].diff[...] = # diff of parameters
  self.blobs[1].diff[...] = # diff for all the blobs
</code>```

You might want to test your implementation of the layer, once you complete it.

Have a look at this PR for a numerical test of the gradients.

Body:
You can add as many internal parameters as you wish, and these parameters (Blobs) may have whatever shape you want them to be.

To add Blobs (in your layer's class):

def setup(self, bottom, top):
  self.blobs.add_blob(2) # add two blobs
  self.blobs[0].reshape(3, 4)  # first blob is 2D
  self.blobs[0].data[...] = 0 # init
  self.blobs[1].reshape(10)  # second blob is 1D with 10 elements
  self.blobs[1].data[...] = 1 # init to 1

What is the "meaning" of each parameter and how to organize them in self.blobs is entirely up to you.

How are trainable parameters being "trained"?

This is one of the cool things about caffe (and other DNN toolkits as well), you don't need to worry about it!

What do you need to do? All you need is to compute the gradient of the loss w.r.t the parameters and store it in self.blobs[i].diff. Once the gradients are updated, caffe's internals takes care of updating the parameters according to the gradients/learning rate/momentum/update policy etc.

So,

You must have a non-trivial backward method for your layer

backward(self, top, propagate_down, bottom):
  self.blobs[0].diff[...] = # diff of parameters
  self.blobs[1].diff[...] = # diff for all the blobs

You might want to test your implementation of the layer, once you complete it.

Have a look at this PR for a numerical test of the gradients.


问:
Pseudoelement selector for inserting icon inside of another element
I would like to use some pseudo-element selector (:before, :after) for including a text or icon on :hover inside some other element. Is there a way how to do that only with pseudo-element selectors? I would like to NOT actually change the content of that element as it's content is loaded from localStorage.

My vision is to visually add some click-able icon (✗, ) when hovering over the header.

```<code><header contenteditable="true" id="title" onkeyup="store(this.id);"></header>
</code>```

Thank you for your suggestions.

答:
i guess you wanted something like this ?

you can also use fontAwesome in the after element or a background-image.

header {
 height:100px;
 width:100px;
 position:relative;
 background:Red;
}
header:after {
 content:"X";
 position:absolute;
 right:0;
 top:0;
 color:#fff;
 transition:0.3s ease-out;
 opacity:0;
}
header:hover:after {
 opacity:1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header contenteditable="true" id="title" onkeyup="store(this.id);"></header></code>```

option2. using plain Javascript

added the fontAwesome icon using javascript ( beforeend = inserted right before the end of the header tag -> you can use beforebegin,afterbegin,beforeend,afterend see more here insertAdjacentHTML )

then, you can add a click event on the previously added icon. ( here i am toggling the class of header changing it's color )

let me know if it helps

var newElem = document.getElementById("title");

newElem.insertAdjacentHTML('beforeend', ' ');

document.getElementById("clickme").onclick = function() {

  newElem.classList.toggle('blue');
};```
<pre class="snippet-code-css lang-css prettyprint-override"><code>header {
  height: 100px;
  width: 100px;
  position: relative;
  background: Red;
  transition: 0.3s;
}

header:hover .fa {
  opacity: 1;
}

.fa {
  color: white;
  position: absolute;
  top: 0;
  right: 0;
  cursor: pointer;
  opacity: 0;
}

header.blue {
  background: blue;
}</code>```

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"/>
```

Body:
I would like to use some pseudo-element selector (:before, :after) for including a text or icon on :hover inside some other element. Is there a way how to do that only with pseudo-element selectors? I would like to NOT actually change the content of that element as it's content is loaded from localStorage.

My vision is to visually add some click-able icon (✗, ) when hovering over the header.

Thank you for your suggestions.

Body:
i guess you wanted something like this ?

you can also use fontAwesome in the after element or a background-image.

header {
 height:100px;
 width:100px;
 position:relative;
 background:Red;
}
header:after {
 content:"X";
 position:absolute;
 right:0;
 top:0;
 color:#fff;
 transition:0.3s ease-out;
 opacity:0;
}
header:hover:after {
 opacity:1;
}

<header contenteditable="true" id="title" onkeyup="store(this.id);"></header>

option2. using plain Javascript

added the fontAwesome icon using javascript ( beforeend = inserted right before the end of the header tag -> you can use beforebegin,afterbegin,beforeend,afterend see more here insertAdjacentHTML )

then, you can add a click event on the previously added icon. ( here i am toggling the class of header changing it's color )

let me know if it helps

var newElem = document.getElementById("title");

newElem.insertAdjacentHTML('beforeend', '<i id="clickme" class="fa fa-times-circle" aria-hidden="true">&nbsp;</i>');

document.getElementById("clickme").onclick = function() {

  newElem.classList.toggle('blue');
};

header {
  height: 100px;
  width: 100px;
  position: relative;
  background: Red;
  transition: 0.3s;
}

header:hover .fa {
  opacity: 1;
}

.fa {
  color: white;
  position: absolute;
  top: 0;
  right: 0;
  cursor: pointer;
  opacity: 0;
}

header.blue {
  background: blue;
}

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"/>
<header contenteditable="true" id="title" onkeyup="store(this.id);"></header>


问:
Invert some values in SQL Server
I have a table like this one:

```<code>ID   |   Description  |  Account  |  DepAccount  |  Value
----------------------------------------------------------
0    |  Something     | 110       | 0            | 500,50
1    |  Something x   | 0         | 110          | -320,95
</code>```

Now I need a query to sum the values but there is an issue with it.

Like in the example, if the account is 110, it is fine, if the DepAccount is 110, I need to invert the value so I sum 320,95 instead of -320,95

So the query should return value: 821,45

So something like:

```<code>SELECT SUM(Value) As Total
FROM Table
WHERE Account = 110 OR DepAccount = 110 WHERE etc...
</code>```

Who can help? I'm using SQL Server 2008 Express Edition

答:
```<code>SELECT SUM(ABS(Value)) As Total FROM Table WHERE Account = 110 OR DepAccount = 110 WHERE etc
</code>```

that should get you what you need.  the abs function returns the absolute value of the number.

Title: Invert some values in SQL Server

Body:
I have a table like this one:

ID   |   Description  |  Account  |  DepAccount  |  Value
----------------------------------------------------------
0    |  Something     | 110       | 0            | 500,50
1    |  Something x   | 0         | 110          | -320,95

Now I need a query to sum the values but there is an issue with it.

Like in the example, if the account is 110, it is fine, if the DepAccount is 110, I need to invert the value so I sum 320,95 instead of -320,95

So the query should return value: 821,45

So something like:

SELECT SUM(Value) As Total
FROM Table
WHERE Account = 110 OR DepAccount = 110 WHERE etc...

Who can help? I'm using SQL Server 2008 Express Edition

Body:
SELECT SUM(ABS(Value)) As Total FROM Table WHERE Account = 110 OR DepAccount = 110 WHERE etc

that should get you what you need.  the abs function returns the absolute value of the number.


问:
Regular expressions in JavaScript with the global flag
It appears that the RegExp intrinsic is stateful.

So calling it twice on the same string will yield different results when the global flag g is supplied, as it advances a search along the string.

So:

var r = /(\d{3})/g;

console.log(r.test('123')); // true
console.log(r.test('123')); // false - because the search has moved past the first match```
</div>
</div>
</p>

<p>But if I add an intermediate test, I get the following:</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-js lang-js prettyprint-override"><code>var r = /(\d{3})/g;

console.log(r.test('123')); // true
console.log(r.test('456')); // true
console.log(r.test('123')); // true!</code>```

So is it correct to say that RegExp instances operate on the principle of considering only the last string evaluated? If the string differs from the last, it is effectively reset?

答:
So is it correct to say that RegExp instances operate on the principle of considering only the last string evaluated?

yes

If the string differs from the last, it is effectively reset?

correct

If the global flag is omitted, is the regular expression reset in between tests?

right

Check out RegExp#lastIndex

Body:
It appears that the RegExp intrinsic is stateful.

So calling it twice on the same string will yield different results when the global flag g is supplied, as it advances a search along the string.

So:

var r = /(\d{3})/g;

console.log(r.test('123')); // true
console.log(r.test('123')); // false - because the search has moved past the first match

But if I add an intermediate test, I get the following:

var r = /(\d{3})/g;

console.log(r.test('123')); // true
console.log(r.test('456')); // true
console.log(r.test('123')); // true!

So is it correct to say that RegExp instances operate on the principle of considering only the last string evaluated? If the string differs from the last, it is effectively reset?


问:
django.core.exceptions.ValidationError: [u"'' value has an invalid
models.py

```<code>    # -*- coding:utf-8 -*-
    from __future__ import unicode_literals
    from django.db import models
    # Create your models here.

    class moption(models.Model):

        pub_date = models.DateTimeField('pub time', auto_now_add=True, editable=True)
</code>```

when I command "python manage.py migrate"

```<code>Operations to perform:
  Apply all migrations: Price, admin, auth, contenttypes, sessions
Running migrations:
  Applying Price.0006_moption_pub_date...Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line
    utility.execute()
  File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 359, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Python27\lib\site-packages\django\core\management\base.py", line 294, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Python27\lib\site-packages\django\core\management\base.py", line 345, in execute
    output = self.handle(*args, **options)
  File "C:\Python27\lib\site-packages\django\core\management\commands\migrate.py", line 204, in handle
    fake_initial=fake_initial,
  File "C:\Python27\lib\site-packages\django\db\migrations\executor.py", line 115, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "C:\Python27\lib\site-packages\django\db\migrations\executor.py", line 145, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "C:\Python27\lib\site-packages\django\db\migrations\executor.py", line 244, in apply_migration
    state = migration.apply(state, schema_editor)
  File "C:\Python27\lib\site-packages\django\db\migrations\migration.py", line 129, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "C:\Python27\lib\site-packages\django\db\migrations\operations\fields.py", line 84, in database_forwards
    field,
  File "C:\Python27\lib\site-packages\django\db\backends\mysql\schema.py", line 43, in add_field
    super(DatabaseSchemaEditor, self).add_field(model, field)
  File "C:\Python27\lib\site-packages\django\db\backends\base\schema.py", line 395, in add_field
    definition, params = self.column_sql(model, field, include_default=True)
  File "C:\Python27\lib\site-packages\django\db\backends\base\schema.py", line 147, in column_sql
    default_value = self.effective_default(field)
  File "C:\Python27\lib\site-packages\django\db\backends\base\schema.py", line 221, in effective_default
    default = field.get_db_prep_save(default, self.connection)
  File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line 755, in get_db_prep_save
    prepared=False)
  File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line 1440, in get_db_prep_value
    value = self.get_prep_value(value)
  File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line 1419, in get_prep_value
    value = super(DateTimeField, self).get_prep_value(value)
  File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line 1275, in get_prep_value
    return self.to_python(value)
  File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line 1403, in to_python
    params={'value': value},
django.core.exceptions.ValidationError: [u"'' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."]
</code>```

who can tell me,thanks,

答:
It seems your migration files are not properly matching with table structure in your db.

If you are okay with flushing with all your db data, you can try this way,

Delete your db file(Take backup if you want)

Remove your migrations folder from each app

Create new migrations, migrate them.

Now, You have a new db file with your new table structure.

If you are NOT okay with flushing with all your db data, you can try this way,

Delete all entries from your django_migrations table using sqlite console

Create new migrations

migrate them

Now, You have a new db file with your new table structure.

Body:
models.py

    # -*- coding:utf-8 -*-
    from __future__ import unicode_literals
    from django.db import models
    # Create your models here.

    class moption(models.Model):

        pub_date = models.DateTimeField('pub time', auto_now_add=True, editable=True)

when I command "python manage.py migrate"

Operations to perform:
  Apply all migrations: Price, admin, auth, contenttypes, sessions
Running migrations:
  Applying Price.0006_moption_pub_date...Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line
    utility.execute()
  File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 359, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Python27\lib\site-packages\django\core\management\base.py", line 294, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Python27\lib\site-packages\django\core\management\base.py", line 345, in execute
    output = self.handle(*args, **options)
  File "C:\Python27\lib\site-packages\django\core\management\commands\migrate.py", line 204, in handle
    fake_initial=fake_initial,
  File "C:\Python27\lib\site-packages\django\db\migrations\executor.py", line 115, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "C:\Python27\lib\site-packages\django\db\migrations\executor.py", line 145, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "C:\Python27\lib\site-packages\django\db\migrations\executor.py", line 244, in apply_migration
    state = migration.apply(state, schema_editor)
  File "C:\Python27\lib\site-packages\django\db\migrations\migration.py", line 129, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "C:\Python27\lib\site-packages\django\db\migrations\operations\fields.py", line 84, in database_forwards
    field,
  File "C:\Python27\lib\site-packages\django\db\backends\mysql\schema.py", line 43, in add_field
    super(DatabaseSchemaEditor, self).add_field(model, field)
  File "C:\Python27\lib\site-packages\django\db\backends\base\schema.py", line 395, in add_field
    definition, params = self.column_sql(model, field, include_default=True)
  File "C:\Python27\lib\site-packages\django\db\backends\base\schema.py", line 147, in column_sql
    default_value = self.effective_default(field)
  File "C:\Python27\lib\site-packages\django\db\backends\base\schema.py", line 221, in effective_default
    default = field.get_db_prep_save(default, self.connection)
  File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line 755, in get_db_prep_save
    prepared=False)
  File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line 1440, in get_db_prep_value
    value = self.get_prep_value(value)
  File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line 1419, in get_prep_value
    value = super(DateTimeField, self).get_prep_value(value)
  File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line 1275, in get_prep_value
    return self.to_python(value)
  File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line 1403, in to_python
    params={'value': value},
django.core.exceptions.ValidationError: [u"'' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."]

who can tell me,thanks,


问:
php - check if database and table exists, if not, create it
I have a db_connect.php which holds all information for the database. I now want to check if database exists and if not, create it.

Then i want to check if the used table exists, and if not, create it.
Anyone have an idea how I exactly do this?

Here is my db_connect.php:

```<code><?php
//outsourced db-informations
$db_host = 'localhost';
$db_user = 'root';
$db_passwort = '';
$db_name = 'test_db';
$db_table = 'data';
$db_mysqli = mysqli_connect("$db_host","$db_user","$db_passwort", "$db_name");
mysqli_connect("$db_host","$db_user","$db_passwort", "$db_name") or die
("Keine Verbindung moeglich");
?>
</code>```

答:
The query will look like </p>

```<code>CREATE TABLE IF NOT EXISTS tbl_user (
id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id),
uname    CHAR(10) NOT NULL,
regdate  DATE NOT NULL)
</code>```

Body:
I have a db_connect.php which holds all information for the database. I now want to check if database exists and if not, create it.

Then i want to check if the used table exists, and if not, create it.
Anyone have an idea how I exactly do this?

Here is my db_connect.php:

<?php
//outsourced db-informations
$db_host = 'localhost';
$db_user = 'root';
$db_passwort = '';
$db_name = 'test_db';
$db_table = 'data';
$db_mysqli = mysqli_connect("$db_host","$db_user","$db_passwort", "$db_name");
mysqli_connect("$db_host","$db_user","$db_passwort", "$db_name") or die
("Keine Verbindung moeglich");
?>

Body:
The query will look like

CREATE TABLE IF NOT EXISTS tbl_user (
id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id),
uname    CHAR(10) NOT NULL,
regdate  DATE NOT NULL)


问:
Duplicate html tags ruin parts of WP site
I'm at a loss with this error, on some parts of my WP site I'm getting duplicate html tags added automatically on saving changes.

On visual editing, after publishing I get these added to my post:

```<code>     <br /> <br />
</code>```

Since it's visual, I can see these tags all over my newly published pages, meaning I have to go back and manually remove these lines and update the post so it looks as intended.

On some plugins I can't add multimedia content because they are automatically replaced by br tags. Doesn't matter if I add media in text or visual, upon updating they automatically disappear.

But the most infuriating is that I can't log out anymore, because the logout URL should look like this:

```<code>     http://example.com/wp-login.php?action=logout&_wpnonce=...
</code>```

But instead it looks like this:

```<code>     http://example.com/wp-login.php?action=logout&_wpnonce=...
</code>```

So "&" becomes "& amp;" which breakes logout.

What I've tried:
Disabling all plugins, resetting plugins folder, deleting all unused plugins, switching back to base theme, disabling global java scripts (I have popups on the site which needs it).

I can't exactly tell when did it go wrong, it could have been a WP-update or something like that but I can't trace back the error and it doesn't seem like any other users experience the problem.

答:
I managed to solve it, it was quite easy.
I needed to edit wp-config.php and disable custom_tags:

```<code> define('CUSTOM_TAGS', false );
</code>```

I do not know what set it to true, maybe it was a plugin I briefly installed and then deleted, but it messed up the site quite badly.

Every problem I mentioned above got solved immediately once I set it to false.

Body:
I'm at a loss with this error, on some parts of my WP site I'm getting duplicate html tags added automatically on saving changes.

On visual editing, after publishing I get these added to my post:

     &lt;br /&gt; &lt;br /&gt;

Since it's visual, I can see these tags all over my newly published pages, meaning I have to go back and manually remove these lines and update the post so it looks as intended.

On some plugins I can't add multimedia content because they are automatically replaced by br tags. Doesn't matter if I add media in text or visual, upon updating they automatically disappear.

But the most infuriating is that I can't log out anymore, because the logout URL should look like this:

     http://example.com/wp-login.php?action=logout&_wpnonce=...

But instead it looks like this:

     http://example.com/wp-login.php?action=logout&_wpnonce=...

So "&" becomes "& amp;" which breakes logout.

What I've tried:
Disabling all plugins, resetting plugins folder, deleting all unused plugins, switching back to base theme, disabling global java scripts (I have popups on the site which needs it).

I can't exactly tell when did it go wrong, it could have been a WP-update or something like that but I can't trace back the error and it doesn't seem like any other users experience the problem.

Body:
I managed to solve it, it was quite easy.
I needed to edit wp-config.php and disable custom_tags:

 define('CUSTOM_TAGS', false );

I do not know what set it to true, maybe it was a plugin I briefly installed and then deleted, but it messed up the site quite badly.

Every problem I mentioned above got solved immediately once I set it to false.


问:
SDL OpenGL smooth camera movement
I am trying to implement a camera motion system into the program I am currently working on. I cant figure out how to move the camera in non-discrete units so when I move the camera it "jumps" to the next position. how can I move the camera smoothly without jumps.

CameraControlls Function:

```<code>void CameraControlls()
{

while (SDL_PollEvent(&e))
{
    if (e.type == SDL_QUIT)
    {
        exit(0);
    }

    switch (e.type)
    {
    case SDL_KEYDOWN:
        switch (e.key.keysym.sym)
        {
        case SDLK_w:
            cam.MoveForward(0.3f);
            break;
        case SDLK_s:
            cam.MoveBackward(0.3f);
            break;
        case SDLK_d:
            cam.MoveRight(0.2f);
            break;
        case SDLK_a:
            cam.MoveLeft(0.2f);
            break;
        case SDLK_ESCAPE:
            exit(0);
            break;
        case SDLK_RIGHT:
            cam.Yaw(-0.01f);
            break;
        case SDLK_LEFT:
            cam.Yaw(0.01f);
            break;
        case SDLK_DOWN:
            cam.Pitch(0.01f);
            break;
        case SDLK_UP:
            cam.Pitch(-0.01f);
            break;
        }
      }
   }
}
</code>```

Camera Structure:

```<code>struct Camera
 {
 public:
Camera(glm::vec3& pos, float fov, float aspect, float zNear, float zFar)
{
    this->pos = pos;
    this->forward = glm::vec3(0.0f, 0.0f, 1.0f);
    this->up = glm::vec3(0.0f, 1.0f, 0.0f);
    this->projection = glm::perspective(fov, aspect, zNear, zFar);
}
inline glm::mat4 GetViewProjection() const
{
    return projection * glm::lookAt(pos, pos + forward, up);
}
void MoveBackward(float amt)
{
    pos -= forward*amt;
}
void MoveForward(float amt)
{
    pos += forward * amt;
}
void MoveRight(float amt)
{
    pos -= glm::cross(up, forward) * amt;
}
void MoveLeft(float amt)
{
    pos += glm::cross(up, forward) * amt;
}
void Pitch(float angle)
{
    glm::vec3 right = glm::normalize(glm::cross(up, forward));
    forward = glm::vec3(glm::normalize(glm::rotate(angle, right) * glm::vec4(forward, 0.0)));
    up = glm::normalize(glm::cross(forward, right));
}
void Yaw(float angle)
{
    static const glm::vec3 UP(0.0f, 1.0f, 0.0f);
    glm::mat4 rotation = glm::rotate(angle, UP);
    forward = glm::vec3(glm::normalize(rotation * glm::vec4(forward, 0.0)));
    up = glm::vec3(glm::normalize(rotation * glm::vec4(up, 0.0)));
}
   private:
glm::mat4 projection;
glm::vec3 pos;
glm::vec3 forward;
glm::vec3 up;
};
</code>```

答:
I guess the key event of sdl is not firing every frame so you shouldn't change the camera position directly from there because camera wont update every frame.

I would create a boolean variable MOVE_FORWARD that will represent if the forward key is pushed or not

In the key event you update the MOVE_FORWARD variable.

```<code>while (SDL_PollEvent(&e))
{
..........
    case SDL_KEYDOWN:
        switch (e.key.keysym.sym)
        {
        case SDLK_w:
            MOVE_FORWARD=true;
            break;
</code>```

In every frame you update the position of the camera

```<code>if (MOVE_FORWARD){pos+=0.3}
</code>```

This way the camera updates its position every frame and not only when the key event fires

You could also avoid creating key state variables using SDL_GetKeyboardState(NULL) instead of SDL_PollEvent(&e):

```<code>Uint8* keystate = SDL_GetKeyState(NULL);
if(keystate[SDL_SCANCODE_W])
{
  pos+=0.3;
}
</code>```

Title: SDL OpenGL smooth camera movement

Body:
I am trying to implement a camera motion system into the program I am currently working on. I cant figure out how to move the camera in non-discrete units so when I move the camera it "jumps" to the next position. how can I move the camera smoothly without jumps.

CameraControlls Function:

void CameraControlls()
{

while (SDL_PollEvent(&e))
{
    if (e.type == SDL_QUIT)
    {
        exit(0);
    }

    switch (e.type)
    {
    case SDL_KEYDOWN:
        switch (e.key.keysym.sym)
        {
        case SDLK_w:
            cam.MoveForward(0.3f);
            break;
        case SDLK_s:
            cam.MoveBackward(0.3f);
            break;
        case SDLK_d:
            cam.MoveRight(0.2f);
            break;
        case SDLK_a:
            cam.MoveLeft(0.2f);
            break;
        case SDLK_ESCAPE:
            exit(0);
            break;
        case SDLK_RIGHT:
            cam.Yaw(-0.01f);
            break;
        case SDLK_LEFT:
            cam.Yaw(0.01f);
            break;
        case SDLK_DOWN:
            cam.Pitch(0.01f);
            break;
        case SDLK_UP:
            cam.Pitch(-0.01f);
            break;
        }
      }
   }
}

Camera Structure:

struct Camera
 {
 public:
Camera(glm::vec3& pos, float fov, float aspect, float zNear, float zFar)
{
    this->pos = pos;
    this->forward = glm::vec3(0.0f, 0.0f, 1.0f);
    this->up = glm::vec3(0.0f, 1.0f, 0.0f);
    this->projection = glm::perspective(fov, aspect, zNear, zFar);
}
inline glm::mat4 GetViewProjection() const
{
    return projection * glm::lookAt(pos, pos + forward, up);
}
void MoveBackward(float amt)
{
    pos -= forward*amt;
}
void MoveForward(float amt)
{
    pos += forward * amt;
}
void MoveRight(float amt)
{
    pos -= glm::cross(up, forward) * amt;
}
void MoveLeft(float amt)
{
    pos += glm::cross(up, forward) * amt;
}
void Pitch(float angle)
{
    glm::vec3 right = glm::normalize(glm::cross(up, forward));
    forward = glm::vec3(glm::normalize(glm::rotate(angle, right) * glm::vec4(forward, 0.0)));
    up = glm::normalize(glm::cross(forward, right));
}
void Yaw(float angle)
{
    static const glm::vec3 UP(0.0f, 1.0f, 0.0f);
    glm::mat4 rotation = glm::rotate(angle, UP);
    forward = glm::vec3(glm::normalize(rotation * glm::vec4(forward, 0.0)));
    up = glm::vec3(glm::normalize(rotation * glm::vec4(up, 0.0)));
}
   private:
glm::mat4 projection;
glm::vec3 pos;
glm::vec3 forward;
glm::vec3 up;
};

Body:
I guess the key event of sdl is not firing every frame so you shouldn't change the camera position directly from there because camera wont update every frame.

I would create a boolean variable MOVE_FORWARD that will represent if the forward key is pushed or not

In the key event you update the MOVE_FORWARD variable.

while (SDL_PollEvent(&e))
{
..........
    case SDL_KEYDOWN:
        switch (e.key.keysym.sym)
        {
        case SDLK_w:
            MOVE_FORWARD=true;
            break;

In every frame you update the position of the camera

if (MOVE_FORWARD){pos+=0.3}

This way the camera updates its position every frame and not only when the key event fires

You could also avoid creating key state variables using SDL_GetKeyboardState(NULL) instead of SDL_PollEvent(&e):

Uint8* keystate = SDL_GetKeyState(NULL);
if(keystate[SDL_SCANCODE_W])
{
  pos+=0.3;
}


问:
Error when taking some variables from multiple lines with same pattern
I am really new to perl. I need to grab some variables from multiple lines with same pattern using perl script.

These are the example of multiple lines with same pattern and are stored in input.txt:

```<code>input -input_port -port top_port 21.303 [open_port -op {input_port[0]} -file "file_name == top_input_port[0]"]
input -input_port -port bot_port 98.324 [open_port -op {input_port[10]} -file "file_name == bot_input_port[10]"]
</code>```

The format of the line is :

```<code>input -input_port -port portname value [open_port -op {input_port[10]} -file "file_name == filename"]
</code>```

So, i tried to create this script using examples in Google:

```<code>#! /tools/perl/5.8.8/linux/bin/perl
use strict;
use warnings;

while (<>) {
    if ($_ =~ /^(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\d+)\s+
              \[(\S+)\s+(\S+)\s
              \{(\S+)\[(\d+)\]\}\s(\S+)\s(\S+)\s*==\s(\S+)*"\]$/x ) {
        $io = $1;
        $io_port = $2;
        $port = $3;
        $portname = $4;
        $value = $5;
        $openclose = $6;
        $op = $7;
        $io_num = $8;
        $number = $9;
        $filetype = $10;
        $file = $11;
        $file_name = $12;
        print "$io $portname $value $file_name\n";
    }
}
</code>```

I only want to print $io, $portname, $value and $file_name. However, it displays compilation errors. How do i fix this error?

I am expecting the output to be in new txt file:

input top_port 21.303 top_input_port[0]

input bot_port 98.324 bot_input_port[10]

答:
Honestly, that regex is way too complicated. You're doing a load of matching, and it's brittle.

Most likely you're being tripped up on 21.303 isn't matched by \d+.

So your regex breaks, and that's... that.

But can I suggest a different approach? Don't regex  the whole thing, that means complicated and hard to read - and brittle - regular expressions.

Why not instead:

```<code>#!/usr/bin/env perl
use strict;
use warnings;

while ( <DATA> ) {

   my ( $io ) = m/^(\w+)/; #first word on line
   my ( $portname, $value ) = m/-port (\w+) ([\d\.]+)/;  #look for 'port' keyword.
   my ( $file_name ) = m/file_name == (\S+)\"/; #look for 'file_name' keyword

   print "$io $portname $value $file_name\n";
}

__DATA__
input -input_port -port top_port 21.303 [open_port -op {input_port[0]} -file "file_name == top_input_port[0]"]
input -input_port -port bot_port 98.324 [open_port -op {input_port[10]} -file "file_name == bot_input_port[10]"]
</code>```

Body:
I am really new to perl. I need to grab some variables from multiple lines with same pattern using perl script.

These are the example of multiple lines with same pattern and are stored in input.txt:

input -input_port -port top_port 21.303 [open_port -op {input_port[0]} -file "file_name == top_input_port[0]"]
input -input_port -port bot_port 98.324 [open_port -op {input_port[10]} -file "file_name == bot_input_port[10]"]

The format of the line is :

input -input_port -port portname value [open_port -op {input_port[10]} -file "file_name == filename"]

So, i tried to create this script using examples in Google:

#! /tools/perl/5.8.8/linux/bin/perl
use strict;
use warnings;

while (<>) {
    if ($_ =~ /^(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\d+)\s+
              \[(\S+)\s+(\S+)\s
              \{(\S+)\[(\d+)\]\}\s(\S+)\s(\S+)\s*==\s(\S+)*"\]$/x ) {
        $io = $1;
        $io_port = $2;
        $port = $3;
        $portname = $4;
        $value = $5;
        $openclose = $6;
        $op = $7;
        $io_num = $8;
        $number = $9;
        $filetype = $10;
        $file = $11;
        $file_name = $12;
        print "$io $portname $value $file_name\n";
    }
}

I only want to print $io, $portname, $value and $file_name. However, it displays compilation errors. How do i fix this error?

I am expecting the output to be in new txt file:

input top_port 21.303 top_input_port[0]

input bot_port 98.324 bot_input_port[10]

Body:
Honestly, that regex is way too complicated. You're doing a load of matching, and it's brittle.

Most likely you're being tripped up on 21.303 isn't matched by \d+.

So your regex breaks, and that's... that.

But can I suggest a different approach? Don't regex  the whole thing, that means complicated and hard to read - and brittle - regular expressions.

Why not instead:

#!/usr/bin/env perl
use strict;
use warnings;

while ( <DATA> ) {

   my ( $io ) = m/^(\w+)/; #first word on line
   my ( $portname, $value ) = m/-port (\w+) ([\d\.]+)/;  #look for 'port' keyword.
   my ( $file_name ) = m/file_name == (\S+)\"/; #look for 'file_name' keyword

   print "$io $portname $value $file_name\n";
}

__DATA__
input -input_port -port top_port 21.303 [open_port -op {input_port[0]} -file "file_name == top_input_port[0]"]
input -input_port -port bot_port 98.324 [open_port -op {input_port[10]} -file "file_name == bot_input_port[10]"]


问:
How can I apply a common extension method to multiple unrelated types in a third party SDK?
I'm beginning to fall in love with Extension Methods, but I just don't know how to create an EM only for a determinate Object type.

I have for example:

```<code>public static void AddPhoneNumberToContact(this Contact contact, PhoneType type, String number)
{
    lock (contact)
    {
        PhoneRow pr = PhoneRow.CreateNew();
        pr.SetDefaults();
        pr.PtypeIdx = type;
        pr.PhoneNumber = number;
        contact.Phones.Add(pr);
        pr = null;
    }
}
</code>```

My problem is that I want to also Have this method in the Person object, and that is why I named

```<code>AddPhoneNumberToContact
AddPhoneNumberToPerson
</code>```

Is there a way to have AddPhoneNumber and deal with the object that is provided?

or the solution is to have

```<code>public static void AddPhoneNumber(this object contact, ...
{
   ...

   if(typeof(Contact) == contact)
      ((Contact)contact).Phones.Add(pr);
   else if(typeof(Person) == contact)
      ((Person)contact).Phones.Add(pr);
}
</code>```

Thank you.

答:
If you can not change Person and Contact you can create a subclass of them and let them implement the common interface.

In the extension method you declare the common interface as parameter:

```<code>using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        var p = new MyPerson();
        p.Name = "test";
        p.AddPhonenumber("555-2356");
        Console.WriteLine(string.Join(", ", p.Phonenumber));

        var c = new MyContact();
        c.Name = "contact";
        c.AddPhonenumber("222-235");
        Console.WriteLine(string.Join(", ", c.Phonenumber));
    }
}

public class Contact
{
    public Contact() {
        this.Phonenumber = new List<string>();
    }
    public string Name { get; set; }
    public List<string> Phonenumber { get; set; }
    public string Foo { get; set; }
}
public class Person
{
    public Person() {
        this.Phonenumber = new List<string>();
    }
    public string Name { get; set; }
    public List<string> Phonenumber { get; set; }
    public string Bar { get; set; }
}

public class MyContact: Contact, IType {
}

public class MyPerson: Person, IType {
}

public static class Extensions {
    public static void AddPhonenumber(this IType type, string number){
        type.Phonenumber.Add(number);
    }
}

public interface IType {
    string Name {get; set; }
    List<string> Phonenumber {get; set;}
}
</code>```

OwnerDisplayName: balexandre

Body:
I'm beginning to fall in love with Extension Methods, but I just don't know how to create an EM only for a determinate Object type.

I have for example:

public static void AddPhoneNumberToContact(this Contact contact, PhoneType type, String number)
{
    lock (contact)
    {
        PhoneRow pr = PhoneRow.CreateNew();
        pr.SetDefaults();
        pr.PtypeIdx = type;
        pr.PhoneNumber = number;
        contact.Phones.Add(pr);
        pr = null;
    }
}

My problem is that I want to also Have this method in the Person object, and that is why I named

AddPhoneNumberToContact
AddPhoneNumberToPerson

Is there a way to have AddPhoneNumber and deal with the object that is provided?

or the solution is to have

public static void AddPhoneNumber(this object contact, ...
{
   ...

   if(typeof(Contact) == contact)
      ((Contact)contact).Phones.Add(pr);
   else if(typeof(Person) == contact)
      ((Person)contact).Phones.Add(pr);
}

Thank you.

LastEditorDisplayName: balexandre

Body:
If you can not change Person and Contact you can create a subclass of them and let them implement the common interface.

In the extension method you declare the common interface as parameter:

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        var p = new MyPerson();
        p.Name = "test";
        p.AddPhonenumber("555-2356");
        Console.WriteLine(string.Join(", ", p.Phonenumber));

        var c = new MyContact();
        c.Name = "contact";
        c.AddPhonenumber("222-235");
        Console.WriteLine(string.Join(", ", c.Phonenumber));
    }
}

public class Contact
{
    public Contact() {
        this.Phonenumber = new List<string>();
    }
    public string Name { get; set; }
    public List<string> Phonenumber { get; set; }
    public string Foo { get; set; }
}
public class Person
{
    public Person() {
        this.Phonenumber = new List<string>();
    }
    public string Name { get; set; }
    public List<string> Phonenumber { get; set; }
    public string Bar { get; set; }
}

public class MyContact: Contact, IType {
}

public class MyPerson: Person, IType {
}

public static class Extensions {
    public static void AddPhonenumber(this IType type, string number){
        type.Phonenumber.Add(number);
    }
}

public interface IType {
    string Name {get; set; }
    List<string> Phonenumber {get; set;}
}


问:
Converting a JS object to an array using jQuery
My application creates a JavaScript object, like the following:

```<code>myObj= {1:[Array-Data], 2:[Array-Data]}
</code>```

But I need this object as an array.

```<code>array[1]:[Array-Data]
array[2]:[Array-Data]
</code>```

So I tried to convert this object to an array by iterating with $.each through the object and adding the element to an array:

```<code>x=[]
$.each(myObj, function(i,n) {
    x.push(n);});
</code>```

Is there an better way to convert an object to an array or maybe a function?

答:
You can create a simple function to do the conversion from object to array, something like this can do the job for you using pure javascript:

```<code>var objectToArray = function(obj) {
  var arr = [];
  if ('object' !== typeof obj || 'undefined' === typeof obj || Array.isArray(obj)) {
    return obj;
  } else {
    Object.keys(obj).map(x=>arr.push(obj[x]));
  }
  return arr;
};
</code>```

or this one:

```<code>var objectToArray = function(obj) {
  var arr =[];
  for(let o in obj) {
    if (obj.hasOwnProperty(o)) {
      arr.push(obj[o]);
    }
  }
  return arr;
};
</code>```

and call and use the function as below:

```<code>var obj = {1:'a', 2:'b', 3:'c', 4:'d', 5:'e'};
objectToArray(obj); // return ["a", "b", "c", "d", "e"]
</code>```

Also in the future we will have something called Object.values(obj), similar to Object.keys(obj) which will return all properties for you as an array, but not supported in many browsers yet...

Body:
My application creates a JavaScript object, like the following:

myObj= {1:[Array-Data], 2:[Array-Data]}

But I need this object as an array.

array[1]:[Array-Data]
array[2]:[Array-Data]

So I tried to convert this object to an array by iterating with $.each through the object and adding the element to an array:

x=[]
$.each(myObj, function(i,n) {
    x.push(n);});

Is there an better way to convert an object to an array or maybe a function?

Body:
You can create a simple function to do the conversion from object to array, something like this can do the job for you using pure javascript:

var objectToArray = function(obj) {
  var arr = [];
  if ('object' !== typeof obj || 'undefined' === typeof obj || Array.isArray(obj)) {
    return obj;
  } else {
    Object.keys(obj).map(x=>arr.push(obj[x]));
  }
  return arr;
};

or this one:

var objectToArray = function(obj) {
  var arr =[];
  for(let o in obj) {
    if (obj.hasOwnProperty(o)) {
      arr.push(obj[o]);
    }
  }
  return arr;
};

and call and use the function as below:

var obj = {1:'a', 2:'b', 3:'c', 4:'d', 5:'e'};
objectToArray(obj); // return ["a", "b", "c", "d", "e"]

Also in the future we will have something called Object.values(obj), similar to Object.keys(obj) which will return all properties for you as an array, but not supported in many browsers yet...


问:
How to write a single query for the below scenario?
I am new to SQL and I am facing a problem in writing a query for one scenario. I have 3 tables:

Table 1 has actor names and movie-id's

```<code>Table1
Actor-ID  Actor-name    Movies_id
</code>```

Table 2 has movie-id's and corresponding movie names.

```<code>Table2
Movies_id   Movies_name
</code>```

Table 3 has movie-id's and corresponding revenue generated by the movies.

```<code>Table3
Movies_id   Revenue_generated
</code>```

I want to write a query to fetch data for the below scenario:
All the movies of any one actor which has earned more than 100 crores.

I haven't mention any data in the tables, so feel free to add data from your side.

答:
You should re-design the database with these tables:

actor (actor_id, name)

movie (movie_id, name, revenue)

actor_movie (actor_id, movie_id)

And the query would be:

```<code>select *
from movie
where revenue > 1000000000
and movie_id in
(
  select movie_id
  from actor_movie
  where actor_id = (select actor_id from actor where name = 'Bruce Willis')
);
</code>```

Body:
I am new to SQL and I am facing a problem in writing a query for one scenario. I have 3 tables:

Table 1 has actor names and movie-id's

Table1
Actor-ID  Actor-name    Movies_id

Table 2 has movie-id's and corresponding movie names.

Table2
Movies_id   Movies_name

Table 3 has movie-id's and corresponding revenue generated by the movies.

Table3
Movies_id   Revenue_generated

I want to write a query to fetch data for the below scenario:
All the movies of any one actor which has earned more than 100 crores.

I haven't mention any data in the tables, so feel free to add data from your side.

Body:
You should re-design the database with these tables:

actor (actor_id, name)

movie (movie_id, name, revenue)

actor_movie (actor_id, movie_id)

And the query would be:

select *
from movie
where revenue > 1000000000
and movie_id in
(
  select movie_id
  from actor_movie
  where actor_id = (select actor_id from actor where name = 'Bruce Willis')
);


问:
pandas groupby sum takes to long, how can I optimize this?
I have a dataframe of around 2 million rows. If I do this groupby

```<code> df = df.groupby(by=['country','os','device'], as_index=False)
</code>```

It only takes a short time. But if I do:

```<code> df = df.groupby(by=['country','os','device'], as_index=False).sum()
</code>```

It takes forever and I have to kill the script.

This started when I updated from Pandas 17 to 20.

Why is this happening and how can I rewrite it so it works fast again?

EDIT:

```<code>   nl,windows,c,awdo2323fa3rj90
   uk,mac,c, awdawdoj93di303
   nl,ios,m, aawd9efri403
   nl,ios,m, 39fnsefwfpiw3r
</code>```

[country,os,device,md5_id]
output should be

```<code>   nl,windows,c
   uk,mac,c
   nl,ios,m
</code>```

Like EdChum said the groupby returns groupby object so I added sum() and this worked in pandas 17, but I think this is now in 20 causing a problem, because there are no numeric columns.

答:
To answer some of your queries, a groupby object is just metadata, it describes how to perform the grouping, it only does some work when you call some aggregation  function on it, as you have no numerical columns I'm not sure what you're expecting by calling sum.

It looks like all you want is to drop_duplicates:

```<code>df.drop_duplicates(subset=['country','os','device'])
</code>```

So that what is left are non-repeated rows based on the passed subset of columns

Body:
I have a dataframe of around 2 million rows. If I do this groupby

 df = df.groupby(by=['country','os','device'], as_index=False)

It only takes a short time. But if I do:

 df = df.groupby(by=['country','os','device'], as_index=False).sum()

It takes forever and I have to kill the script.

This started when I updated from Pandas 17 to 20.

Why is this happening and how can I rewrite it so it works fast again?

EDIT:

   nl,windows,c,awdo2323fa3rj90
   uk,mac,c, awdawdoj93di303
   nl,ios,m, aawd9efri403
   nl,ios,m, 39fnsefwfpiw3r

[country,os,device,md5_id]
output should be

   nl,windows,c
   uk,mac,c
   nl,ios,m

Like EdChum said the groupby returns groupby object so I added sum() and this worked in pandas 17, but I think this is now in 20 causing a problem, because there are no numeric columns.

Body:
To answer some of your queries, a groupby object is just metadata, it describes how to perform the grouping, it only does some work when you call some aggregation  function on it, as you have no numerical columns I'm not sure what you're expecting by calling sum.

It looks like all you want is to drop_duplicates:

df.drop_duplicates(subset=['country','os','device'])

So that what is left are non-repeated rows based on the passed subset of columns


问:
Easier way to fuse two adjacent rows by indices into one in pandas dataframe
If one has a dataframe in python and wishes two concatenate any two adjacent rows using their indices, what would be the simplest way?
Example:

```<code>       0      1
  0    a      b
  1    c      d
</code>```

Output:

```<code>     0      1
0   a-b    c-d
</code>```

答:
Well, I got a work around, You could extract the rows you want to fuse and then turn them into lists. The lists can then easily be fused. Example: fusing two lists;

```<code>New_list=["{}-{}".format(list1_, list2_) for list1_, list2_ in zip(list1, list2)]
</code>```

Then convert the list into a dataframe and transpose it:

```<code>DataFrame_row=DataFrame(New_list)

DataFrame_row1=DataFrame_row.transpose()
</code>```

Lastly, concatenate the two dataframes, you could also easily delete the two original rows in the original dataframe:

```<code>NewDataFrame = pd.concat([DataFrame_row1, OriginalDataFrame])
</code>```

Cheers.

Body:
If one has a dataframe in python and wishes two concatenate any two adjacent rows using their indices, what would be the simplest way?
Example:

       0      1
  0    a      b
  1    c      d

Output:

     0      1
0   a-b    c-d

Body:
Well, I got a work around, You could extract the rows you want to fuse and then turn them into lists. The lists can then easily be fused. Example: fusing two lists;

New_list=["{}-{}".format(list1_, list2_) for list1_, list2_ in zip(list1, list2)]

Then convert the list into a dataframe and transpose it:

DataFrame_row=DataFrame(New_list)

DataFrame_row1=DataFrame_row.transpose()

Lastly, concatenate the two dataframes, you could also easily delete the two original rows in the original dataframe:

NewDataFrame = pd.concat([DataFrame_row1, OriginalDataFrame])

Cheers.


问:
Why is switch not working as programmed?
When I am executing this code, the LED is ON by default whereas it should only be ON when switch is pressed. And when I press the switch, it turns off. Can anyone please explain me, what I am doing wrong with my code.</p>

```<code>#include <lpc17xx.h>

#define SwitchPinNumber 11
#define LedPinNumber 6

void main()
{
    uint32_t switchStatus;

    SystemInit();

    LPC_PINCON->PINSEL4 = 0x000000; // Configure the Pins for GPIO;

    /* Configure the LED pin as output and SwitchPin as input */
    LPC_GPIO2->FIODIR = ((1 << LedPinNumber) | (0 << SwitchPinNumber));

    while (1)
    {
        /* Turn On all the leds and wait for one second */
        switchStatus = (LPC_GPIO2->FIOPIN >> SwitchPinNumber) & 0x01; // Read switch status
        if (switchStatus == 1)
        {
            LPC_GPIO2->FIOPIN = (1 << LedPinNumber);
        }
        else
        {
            LPC_GPIO2->FIOPIN = (0 << LedPinNumber);
        }
    }
}
</code>```

答:
If this is actually a mechanical switch, then you must always:

de-bounce the signal somewhere, usually done in code but can also be done with external RC filter.

ensure that the signal is pulled to the inactive state with a pull resistor, external or internal. It is not clear from the question if you need this signal to be active high or active low.

These are very basic things that can be solved in either hardware or software. Your question shows no trace of doing any of the above, so it is unlikely that your program will ever work as intended.

Body:
When I am executing this code, the LED is ON by default whereas it should only be ON when switch is pressed. And when I press the switch, it turns off. Can anyone please explain me, what I am doing wrong with my code.

#include <lpc17xx.h>

#define SwitchPinNumber 11
#define LedPinNumber 6

void main()
{
    uint32_t switchStatus;

    SystemInit();

    LPC_PINCON->PINSEL4 = 0x000000; // Configure the Pins for GPIO;

    /* Configure the LED pin as output and SwitchPin as input */
    LPC_GPIO2->FIODIR = ((1 << LedPinNumber) | (0 << SwitchPinNumber));

    while (1)
    {
        /* Turn On all the leds and wait for one second */
        switchStatus = (LPC_GPIO2->FIOPIN >> SwitchPinNumber) & 0x01; // Read switch status
        if (switchStatus == 1)
        {
            LPC_GPIO2->FIOPIN = (1 << LedPinNumber);
        }
        else
        {
            LPC_GPIO2->FIOPIN = (0 << LedPinNumber);
        }
    }
}


问:
Does Apple allow TabBar position on top of view controller?
I am working on an application and in this application, there is a requirement of UITabBar on the top position of UIViewController. I need your support to know that, does Apple Guideline allow to set UITabBar position on the top of view?</p>

答:
you won't use UITabBar, but you might want to make custom view, or segmented control, or even scroll view.

all depends on your approach

but definitely you can't use UITabBar


Title: Merge two lines conditionally

Body:
200005251|AAAAAA
200005252|BBBBB
200005261|CCCCCC
200005262|DDDDD
200005292|EEEEEE
200005301|FFFFFF
200005302|VVVVVV
200005311|AAAAAA
200005312|JJJJJJ
200006011|LLLLLL
200006021|SSSSSS
200006022|HHHHHH
200006051|OOOOOO
200006052|GGGGGG
200006061|KKKKKK
200006062|FFFFF
200006071|TTTTTT

I have a file in first field as above. I need to merge every two lines if they only end ......1 and ......2. and leave the others as is. Desired output:

200005251|AAAAAA 200005252|BBBBB
200005261|CCCCCC 200005262|DDDDD
200005292|EEEEEE
200005301|FFFFFF 200005302|VVVVVV
200005311|AAAAAA 200005312|JJJJJJ
200006011|LLLLLL
200006021|SSSSSS 200006022|HHHHHH
200006051|OOOOOO 200006052|GGGGGG
200006061|KKKKKK 200006062|FFFFF
200006071|TTTTTT

Thanks in advance.

Body:
awk solution:

awk -v RS=" " '{ for(i=1;i<=NF;i++)
                    if ($i~/1$/ && $(i+1)~/2$/) {
                        printf("%s %s\n",$i,$(i+1)); i++;
                    } else {
                        printf("%s\n",$i)
                    }
                }' file

The output:

200005251 200005252
200005261 200005262
200005292
200005301 200005302
200005311 200005312
200006011
200006021 200006022
200006051 200006052
200006061 200006062
200006071

As you have changed your initial input - here's extended version:

awk -v RS=" " '{ for(i=1;i<=NF;i++)
                     if ($i~/1\|[[:alpha:]]+$/ && $(i+1)~/2\|[[:alpha:]]+$/) {
                         printf("%s %s\n",$i,$(i+1)); i++;
                     } else {
                         printf("%s\n",$i)
                     }
               }' file

The output v.2:

200005251|AAAAAA 200005252|BBBBB
200005261|CCCCCC 200005262|DDDDD
200005292|EEEEEE
200005301|FFFFFF 200005302|VVVVVV
200005311|AAAAAA 200005312|JJJJJJ
200006011|LLLLLL
200006021|SSSSSS 200006022|HHHHHH
200006051|OOOOOO 200006052|GGGGGG
200006061|KKKKKK 200006062|FFFFF
200006071|TTTTTT

Details:

-v RS=" " - treat space as record separator instead of newline

for(i=1;i<=NF;i++) - iterating through all fields

if ($i~/1\|[[:alpha:]]+$/ && $(i+1)~/2\|[[:alpha:]]+$/) - condition to check if current field has 1 at the end of its 1st section and next field has 2 at the end of its 1st section


问:
NSIS Installer slow on machine with Microsoft Security Essentials
So I've got an issue where our NSIS installers slow down heaps when installing over the top of an existing installation?

It seems to be directly related to Microsoft's Security Essentials and turning off runtime checking causes it to go away, but I've never encountered anything similar with any other installers - so is there a known issue here or should we be doing things differently to avoid this kind of thing?

To give you an idea how slow.. each .EXE takes 10-15 seconds to unpack but on a clean machine or with Security Essentials turned off it takes only a second or two - and this is on the a top of the line core i7 with 12GB of ram.

Only thing I can think of is to copy the exe to a temporary file and then move it over afterwards, but this seems a bit clunky.

答:
-- Outdated answer. Microsoft Defender is kinda good now --

You're gonna hate me.

If you're competent, lose the antivirus.

Antivirus is only needed by those who are unable to keep their machines from getting infected without it.

I ran antivirus for years, and had it legitimately trip only once, on a six month old backup of my mail folder. What's weird is it sat for 6 months before the antivirus caught it. In the meantime, it tripped many times on false positives.

I don't run antivirus anymore and would be glad if I never ran it again.

ContentLicense: CC BY-SA 4.0


问:
Laravel 5.4 artisan serve htaccess / and Routes::get for existing folders at /public
I'm still trying things with Laravel 5.4.
however running

```<code>php artisan server
</code>```

is not taking .htaccess file in /public into consideration, no matter what i edit in there it's still not processing it, the artisan serve runs at 127.0.0.1:8000

--- i reached this issue cuz i was looking for one other thing which is:

i wanted to have a route::get for the /images folder which is already located at /public, removing -d from htaccess conditions should solve this normally, thus making apache redirect requests even from folders to index.php,

so while testing locally using php artisan serve i noticed that changes or even clearing the htaccess file does not change the behavior of laravel.

Thank you for your time.

[note]
htaccess works if i run laravel from apache, or anything but php artisan serve. so my question is only about the serve command and it's behavior.

答:
you need to define it in the artisan config file!

```<code>sites:
    - map: homestead.app
      to: /home/vagrant/Code/Laravel/public
</code>```

As explained on https://laravel.com/docs/5.4/homestead (homestead is vagrant+)

Laravel Homestead is an official, pre-packaged Vagrant box that
  provides you a wonderful development environment without requiring you
  to install PHP, a web server, and any other server software on your
  local machine. No more worrying about messing up your operating
  system! Vagrant boxes are completely disposable. If something goes
  wrong, you can destroy and re-create the box in minutes!

Body:
I'm still trying things with Laravel 5.4.
however running

php artisan server

is not taking .htaccess file in /public into consideration, no matter what i edit in there it's still not processing it, the artisan serve runs at 127.0.0.1:8000

--- i reached this issue cuz i was looking for one other thing which is:

i wanted to have a route::get for the /images folder which is already located at /public, removing -d from htaccess conditions should solve this normally, thus making apache redirect requests even from folders to index.php,

so while testing locally using php artisan serve i noticed that changes or even clearing the htaccess file does not change the behavior of laravel.

Thank you for your time.

[note]
htaccess works if i run laravel from apache, or anything but php artisan serve. so my question is only about the serve command and it's behavior.

Body:
you need to define it in the artisan config file!

sites:
    - map: homestead.app
      to: /home/vagrant/Code/Laravel/public

As explained on https://laravel.com/docs/5.4/homestead (homestead is vagrant+)

Laravel Homestead is an official, pre-packaged Vagrant box that
  provides you a wonderful development environment without requiring you
  to install PHP, a web server, and any other server software on your
  local machine. No more worrying about messing up your operating
  system! Vagrant boxes are completely disposable. If something goes
  wrong, you can destroy and re-create the box in minutes!


问:
Show this element without having code repeating each time
I'm showing / hidding data from Json on click of a marker which is working totally great.</p>

答:
One Last thing i'm trying to do is to call the Json Data from an external file

I tried to wrap the functio into

```<code>   $.getJSON('js/data.json', function(data) {
</code>```

without success...

it's telling me on the line that json is not defined ( in the console)

```<code>Object.keys(json).forEach(function (country) {
</code>```

any idea ?

Thanks a lot !

--UPDATE JSON STRUCTURE ----

```<code>{
    "france": [
        {
            "image": "img/ausralia.jpg",
            "description": "number django 1",
        }
    ],
       "australia": [
        {
            "image": "img/ausralia.jpg",
            "description": "number django 2",
        }
    ],

         "uk": [
        {
            "image": "img/ausralia.jpg",
            "description": "number django 3",
        }
    ]
}
</code>```

Body:
One Last thing i'm trying to do is to call the Json Data from an external file

I tried to wrap the functio into

   $.getJSON('js/data.json', function(data) {

without success...

it's telling me on the line that json is not defined ( in the console)

Object.keys(json).forEach(function (country) {

any idea ?

Thanks a lot !

--UPDATE JSON STRUCTURE ----

{
    "france": [
        {
            "image": "img/ausralia.jpg",
            "description": "number django 1",
        }
    ],
       "australia": [
        {
            "image": "img/ausralia.jpg",
            "description": "number django 2",
        }
    ],

         "uk": [
        {
            "image": "img/ausralia.jpg",
            "description": "number django 3",
        }
    ]
}


问:
Programmatically change rootViewController of storyBoard
I have created my project using Storyboards. The root ViewController lies inside a Storyboard, I have not written a single code in the appDelegate.

Now I want to show a tour of my app, so I want to change the root ViewController from Tab Bar to my TourVC and when the tour of the app is finished , I want to again switch back my root ViewController to Tab Bar.

So I looked up online and followed the following points

1) Remove Storyboards from app.plist file,
2) Uncheck option "isInitialViewController" from Storyboards which is checked in case of Tab Bar controller because its a root ViewController,
3) Add this code in appDelegate.m file.

```<code>self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
ProductTourViewController *PT = [[ProductTourViewController alloc] initWithNibName:@"ProductTourViewController" bundle:nil];
self.window.rootViewController = PT;
[self.window makeKeyAndVisible];
return YES;
</code>```

But my app crashes with this error log,

```<code>[ProductTourViewController selectedViewController]: unrecognized selector sent to instance 0x1766a9e0
</code>```

And also I get a warning,

```<code>Unsupported Configuration: Scene is unreachable due to lack of entry points and does not have an identifier for runtime access via -instantiateViewControllerWithIdentifier:.
</code>```

答:
Swift 3 code:

Use below in didFinishLaunchingWithOptions Appdelegate function.
Replace "HomeViewController" with ViewController you want to set as Root ViewController on app launch.

```<code>self.window = UIWindow(frame: UIScreen.main.bounds)

let storyboard = UIStoryboard(name: "Main", bundle: nil)

let initialViewController = storyboard.instantiateViewController(withIdentifier: "HomeViewController")

self.window?.rootViewController = initialViewController
self.window?.makeKeyAndVisible()

return true
</code>```

Body:
I have created my project using Storyboards. The root ViewController lies inside a Storyboard, I have not written a single code in the appDelegate.

Now I want to show a tour of my app, so I want to change the root ViewController from Tab Bar to my TourVC and when the tour of the app is finished , I want to again switch back my root ViewController to Tab Bar.

So I looked up online and followed the following points

1) Remove Storyboards from app.plist file,
2) Uncheck option "isInitialViewController" from Storyboards which is checked in case of Tab Bar controller because its a root ViewController,
3) Add this code in appDelegate.m file.

self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
ProductTourViewController *PT = [[ProductTourViewController alloc] initWithNibName:@"ProductTourViewController" bundle:nil];
self.window.rootViewController = PT;
[self.window makeKeyAndVisible];
return YES;

But my app crashes with this error log,

[ProductTourViewController selectedViewController]: unrecognized selector sent to instance 0x1766a9e0

And also I get a warning,

Unsupported Configuration: Scene is unreachable due to lack of entry points and does not have an identifier for runtime access via -instantiateViewControllerWithIdentifier:.

Body:
Swift 3 code:

Use below in didFinishLaunchingWithOptions Appdelegate function.
Replace "HomeViewController" with ViewController you want to set as Root ViewController on app launch.

self.window = UIWindow(frame: UIScreen.main.bounds)

let storyboard = UIStoryboard(name: "Main", bundle: nil)

let initialViewController = storyboard.instantiateViewController(withIdentifier: "HomeViewController")

self.window?.rootViewController = initialViewController
self.window?.makeKeyAndVisible()

return true


问:
Java programming identify whether its a prime or not
Write a program that prompts the user to input a positive ineteger. It should then output a message indicating whether the number is prime number. Note: 2 is the only even number that is prime. An odd integer is prime if it is not divisible by an odd integer less than or equal to the square root of the number.

Update:

This is my program its not done really still figuring it out :(

```<code>import java.util.*;

public class prime {

    static Scanner kb = new Scanner(System.in);

    public static void main() {

        System.out.print("\fEnter positive integer:");

        int num = kb.nextInt();

        if (num < 1)

            System.out.print("Please enter number greater than 1"
                    + "Perform the program again");

        else if (num == 2)
            System.out.print("its a prime yey!");

        else if (num % 2 == 0)
            System.out.print("its not a prime ");

    }
}
</code>```

Idk whats next still figuring it out T.T

答:
Given Number is Prime or Not. Here i am adding the program to find the given number is Prime Number or Not.

Note: Prime Number is should divided by itself only.

```<code>import java.util.ArrayList;
import java.util.List;

public class CheckPrime {
static int num = 11;  //Given Number

public static void main(String[] args) {
    if (checkPrime()) {
        System.out.println("Given Number is Prime");
    } else {
        System.out.println("Given Number is Not Prime");
    }
}

private static boolean checkPrime() {
    List l = new ArrayList();
    for (int i = 1; i <= num; i++) {
        if (num % i == 0) {
            l.add(i);
        }
    }
    return  (l.size() > 2)?false:true; //if List size more than 2, it wont be Prime Number,
    //because it should be divided by itself and One
}
}
</code>```

Body:
Write a program that prompts the user to input a positive ineteger. It should then output a message indicating whether the number is prime number. Note: 2 is the only even number that is prime. An odd integer is prime if it is not divisible by an odd integer less than or equal to the square root of the number.

Update:

This is my program its not done really still figuring it out :(

import java.util.*;

public class prime {

    static Scanner kb = new Scanner(System.in);

    public static void main() {

        System.out.print("\fEnter positive integer:");

        int num = kb.nextInt();

        if (num < 1)

            System.out.print("Please enter number greater than 1"
                    + "Perform the program again");

        else if (num == 2)
            System.out.print("its a prime yey!");

        else if (num % 2 == 0)
            System.out.print("its not a prime ");

    }
}

Idk whats next still figuring it out T.T

Body:
Given Number is Prime or Not. Here i am adding the program to find the given number is Prime Number or Not.

Note: Prime Number is should divided by itself only.

import java.util.ArrayList;
import java.util.List;

public class CheckPrime {
static int num = 11;  //Given Number

public static void main(String[] args) {
    if (checkPrime()) {
        System.out.println("Given Number is Prime");
    } else {
        System.out.println("Given Number is Not Prime");
    }
}

private static boolean checkPrime() {
    List l = new ArrayList();
    for (int i = 1; i <= num; i++) {
        if (num % i == 0) {
            l.add(i);
        }
    }
    return  (l.size() > 2)?false:true; //if List size more than 2, it wont be Prime Number,
    //because it should be divided by itself and One
}
}