问:
CBManager state always unknown
I am trying to check if the bluetooth of a device is on or off. This is the code I've written so far

```<code>   CBCentralManager *cbManager = [[CBCentralManager alloc] initWithDelegate:self
                                                                       queue:nil
                                                                     options:
                                   [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:0]
                                                               forKey:CBCentralManagerOptionShowPowerAlertKey]];

    [cbManager scanForPeripheralsWithServices:nil options:
                                    [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:0]
                                                                forKey:CBCentralManagerOptionShowPowerAlertKey]];

    if (cbManager.state==CBCentralManagerStatePoweredOff)
    {
        //do stuff
    }

- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    NSString *stateString = nil;
    switch(bluetoothManager.state)
    {
        case CBCentralManagerStateResetting: stateString = @"The connection with the system service was momentarily lost, update imminent."; break;
        case CBCentralManagerStateUnsupported: stateString = @"The platform doesn't support Bluetooth Low Energy."; break;
        case CBCentralManagerStateUnauthorized: stateString = @"The app is not authorized to use Bluetooth Low Energy."; break;
        case CBCentralManagerStatePoweredOff: stateString = @"Bluetooth is currently powered off."; break;
        case CBCentralManagerStatePoweredOn: stateString = @"Bluetooth is currently powered on and available to use."; break;
        default: stateString = @"State unknown, update imminent."; break;
    }
    UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"Bluetooth state"
                                                     message:stateString
                                                    delegate:nil
                                           cancelButtonTitle:@"Okay" otherButtonTitleArray:nil] autorelease];
    [alert show];
}
</code>```

The problem is that the state of the manager is always Unknown regardless if the bluetooth on the device is turned on or not.
Any ideas on why this happens ?

答:
I had the same issue after upgrade from Sierra, Xcode 8, Swift 3 to High Sierra, Xcode 9, Swift 4.

Solution 1: (Just for tests) Wait a second bit between init and start of scan

```<code>var scanner = BLESensorScanner(sensorName: sensorName);
sleep(1);
DispatchQueue.global(qos: .userInteractive).async {
    if (scanner.isPoweredOn()) {
        DBG("Bluetooth is powered on");
        scanner.startScan();
    }
    else {
        DBG("Bluetooth is not powered");
        exit(-1);
    }
}
</code>```

Note: BLESensorScanner implements NSObject, CBCentralManagerDelegate, CBPeripheralDelegate. sensorName is the name of the bluetooth device

Solution 2: Use event handler to wait until state becomes poweredOn

```<code>public func centralManagerDidUpdateState(_ central: CBCentralManager) {
    DBG("CBCentralManager.centralManagerDidUpdateState");
    DBGI("state=\(toString(central.state))");
    if (state == CBManagerState.poweredOn) {
        scanner.startScan();
    }
}
</code>```

Title: CBManager state always unknown

Body:
I am trying to check if the bluetooth of a device is on or off. This is the code I've written so far

   CBCentralManager *cbManager = [[CBCentralManager alloc] initWithDelegate:self
                                                                       queue:nil
                                                                     options:
                                   [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:0]
                                                               forKey:CBCentralManagerOptionShowPowerAlertKey]];

    [cbManager scanForPeripheralsWithServices:nil options:
                                    [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:0]
                                                                forKey:CBCentralManagerOptionShowPowerAlertKey]];

    if (cbManager.state==CBCentralManagerStatePoweredOff)
    {
        //do stuff
    }

- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    NSString *stateString = nil;
    switch(bluetoothManager.state)
    {
        case CBCentralManagerStateResetting: stateString = @"The connection with the system service was momentarily lost, update imminent."; break;
        case CBCentralManagerStateUnsupported: stateString = @"The platform doesn't support Bluetooth Low Energy."; break;
        case CBCentralManagerStateUnauthorized: stateString = @"The app is not authorized to use Bluetooth Low Energy."; break;
        case CBCentralManagerStatePoweredOff: stateString = @"Bluetooth is currently powered off."; break;
        case CBCentralManagerStatePoweredOn: stateString = @"Bluetooth is currently powered on and available to use."; break;
        default: stateString = @"State unknown, update imminent."; break;
    }
    UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"Bluetooth state"
                                                     message:stateString
                                                    delegate:nil
                                           cancelButtonTitle:@"Okay" otherButtonTitleArray:nil] autorelease];
    [alert show];
}

The problem is that the state of the manager is always Unknown regardless if the bluetooth on the device is turned on or not.
Any ideas on why this happens ?

Body:
I had the same issue after upgrade from Sierra, Xcode 8, Swift 3 to High Sierra, Xcode 9, Swift 4.

Solution 1: (Just for tests) Wait a second bit between init and start of scan

var scanner = BLESensorScanner(sensorName: sensorName);
sleep(1);
DispatchQueue.global(qos: .userInteractive).async {
    if (scanner.isPoweredOn()) {
        DBG("Bluetooth is powered on");
        scanner.startScan();
    }
    else {
        DBG("Bluetooth is not powered");
        exit(-1);
    }
}

Note: BLESensorScanner implements NSObject, CBCentralManagerDelegate, CBPeripheralDelegate. sensorName is the name of the bluetooth device

Solution 2: Use event handler to wait until state becomes poweredOn

public func centralManagerDidUpdateState(_ central: CBCentralManager) {
    DBG("CBCentralManager.centralManagerDidUpdateState");
    DBGI("state=\(toString(central.state))");
    if (state == CBManagerState.poweredOn) {
        scanner.startScan();
    }
}


来源: stackexchange

问:
How to use exception handling in a loop (for n iterations) in python so that results are stored in a file but loop doesn't terminate?
I want to raise exceptions in the form of logs in file and loop should not terminate if exception occurs in a particular iteration.

Input:

```<code>str = 'my name and age are not known'
for i in range(0,n):
    try:
        list =['name','age']
        for word in list:
           if word in str:
               print('output verified')
           else:
               raise Exception('unmatched values')
               print('unmatched values for iteration n')

     except Exception as ex:
        TestCase.status = FAIL
        raise ex
</code>```

Output:

```<code>  unmatched values
</code>```

I want output to be stored in a file and loop should continue for next iteration

答:
Have a look into the below code logging in the file can be done as per requirement :

```<code>for i in range(0,n):
    try:
        list =['name','age']
        for word in list:
            if word in str:
                print('output verified')
            else:
                # instead of a generic exception a specific exception can be raised
                raise Exception('unmatched values')
                print('unmatched values for iteration n')
    except Exception:
        TestCase.status = FAIL
        print "Log you result in a file "
        # raise ex  - need not be here
</code>```

Happy Coding :)

ContentLicense: CC BY-SA 3.0

Body:
I want to raise exceptions in the form of logs in file and loop should not terminate if exception occurs in a particular iteration.

Input:

str = 'my name and age are not known'
for i in range(0,n):
    try:
        list =['name','age']
        for word in list:
           if word in str:
               print('output verified')
           else:
               raise Exception('unmatched values')
               print('unmatched values for iteration n')

     except Exception as ex:
        TestCase.status = FAIL
        raise ex

Output:

  unmatched values

I want output to be stored in a file and loop should continue for next iteration

Body:
Have a look into the below code logging in the file can be done as per requirement :

for i in range(0,n):
    try:
        list =['name','age']
        for word in list:
            if word in str:
                print('output verified')
            else:
                # instead of a generic exception a specific exception can be raised
                raise Exception('unmatched values')
                print('unmatched values for iteration n')
    except Exception:
        TestCase.status = FAIL
        print "Log you result in a file "
        # raise ex  - need not be here

Happy Coding :)


问:
Getting syntax error while running a SQL script in psql
I get a syntax error when running the below command.</p>
```<code>yyyyyydb=# psql yyyyyydb< /tmp/yyyyyydb_bkp_11202017.sql;
ERROR:  syntax error at or near "psql"
LINE 1: psql waivrdb < /tmp/yyyyyydb_bkp_11202017.sql;
</code>```

答:
psql is a command line program, not a SQL command. Your prompt shows that you are already inside of psql so you don't need to start that program again.

To run a SQL script from within psql, use the \i command:

```<code>waivrdb=# \i /tmp/waivrdb_bkp_11202017.sql
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I get a syntax error when running the below command.

yyyyyydb=# psql yyyyyydb< /tmp/yyyyyydb_bkp_11202017.sql;
ERROR:  syntax error at or near "psql"
LINE 1: psql waivrdb < /tmp/yyyyyydb_bkp_11202017.sql;

Body:
psql is a command line program, not a SQL command. Your prompt shows that you are already inside of psql so you don't need to start that program again.

To run a SQL script from within psql, use the \i command:

waivrdb=# \i /tmp/waivrdb_bkp_11202017.sql


问:
Windows Phone 7 download pure HTML as string?
I have been trying to get a clear answer on how to download a page's HTML as a string for months, but have made zero progress. I can mess with all of the parsing myself, and I'll be able to figure out where it needs to fit into the application as I mess around with it. I would be very very grateful if someone could give me a clear code block to download a page's HTML as a string from a given url.</p>

答:
Well the simplest way is to use WebClient:

```<code>WebClient client = new WebClient();
client.DownloadStringCompleted += YourEventHandler;
client.DownloadStringAsync(uri);
</code>```

where the event handler then takes whatever action it needs to.

However, it's worth bearing in mind that WebClient does rather a lot of work on the UI thread (despite the "async" part) - if this is for a production app, you probably want to use WebRequest directly. That's significantly more work (you end up with a Stream from the WebResponse, so you need to use the appropriate string encoding and construct a StreamReader around it in order to read a string).

ContentLicense: CC BY-SA 2.5

Body:
Well the simplest way is to use WebClient:

WebClient client = new WebClient();
client.DownloadStringCompleted += YourEventHandler;
client.DownloadStringAsync(uri);

where the event handler then takes whatever action it needs to.

However, it's worth bearing in mind that WebClient does rather a lot of work on the UI thread (despite the "async" part) - if this is for a production app, you probably want to use WebRequest directly. That's significantly more work (you end up with a Stream from the WebResponse, so you need to use the appropriate string encoding and construct a StreamReader around it in order to read a string).


问:
CodeIgniter upload and resize image
I need this to upload and resize an image. I keep getting a 404 error and don't know why. it is also suppose to output the image on the success page but I have not gotten that fat. I'm not very good at codeignighter any help is appreciated.

known problem the table I am putting the image in in MySQL is called image_upload. I know this is never referenced also I know now that I am suppose to have a $this->load->database(); in the construct.

controller

```<code><?php

class Upload extends CI_Controller {

   public function __construct()
    {
            parent::__construct();
            $this->load->helper(array('form', 'url'));
    }

    public function index()
    {
            $this->load->view('upload_form', array('error' => ' ' ));
    }

    public function do_upload()
    {
            $config['upload_path']          = './images/';
            $config['allowed_types']        = 'gif|jpg|png';
            $config['max_size']             = 100;
            $config['max_width']            = 1024;
            $config['max_height']           = 768;

            $this->load->library('upload', $config);

         $this->upload->do_upload('image');
    $fInfo = $this->upload->data(); // get all info of uploaded file

    //for image resize
    $img_array = array();
    $img_array['image_library'] = 'gd2';
    $img_array['maintain_ratio'] = TRUE;
    $img_array['create_thumb'] = TRUE;
    //you need this setting to tell the image lib which image to process
    $img_array['source_image'] = $fInfo['full_path'];
    $img_array['width'] = 113;
    $img_array['height'] = 75;

    $this->image_lib->clear(); // added this line
    $this->image_lib->initialize($img_array); // added this line
    if (!$this->image_lib->resize())

            if ( ! $this->upload->do_upload('userfile'))
            {
                    $error = array('error' => $this->upload->display_errors());

                    $this->load->view('upload_form', $error);
            }
            else
            {
                    $data = array('upload_data' => $this->upload->data());

                    $this->load->view('upload_success', $data);
            }
    }
   }
</code>```

views/form

```<code>    <html>
    <head>
    <title>Upload Form</title>
    </head>
    <body>

    <?php echo $error;?>

    <form>

    <input type="file" name="userfile" size="20" />

    <br /><br />

    <input type="submit" value="upload" />

    </form>

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

views/form_success

```<code>    <html>
    <head>
    <title>Upload Form</title>
    </head>
    <body>

    <h3>Your file was successfully uploaded!</h3>

    <ul>
    <?php foreach ($upload_data as $item => $value):?>
    <li><?php echo $item;?>: <?php echo $value;?></li>
    <?php endforeach; ?>
    </ul>

     <p><?php echo anchor('upload', 'Upload Another File!'); ?></p>

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

答:
```<code>$this->upload->do_upload('image');
</code>```

Change this to input type file name

```<code>$this->upload->do_upload('userfile');
</code>```

and put image resize code if image successfully uploaded

```<code>if(!$this->upload->do_upload('userfile'))
{
    $fInfo = $this->upload->data(); // get all info of uploaded file
    //for image resize
    $img_array = array();
    $img_array['image_library'] = 'gd2';
    $img_array['maintain_ratio'] = TRUE;
    $img_array['create_thumb'] = TRUE;
    //you need this setting to tell the image lib which image to process
    $img_array['source_image'] = $fInfo['full_path'];
    $img_array['width'] = 113;
    $img_array['height'] = 75;

    $this->image_lib->clear(); // added this line
    $this->image_lib->initialize($img_array); // added this line
    $data = array('upload_data' => $this->upload->data());
    $this->load->view('upload_success', $data);
}
else
{
    $data = array('upload_data' => $this->upload->data());
    $this->load->view('upload_success', $data);
}
</code>```

Title: CodeIgniter upload and resize image

Body:
I need this to upload and resize an image. I keep getting a 404 error and don't know why. it is also suppose to output the image on the success page but I have not gotten that fat. I'm not very good at codeignighter any help is appreciated.

known problem the table I am putting the image in in MySQL is called image_upload. I know this is never referenced also I know now that I am suppose to have a $this->load->database(); in the construct.

controller

<?php

class Upload extends CI_Controller {

   public function __construct()
    {
            parent::__construct();
            $this->load->helper(array('form', 'url'));
    }

    public function index()
    {
            $this->load->view('upload_form', array('error' => ' ' ));
    }

    public function do_upload()
    {
            $config['upload_path']          = './images/';
            $config['allowed_types']        = 'gif|jpg|png';
            $config['max_size']             = 100;
            $config['max_width']            = 1024;
            $config['max_height']           = 768;

            $this->load->library('upload', $config);

         $this->upload->do_upload('image');
    $fInfo = $this->upload->data(); // get all info of uploaded file

    //for image resize
    $img_array = array();
    $img_array['image_library'] = 'gd2';
    $img_array['maintain_ratio'] = TRUE;
    $img_array['create_thumb'] = TRUE;
    //you need this setting to tell the image lib which image to process
    $img_array['source_image'] = $fInfo['full_path'];
    $img_array['width'] = 113;
    $img_array['height'] = 75;

    $this->image_lib->clear(); // added this line
    $this->image_lib->initialize($img_array); // added this line
    if (!$this->image_lib->resize())

            if ( ! $this->upload->do_upload('userfile'))
            {
                    $error = array('error' => $this->upload->display_errors());

                    $this->load->view('upload_form', $error);
            }
            else
            {
                    $data = array('upload_data' => $this->upload->data());

                    $this->load->view('upload_success', $data);
            }
    }
   }

views/form

    <title>Upload Form</title>

    <?php echo $error;?>

    <form>

    <input type="file" name="userfile" size="20" />

    <input type="submit" value="upload" />

    </form>

views/form_success

    <title>Upload Form</title>

Your file was successfully uploaded!

    <?php foreach ($upload_data as $item => $value):?>

<?php echo $item;?>: <?php echo $value;?>

    <?php endforeach; ?>

<?php echo anchor('upload', 'Upload Another File!'); ?>

Body:
$this->upload->do_upload('image');

Change this to input type file name

$this->upload->do_upload('userfile');

and put image resize code if image successfully uploaded

if(!$this->upload->do_upload('userfile'))
{
    $fInfo = $this->upload->data(); // get all info of uploaded file
    //for image resize
    $img_array = array();
    $img_array['image_library'] = 'gd2';
    $img_array['maintain_ratio'] = TRUE;
    $img_array['create_thumb'] = TRUE;
    //you need this setting to tell the image lib which image to process
    $img_array['source_image'] = $fInfo['full_path'];
    $img_array['width'] = 113;
    $img_array['height'] = 75;

    $this->image_lib->clear(); // added this line
    $this->image_lib->initialize($img_array); // added this line
    $data = array('upload_data' => $this->upload->data());
    $this->load->view('upload_success', $data);
}
else
{
    $data = array('upload_data' => $this->upload->data());
    $this->load->view('upload_success', $data);
}


问:
Get column names, distinct values and its occurrences into a text file with Spark Scala
I am new to Spark Scala and would like to execute the following tasks:

Get all column names, the values and its occurrences from a table

Write the result into a text file, i.e. in the following format:

```<code>Column Name |Value | Occurrences
   Col1     |Test  |      12
   Col2     |123   |      15
</code>```

I am using Spark 1.6, not Spark 2.0.

Thanks a lot in advance for any help.

Cheers,
Matthias

答:
Hope this will help you.
Let me explain with an example.

I have a file, users.txt with content as following:

```<code>1 abc@test.com EN US

2 xyz@test2.com EN GB

3 srt@test3.com FR FR
</code>```

Code:

```<code>var fileRDD=sc.textFile("users.txt")
case class User(ID:Int,email:String,lang:String,country:String)
var rawRDD=fileRDD.flatMap(_.split("\t")).map(_.split(" "))
var userRDD=rawRDD.map(u=>User(u(0).toInt,u(1).toString,u(2).toString,u(3).toString))
userDF.registerTempTable("user_table")

sqlContext.sql("select * from user_table").show()

+---+-------------+----+-------+
| ID|        email|lang|country|
+---+-------------+----+-------+
|  1| abc@test.com|  EN|     US|
|  2|xyz@test2.com|  EN|     GB|
|  3|srt@test3.com|  FR|     FR|
+---+-------------+----+-------+

var emailCount=sqlContext.sql("select 'email' as col,email as value, count(email) as occur from user_table group by email")
var langCount=sqlContext.sql("select 'lang' as col,lang as value, count(lang) as occur from user_table group by lang")
emailCount.unionAll(langCount).show()

+-----+-------------+-----+
|  col|        value|occur|
+-----+-------------+-----+
|email|srt@test3.com|    1|
|email|xyz@test2.com|    1|
|email| abc@test.com|    1|
| lang|           EN|    2|
| lang|           FR|    1|
+-----+-------------+-----+
</code>```

Body:
I am new to Spark Scala and would like to execute the following tasks:

Get all column names, the values and its occurrences from a table

Write the result into a text file, i.e. in the following format:

Column Name |Value | Occurrences
   Col1     |Test  |      12
   Col2     |123   |      15

I am using Spark 1.6, not Spark 2.0.

Thanks a lot in advance for any help.

Cheers,
Matthias

Body:
Hope this will help you.
Let me explain with an example.

I have a file, users.txt with content as following:

1 abc@test.com EN US

2 xyz@test2.com EN GB

3 srt@test3.com FR FR

Code:

var fileRDD=sc.textFile("users.txt")
case class User(ID:Int,email:String,lang:String,country:String)
var rawRDD=fileRDD.flatMap(_.split("\t")).map(_.split(" "))
var userRDD=rawRDD.map(u=>User(u(0).toInt,u(1).toString,u(2).toString,u(3).toString))
userDF.registerTempTable("user_table")

sqlContext.sql("select * from user_table").show()

+---+-------------+----+-------+
| ID|        email|lang|country|
+---+-------------+----+-------+
|  1| abc@test.com|  EN|     US|
|  2|xyz@test2.com|  EN|     GB|
|  3|srt@test3.com|  FR|     FR|
+---+-------------+----+-------+

var emailCount=sqlContext.sql("select 'email' as col,email as value, count(email) as occur from user_table group by email")
var langCount=sqlContext.sql("select 'lang' as col,lang as value, count(lang) as occur from user_table group by lang")
emailCount.unionAll(langCount).show()

+-----+-------------+-----+
|  col|        value|occur|
+-----+-------------+-----+
|email|srt@test3.com|    1|
|email|xyz@test2.com|    1|
|email| abc@test.com|    1|
| lang|           EN|    2|
| lang|           FR|    1|
+-----+-------------+-----+


问:
Jax-rs convert to object Mule
I am using RAML for design api.
Then I convert raml to jaxrs and get java classes (https://github.com/mulesoft-labs/raml-for-jax-rs ).
It gives two classes: interface and *impl classes.
Then I Import them into my project In Anypoint Studio. I want to use them.

But JsonToObject Transfer cannot use convert classes.

org.mule.api.transformer.TransformerMessagingException: Failed to transform from "json" to "classImpl".

I try use without interface classes. It work correct.

How to use interface and *impl Classes for convert json to Object?

答: I solved the problem. 1. RAML need to convert using jackson 2. In Anypoint need to deserialize from the json to the object by ObjectMapper</p>

Title: Jax-rs convert to object Mule


答:
It looks like you're running a shell command psql waivrdb < /tmp/waivrdb_bkp_11202017.sql inside the postgres client rather than from your shell. So, run psql waivrdb < /tmp/waivrdb_bkp_11202017.sql from the shell and you should be good.

You can also run \i /tmp/waivrdb_bkp_11202017.sql from inside the postgres client.

Title: Getting syntax error while running a SQL script in psql


问:
Mongodb: get only array of post comments from this object
So far I achieved is I got the array inside the object and I want the array directly.

Here is my object:

```<code>{
    "_id" : ObjectId("5a28e2a1bf22d2a9ddb8f5d5"),
    "description" : "My Post",
    "postLikes" : [
        {
            "likesCount" : 0,
            "likeByEmail" : "a@a.com",
            "createdOn" : NumberLong(1512631701702),
            "updatedOn" : NumberLong(0)
        }
    ],
    "postComments" : [
        {
            "comment" : "This is first comment",
            "likeByEmail" : "a@a.com",
            "createdOn" : NumberLong(1512643824764),
            "updatedOn" : NumberLong(1512643824764)
        }
    ],
    "createdOn" : NumberLong(0),
    "updatedOn" : NumberLong(0)
}
</code>```

My Query is:

```<code>db.user_posts.find({_id: ObjectId("5a28e2a1bf22d2a9ddb8f5d5")}, {postComments:1})
</code>```

and the result is:

```<code>{
    "_id" : ObjectId("5a28e2a1bf22d2a9ddb8f5d5"),
    "postComments" : [
        {
            "comment" : "This is first comment",
            "likeByEmail" : "a@a.com",
            "createdOn" : NumberLong(1512643824764),
            "updatedOn" : NumberLong(1512643824764)
        }
    ]
}
</code>```

What I want is:

```<code> [
        {
            "_id" : null,
            "comment" : "This is first comment",
            "likeByEmail" : "a@a.com",
            "createdOn" : NumberLong(1512643824764),
            "updatedOn" : NumberLong(1512643824764)
        }
    ]
</code>```

Also I am using MongoRepository in Spring Boot and the query there is:

```<code>@Query(value = "{'_id' : ?0}, {'postComments':1}")
</code>```

and it gave me the same result.

答:
You can add "_id":false

```<code>db.user_posts.find({
    _id: ObjectId("5a28e2a1bf22d2a9ddb8f5d5")
}, {
    postComments: 1,
    "_id": false
})
</code>```

Or "_id":0

```<code>db.user_posts.find({
    _id: ObjectId("5a28e2a1bf22d2a9ddb8f5d5")
}, {
    postComments: 1,
    "_id": 0
})
</code>```

If you only want part of your document then you have to make use of aggregation framework. Luckily there is spring support on that.

As vaibhav mentioned already what find() returns.

You can solve your problem with aggregation like that:

```<code>db.user_posts.aggregate([
{ $match: {_id: ObjectId("5a28e2a1bf22d2a9ddb8f5d5")}},
{ $unwind: "$postComments"},
{ $project: {
    _id: 0,
    comment: "$postComments.comment",
    likeByEmail: "$postComments.likeByEmail",
    createdOn: "$postComments.createdOn",
    updatedOn: "$postComments.updatedOn"
  }
}
])
</code>```

As proposed by @Veeram you can also do this:

```<code>db.user_posts.aggregate([
{ $match: {_id: ObjectId("5a28e2a1bf22d2a9ddb8f5d5")}},
{ $unwind: "$postComments"},
{ $replaceRoot: {"newRoot":"$postComments"}}
])
</code>```

Body:
So far I achieved is I got the array inside the object and I want the array directly.

Here is my object:

{
    "_id" : ObjectId("5a28e2a1bf22d2a9ddb8f5d5"),
    "description" : "My Post",
    "postLikes" : [
        {
            "likesCount" : 0,
            "likeByEmail" : "a@a.com",
            "createdOn" : NumberLong(1512631701702),
            "updatedOn" : NumberLong(0)
        }
    ],
    "postComments" : [
        {
            "comment" : "This is first comment",
            "likeByEmail" : "a@a.com",
            "createdOn" : NumberLong(1512643824764),
            "updatedOn" : NumberLong(1512643824764)
        }
    ],
    "createdOn" : NumberLong(0),
    "updatedOn" : NumberLong(0)
}

My Query is:

db.user_posts.find({_id: ObjectId("5a28e2a1bf22d2a9ddb8f5d5")}, {postComments:1})

and the result is:

{
    "_id" : ObjectId("5a28e2a1bf22d2a9ddb8f5d5"),
    "postComments" : [
        {
            "comment" : "This is first comment",
            "likeByEmail" : "a@a.com",
            "createdOn" : NumberLong(1512643824764),
            "updatedOn" : NumberLong(1512643824764)
        }
    ]
}

What I want is:

 [
        {
            "_id" : null,
            "comment" : "This is first comment",
            "likeByEmail" : "a@a.com",
            "createdOn" : NumberLong(1512643824764),
            "updatedOn" : NumberLong(1512643824764)
        }
    ]

Also I am using MongoRepository in Spring Boot and the query there is:

@Query(value = "{'_id' : ?0}, {'postComments':1}")

and it gave me the same result.

Body:
You can add "_id":false

db.user_posts.find({
    _id: ObjectId("5a28e2a1bf22d2a9ddb8f5d5")
}, {
    postComments: 1,
    "_id": false
})

Or "_id":0

db.user_posts.find({
    _id: ObjectId("5a28e2a1bf22d2a9ddb8f5d5")
}, {
    postComments: 1,
    "_id": 0
})

If you only want part of your document then you have to make use of aggregation framework. Luckily there is spring support on that.

As vaibhav mentioned already what find() returns.

You can solve your problem with aggregation like that:

db.user_posts.aggregate([
{ $match: {_id: ObjectId("5a28e2a1bf22d2a9ddb8f5d5")}},
{ $unwind: "$postComments"},
{ $project: {
    _id: 0,
    comment: "$postComments.comment",
    likeByEmail: "$postComments.likeByEmail",
    createdOn: "$postComments.createdOn",
    updatedOn: "$postComments.updatedOn"
  }
}
])

As proposed by @Veeram you can also do this:

db.user_posts.aggregate([
{ $match: {_id: ObjectId("5a28e2a1bf22d2a9ddb8f5d5")}},
{ $unwind: "$postComments"},
{ $replaceRoot: {"newRoot":"$postComments"}}
])


问:
redux-form input type number returns string
redux-form input type is returning string , it should have returned number

Replicated problem

so i used parse to convert it to number

```<code>      <Field
        name="age"
        parse={value => Number(value)}
        component="input"
        type="number"
        placeholder="Age"
      />
</code>```

Note : In redux form it Shows string

But the problem is it does let us remove last DIGIT ZERO

答:
It happens because Number('') return 0. So Instead of setting the parse attribute to Field, you could just parse the value wherever you need

```<code><form onSubmit={handleSubmit}>
  <div>
    {age ? <div>{typeof Number(age)} {`${age}`}</div>: null}
  </div>

  <div>
    <label>Age</label>
    <div>
      <Field
        name="age"
        component="input"
        type="number"
        placeholder="Age"
      />
    </div>
  </div>
</form>
</code>```

CodeSandbox

Body:
redux-form input type is returning string , it should have returned number

Replicated problem

so i used parse to convert it to number

      <Field
        name="age"
        parse={value => Number(value)}
        component="input"
        type="number"
        placeholder="Age"
      />

Note : In redux form it Shows string

But the problem is it does let us remove last DIGIT ZERO

Body:
It happens because Number('') return 0. So Instead of setting the parse attribute to Field, you could just parse the value wherever you need

<form onSubmit={handleSubmit}>
  <div>
    {age ? <div>{typeof Number(age)} {`${age}`}</div>: null}
  </div>

  <div>
    <label>Age</label>
    <div>
      <Field
        name="age"
        component="input"
        type="number"
        placeholder="Age"
      />
    </div>
  </div>
</form>

CodeSandbox


问:
std::map.clear() is throwing an Read Access Violation

I am trying to invoke the clear() method on a std::map without getting an "Exception thrown: read access violation._Pnode was 0xDDDDDDDD.".

```<code>//I have narrowed down the error to this group of code
#include "stdafx.h"
#include <map>
#include <iostream>

class Input
{
    std::map<int, bool> pressedKeys;
    std::map<int, bool> heldKeys;
    std::map<int, bool> releasedKeys;

public:
    void Update()
    {
        heldKeys.clear();
        pressedKeys.clear();
        releasedKeys.clear();
    }
};

class Window
{
private:
    Input * input;
    void Update()
    {
        input->Update();
    }
public:
    Window()
    {
        input = &Input();

        while (true)
        {
            this->Update();
        }
    }
};

int main()
{
    Window w = Window();
}
</code>```

The exception always happens on "heldKeys.clear();"
The debugger in Visual Studio brings me to a page called "xtree." The code that follows is the code around where the exception happens in "xtree:"

```<code>void _Erase(_Nodeptr _Rootnode)
    {   // free entire subtree, recursively
    for (_Nodeptr _Pnode = _Rootnode; !_Pnode->_Isnil; _Rootnode = _Pnode) //The error occurs here
        {   // free subtrees, then node
        _Erase(_Pnode->_Right);
        _Pnode = _Pnode->_Left;
        _Alnode& _Al = this->_Getal();
        _Alnode_traits::destroy(_Al, _STD addressof(_Rootnode->_Myval));
        _Node::_Freenode0(_Al, _Rootnode);
        }
    }
</code>```

I expect no exceptions.

I am getting the exception  "Exception thrown: read access violation.
_Pnode was 0xDDDDDDDD."
If any more clarification is needed please comment.

答:
Do you have all warnings turned on in your compiler? Really any fairly recent high quality C++ compiler should catch this. E.g. go to http://rextester.com/l/cpp_online_compiler_clang and type in the code, removing the stdafx.h header, which is not needed anyway, and you'll see:

```<code>source_file.cpp:31:17: error: taking the address of a temporary object of type 'Input' [-Waddress-of-temporary]
        input = &Input();
                ^~~~~~~~
</code>```

(Using clang 3.8 as the compiler.)

This proves a much more efficient method for finding a large class of run-of-the-mill programming errors as compared to Stack Overflow. Other classes of errors may involve turning on extra analysis passes or sanitizers such as clang's Address Sanitizer, Memory Sanitizer, or Undefined Behavior Sanitizer.

Body:
I am trying to invoke the clear() method on a std::map without getting an "Exception thrown: read access violation._Pnode was 0xDDDDDDDD.".

//I have narrowed down the error to this group of code
#include "stdafx.h"
#include <map>
#include <iostream>

class Input
{
    std::map<int, bool> pressedKeys;
    std::map<int, bool> heldKeys;
    std::map<int, bool> releasedKeys;

public:
    void Update()
    {
        heldKeys.clear();
        pressedKeys.clear();
        releasedKeys.clear();
    }
};

class Window
{
private:
    Input * input;
    void Update()
    {
        input->Update();
    }
public:
    Window()
    {
        input = &Input();

        while (true)
        {
            this->Update();
        }
    }
};

int main()
{
    Window w = Window();
}

The exception always happens on "heldKeys.clear();"
The debugger in Visual Studio brings me to a page called "xtree." The code that follows is the code around where the exception happens in "xtree:"

void _Erase(_Nodeptr _Rootnode)
    {   // free entire subtree, recursively
    for (_Nodeptr _Pnode = _Rootnode; !_Pnode->_Isnil; _Rootnode = _Pnode) //The error occurs here
        {   // free subtrees, then node
        _Erase(_Pnode->_Right);
        _Pnode = _Pnode->_Left;
        _Alnode& _Al = this->_Getal();
        _Alnode_traits::destroy(_Al, _STD addressof(_Rootnode->_Myval));
        _Node::_Freenode0(_Al, _Rootnode);
        }
    }

I expect no exceptions.

I am getting the exception  "Exception thrown: read access violation.
_Pnode was 0xDDDDDDDD."
If any more clarification is needed please comment.

Body:
Do you have all warnings turned on in your compiler? Really any fairly recent high quality C++ compiler should catch this. E.g. go to http://rextester.com/l/cpp_online_compiler_clang and type in the code, removing the stdafx.h header, which is not needed anyway, and you'll see:

source_file.cpp:31:17: error: taking the address of a temporary object of type 'Input' [-Waddress-of-temporary]
        input = &Input();
                ^~~~~~~~

(Using clang 3.8 as the compiler.)

This proves a much more efficient method for finding a large class of run-of-the-mill programming errors as compared to Stack Overflow. Other classes of errors may involve turning on extra analysis passes or sanitizers such as clang's Address Sanitizer, Memory Sanitizer, or Undefined Behavior Sanitizer.


问:
Groovy+ XML: handle Attributes with Namespace-Prefix
I'm working on a XML-document with Groovy and test a node for a certain attribute, which has a  namespace prefix. How could it work:

in groovy-script:

```<code>...
Element.Subelement.each {
  if (it.'@type'=='ns2:xyType')
    ...do what ever...
}
</code>```

in XML document:

```<code><Element>
   <Subelement xsi:type="ns2:xyType">
      <!-- or another type, want to do something with
           subelement only if type is "ns2:xyType" -->
   </Subelement>
</Element>
</code>```

Looking for something like:

```<code>if (it.'@xsi:type'=='ns2:xyType')
</code>```

THX
Seldon

答:
Well, your document is a little confusing, since it seems that neither xsi nor ns2 namespaces were ever declared, but I'm going to assume they were declared somewhere in the complete doc.

From The Groovy Docs

```<code>def wsdl = '''
<definitions name="AgencyManagementService"
    xmlns:ns1="http://www.example.org/NS1"
    xmlns:ns2="http://www.example.org/NS2">
    <ns1:message name="SomeRequest">
        <ns1:part name="parameters" element="SomeReq" />
    </ns1:message>
    <ns2:message name="SomeRequest">
        <ns2:part name="parameters" element="SomeReq" />
    </ns2:message>
</definitions>
'''

def xml = new XmlSlurper().parseText(wsdl).declareNamespace(ns1: 'http://www.example.org/NS1', ns2: 'http://www.example.org/NS2')
println xml.'ns1:message'.'ns1:part'.size()
println xml.'ns2:message'.'ns2:part'.size()
</code>```

For your example (note, you'll have to fill in the URLs for the namespaces):

```<code>def ggg = '''
<Element xmlns:xsi="http://www.example.org/xsi"
    xmlns:ns2="http://www.example.org/NS2">
   <Subelement xsi:type="ns2:xyType">
      <SubSub name="bob" />
   </Subelement>
</Element>
'''
def xml = new XmlSlurper().parseText(ggg).declareNamespace(xsi: 'http://www.example.org/xsi', ns2: 'http://www.example.org/NS2')
def elem = xml.'Subelement'
if ( elem.'@xsi:type'.text() == 'ns2:xyType' ){
   // do it
}
</code>```

OwnerDisplayName: Seldon

LastEditorDisplayName: Tomalak

Body:
I'm working on a XML-document with Groovy and test a node for a certain attribute, which has a  namespace prefix. How could it work:

in groovy-script:

...
Element.Subelement.each {
  if (it.'@type'=='ns2:xyType')
    ...do what ever...
}

in XML document:

<Element>
   <Subelement xsi:type="ns2:xyType">

   </Subelement>
</Element>

Looking for something like:

if (it.'@xsi:type'=='ns2:xyType')

THX
Seldon

Body:
Well, your document is a little confusing, since it seems that neither xsi nor ns2 namespaces were ever declared, but I'm going to assume they were declared somewhere in the complete doc.

From The Groovy Docs

def wsdl = '''
<definitions name="AgencyManagementService"
    xmlns:ns1="http://www.example.org/NS1"
    xmlns:ns2="http://www.example.org/NS2">
    <ns1:message name="SomeRequest">
        <ns1:part name="parameters" element="SomeReq" />
    </ns1:message>
    <ns2:message name="SomeRequest">
        <ns2:part name="parameters" element="SomeReq" />
    </ns2:message>
</definitions>
'''

def xml = new XmlSlurper().parseText(wsdl).declareNamespace(ns1: 'http://www.example.org/NS1', ns2: 'http://www.example.org/NS2')
println xml.'ns1:message'.'ns1:part'.size()
println xml.'ns2:message'.'ns2:part'.size()

For your example (note, you'll have to fill in the URLs for the namespaces):

def ggg = '''
<Element xmlns:xsi="http://www.example.org/xsi"
    xmlns:ns2="http://www.example.org/NS2">
   <Subelement xsi:type="ns2:xyType">
      <SubSub name="bob" />
   </Subelement>
</Element>
'''
def xml = new XmlSlurper().parseText(ggg).declareNamespace(xsi: 'http://www.example.org/xsi', ns2: 'http://www.example.org/NS2')
def elem = xml.'Subelement'
if ( elem.'@xsi:type'.text() == 'ns2:xyType' ){
   // do it
}

OwnerDisplayName: Bill James

LastEditorDisplayName: Bill James


问:
What's wrong with this HTML code?
I want the body part to be underneath the menu, but instead the menu is merged with the body.

http://jsfiddle.net/aqFGD/

```<code><!DOCTYPE html>
<html>
<head>
    <title>Hi</title>
    <style type="text/css">
    body
    {
        background-color: #369;
    }
    li.changeMe
    {
        background-color: #DEE;
        color: #369;
        font-weight: bold;
        padding: 8px 16px;
        margin: 5px;
        display: inline;
    }
    #bodystuff
    {
        background-color: White;
        display: block;
        padding: 15px 10px;
    }

    </style>
</head>

<body>
    <div style="margin: 15px 10px 0;">
    <div style="font-size: 30pt; font-weight: bold; color: White; font-family: Arial;">My Website</div>
    <div style="float: right; display: block; margin: 0 0 25px 0"><ul style="list-style-type: none; "><li class="changeMe">Hi</li><li class="changeMe">Hello</li></ul></div>
    <div id="bodystuff">Hi this is the body</div>
    </div>
</body>
</html>
</code>```

答:
If you're intending to do anything more than just play around with this, you should use my updated code.

I improved many things - I can explain what and why, if you would like.

I assumed that you wanted the menu buttons to touch the top of #bodystuff, which as far as I can see, none of the other posted answers do without further changes.

Live Demo

```<code><!DOCTYPE html>
<html>
<head>
<title>Hi</title>
<style type="text/css">
body {
    background-color: #369;
    font-family: Arial, sans-serif;
}
#container {
    margin: 15px 10px 0;
}
#header {
    font-size: 30pt;
    color: #fff;
    margin: 0;
    padding: 0;
    font-weight: bold
}
#bodystuff {
    background-color: #fff;
    clear: both;
    padding: 15px 10px
}
#menu {
    float: right
}
#menu ul {
    list-style-type: none
}
#menu li {
    background-color: #dee;
    color: #369;
    font-weight: bold;
    float: right;
    margin: 0 5px;
}
#menu a {
    display: block;
    padding: 8px 16px;
}
</style>
</head>

<body>

<div id="container">
    <h1 id="header">My Website</h1>
    <div id="menu">
        <ul>
            <li><a href="#">Hi</a></li>
            <li><a href="#">Hello</a></li>
        </ul>
    </div>
    <div id="bodystuff">
        Hi this is the body
    </div>
</div>

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

Title: What's wrong with this HTML code?

Body:
I want the body part to be underneath the menu, but instead the menu is merged with the body.

http://jsfiddle.net/aqFGD/

<!DOCTYPE html>

    <title>Hi</title>

My Website

Hi

Hello

Hi this is the body

Body:
If you're intending to do anything more than just play around with this, you should use my updated code.

I improved many things - I can explain what and why, if you would like.

I assumed that you wanted the menu buttons to touch the top of #bodystuff, which as far as I can see, none of the other posted answers do without further changes.

Live Demo

<!DOCTYPE html>
<html>
<head>
<title>Hi</title>
<style type="text/css">
body {
    background-color: #369;
    font-family: Arial, sans-serif;
}
#container {
    margin: 15px 10px 0;
}
#header {
    font-size: 30pt;
    color: #fff;
    margin: 0;
    padding: 0;
    font-weight: bold
}
#bodystuff {
    background-color: #fff;
    clear: both;
    padding: 15px 10px
}
#menu {
    float: right
}
#menu ul {
    list-style-type: none
}
#menu li {
    background-color: #dee;
    color: #369;
    font-weight: bold;
    float: right;
    margin: 0 5px;
}
#menu a {
    display: block;
    padding: 8px 16px;
}
</style>
</head>

<body>

<div id="container">
    <h1 id="header">My Website</h1>
    <div id="menu">
        <ul>
            <li><a href="#">Hi</a></li>
            <li><a href="#">Hello</a></li>
        </ul>
    </div>
    <div id="bodystuff">
        Hi this is the body
    </div>
</div>

</body>
</html>


问:
How can I split and insert a string into a SQL Server table?
I need to insert these IMS080','IMS108','IMS218 values into temptable in separate rows, like this:

```<code>row 1: IMS080
row 2: IMS108
row 3: IMS218
</code>```

Query :

```<code>INSERT INTO #TableName
    SELECT UserID
    FROM ('IMS080', 'IMS108', 'IMS218')
</code>```

Thanks in advance

答:
You can add all the id in one string separated by comma and can split it to each row. This will help you.</p>

```<code>INSERT INTO #TableName
SELECT Split.a.value('.', 'VARCHAR(100)') AS USERID
FROM
(
    SELECT CAST ('<M>' + REPLACE('IMS080,IMS108,IMS218', ',', '</M><M>') + '</M>' AS XML) AS Data
)AS A CROSS APPLY Data.nodes ('/M') AS Split(a);
</code>```

Body:
I need to insert these IMS080','IMS108','IMS218 values into temptable in separate rows, like this:

row 1: IMS080
row 2: IMS108
row 3: IMS218

Query :

INSERT INTO #TableName
    SELECT UserID
    FROM ('IMS080', 'IMS108', 'IMS218')

Thanks in advance

Body:
You can add all the id in one string separated by comma and can split it to each row. This will help you.

INSERT INTO #TableName
SELECT Split.a.value('.', 'VARCHAR(100)') AS USERID
FROM
(
    SELECT CAST ('<M>' + REPLACE('IMS080,IMS108,IMS218', ',', '</M><M>') + '</M>' AS XML) AS Data
)AS A CROSS APPLY Data.nodes ('/M') AS Split(a);


问:
Possible to replace tokenized values within a .properties file within Jenkins?
Possible to replace tokenized values within a .properties file within Jenkins?

Iam running an automation project in Jenkins which uses Java, I have a central config.properties file, is there a feature within Jenkins which would enable me to replace tokenized values via the Jenkins portal?

Current Config .properties File:

```<code><!--BROWSER TYPE: chrome | firefox -->
browser=#{browserType}#

<!--BASE BAG HOMEPAGE URL: www.google.com
url=#{homepageUrl}#

<!--Username: example21@mail.com !-->
username=#{username}#
</code>```

I need to replace all values which are contained within: #{}# therefore if i set the variable: browser with the value chrome then jenkins would replace the value and the end product would be:

```<code><!--BROWSER TYPE: chrome | firefox -->
browser=chrome
</code>```

答:
AFAIK, properties files are not updated on the fly , you can use a sed instead

```<code>sed -i "s|#{browserType}#|${browser_jenkins build_variable}|g" Config .properties
</code>```

browser_jenkins build_variable : This would a build parameter which you select when building the job

Updated solution :

define a jenkins build parameter ( choice ) as : browser_value ( variable name)

update your Config.properties file as

```<code>browser=browser_value
</code>```

Use a execute shell and use below command

```<code> sed -i "s|browser_value|${browser_value}|g" Config.properties
</code>```

The above command should replace the browser_value string in config.properties with the option you select in jenkins job choice parameter

Body:
Possible to replace tokenized values within a .properties file within Jenkins?

Iam running an automation project in Jenkins which uses Java, I have a central config.properties file, is there a feature within Jenkins which would enable me to replace tokenized values via the Jenkins portal?

Current Config .properties File:

browser=#{browserType}#

username=#{username}#

I need to replace all values which are contained within: #{}# therefore if i set the variable: browser with the value chrome then jenkins would replace the value and the end product would be:

browser=chrome

Body:
AFAIK, properties files are not updated on the fly , you can use a sed instead

sed -i "s|#{browserType}#|${browser_jenkins build_variable}|g" Config .properties

browser_jenkins build_variable : This would a build parameter which you select when building the job

Updated solution :

define a jenkins build parameter ( choice ) as : browser_value ( variable name)

update your Config.properties file as

browser=browser_value

Use a execute shell and use below command

 sed -i "s|browser_value|${browser_value}|g" Config.properties

The above command should replace the browser_value string in config.properties with the option you select in jenkins job choice parameter


问:
Normal distributed sub-sampling from a numpy array in python
I have a numpy array whose values are distributed in the following manner

From this array I need to get a random sub-sample which is normally distributed.

I need to get rid of the values from the array which are above the red line in the picture. i.e. I need to get rid of some occurences of certain values from the array so that my distribution gets smoothened when the abrupt peaks are removed.

And my array's distribution should become like this:

Can this be achieved in python, without manually looking for entries corresponding to the peaks and remove some occurences of them ? Can this be done in a simpler way ?

答:
The following kind of works, it is rather aggressive, though:

It works by ordering the samples, transforming to uniform and then trying to select a regular griddish subsample. If you feel it is too aggressive you could increase ns which is essentially the number of samples kept.

Also, please note that it requires the knowledge of the true distribution. In case of normal distribution you should be fine with using sample mean and unbiased variance estimate (the one with n-1).

Code (without plotting):

```<code>import scipy.stats as ss
import numpy as np

a = ss.norm.rvs(size=1000)
b = ss.uniform.rvs(size=1000)<0.4
a[b] += 0.1*np.sin(10*a[b])

def smooth(a, gran=25):
    o = np.argsort(a)
    s = ss.norm.cdf(a[o])
    ns = int(gran / np.max(s[gran:] - s[:-gran]))
    grid, dp = np.linspace(0, 1, ns, endpoint=False, retstep=True)
    grid += dp/2
    idx = np.searchsorted(s, grid)
    c = np.flatnonzero(idx[1:] <= idx[:-1])
    while c.size > 0:
        idx[c+1] = idx[c] + 1
        c = np.flatnonzero(idx[1:] <= idx[:-1])
    idx = idx[:np.searchsorted(idx, len(a))]
    return o[idx]

ap = a[smooth(a)]
c, b = np.histogram(a, 40)
cp, _ = np.histogram(ap, b)
</code>```

Body:
The following kind of works, it is rather aggressive, though:

It works by ordering the samples, transforming to uniform and then trying to select a regular griddish subsample. If you feel it is too aggressive you could increase ns which is essentially the number of samples kept.

Also, please note that it requires the knowledge of the true distribution. In case of normal distribution you should be fine with using sample mean and unbiased variance estimate (the one with n-1).

Code (without plotting):

import scipy.stats as ss
import numpy as np

a = ss.norm.rvs(size=1000)
b = ss.uniform.rvs(size=1000)<0.4
a[b] += 0.1*np.sin(10*a[b])

def smooth(a, gran=25):
    o = np.argsort(a)
    s = ss.norm.cdf(a[o])
    ns = int(gran / np.max(s[gran:] - s[:-gran]))
    grid, dp = np.linspace(0, 1, ns, endpoint=False, retstep=True)
    grid += dp/2
    idx = np.searchsorted(s, grid)
    c = np.flatnonzero(idx[1:] <= idx[:-1])
    while c.size > 0:
        idx[c+1] = idx[c] + 1
        c = np.flatnonzero(idx[1:] <= idx[:-1])
    idx = idx[:np.searchsorted(idx, len(a))]
    return o[idx]

ap = a[smooth(a)]
c, b = np.histogram(a, 40)
cp, _ = np.histogram(ap, b)


问:
SQL Server stored procedure not able concat varchar at input parameter
I trying to insert data from a database into multiple reports. I would like to made the destination file name to be dynamic, which was a variable. But when I replace the file name with variable, I get a syntax error.

```<code>insert into OPENROWSET('Microsoft.ACE.OLEDB.12.0',
'Excel 12.0;Database=D:\Report\PeopleCounter\myDynamicFileName.xlsx;',
'SELECT * FROM [Sheet1$]')
    select * from myresult;
</code>```

What would be the easy way to fix this?

答:
Use a dynamic query

```<code>DECLARE @value NVARCHAR(MAX)
SET @value = 'Excel 12.0;Database=D:\Report\PeopleCounter\myDynamicFileName.xlsx;'

DECLARE @a NVARCHAR(MAX)
SET @a = 'insert into OPENROWSET(''Microsoft.ACE.OLEDB.12.0'',
''' + @value + ''',
''SELECT * FROM [Sheet1$]'')
    select * from myresult;'

PRINT @a
EXEC @a
</code>```

Print @a result:

```<code>    insert into OPENROWSET('Microsoft.ACE.OLEDB.12.0',
    'Excel 12.0;Database=D:\Report\PeopleCounter\myDynamicFileName.xlsx;',
    'SELECT * FROM [Sheet1$]')
     select * from myresult;
</code>```

Body:
I trying to insert data from a database into multiple reports. I would like to made the destination file name to be dynamic, which was a variable. But when I replace the file name with variable, I get a syntax error.

insert into OPENROWSET('Microsoft.ACE.OLEDB.12.0',
'Excel 12.0;Database=D:\Report\PeopleCounter\myDynamicFileName.xlsx;',
'SELECT * FROM [Sheet1$]')
    select * from myresult;

What would be the easy way to fix this?

Body:
Use a dynamic query

DECLARE @value NVARCHAR(MAX)
SET @value = 'Excel 12.0;Database=D:\Report\PeopleCounter\myDynamicFileName.xlsx;'

DECLARE @a NVARCHAR(MAX)
SET @a = 'insert into OPENROWSET(''Microsoft.ACE.OLEDB.12.0'',
''' + @value + ''',
''SELECT * FROM [Sheet1$]'')
    select * from myresult;'

PRINT @a
EXEC @a

Print @a result:

    insert into OPENROWSET('Microsoft.ACE.OLEDB.12.0',
    'Excel 12.0;Database=D:\Report\PeopleCounter\myDynamicFileName.xlsx;',
    'SELECT * FROM [Sheet1$]')
     select * from myresult;


问:
php show array value for variable key
I am trying to make a site multi lingual. by building a language dictionary array ( if it is not the best way please don't hesitate to let me know )

```<code>$fr=array();

$fr['hello']="Bonjour";
</code>```

I would like to make a function that does the following :

for every word and language  function ( $word ="hello",$language="fr")

it would return the right value. So far the way I am doing isn't working

```<code>echo $$language[$word];
</code>```

any ideas?
thank you

答:
You might want to consider using a single (nested) array

```<code>$strings = array(
    "french" => array(
        "stringID" => "foobar"
    )
);

echo( $strings["french"]["stringID"] );
</code>```

If you are not utilising a database I would highly recommend looking into this. MySQL and PostgreSQL tend to be popular choices for independent and small development shops.

Title: php show array value for variable key

Body:
I am trying to make a site multi lingual. by building a language dictionary array ( if it is not the best way please don't hesitate to let me know )

$fr=array();

$fr['hello']="Bonjour";

I would like to make a function that does the following :

for every word and language  function ( $word ="hello",$language="fr")

it would return the right value. So far the way I am doing isn't working

echo $$language[$word];

any ideas?
thank you

Body:
You might want to consider using a single (nested) array

$strings = array(
    "french" => array(
        "stringID" => "foobar"
    )
);

echo( $strings["french"]["stringID"] );

If you are not utilising a database I would highly recommend looking into this. MySQL and PostgreSQL tend to be popular choices for independent and small development shops.


问:
Windows cmd encoding change causes Python crash
First I change Windows CMD encoding to utf-8 and run Python interpreter:

```<code>chcp 65001
python
</code>```

Then I try to print a unicode sting inside it and when i do this Python crashes in a peculiar way (I just get a cmd prompt in the same window).

```<code>>>> import sys
>>> print u'ëèæîð'.encode(sys.stdin.encoding)
</code>```

Any ideas why it happens and how to make it work?

UPD: sys.stdin.encoding returns 'cp65001'

UPD2: It just came to me that the issue might be connected with the fact that utf-8 uses multi-byte character set (kcwu made a good point on that). I tried running the whole example with 'windows-1250' and got 'ëeaî?'. Windows-1250 uses single-character set so it worked for those characters it understands. However I still have no idea how to make 'utf-8' work here.

UPD3: Oh, I found out it is a known Python bug. I guess what happens is that Python copies the cmd encoding as 'cp65001 to sys.stdin.encoding and tries to apply it to all the input. Since it fails to understand 'cp65001' it crashes on any input that contains non-ascii characters.

答:
For unknown encoding: cp65001 issue, can set new Variable as PYTHONIOENCODING and Value as UTF-8. (This works for me)

View this:

Body:
First I change Windows CMD encoding to utf-8 and run Python interpreter:

chcp 65001
python

Then I try to print a unicode sting inside it and when i do this Python crashes in a peculiar way (I just get a cmd prompt in the same window).

>>> import sys
>>> print u'ëèæîð'.encode(sys.stdin.encoding)

Any ideas why it happens and how to make it work?

UPD: sys.stdin.encoding returns 'cp65001'

UPD2: It just came to me that the issue might be connected with the fact that utf-8 uses multi-byte character set (kcwu made a good point on that). I tried running the whole example with 'windows-1250' and got 'ëeaî?'. Windows-1250 uses single-character set so it worked for those characters it understands. However I still have no idea how to make 'utf-8' work here.

UPD3: Oh, I found out it is a known Python bug. I guess what happens is that Python copies the cmd encoding as 'cp65001 to sys.stdin.encoding and tries to apply it to all the input. Since it fails to understand 'cp65001' it crashes on any input that contains non-ascii characters.


问:
Jenkins: Run Windows batch commands in 32-bit mode
Using Jenkins, we have setup automation testing - install application and run test cases in a remote machine. This process is done using a batch file. As it is a windows application I have to logout (remote machine) of the system keeping the session active. For that I have used the below script:

```<code>for /F "skip=1 tokens=3" %%s in ('query user testuser') do
(C:\Windows\system32\tscon.exe %%s /dest:console )
</code>```

In remote machine, when I run this script manually, it works perfectly. But when the same script (batch file) is run from Jenkins I am getting following error:

'query' is not recognized as an internal or external command, operable program or batch file.

答:
It's because you're running query from a 32-bit process. On 64-bit Windows 32-bit processes will be put under File System Redirector

In most cases, whenever a 32-bit application attempts to access %windir%\System32, the access is redirected to %windir%\SysWOW64. Access to %windir%\lastgood\system32 is redirected to %windir%\lastgood\SysWOW64. Access to %windir%\regedit.exe is redirected to %windir%\SysWOW64\regedit.exe

On 64-bit Windows System32 is for 64-bit system tools and SysWOW64 is for 32-bit ones. query is 64-bit only so it won't be available in SysWOW64 and can't be seen by 32-bit processes

```<code>C:\>where query
C:\Windows\System32\query.exe
</code>```

You can check this with the 32-bit cmd in SysWOW64:

```<code>>C:\Windows\SysWOW64\cmd.exe /c query user testuser
'query' is not recognized as an internal or external command,
operable program or batch file.

>C:\Windows\SysWOW64\cmd.exe /c where query
INFO: Could not find files for the given pattern(s).
</code>```

You need to change query user testuser to %windir%\sysnative\query.exe user testuser. Or better change to 64-bit Jenkins

Body:
Using Jenkins, we have setup automation testing - install application and run test cases in a remote machine. This process is done using a batch file. As it is a windows application I have to logout (remote machine) of the system keeping the session active. For that I have used the below script:

for /F "skip=1 tokens=3" %%s in ('query user testuser') do
(C:\Windows\system32\tscon.exe %%s /dest:console )

In remote machine, when I run this script manually, it works perfectly. But when the same script (batch file) is run from Jenkins I am getting following error:

'query' is not recognized as an internal or external command, operable program or batch file.

Body:
It's because you're running query from a 32-bit process. On 64-bit Windows 32-bit processes will be put under File System Redirector

In most cases, whenever a 32-bit application attempts to access %windir%\System32, the access is redirected to %windir%\SysWOW64. Access to %windir%\lastgood\system32 is redirected to %windir%\lastgood\SysWOW64. Access to %windir%\regedit.exe is redirected to %windir%\SysWOW64\regedit.exe

On 64-bit Windows System32 is for 64-bit system tools and SysWOW64 is for 32-bit ones. query is 64-bit only so it won't be available in SysWOW64 and can't be seen by 32-bit processes

C:\>where query
C:\Windows\System32\query.exe

You can check this with the 32-bit cmd in SysWOW64:

>C:\Windows\SysWOW64\cmd.exe /c query user testuser
'query' is not recognized as an internal or external command,
operable program or batch file.

>C:\Windows\SysWOW64\cmd.exe /c where query
INFO: Could not find files for the given pattern(s).

You need to change query user testuser to %windir%\sysnative\query.exe user testuser. Or better change to 64-bit Jenkins


问:
I want to take input from multiple text inputs and send them to my database, but only the last input sends
I have a mysql database/node backend, connected to an Angular frontend, that I am querying, specifically to send it the data from 3 simple text inputs in a form.

I believe my error is quite trivial for anyone with node/angular experience because I can successfully send my database input from one of the text inputs; however, when I try to detect and send data from all three inputs, it only sends the data from whichever input has its matching controller function as the last one (of the three) in my script.

Here is my html file and the script

var button = document.getElementById("clickButton");

const app = angular.module('app',[]);

app.service('appService', ['$http', function($http){
 return {
  'getSuggestion' : function(suggestion,callback){
   $http.post('/getSuggestion', {
    'suggestion': suggestion
   }).success(function (response) {
    callback(response);
   })
   .error(function (data, status, header, config) {
    callback({
     'error': true,
     'message': "Something went wrong."
    });
   });
  }
 }
}]);

app.controller('app', function($scope,appService) {
 //message send Function
 $scope.$watch('messageInput', function (newValue, oldValue) {
  //null check
  if (newValue !== null) {
   //wait for the button to be pressed
   button.onclick = function() {
    alert("USERNAME");
    //call server query function
    appService.getSuggestion(newValue, function (response) {
     $scope.suggestionCollection = response.rows;
    });
   };
  }
 });

 $scope.$watch('messageInput2', function (newValue, oldValue) {
  //null check
  if (newValue !== null) {
   //wait for the button to be pressed
   button.onclick = function() {
    alert("PASSWORD");
    //call server query function
    appService.getSuggestion(newValue, function (response) {
     $scope.suggestionCollection = response.rows;
    });
   };
  }
 });

 $scope.$watch('messageInput3', function (newValue, oldValue) {
  //null check
  if (newValue !== null) {
   //wait for the button to be pressed
   button.onclick = function() {
    alert("PASSWORD");
    //call server query function
    appService.getSuggestion(newValue, function (response) {
     $scope.suggestionCollection = response.rows;
    });
   };
  }
 });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html ng-app="app" ng-controller="app">

  <head>
    <title>Node app</title>
    <link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
  </head>

  <body>

    <div class="formFields">

      <form class="defaultForm" id="loginForm">

        <input class="loginField" type="text" name="username" ng-model="messageInput" placeholder="username"> <br>

        <input class="loginField" type="text" name="password" ng-model="messageInput2" placeholder="password"> <br>

        <input class="loginField" type="text" name="username" ng-model="messageInput3" placeholder="pass conf"> <br>

        <button id="clickButton" class="submitButton">submit</button>

      </form>

    </div>
    <!--<script src="Scripts/login.js"></script>-->
  <script src="js/angular.min.js"></script>
  <script src="js/script.js"></script>
  </body>
</html></code>```

答:
If I understand your question correctly, you want to watch for changes of values in all three input fields. If user types anything in any one of the three input fields, you want to send the values from all three input fields to your backend. And when user hits "Submit", you want to get values from all three input fields as well.

To solve this problem, you need two pieces:

set up a persistent click event handler on the button, as opposed to adding one only when some change happens. Note that in your code, you are updating this click handler each time one of the three input fields changes. This would cause the new input handler to overwrite the old one. That's why you only get the last touched value. I would recommend looking into the ng-click directive.

get inputs from all three form fields when any one of them is changed. This can be achieved through the ng-change directive. Or alternatively, you can put all three ngModels under one parent object and just $watch() that one parent object, as Hatzav Wolff suggests in his answer.

Here is how I would approach it:

var button = document.getElementById("clickButton");

const app = angular.module('app',[]);

app.service('appService', ['$http', function($http){
return {
 'getSuggestion' : function(suggestion,callback){
  $http.post('/getSuggestion', {
   'suggestion': suggestion
  }).success(function (response) {
   callback(response);
  })
  .error(function (data, status, header, config) {
   callback({
    'error': true,
    'message': "Something went wrong."
   });
  });
 }
}
}]);

app.controller('app', function($scope,appService) {
  $scope.handleChange= function() {
    /* Do whatever you want with the input. They are all here */
    console.log($scope.messageInput + ' ' + $scope.messageInput2 + ' ' + $scope.messageInput3);
  }

  $scope.handleSubmit= function() {
    /* Do whatever you want with the input. They are all here */
    console.log($scope.messageInput + ' ' + $scope.messageInput2 + ' ' + $scope.messageInput3);
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html ng-app="app" ng-controller="app">

  <head>
    <title>Node app</title>
    <link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
  </head>

  <body>

    <div class="formFields">

      <form class="defaultForm" id="loginForm">

        <input class="loginField" type="text" name="username" ng-model="messageInput" ng-change="handleChange()" placeholder="username"> <br>

        <input class="loginField" type="text" name="password" ng-model="messageInput2"ng-change="handleChange()" placeholder="password"> <br>

        <input class="loginField" type="text" name="username" ng-model="messageInput3" ng-change="handleChange()" placeholder="pass conf"> <br>

        <button id="clickButton" ng-click="handleSubmit()" class="submitButton">submit</button>

      </form>

    </div>
    <!--<script src="Scripts/login.js"></script>-->
  <script src="js/angular.min.js"></script>
  <script src="js/script.js"></script>
  </body>
</html></code>```

Body:
I have a mysql database/node backend, connected to an Angular frontend, that I am querying, specifically to send it the data from 3 simple text inputs in a form.

I believe my error is quite trivial for anyone with node/angular experience because I can successfully send my database input from one of the text inputs; however, when I try to detect and send data from all three inputs, it only sends the data from whichever input has its matching controller function as the last one (of the three) in my script.

Here is my html file and the script

var button = document.getElementById("clickButton");

const app = angular.module('app',[]);

app.service('appService', ['$http', function($http){
 return {
  'getSuggestion' : function(suggestion,callback){
   $http.post('/getSuggestion', {
    'suggestion': suggestion
   }).success(function (response) {
    callback(response);
   })
   .error(function (data, status, header, config) {
    callback({
     'error': true,
     'message': "Something went wrong."
    });
   });
  }
 }
}]);

app.controller('app', function($scope,appService) {
 //message send Function
 $scope.$watch('messageInput', function (newValue, oldValue) {
  //null check
  if (newValue !== null) {
   //wait for the button to be pressed
   button.onclick = function() {
    alert("USERNAME");
    //call server query function
    appService.getSuggestion(newValue, function (response) {
     $scope.suggestionCollection = response.rows;
    });
   };
  }
 });

 $scope.$watch('messageInput2', function (newValue, oldValue) {
  //null check
  if (newValue !== null) {
   //wait for the button to be pressed
   button.onclick = function() {
    alert("PASSWORD");
    //call server query function
    appService.getSuggestion(newValue, function (response) {
     $scope.suggestionCollection = response.rows;
    });
   };
  }
 });

 $scope.$watch('messageInput3', function (newValue, oldValue) {
  //null check
  if (newValue !== null) {
   //wait for the button to be pressed
   button.onclick = function() {
    alert("PASSWORD");
    //call server query function
    appService.getSuggestion(newValue, function (response) {
     $scope.suggestionCollection = response.rows;
    });
   };
  }
 });
});

<!DOCTYPE html>

    <title>Node app</title>
    <link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

      <form class="defaultForm" id="loginForm">

        <input class="loginField" type="text" name="username" ng-model="messageInput" placeholder="username">

        <input class="loginField" type="text" name="password" ng-model="messageInput2" placeholder="password">

        <input class="loginField" type="text" name="username" ng-model="messageInput3" placeholder="pass conf">

        <button id="clickButton" class="submitButton">submit</button>

      </form>

Body:
If I understand your question correctly, you want to watch for changes of values in all three input fields. If user types anything in any one of the three input fields, you want to send the values from all three input fields to your backend. And when user hits "Submit", you want to get values from all three input fields as well.

To solve this problem, you need two pieces:

set up a persistent click event handler on the button, as opposed to adding one only when some change happens. Note that in your code, you are updating this click handler each time one of the three input fields changes. This would cause the new input handler to overwrite the old one. That's why you only get the last touched value. I would recommend looking into the ng-click directive.

get inputs from all three form fields when any one of them is changed. This can be achieved through the ng-change directive. Or alternatively, you can put all three ngModels under one parent object and just $watch() that one parent object, as Hatzav Wolff suggests in his answer.

Here is how I would approach it:

var button = document.getElementById("clickButton");

const app = angular.module('app',[]);

app.service('appService', ['$http', function($http){
return {
 'getSuggestion' : function(suggestion,callback){
  $http.post('/getSuggestion', {
   'suggestion': suggestion
  }).success(function (response) {
   callback(response);
  })
  .error(function (data, status, header, config) {
   callback({
    'error': true,
    'message': "Something went wrong."
   });
  });
 }
}
}]);

app.controller('app', function($scope,appService) {
  $scope.handleChange= function() {
    /* Do whatever you want with the input. They are all here */
    console.log($scope.messageInput + ' ' + $scope.messageInput2 + ' ' + $scope.messageInput3);
  }

  $scope.handleSubmit= function() {
    /* Do whatever you want with the input. They are all here */
    console.log($scope.messageInput + ' ' + $scope.messageInput2 + ' ' + $scope.messageInput3);
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html ng-app="app" ng-controller="app">

  <head>
    <title>Node app</title>
    <link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
  </head>

  <body>

    <div class="formFields">

      <form class="defaultForm" id="loginForm">

        <input class="loginField" type="text" name="username" ng-model="messageInput" ng-change="handleChange()" placeholder="username"> <br>

        <input class="loginField" type="text" name="password" ng-model="messageInput2"ng-change="handleChange()" placeholder="password"> <br>

        <input class="loginField" type="text" name="username" ng-model="messageInput3" ng-change="handleChange()" placeholder="pass conf"> <br>

        <button id="clickButton" ng-click="handleSubmit()" class="submitButton">submit</button>

      </form>

    </div>
    <!--<script src="Scripts/login.js"></script>-->
  <script src="js/angular.min.js"></script>
  <script src="js/script.js"></script>
  </body>
</html>


问:
How to update sqlalchemy orm object by a python dict
the dict's key names are mapping to the sqlalchemy object attrs

ex:

```<code>class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    name = Column(String)
    fullname = Column(String)
    password = Column(String)
</code>```

can update from id = 3, {name: "diana"} or id = 15, {name: "marchel", fullname: "richie marchel"}

答:
base on answer of @martijn-pieters,
you can not only dynamic update column with setattr, but also can use dynamic table and column combine with getattr and setattr

example:

```<code># models.py
class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    name = Column(String)
    fullname = Column(String)
    password = Column(String)

# update.py
import models

def dynamic_update(dynamic_table, col_id, dynamic_cols):
    """
    dynamic_table: name of the table, "User" for example
    col_id: id of which column you want to update
    dynamic_cols: key value pairs {name: "diana"}
    """
    if hasattr(models, dynamic_table):
        table = getattr(models, dynamic_table)
        col_info = table.query.filter_by(id=col_id).first()
        for (key, value) in dynamic_cols.items():
            if hasattr(table, key):
                setattr(col_info, key, value)
                session.commit()
</code>```

BTW, you can get more info about setattr, getattr, hasattr from python offical doc
https://docs.python.org/2/library/functions.html#setattr

https://docs.python.org/2/library/functions.html#getattr

https://docs.python.org/2/library/functions.html#hasattr

Body:
the dict's key names are mapping to the sqlalchemy object attrs

ex:

class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    name = Column(String)
    fullname = Column(String)
    password = Column(String)

can update from id = 3, {name: "diana"} or id = 15, {name: "marchel", fullname: "richie marchel"}

Body:
base on answer of @martijn-pieters,
you can not only dynamic update column with setattr, but also can use dynamic table and column combine with getattr and setattr

example:

# models.py
class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    name = Column(String)
    fullname = Column(String)
    password = Column(String)

# update.py
import models

def dynamic_update(dynamic_table, col_id, dynamic_cols):
    """
    dynamic_table: name of the table, "User" for example
    col_id: id of which column you want to update
    dynamic_cols: key value pairs {name: "diana"}
    """
    if hasattr(models, dynamic_table):
        table = getattr(models, dynamic_table)
        col_info = table.query.filter_by(id=col_id).first()
        for (key, value) in dynamic_cols.items():
            if hasattr(table, key):
                setattr(col_info, key, value)
                session.commit()

BTW, you can get more info about setattr, getattr, hasattr from python offical doc
https://docs.python.org/2/library/functions.html#setattr

https://docs.python.org/2/library/functions.html#getattr

https://docs.python.org/2/library/functions.html#hasattr


问:
Change URL with wildcard
I don't know if The tittle suitable or not (sorry for that).
First, I have to tell you that I am very novice at javascript.

I want to make javascirpt that change URL and redirect it on click (create on boookmark bar).
The idea is to change URL:

https://mail.google.com/mail/u/0/h/[12_random_aphanumeric]/?&th=[16_random_aphanumeric]&v=c&s=a

to

https://mail.google.com/mail/u/0/#all/[16_random_aphanumeric]

for example Change:

https://mail.google.com/mail/u/0/h/bv293r3qycgk/?&th=16032287bb796882&v=c&s=a

to

https://mail.google.com/mail/u/0/#all/16032287bb796882

so I use "window.location.assign" like :

```<code>javascript: window.location.assign(window.location.toString().replace('*?&th=', 'https://mail.google.com/mail/u/0/#all/')); window.location.assign(window.location.toString().replace('&v=c&s=a', ' '));
</code>```

and of course its not working.

I just don't know how to use [*] wildcard on it.

Any suggestion would be appreciated.

答:
Capture the th param and  concatenate to new path

var str='https://mail.google.com/mail/u/0/h/1a2b3c4d5e6f/?&th=abcd1234abcd1234&v=c&s=a',
 th = str.match(/(th=[a-z0-9]{16})/i)[0],
 url = 'https://mail.google.com/mail/u/0/#all/' + th;

console.log(url)```

Title: Change URL with wildcard

Body:
I don't know if The tittle suitable or not (sorry for that).
First, I have to tell you that I am very novice at javascript.

I want to make javascirpt that change URL and redirect it on click (create on boookmark bar).
The idea is to change URL:

https://mail.google.com/mail/u/0/h/[12_random_aphanumeric]/?&th=[16_random_aphanumeric]&v=c&s=a

to

https://mail.google.com/mail/u/0/#all/[16_random_aphanumeric]

for example Change:

https://mail.google.com/mail/u/0/h/bv293r3qycgk/?&th=16032287bb796882&v=c&s=a

to

https://mail.google.com/mail/u/0/#all/16032287bb796882

so I use "window.location.assign" like :

javascript: window.location.assign(window.location.toString().replace('*?&th=', 'https://mail.google.com/mail/u/0/#all/')); window.location.assign(window.location.toString().replace('&v=c&s=a', ' '));

and of course its not working.

I just don't know how to use [*] wildcard on it.

Any suggestion would be appreciated.


问:
Create link to sort columns PHP
I need to create links that allow someone to sort the data based on the column header. I was able to get a working model which sorts the data by ID either ASC or DESC. How could I create this same function for more than just the ID column?</p>

```<code><?php
    $order = (isset($_GET['sort']) && strcasecmp($_GET['sort'], 'desc') == 0) ? 'DESC' : 'ASC';
    $query = 'SELECT DISTINCT `case`, firstname, lastname FROM `cases` ORDER BY id ' . $order;
          $result = mysql_query($query);
    ?>

    <td><a href=<?php echo "'?sort=" . ($order == 'DESC' ? 'ASC' : 'DESC') . "'";?>>Case ID</a></td>
    <td>Name</td>

    <?php
    // list records
         while ($nt = mysql_fetch_assoc($result)) {
    ?>

    <td><?php echo $nt['case']; ?></td>
    <td><?php echo $nt['firstname']; ?> <?php echo $nt['lastname']; ?>
</code>```

答:
I would define an array to define your allowed sorts, so you don't send table names via links and the user ( a malicious user doesn't know what sort=1, 2, 3, etc do), and when you print your links  I disabled the link to the curent sort (You could use css to make it different from the rest of them so the user knows where it is ).

here is the code sample:

```<code><?php
$sorts = array
(
    1=>array('order'=>' ORDER BY id', 'name'='case id'),
    2=>array('order'=>' ORDER BY id DESC', 'name'='case id desc'),
    3=>array('order'=>' ORDER BY firstname', 'name'='case firstname'),
    4=>array('order'=>' ORDER BY firstname DESC', 'name'='case firstname desc')
    // and so on
);

if(!is_numeric($_GET['sort']))
{
    echo 'Invalid sort type !';exit; // use your custom error reporting function.
}
    foreach($sorts as $key => $value)
    {
        $order = ($key == $_GET['sort'])?$value['order']:'';
        echo '<td><a href = "example.com?sort='.$_GET['sort'].'" '.(($key == $_GET['sort'])? disabled="disabled":'').'>'.$value['name'].'</a></td>';
    }

$query = 'SELECT DISTINCT case, firstname, lastname FROM cases '.$order;
// ...
</code>```

Title: Create link to sort columns PHP

Body:
I need to create links that allow someone to sort the data based on the column header. I was able to get a working model which sorts the data by ID either ASC or DESC. How could I create this same function for more than just the ID column?

<?php
    $order = (isset($_GET['sort']) && strcasecmp($_GET['sort'], 'desc') == 0) ? 'DESC' : 'ASC';
    $query = 'SELECT DISTINCT `case`, firstname, lastname FROM `cases` ORDER BY id ' . $order;
          $result = mysql_query($query);
    ?>

    <a href=<?php echo "'?sort=" . ($order == 'DESC' ? 'ASC' : 'DESC') . "'";?>>Case ID
    Name

    <?php
    // list records
         while ($nt = mysql_fetch_assoc($result)) {
    ?>

    <?php echo $nt['case']; ?>
    <?php echo $nt['firstname']; ?> <?php echo $nt['lastname']; ?>

Body:
I would define an array to define your allowed sorts, so you don't send table names via links and the user ( a malicious user doesn't know what sort=1, 2, 3, etc do), and when you print your links  I disabled the link to the curent sort (You could use css to make it different from the rest of them so the user knows where it is ).

here is the code sample:

<?php
$sorts = array
(
    1=>array('order'=>' ORDER BY id', 'name'='case id'),
    2=>array('order'=>' ORDER BY id DESC', 'name'='case id desc'),
    3=>array('order'=>' ORDER BY firstname', 'name'='case firstname'),
    4=>array('order'=>' ORDER BY firstname DESC', 'name'='case firstname desc')
    // and so on
);

if(!is_numeric($_GET['sort']))
{
    echo 'Invalid sort type !';exit; // use your custom error reporting function.
}
    foreach($sorts as $key => $value)
    {
        $order = ($key == $_GET['sort'])?$value['order']:'';
        echo '<td><a href = "example.com?sort='.$_GET['sort'].'" '.(($key == $_GET['sort'])? disabled="disabled":'').'>'.$value['name'].'</a></td>';
    }

$query = 'SELECT DISTINCT case, firstname, lastname FROM cases '.$order;
// ...


问:
Bootstrap not compatible with angular 5
I am using Angular 5. After installing ng-bootstrap there are few errors. Is ng-bootstrap not compatible with Angular 5, or are their any other packages that are compatible?

答: I used ngx-bootstrap which is compatible  as ng-bootstrap is not compatible </p>

Title: Bootstrap not compatible with angular 5


答:
You could use of union

```<code>Insert into #TableName
SELECT 'IMS080' UserID
union
select 'IMS108' UserID
union
select 'IMS218' UserID
</code>```

Edit :

```<code>Insert into #TableName
values ('IMS080'), ('IMS108'), ('IMS218')
</code>```

Title: How can I split and insert a string into a SQL Server table?

Body:
I need to insert these IMS080','IMS108','IMS218 values into temptable in separate rows, like this:

row 1: IMS080
row 2: IMS108
row 3: IMS218

Query :

INSERT INTO #TableName
    SELECT UserID
    FROM ('IMS080', 'IMS108', 'IMS218')

Thanks in advance

Body:
You could use of union

Insert into #TableName
SELECT 'IMS080' UserID
union
select 'IMS108' UserID
union
select 'IMS218' UserID

Edit :

Insert into #TableName
values ('IMS080'), ('IMS108'), ('IMS218')


问:
What are the advantages of developing applications in C++ as compared to managed languages?
Hi I want to know why people develop library applications and employee management applications in C++ (this application, for example), when clearly the same thing can be done in C# and VB.NET in a much prettier way. Even banking applications are mostly in C++. Is there a good reason why, apart from the fact that compiled C++ code executes faster?

Can anyone shed some light on this?

答:
The main reasons for C++ for say banking applications is:

Legacy code. A large financial firm typically has ~10-20-30 years of business specific C/C++ libraries developed in-house, plus a bunch of business specific vendor libraries which may not be available for C#

A LOT of that financial code runs on Unix/Linux. While you can purely theoretically build C# code for Linux, it's definitely NOT an established technology you want to bet billion dollar amounts on.


问:
Use gradle to execute webpack which is not in the root directory of project
The structure of my project is similar to the following:

```<code>-- root
  -- gradlew
  -- build.gradle
  -- src
     -- main
       -- frontend
          -- webpack.config.js
          -- package.json
          -- src
          -- node_modules
       -- java
       -- resources
          -- static
</code>```

I'd like to get gradle run the webpack.config.js located inside the root/src/main/frontend folder, and write it to bundle.js in src/main/java/resources/static. I tried this script:

```<code>task myNpmInstall(type: NodeTask) {
    args = ['install']
    inputs.file file('src/main/frontend/package.json')
    outputs.dir file('src/main/frontend/node_modules')
}

task webpack(type: NodeTask, dependsOn: 'myNpmInstall') {
    script = file('src/main/frontend/node_modules/.bin/webpack')
}

processResources.dependsOn 'webpack'
</code>```

This is a part of my package.json:

```<code>  "engines": {
    "npm": "5.5.1",
    "node": "8.9.1"
  },
  "scripts": {
    "build": "node ./node_modules/webpack/bin/webpack.js",
    "test": "mocha --compilers js:babel-core/register --require ./test/test_helper.js --recursive ./test",
    "test:watch": "npm run test -- --watch"
  },
</code>```

and this is the webpack.config.js:

```<code>module.exports = {
  entry: [
    './src/index.js'
  ],
  output: {
    path: __dirname,
    publicPath: '/',
    filename: 'bundle.js'
  },
  module: {
    loaders: [{
      test: /\.js$/,
      exclude: /node_modules/,
      loader: 'babel-loader'
    }]
  }
};
</code>```

I get this error:

```<code>Caused by: java.lang.IllegalStateException: Required script property is not set.
</code>```

I noticed that even when I run ./gradlew myNpmInstall I get the same error. How can I fix this ?

Update 1
I updated the gradle file content to

```<code>node {
    version = '8.9.1'
    npmWorkDir = file('src/main/frontend')
    nodeModulesDir = file('src/main/frontend')
    download = true
}

task webpack(type: NodeTask, dependsOn: 'npmInstall') {
    script = file("$projectDir/src/main/frontend/node_modules/.bin/webpack")
}

processResources.dependsOn 'webpack'
</code>```

and now I get this error:

```<code>No configuration file found and no output filename configured via CLI option.
A configuration file could be named 'webpack.config.js' in the current directory.
Use --help to display the CLI options.

Execution failed for task ':webpack' Caused by: org.gradle.process.internal.ExecException: Process 'command '/home/arian/workspace/myproj/.gradle/nodejs/node-v8.9.1-linux-x64/bin/node'' finished with non-zero exit value 255
</code>```

答:
First of all here is com.moowork.node docs
You can specify project location with nodeModulesDir

```<code>node {
    download = true
    // Set the work directory where node_modules should be located
    nodeModulesDir = file("${project.projectDir}/src/main/frontend")
}
</code>```

NodeTask is used to run something like ./node script. That is why it complains that Required script property is not set.. But usually what you really want is to run yarn/npm task declared in package.json

I prefer to use YarnTask, because it feels faster for me

```<code>task webpack(type: YarnTask, dependsOn: yarn) {
    args = ['build-spring']
    // 'build-spring' is script in your package.json you want to run
}
</code>```

For npm it would look something like

```<code>task webpack(type: NpmTask, dependsOn: npmInstall) {
    args = ['run','build-spring']
}
</code>```

Body:
The structure of my project is similar to the following:

-- root
  -- gradlew
  -- build.gradle
  -- src
     -- main
       -- frontend
          -- webpack.config.js
          -- package.json
          -- src
          -- node_modules
       -- java
       -- resources
          -- static

I'd like to get gradle run the webpack.config.js located inside the root/src/main/frontend folder, and write it to bundle.js in src/main/java/resources/static. I tried this script:

task myNpmInstall(type: NodeTask) {
    args = ['install']
    inputs.file file('src/main/frontend/package.json')
    outputs.dir file('src/main/frontend/node_modules')
}

task webpack(type: NodeTask, dependsOn: 'myNpmInstall') {
    script = file('src/main/frontend/node_modules/.bin/webpack')
}

processResources.dependsOn 'webpack'

This is a part of my package.json:

  "engines": {
    "npm": "5.5.1",
    "node": "8.9.1"
  },
  "scripts": {
    "build": "node ./node_modules/webpack/bin/webpack.js",
    "test": "mocha --compilers js:babel-core/register --require ./test/test_helper.js --recursive ./test",
    "test:watch": "npm run test -- --watch"
  },

and this is the webpack.config.js:

module.exports = {
  entry: [
    './src/index.js'
  ],
  output: {
    path: __dirname,
    publicPath: '/',
    filename: 'bundle.js'
  },
  module: {
    loaders: [{
      test: /\.js$/,
      exclude: /node_modules/,
      loader: 'babel-loader'
    }]
  }
};

I get this error:

Caused by: java.lang.IllegalStateException: Required script property is not set.

I noticed that even when I run ./gradlew myNpmInstall I get the same error. How can I fix this ?

Update 1
I updated the gradle file content to

node {
    version = '8.9.1'
    npmWorkDir = file('src/main/frontend')
    nodeModulesDir = file('src/main/frontend')
    download = true
}

task webpack(type: NodeTask, dependsOn: 'npmInstall') {
    script = file("$projectDir/src/main/frontend/node_modules/.bin/webpack")
}

processResources.dependsOn 'webpack'

and now I get this error:

No configuration file found and no output filename configured via CLI option.
A configuration file could be named 'webpack.config.js' in the current directory.
Use --help to display the CLI options.

Execution failed for task ':webpack' Caused by: org.gradle.process.internal.ExecException: Process 'command '/home/arian/workspace/myproj/.gradle/nodejs/node-v8.9.1-linux-x64/bin/node'' finished with non-zero exit value 255

Body:
First of all here is com.moowork.node docs
You can specify project location with nodeModulesDir

node {
    download = true
    // Set the work directory where node_modules should be located
    nodeModulesDir = file("${project.projectDir}/src/main/frontend")
}

NodeTask is used to run something like ./node script. That is why it complains that Required script property is not set.. But usually what you really want is to run yarn/npm task declared in package.json

I prefer to use YarnTask, because it feels faster for me

task webpack(type: YarnTask, dependsOn: yarn) {
    args = ['build-spring']
    // 'build-spring' is script in your package.json you want to run
}

For npm it would look something like

task webpack(type: NpmTask, dependsOn: npmInstall) {
    args = ['run','build-spring']
}


问:
Master-Detail (parent-child) Input form with Admin-on-rest
I need help/recommendation for creating an order like input form with MASTER inputs like (order no, date, customer name, address) along with DETAIL info in multiple rows like (Item no, Description, Qty, Rate, Amount).

I am using Admin-on-rest as front-end interface and Loopback for my backend api.

Being new to react/redux and still learning core concepts, I am getting a hard time in finding a good example/starting point to build this functionality. So far, I think this example based on redux-form can help in creating a custom component, but I am yet not competent enough to build this myself.

Any reference to a similar example or some simple code to get me started will be very helpful.

Ref. Image

 Orders">

答:
I think you need this.

How to richly style AOR Edit page

The last answer on the page is a somewhat detailed guide on creating a custom edit component in AOR. Feel free to ask more questions here about how this will be done.

Looking at your design you will need to also think how this data will be updated at the API level. AOR itself will make a single request when you hit save. So how will your API handle updates to multiple models etc.


问:
Word Spell Check pops up hidden and "freezes" my App
I am using Word's Spell Check in my in house WinForm app.  My clients are all XP machines with Office 2007 and randomly the spell check suggestion box pops up behind the App and makes everything "appear" frozen as you cannot get at it.

Suggestions?  What do other people do to work around this or stop it altogether?

Thanks

Below is my code, for reference.

```<code>public class SpellCheckers
{
    public string CheckSpelling(string text)
    {
        Word.Application app = new Word.Application();
        object nullobj = Missing.Value;
        object template = Missing.Value;
        object newTemplate = Missing.Value;
        object documentType = Missing.Value;
        object visible = false;
        object optional = Missing.Value;
        object savechanges = false;
        app.ShowMe();

        Word._Document doc = app.Documents.Add(ref template, ref newTemplate, ref documentType, ref visible);

        doc.Words.First.InsertBefore(text);
        Word.ProofreadingErrors errors = doc.SpellingErrors;

        var ecount = errors.Count;
        doc.CheckSpelling(ref optional, ref optional, ref optional, ref optional,
            ref optional, ref optional, ref optional, ref optional, ref optional,
            ref optional, ref optional, ref optional);
        object first = 0;
        object last = doc.Characters.Count - 1;
        var results = doc.Range(ref first, ref last).Text;
        doc.Close(ref savechanges, ref nullobj, ref nullobj);
        app.Quit(ref savechanges, ref nullobj, ref nullobj);

        Marshal.ReleaseComObject(doc);
        Marshal.ReleaseComObject(app);
        Marshal.ReleaseComObject(errors);

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

And I call it from my WinForm app like so -->

```<code>  public static void SpellCheckControl(Control control)
    {
        if (IsWord2007Available())
        {
            if (control.HasChildren)
            {
                foreach (Control ctrl in control.Controls)
                {
                    SpellCheckControl(ctrl);
                }
            }

            if (IsValidSpellCheckControl(control))
            {
                if (control.Text != String.Empty)
                {
                    control.BackColor = Color.FromArgb(180, 215, 195);
                    control.Text = Spelling.CheckSpelling(control.Text);
                    control.Text = control.Text.Replace("\r", "\r\n");
                    control.ResetBackColor();
                }
            }
        }
    }
</code>```

答:
On top of CheckSpelling() Method I have added following block of code which helped me for VS2010 winform application</p>

```<code>    [DllImport("user32.dll")]
    private static extern IntPtr GetForegroundWindow();

    public string CheckSpelling(string text)
    {
     ---------
     ****Your code for Spell Check ****
     ---------
    }
</code>```

Body:
I am using Word's Spell Check in my in house WinForm app.  My clients are all XP machines with Office 2007 and randomly the spell check suggestion box pops up behind the App and makes everything "appear" frozen as you cannot get at it.

Suggestions?  What do other people do to work around this or stop it altogether?

Thanks

Below is my code, for reference.

public class SpellCheckers
{
    public string CheckSpelling(string text)
    {
        Word.Application app = new Word.Application();
        object nullobj = Missing.Value;
        object template = Missing.Value;
        object newTemplate = Missing.Value;
        object documentType = Missing.Value;
        object visible = false;
        object optional = Missing.Value;
        object savechanges = false;
        app.ShowMe();

        Word._Document doc = app.Documents.Add(ref template, ref newTemplate, ref documentType, ref visible);

        doc.Words.First.InsertBefore(text);
        Word.ProofreadingErrors errors = doc.SpellingErrors;

        var ecount = errors.Count;
        doc.CheckSpelling(ref optional, ref optional, ref optional, ref optional,
            ref optional, ref optional, ref optional, ref optional, ref optional,
            ref optional, ref optional, ref optional);
        object first = 0;
        object last = doc.Characters.Count - 1;
        var results = doc.Range(ref first, ref last).Text;
        doc.Close(ref savechanges, ref nullobj, ref nullobj);
        app.Quit(ref savechanges, ref nullobj, ref nullobj);

        Marshal.ReleaseComObject(doc);
        Marshal.ReleaseComObject(app);
        Marshal.ReleaseComObject(errors);

        return results;
    }
}

And I call it from my WinForm app like so -->

  public static void SpellCheckControl(Control control)
    {
        if (IsWord2007Available())
        {
            if (control.HasChildren)
            {
                foreach (Control ctrl in control.Controls)
                {
                    SpellCheckControl(ctrl);
                }
            }

            if (IsValidSpellCheckControl(control))
            {
                if (control.Text != String.Empty)
                {
                    control.BackColor = Color.FromArgb(180, 215, 195);
                    control.Text = Spelling.CheckSpelling(control.Text);
                    control.Text = control.Text.Replace("\r", "\r\n");
                    control.ResetBackColor();
                }
            }
        }
    }

Body:
On top of CheckSpelling() Method I have added following block of code which helped me for VS2010 winform application

    [DllImport("user32.dll")]
    private static extern IntPtr GetForegroundWindow();

    public string CheckSpelling(string text)
    {
     ---------
     ****Your code for Spell Check ****
     ---------
    }