问:
Mysql select statement using php array
Suppose I have an array as following

```<code>$sql_column_headings = array("Week Period", "Comments Approved", "Comment Replies");
</code>```

Number of items in the array is not fixed as they are selected from a 'select multiple lists'.

The list may consist more than 3 items and any number of items may be selected. Then submit button is pressed.
How can I create a select statement where the column headings are taken from the array mentioned above. Thanks.

答:
Try this,

```<code>$sql_column_headings = array("Week Period", "Comments Approved", "Comment Replies");

    $itemStr = implode(",",$sql_column_headings);

    $qry = "SELECT * FROM table_name WHERE field_name IN('$itemStr')";

    $resSet = mysql_query($qry);
</code>```

Check this,
https://www.w3schools.com/php/func_string_implode.asp

Title: Mysql select statement using php array

Body:
Suppose I have an array as following

$sql_column_headings = array("Week Period", "Comments Approved", "Comment Replies");

Number of items in the array is not fixed as they are selected from a 'select multiple lists'.

The list may consist more than 3 items and any number of items may be selected. Then submit button is pressed.
How can I create a select statement where the column headings are taken from the array mentioned above. Thanks.

Body:
Try this,

$sql_column_headings = array("Week Period", "Comments Approved", "Comment Replies");

    $itemStr = implode(",",$sql_column_headings);

    $qry = "SELECT * FROM table_name WHERE field_name IN('$itemStr')";

    $resSet = mysql_query($qry);

Check this,
https://www.w3schools.com/php/func_string_implode.asp


来源: stackexchange

问:
how to use onclick in addeventlistener to prevent form data to be submitted?
This is just some part of my code .the thing which I am not understanding is how to use onclick in my html to prevent my php file from running. I have html file where my input is button type and I am using DOM2 that is .addeventlistener

```<code>function checku(event) {

    var start=event.currentTarget;
    var warning="";
    if(start.name=="pressed"){
        alert("sdf");
         var temp=document.getElementById("form");
    }
    else
        var temp=start;

        var size=temp.length;

    for(var i=0;i<size;i++) {
        //alert(temp[i].name);

        if(temp[i].name=="Email"){

            var re = /^[0-9a-zA-Z]+@+[a-zA-Z]+?\.[a-z]{2,3}$/;
            var len=temp[i].value.length;
            var t=re.test(temp[i].value)

            if(t==true||len==0){
                document.getElementById("user").innerHTML="";
                //  Email.style.color="black";
                if(len==0){
                    warning+="Email Address cannot be empty, ";
                    //return false;
                }
                //return true;

             } else {
                 user.style.fontStretch="condensed";
                 user.style.color="red";
                 user.style.fontWeight="600";
                 user.style.fontFamily="Arial, Helvetica, sans-serif";
                 //  Email.style.color="red";
                 document.getElementById("user").innerHTML="It should contain @ and .com or.ca ";
                 warning+="Email Address, ";
                 //return false;
             }
        }
</code>```

答:
The button inside your form tag, when clicked, will trigger the submit event and submit the form to the URL specified in the action attribute of the form.

If you are adding an event to carry out validation or other stuff, make sure that you change your button's type attribute to button i.e. <button type='button'>Submit</button>

ContentLicense: CC BY-SA 3.0

Body:
This is just some part of my code .the thing which I am not understanding is how to use onclick in my html to prevent my php file from running. I have html file where my input is button type and I am using DOM2 that is .addeventlistener

function checku(event) {

    var start=event.currentTarget;
    var warning="";
    if(start.name=="pressed"){
        alert("sdf");
         var temp=document.getElementById("form");
    }
    else
        var temp=start;

        var size=temp.length;

    for(var i=0;i<size;i++) {
        //alert(temp[i].name);

        if(temp[i].name=="Email"){

            var re = /^[0-9a-zA-Z]+@+[a-zA-Z]+?\.[a-z]{2,3}$/;
            var len=temp[i].value.length;
            var t=re.test(temp[i].value)

            if(t==true||len==0){
                document.getElementById("user").innerHTML="";
                //  Email.style.color="black";
                if(len==0){
                    warning+="Email Address cannot be empty, ";
                    //return false;
                }
                //return true;

             } else {
                 user.style.fontStretch="condensed";
                 user.style.color="red";
                 user.style.fontWeight="600";
                 user.style.fontFamily="Arial, Helvetica, sans-serif";
                 //  Email.style.color="red";
                 document.getElementById("user").innerHTML="It should contain @ and .com or.ca ";
                 warning+="Email Address, ";
                 //return false;
             }
        }


问:
Image stretched when I capture image and save to SD card in Android
```<code>BitmapFactory.Options opts = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, opts);
bitmap = Bitmap.createScaledBitmap(bitmap, 150, 50, false);
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int newWidth = 150;
int newHeight = 50;

// calculate the scale - in this case = 0.4f
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;

// createa matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);
// rotate the Bitmap
matrix.postRotate(-90);
Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
        width, height, matrix, true);
//      HomePage.image.setImageBitmap(resizedBitmap);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
resizedBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();

Intent in1 = new Intent(CameraView.this, ImageDisplay.class);
in1.putExtra("picture",byteArray);
startActivity(in1);
</code>```

This is my code. I am unable to set image because image becomes stretched. It's not coming clear image full screen. Where am I doing wrong?

My image come like this we have fix it it should not stretched.

答:
Code for saving:

```<code> FileOutputStream outStream = null;
    File sdCard = Environment.getExternalStorageDirectory();
    File dir = new File(sdCard.getAbsolutePath() + "/camtest");
    dir.mkdirs();
    String fileName = String.format("%d.jpg", System.currentTimeMillis());
    File outFile = new File(dir, fileName);
    outStream = new FileOutputStream(outFile);
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
    outStream.flush();
    outStream.close();
    refreshGallery(outFile);
</code>```

Permissions:

```<code><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
</code>```

Finally:

Go to Device Settings>Device>Applications>Application Manager>"your app">Permissions>Enable Storage permission!

Body:
BitmapFactory.Options opts = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, opts);
bitmap = Bitmap.createScaledBitmap(bitmap, 150, 50, false);
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int newWidth = 150;
int newHeight = 50;

// calculate the scale - in this case = 0.4f
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;

// createa matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);
// rotate the Bitmap
matrix.postRotate(-90);
Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
        width, height, matrix, true);
//      HomePage.image.setImageBitmap(resizedBitmap);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
resizedBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();

Intent in1 = new Intent(CameraView.this, ImageDisplay.class);
in1.putExtra("picture",byteArray);
startActivity(in1);

This is my code. I am unable to set image because image becomes stretched. It's not coming clear image full screen. Where am I doing wrong?

My image come like this we have fix it it should not stretched.

Body:
Code for saving:

 FileOutputStream outStream = null;
    File sdCard = Environment.getExternalStorageDirectory();
    File dir = new File(sdCard.getAbsolutePath() + "/camtest");
    dir.mkdirs();
    String fileName = String.format("%d.jpg", System.currentTimeMillis());
    File outFile = new File(dir, fileName);
    outStream = new FileOutputStream(outFile);
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
    outStream.flush();
    outStream.close();
    refreshGallery(outFile);

Permissions:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Finally:

Go to Device Settings>Device>Applications>Application Manager>"your app">Permissions>Enable Storage permission!


问:
Angular 2 filter/search list
I'm looking for the angular 2 way to do this.

I simply have a list of items, and I want to make an input whos job is to filter the list.

```<code><md-input placeholder="Item name..." [(ngModel)]="name"></md-input>

<div *ngFor="let item of items">
{{item.name}}
</div>
</code>```

What's the actual way of doing this in Angular 2? Does that requires a pipe?

答:
data

```<code>names = ['Prashobh','Abraham','Anil','Sam','Natasha','Marry','Zian','karan']
</code>```

You can achieve this by creating a simple pipe

```<code><input type="text" [(ngModel)]="queryString" id="search" placeholder="Search to type">
</code>```

Pipe

```<code>import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'FilterPipe',
})
export class FilterPipe implements PipeTransform {
    transform(value: any, input: string) {
        if (input) {
            input = input.toLowerCase();
            return value.filter(function (el: any) {
                return el.toLowerCase().indexOf(input) > -1;
            })
        }
        return value;
    }
}
</code>```

This will filter the result based on the search term

More Info

Title: Angular 2 filter/search list

Body:
I'm looking for the angular 2 way to do this.

I simply have a list of items, and I want to make an input whos job is to filter the list.

<md-input placeholder="Item name..." [(ngModel)]="name"></md-input>

{{item.name}}

What's the actual way of doing this in Angular 2? Does that requires a pipe?

Body:
data

names = ['Prashobh','Abraham','Anil','Sam','Natasha','Marry','Zian','karan']

You can achieve this by creating a simple pipe

<input type="text" [(ngModel)]="queryString" id="search" placeholder="Search to type">

Pipe

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'FilterPipe',
})
export class FilterPipe implements PipeTransform {
    transform(value: any, input: string) {
        if (input) {
            input = input.toLowerCase();
            return value.filter(function (el: any) {
                return el.toLowerCase().indexOf(input) > -1;
            })
        }
        return value;
    }
}

This will filter the result based on the search term

More Info


问:
How can I create a common file between JavaScript and C/C++ for a constant?
I have a C++ program with the following in the header file:
#define VARIABLE_X 100

Also, a JavaScript file with the global: VARIABLE_X = 100;

These values will always need to be the same.

Instead of having to change them in both places (.h and .js), I need a common file where both can get this value, thus only needing to be changed in one place.

How can I create a common file between JavaScript and C/C++........ for a #define/constant ?

Thank You.

答: What build system are you using? Build system is a very good place for this type of stuff.</p>

ContentLicense: CC BY-SA 2.5


问:
How to integration test auto configuration for a custom Spring Boot style starter library?
I am writing a library to provide some functionality that is shared between multiple different Spring Boot applications that I work with.

I would like to do something similar to the auto-configuration that is provided by the many Spring Boot starter libraries exist. That, or some other simple declarative way to integrate my library with the ApplicationContext of the apps using it.

I have found some resources explaining how auto configuration works. I can figure out the above problem.

However, I have not been able to find any good examples of how I can test as part of my library's test suite that it suitably integrates with a Spring Boot application. Ideally, I would start up a simple Spring Boot app written in the library's test directly just for the sake of testing, add the right annotation to it, and be able to assert that the correct beans are then configured.

I have tried creating a TestApplication class that does that and writing integration tests using the SpringBootTest annotation but the TestApplication was never started before my test started.

What can I do to start up a simple app like that solely for the purpose of testing my library? My tests are written with Spock and Spock-Spring in case that changes things versus other test frameworks.

答:
Your auto-configuration should be automatically picked while your main spring application/test is starting and all beans will be registered in your context. They will be available for auto-wiring and follow your conditions and init order.

As a summary, make sure you have an auto-configuration annotated by @Configuration class with an @Import that imports your @Configuration annotated configuration classes (inside of them you define beans with methods annotated with @Bean). Also make sure you created a spring.factories file that include your auto-configuration class and that you removed the spring boot maven plugin (for the packaging to be right).

Also, make sure your auto-configuration project is NOT annotated by things like @SpringBootApplication, @EnableAutoConfiguration, @ComponentScan or other spring boot annotations that need to be only in the main spring boot projects (There should be one of them in each stack).

Please also see the article below:

Spring boot is based on a lot of pre-made auto-configuration parent projects. You should already be familiar with spring boot starter projects.

You can easily create your own starter project by doing the following easy steps:

Create some @Configuration classes to define default beans. You should use external properties as much as possible to allow customization and try to use auto-configuration helper annotations like @AutoConfigureBefore, @AutoConfigureAfter, @ConditionalOnBean, @ConditionalOnMissingBean etc. You can find more detailed information on each annotation in the official documentation Condition annotations

Place an auto-configuration file/files that aggregates all of the @Configuration classes.

Create a file named spring.factories and place it in src/main/resources/META-INF.

In spring.factories, set org.springframework.boot.autoconfigure.EnableAutoConfiguration property with comma separated values of your @Configuration classes:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=

com.mycorp.libx.autoconfigure.LibXAutoConfiguration,

com.mycorp.libx.autoconfigure.LibXWebAutoConfiguration
Using this method you can create your own auto-configuration classes that will be picked by spring-boot. Spring-boot automatically scan all maven/gradle dependencies for a spring.factories file, if it finds one, it adds all @Configuration classes specified in it to its auto-configuration process.

Make sure your auto-configuration starter project does not contain spring boot maven plugin because it will package the project as an executable JAR and won't be loaded by the classpath as intended - spring boot will not be able to find your spring.factories and won't load your configuration

ContentLicense: CC BY-SA 4.0


问:
Python OSError No space left on device
Im writing a lot of files to a folder, no subdirectories, however after 2.8 million files this error shows up:

```<code>with open(bottleneck_path, 'w') as save_file:
OSError: [Errno 28] No space left on device: '/home/user/path/redacted'
</code>```

I've checked the length of the filename which is only 149 characters long. The file size is supposed to be around 18K.

My operating system is Linux.

df -i:

```<code>Filesystem                               Inodes   IUsed    IFree IUse% Mounted on
udev                                    4106923     544  4106379    1% /dev
tmpfs                                   4113022     836  4112186    1% /run
/dev/sda2                              28401664 9008557 19393107   32% /
tmpfs                                   4113022      40  4112982    1% /dev/shm
tmpfs                                   4113022       5  4113017    1% /run/lock
tmpfs                                   4113022      16  4113006    1% /sys/fs/cgroup
/dev/sda1                                     0       0        0     - /boot/efi
</code>```

df -T

```<code>Filesystem                             Type      1K-blocks       Used  Available Use% Mounted on
udev                                   devtmpfs   16427692          0   16427692   0% /dev
tmpfs                                  tmpfs       3290420      22136    3268284   1% /run
/dev/sda2                              ext4      447088512  355325584   69029056  84% /
tmpfs                                  tmpfs      16452088      82448   16369640   1% /dev/shm
tmpfs                                  tmpfs          5120          4       5116   1% /run/lock
tmpfs                                  tmpfs      16452088          0   16452088   0% /sys/fs/cgroup
/dev/sda1                              vfat         523248       3684     519564   1% /boot/efi
</code>```

du -sh .

```<code>56G
</code>```

ls | wc -l

```<code>2892084
</code>```

From my understanding ext4 should be able to handle this just fine.

EDIT:

tune2fs -l /dev/sda2

```<code>tune2fs 1.42.13 (17-May-2015)
Filesystem volume name:   <none>
Last mounted on:          /
Filesystem UUID:          cd620466-1f88-400b-acf5-457a9c9544cf
Filesystem magic number:  0xEF53
Filesystem revision #:    1 (dynamic)
Filesystem features:      has_journal ext_attr resize_inode dir_index filetype needs_recovery extent flex_bg sparse_super large_file huge_file uninit_bg dir_nlink extra_isize
Filesystem flags:         signed_directory_hash
Default mount options:    user_xattr acl
Filesystem state:         clean
Errors behavior:          Continue
Filesystem OS type:       Linux
Inode count:              28401664
Block count:              113587456
Reserved block count:     5679372
Free blocks:              82864623
Free inodes:              25755495
First block:              0
Block size:               4096
Fragment size:            4096
Reserved GDT blocks:      996
Blocks per group:         32768
Fragments per group:      32768
Inodes per group:         8192
Inode blocks per group:   512
Flex block group size:    16
Filesystem created:       Wed Mar  1 15:14:22 2017
Last mount time:          Mon Mar 27 13:20:00 2017
Last write time:          Mon Mar 27 13:20:00 2017
Mount count:              35
Maximum mount count:      -1
Last checked:             Wed Mar  1 15:14:22 2017
Check interval:           0 (<none>)
Lifetime writes:          1813 GB
Reserved blocks uid:      0 (user root)
Reserved blocks gid:      0 (group root)
First inode:              11
Inode size:           256
Required extra isize:     28
Desired extra isize:      28
Journal inode:            8
First orphan inode:       1312056
Default directory hash:   half_md4
Directory Hash Seed:      e186507d-32b5-49c0-8ce1-09bf2a75d816
Journal backup:           inode blocks
</code>```

Using

```<code>touch /home/user/path/redacted/somefile_1
</code>```

throws an error but the same filename structure with a different name works fine. eg:

```<code>touch /home/user/path/redacted/somefile_2
</code>```

答:
There is no default limit on the maximum inodes for ext4, it depends on the size of the device and the options chosen at creation. Check the existing limits using</p>

```<code>tune2fs -l /path/to/device
</code>```

Title: Python OSError No space left on device

Body:
Im writing a lot of files to a folder, no subdirectories, however after 2.8 million files this error shows up:

with open(bottleneck_path, 'w') as save_file:
OSError: [Errno 28] No space left on device: '/home/user/path/redacted'

I've checked the length of the filename which is only 149 characters long. The file size is supposed to be around 18K.

My operating system is Linux.

df -i:

Filesystem                               Inodes   IUsed    IFree IUse% Mounted on
udev                                    4106923     544  4106379    1% /dev
tmpfs                                   4113022     836  4112186    1% /run
/dev/sda2                              28401664 9008557 19393107   32% /
tmpfs                                   4113022      40  4112982    1% /dev/shm
tmpfs                                   4113022       5  4113017    1% /run/lock
tmpfs                                   4113022      16  4113006    1% /sys/fs/cgroup
/dev/sda1                                     0       0        0     - /boot/efi

df -T

Filesystem                             Type      1K-blocks       Used  Available Use% Mounted on
udev                                   devtmpfs   16427692          0   16427692   0% /dev
tmpfs                                  tmpfs       3290420      22136    3268284   1% /run
/dev/sda2                              ext4      447088512  355325584   69029056  84% /
tmpfs                                  tmpfs      16452088      82448   16369640   1% /dev/shm
tmpfs                                  tmpfs          5120          4       5116   1% /run/lock
tmpfs                                  tmpfs      16452088          0   16452088   0% /sys/fs/cgroup
/dev/sda1                              vfat         523248       3684     519564   1% /boot/efi

du -sh .

56G

ls | wc -l

2892084

From my understanding ext4 should be able to handle this just fine.

EDIT:

tune2fs -l /dev/sda2

tune2fs 1.42.13 (17-May-2015)
Filesystem volume name:   <none>
Last mounted on:          /
Filesystem UUID:          cd620466-1f88-400b-acf5-457a9c9544cf
Filesystem magic number:  0xEF53
Filesystem revision #:    1 (dynamic)
Filesystem features:      has_journal ext_attr resize_inode dir_index filetype needs_recovery extent flex_bg sparse_super large_file huge_file uninit_bg dir_nlink extra_isize
Filesystem flags:         signed_directory_hash
Default mount options:    user_xattr acl
Filesystem state:         clean
Errors behavior:          Continue
Filesystem OS type:       Linux
Inode count:              28401664
Block count:              113587456
Reserved block count:     5679372
Free blocks:              82864623
Free inodes:              25755495
First block:              0
Block size:               4096
Fragment size:            4096
Reserved GDT blocks:      996
Blocks per group:         32768
Fragments per group:      32768
Inodes per group:         8192
Inode blocks per group:   512
Flex block group size:    16
Filesystem created:       Wed Mar  1 15:14:22 2017
Last mount time:          Mon Mar 27 13:20:00 2017
Last write time:          Mon Mar 27 13:20:00 2017
Mount count:              35
Maximum mount count:      -1
Last checked:             Wed Mar  1 15:14:22 2017
Check interval:           0 (<none>)
Lifetime writes:          1813 GB
Reserved blocks uid:      0 (user root)
Reserved blocks gid:      0 (group root)
First inode:              11
Inode size:           256
Required extra isize:     28
Desired extra isize:      28
Journal inode:            8
First orphan inode:       1312056
Default directory hash:   half_md4
Directory Hash Seed:      e186507d-32b5-49c0-8ce1-09bf2a75d816
Journal backup:           inode blocks

Using

touch /home/user/path/redacted/somefile_1

throws an error but the same filename structure with a different name works fine. eg:

touch /home/user/path/redacted/somefile_2

Body:
There is no default limit on the maximum inodes for ext4, it depends on the size of the device and the options chosen at creation. Check the existing limits using

tune2fs -l /path/to/device


问:
PHP merge and rearrange 2 or more arrays
It will be 2 or more arrays come out from foreach loop. Like following

```<code>array1
    [0] => Array
        (
            [0] => 1207
            [1] => 4
            [2] => haha.mp4
        )

    [1] => Array
        (
            [0] => 1208
            [1] => 4
            [2] => hehe.mp4
        )

array2
   [0] => Array
        (
            [0] => 1209
            [1] => 16
            [2] => SampleVideo.mp4
        )

    [1] => Array
        (
            [0] => 1210
            [1] => 16
            [2] => 295.mp4
        )
</code>```

I want to get same index value from these 2 arrays and merge these array like that.

```<code>**FinalArray = array1[0],array2[0],array1[1],array2[1]**
</code>```

E.g

```<code>FinalArray

    [0] => Array
        (
            [0] => 1207
            [1] => 4
            [2] => haha.mp4
        )
    [1] => Array
        (
            [0] => 1209
            [1] => 16
            [2] => SampleVideo.mp4
        )

    [2] => Array
        (
            [0] => 1208
            [1] => 4
            [2] => hehe.mp4
        )

    [3] => Array
        (
            [0] => 1210
            [1] => 16
            [2] => 295.mp4
        )
</code>```

please help how to get same index values and merge that 2 arrays. Thanks

答:
```<code>$result = array_merge($array1, $array2);
print_r($result);
</code>```

From:
http://php.net/manual/en/function.array-merge.php

Body:
It will be 2 or more arrays come out from foreach loop. Like following

array1
    [0] => Array
        (
            [0] => 1207
            [1] => 4
            [2] => haha.mp4
        )

    [1] => Array
        (
            [0] => 1208
            [1] => 4
            [2] => hehe.mp4
        )

array2
   [0] => Array
        (
            [0] => 1209
            [1] => 16
            [2] => SampleVideo.mp4
        )

    [1] => Array
        (
            [0] => 1210
            [1] => 16
            [2] => 295.mp4
        )

I want to get same index value from these 2 arrays and merge these array like that.

**FinalArray = array1[0],array2[0],array1[1],array2[1]**

E.g

FinalArray

    [0] => Array
        (
            [0] => 1207
            [1] => 4
            [2] => haha.mp4
        )
    [1] => Array
        (
            [0] => 1209
            [1] => 16
            [2] => SampleVideo.mp4
        )

    [2] => Array
        (
            [0] => 1208
            [1] => 4
            [2] => hehe.mp4
        )

    [3] => Array
        (
            [0] => 1210
            [1] => 16
            [2] => 295.mp4
        )

please help how to get same index values and merge that 2 arrays. Thanks

Body:
$result = array_merge($array1, $array2);
print_r($result);

From:
http://php.net/manual/en/function.array-merge.php


问:
Admin-LTE theme integration in yii2 & changing its default theme
I have integrated the AdminLTE theme in my web app now I want to change the theme of the AdminLTE from its default blue black to red color, How can I do this? In which files I need to make the required changes..?</p>

答:
Are you using dmstr extension for this? If so set this in configuration:

```<code>'components' => [
    'assetManager' => [
        'bundles' => [
            'dmstr\web\AdminLteAsset' => [
                'skin' => 'skin-red',
            ],
        ],
    ],
],
</code>```

and then in layout add

```<code><body class="<?= \dmstr\helpers\AdminLteHelper::skinClass() ?>">
</code>```

If you are not using this extension or just don't want to play with config file add the proper class name in layout's body like:

```<code><body class="skin-red">
</code>```

Just make sure you have got proper css file in dist/css/skins folder.

Body:
Are you using dmstr extension for this? If so set this in configuration:

'components' => [
    'assetManager' => [
        'bundles' => [
            'dmstr\web\AdminLteAsset' => [
                'skin' => 'skin-red',
            ],
        ],
    ],
],

and then in layout add

<body class="<?= \dmstr\helpers\AdminLteHelper::skinClass() ?>">

If you are not using this extension or just don't want to play with config file add the proper class name in layout's body like:

<body class="skin-red">

Just make sure you have got proper css file in dist/css/skins folder.


问:
Raw SQL 'Insert Into' in ASP MVC
i'm trying to insert data from a form into two tables in db.

```<code>public ActionResult Cr([Bind(Include = "id,name,time")] appointment appointment, [Bind(Include = "pid,phone")] customer customer , string submit)
        {
        string str1 = "Insert Into appointment.id, appointment.name, appointment.time Values id,name,time"
        string str2= "Insert Into customer.pid, customer.phone Values pid,phone"
        var Query = dbb.Database.SqlQuery<ViewModel.custapp>(str1).ToList();
        var Query = dbb.Database.SqlQuery<ViewModel.custapp>(str2).ToList();
        return View("Index");
        }
</code>```

I am not sure if my code is wrong but the data are not inserted in the tables.

答:
Actually you wrote the query string wrong, the correct syntax for insertion of data into table is:

```<code>INSERT INTO table_name (column 1, column 2, ...) VALUES (values)
</code>```

The query string should be:

```<code>string str1 = "Insert Into appointment (id, name, time) Values (id, name, time)";
string str2 = "Insert Into customer (pid, phone) Values (pid, phone)";
</code>```

Hope that helps you.

Title: Raw SQL 'Insert Into' in ASP MVC

Body:
i'm trying to insert data from a form into two tables in db.

public ActionResult Cr([Bind(Include = "id,name,time")] appointment appointment, [Bind(Include = "pid,phone")] customer customer , string submit)
        {
        string str1 = "Insert Into appointment.id, appointment.name, appointment.time Values id,name,time"
        string str2= "Insert Into customer.pid, customer.phone Values pid,phone"
        var Query = dbb.Database.SqlQuery<ViewModel.custapp>(str1).ToList();
        var Query = dbb.Database.SqlQuery<ViewModel.custapp>(str2).ToList();
        return View("Index");
        }

I am not sure if my code is wrong but the data are not inserted in the tables.

Body:
Actually you wrote the query string wrong, the correct syntax for insertion of data into table is:

INSERT INTO table_name (column 1, column 2, ...) VALUES (values)

The query string should be:

string str1 = "Insert Into appointment (id, name, time) Values (id, name, time)";
string str2 = "Insert Into customer (pid, phone) Values (pid, phone)";

Hope that helps you.


问:
MySQL Select where multiple rows in joined table
Let's say I have two tables, something like:

```<code>+-----------------------------+
|a                            |
+------+-----------+----------+
| a_id | firstname | lastname |
+------+-----------+----------+
|    1 | Tom       | Cruise   |
|    3 | Matt      | Damon    |
|    4 | Ben       | Affleck  |
|    8 | Ryan      | Gosling  |
+------+-----------+----------+

+-----------------------+
| b                     |
+------+------+---------+
| b_id | a_id | b_value |
+------+------+---------+
|    2 |    3 | one     |
|    1 |    3 | two     |
|    4 |    8 | three   |
|    8 |    1 | four    |
+------+------+---------+
</code>```

I would like to be able toSELECT rows from a which meet a set of criteria from b, where there might be multiple rows.

For example:

Get the first and last name(s) of anyone who has a b_value of one, and other b_value of two. In the example data, this refers only to Matt Damon.

Get the first and last name(s) of anyone who has a b_value of three, or a b_value of four. In the example data, Ryan Gosling has a b_value of three, and Tom Cruise has a b_value of four, so both Ryan Gosling and Tom Cruise would be returned.

Get the first and last name(s) of anyone that has either:

A b_value of one and another b_value of two.

A b_value of three.

In the example data, Matt Damon meets the first condition, and Ryan Gosling meets the second condition, so both are returned.

The difficulty comes from when these conditions are complex, combining multiple and/or conditions, and a variable in length.

My current attempt (solving specifically example 3 in this case), is using aggregate functions in the HAVING:

```<code>SELECT firstname, lastname
FROM temp_a INNER JOIN temp_b ON temp_a.a_id = temp_b.a_id
GROUP BY temp_a.a_id
HAVING (SUM(b_value="one") AND SUM(b_value="two")) OR SUM(b_value="three");
</code>```

Which gets the correct rows, but there's two immediate problems with this approach for me:

SUM seems wrong and complicated. I'd have to find each of the conditionals and make sure each one is wrapped in a SUM, of which there might be lots.

The b_value is indexed, and b has lots of rows. The HAVING clause doesn't use the index and so the query is noticeably slow.

Is there a different approach I should be taking to do this sort of query, bearing in mind I'm not really in direct control of the conditionals used for filtering.

答:
In dynamic SQL it would somthing like this, first I would suggest creating a variable in your application which you fill up based on the selection of filters

```<code> - var exampleOne = "(b_value = 'one') OR (b_value = 'two')";
 - var exampleTwo = "(b_value = 'three') OR (b_value = 'four')";
 - var exampleThree = "(b_value = 'one' or b_value = 'two') OR (b_value = 'three')"
</code>```

Then you can create a stored procedure with one parameter, here you pass in your variable

```<code>CREATE PROCEDURE `spNames`(IN whereFilter VARCHAR(255))
BEGIN
  SET @SqlText = CONCAT('SELECT DISTINCT a.firstname, a.lastname
                         FROM @a AS a INNER JOIN @b AS b ON a.a_id=b.a_id
                         WHERE ', whereFilter);
  PREPARE stmt FROM @SqlText;
  EXECUTE stmt;
  DEALLOCATE PREPARE stmt
END
</code>```

Then you can call this stored procedure from your code and pass in the variable

```<code>CALL spNames (exampleOne);
</code>```

Body:
Let's say I have two tables, something like:

+-----------------------------+
|a                            |
+------+-----------+----------+
| a_id | firstname | lastname |
+------+-----------+----------+
|    1 | Tom       | Cruise   |
|    3 | Matt      | Damon    |
|    4 | Ben       | Affleck  |
|    8 | Ryan      | Gosling  |
+------+-----------+----------+

+-----------------------+
| b                     |
+------+------+---------+
| b_id | a_id | b_value |
+------+------+---------+
|    2 |    3 | one     |
|    1 |    3 | two     |
|    4 |    8 | three   |
|    8 |    1 | four    |
+------+------+---------+

I would like to be able toSELECT rows from a which meet a set of criteria from b, where there might be multiple rows.

For example:

Get the first and last name(s) of anyone who has a b_value of one, and other b_value of two. In the example data, this refers only to Matt Damon.

Get the first and last name(s) of anyone who has a b_value of three, or a b_value of four. In the example data, Ryan Gosling has a b_value of three, and Tom Cruise has a b_value of four, so both Ryan Gosling and Tom Cruise would be returned.

Get the first and last name(s) of anyone that has either:

A b_value of one and another b_value of two.

A b_value of three.

In the example data, Matt Damon meets the first condition, and Ryan Gosling meets the second condition, so both are returned.

The difficulty comes from when these conditions are complex, combining multiple and/or conditions, and a variable in length.

My current attempt (solving specifically example 3 in this case), is using aggregate functions in the HAVING:

SELECT firstname, lastname
FROM temp_a INNER JOIN temp_b ON temp_a.a_id = temp_b.a_id
GROUP BY temp_a.a_id
HAVING (SUM(b_value="one") AND SUM(b_value="two")) OR SUM(b_value="three");

Which gets the correct rows, but there's two immediate problems with this approach for me:

SUM seems wrong and complicated. I'd have to find each of the conditionals and make sure each one is wrapped in a SUM, of which there might be lots.

The b_value is indexed, and b has lots of rows. The HAVING clause doesn't use the index and so the query is noticeably slow.

Is there a different approach I should be taking to do this sort of query, bearing in mind I'm not really in direct control of the conditionals used for filtering.

Body:
In dynamic SQL it would somthing like this, first I would suggest creating a variable in your application which you fill up based on the selection of filters

 - var exampleOne = "(b_value = 'one') OR (b_value = 'two')";
 - var exampleTwo = "(b_value = 'three') OR (b_value = 'four')";
 - var exampleThree = "(b_value = 'one' or b_value = 'two') OR (b_value = 'three')"

Then you can create a stored procedure with one parameter, here you pass in your variable

CREATE PROCEDURE `spNames`(IN whereFilter VARCHAR(255))
BEGIN
  SET @SqlText = CONCAT('SELECT DISTINCT a.firstname, a.lastname
                         FROM @a AS a INNER JOIN @b AS b ON a.a_id=b.a_id
                         WHERE ', whereFilter);
  PREPARE stmt FROM @SqlText;
  EXECUTE stmt;
  DEALLOCATE PREPARE stmt
END

Then you can call this stored procedure from your code and pass in the variable

CALL spNames (exampleOne);


问:
Get multiple density plots of specifics columns for every data frame in a list
I have 60 data frames which have the same columns names store in a list which i got by using this code:

```<code>setwd("C:/Users/Visitor/Desktop/Unesco/")
temp = list.files(pattern="*.csv")
myfiles = lapply(temp, read.csv)
</code>```

A part of one of my csv files :

```<code>"","PRO","TRA","MEN","ENF","COU","TOI","REP","SOM","TEL","LOI"
"HAU","610","140","60","10","120","95","115","760","175","315"
"FAU","475","90","250","30","140","120","100","775","115","305"
"FNU","105","0","495","110","170","110","130","785","160","430"
"HMU","616","141","65","10","115","90","115","765","180","305"
"FMU","179","29","421","87","161","112","119","776","143","373"
</code>```

I did a ggplot of the columns PRO and TRA of all my dataframes merge in one dataframe with this :

```<code>library(dplyr)
library(reshape2)
library(ggplot2)

cols <-lapply(myfiles,function(x)select(x,PRO,TRA))
big_df2 <- do.call(rbind,cols)
df.m2 <- melt(big_df2)
ggplot(df.m2) + geom_freqpoly(aes(x = value,
+                                  y = ..density.., colour = variable))
</code>```

I have this output:

But I want the same plot for all my data frames separately but i can't seem to find how to do that.

Maybe I can do something with this loop over my list :

```<code>for(i in 1:length(myfiles)){
    myfiles[[i]]$df_num <- i
}
</code>```

答:
Try this example:</p>

```<code>library(ggplot2)
library(dplyr)
library(reshape2)

# dummy data
set.seed(1)
df1 <- cars[sample(seq(nrow(cars)), 10), ]
df2 <- cars[sample(seq(nrow(cars)), 10), ]
df3 <- cars[sample(seq(nrow(cars)), 10), ]
mylist <- list(df1, df2, df3) #this is similar example of your "myfiles"
mylist <- lapply(mylist, melt)

# merge them with an id column
df_merged <- bind_rows(mylist, .id = "df_id")

# Option 1: One plot as facets, 1 file 1 page
ggsave("option1.PDF",
       ggplot(df_merged, aes(value, col = variable)) + geom_freqpoly() +
         facet_grid(.~df_id)
       )

# Option 2: plot into files - output 3 PDF files
for(i in unique(df_merged$df_id)){
  filePDF <- paste0("option2_", i, ".PDF")
  myPlot <- df_merged %>%
    filter(df_id == i) %>%
    ggplot(aes(value, col = variable)) + geom_freqpoly()
  ggsave(filePDF, myPlot)
  }

# Option 3: plot into one file 3 pages
pdf("option3.PDF")
for(i in seq(length(df_merged))){
  plotDat <- df_merged %>%
    filter(df_id == i)
  myPlot <-  ggplot(plotDat, aes(value, col = variable)) + geom_freqpoly()
  print(myPlot)
  }
dev.off()
</code>```

Body:
I have 60 data frames which have the same columns names store in a list which i got by using this code:

setwd("C:/Users/Visitor/Desktop/Unesco/")
temp = list.files(pattern="*.csv")
myfiles = lapply(temp, read.csv)

A part of one of my csv files :

"","PRO","TRA","MEN","ENF","COU","TOI","REP","SOM","TEL","LOI"
"HAU","610","140","60","10","120","95","115","760","175","315"
"FAU","475","90","250","30","140","120","100","775","115","305"
"FNU","105","0","495","110","170","110","130","785","160","430"
"HMU","616","141","65","10","115","90","115","765","180","305"
"FMU","179","29","421","87","161","112","119","776","143","373"

I did a ggplot of the columns PRO and TRA of all my dataframes merge in one dataframe with this :

library(dplyr)
library(reshape2)
library(ggplot2)

cols <-lapply(myfiles,function(x)select(x,PRO,TRA))
big_df2 <- do.call(rbind,cols)
df.m2 <- melt(big_df2)
ggplot(df.m2) + geom_freqpoly(aes(x = value,
+                                  y = ..density.., colour = variable))

I have this output:

But I want the same plot for all my data frames separately but i can't seem to find how to do that.

Maybe I can do something with this loop over my list :

for(i in 1:length(myfiles)){
    myfiles[[i]]$df_num <- i
}

Body:
Try this example:

library(ggplot2)
library(dplyr)
library(reshape2)

# dummy data
set.seed(1)
df1 <- cars[sample(seq(nrow(cars)), 10), ]
df2 <- cars[sample(seq(nrow(cars)), 10), ]
df3 <- cars[sample(seq(nrow(cars)), 10), ]
mylist <- list(df1, df2, df3) #this is similar example of your "myfiles"
mylist <- lapply(mylist, melt)

# merge them with an id column
df_merged <- bind_rows(mylist, .id = "df_id")

# Option 1: One plot as facets, 1 file 1 page
ggsave("option1.PDF",
       ggplot(df_merged, aes(value, col = variable)) + geom_freqpoly() +
         facet_grid(.~df_id)
       )

# Option 2: plot into files - output 3 PDF files
for(i in unique(df_merged$df_id)){
  filePDF <- paste0("option2_", i, ".PDF")
  myPlot <- df_merged %>%
    filter(df_id == i) %>%
    ggplot(aes(value, col = variable)) + geom_freqpoly()
  ggsave(filePDF, myPlot)
  }

# Option 3: plot into one file 3 pages
pdf("option3.PDF")
for(i in seq(length(df_merged))){
  plotDat <- df_merged %>%
    filter(df_id == i)
  myPlot <-  ggplot(plotDat, aes(value, col = variable)) + geom_freqpoly()
  print(myPlot)
  }
dev.off()


问:
The result of a database query is not getting displayed on my page
I am trying to get details of products to be displayed on my webpage in a specific format by submitting an id number through a form. But no data is being displayed on submitting the query. I want the latest retrieved data to be appended below the already existing data on the same page from where the form was submitted.

This is my home.php :

```<code><?php
    ob_start();
    session_start();
    require_once 'dbconnect.php';
    // if session is not set this will redirect to login page
    if( !isset($_SESSION['user']) )
    {
        header("Location: index.php");
        exit;
    }
    // select loggedin users detail
    $res=mysqli_query($conn, "SELECT * FROM users WHERE userId=".$_SESSION['user']);
    $userRow=mysqli_fetch_array($res);
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta charset="utf-8" />
        <title> ShopNGo </title>
        <link rel="stylesheet" type="text/css" href="style.css">
        <link rel="stylesheet" href="assets/css/bootstrap.min.css" type="text/css"  />
        <link rel="stylesheet" href="style.css" type="text/css" />
        <script src="ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
        <script>
            $(document).ready(function()
            {
                $("#scan").on('click',function()
                {
                    var id =$("#id").val();
                    $.ajax(
                    {
                        type: "POST",
                        url: "getdata.php",
                        data: {id: id},
                        success: function(data)
                        {
                            $('.results').append(data);
                        }
                    });
                });
            });
        </script>
    </head>
    <body>
        <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
        <span class="glyphicon glyphicon-user"></span> Hi' <?php echo $userRow['userEmail']; ?> <span class="caret"></span></a>
        <a href="logout.php?logout"><span class="glyphicon glyphicon-log-out"></span> Sign Out</a>
        <header id="header">
            <div class="container">
                <form name="products" method="POST" action="">
                    <br><br>
                    <input type="submit" name="scan" id="scan" value="SCAN">
                    <br><br><br>
                    <input type="text" name="id" id="id">
                </form>
            </div>
        </header>
        <div class="main">
            <table border="0">
                <div class="results" id="results">
                </div>
            </table>
        </div>
    </body>
</html>
<?php ob_end_flush(); ?>
</code>```

This is my getdata.php :

```<code>$query = "SELECT name, price, img FROM product WHERE id = $_POST[id]";
$result = mysqli_query($conn, $query);
if(mysqli_num_rows($result) > 0)
{
    while($row = mysqli_fetch_assoc($result))
    {
        $element = "<tr> <table border='0'> <tr>";
        $element .= "<img src='$row[img]'>";
        $element .= "<br>";
        $element .= $row["name"];
        $element .= "<br>";
        $element .= $row["price"];
        $element .= "</tr> </table> </tr>";
    }
}
echo $element;
</code>```

This is dbconnect.php

```<code><?php
    // this will avoid mysql_connect() deprecation error.
    error_reporting( ~E_DEPRECATED & ~E_NOTICE );
    // but I strongly suggest you to use PDO or MySQLi.

    $servername = "localhost";
    $username = "#usernasme";
    $password = "#password";
    $dbname = "#dbname";

    $conn = mysqli_connect($servername, $username, $password, $dbname);

    if ( !$conn )
    {
        die("Connection failed : " . mysqli_error());
    }
?>
</code>```

FYI - I am using a php script that maintains a user login session that connects to a database and keeps a user logged in until he signs out. Is there by any an interference between the two scripts: one that maintains user sessions and another that accesses database for getting product details. Thanks in advance.

答:
You are not sending any data via ajax;
I'm supposing that you'have included jquery correctly;
 Then try this

```<code>$(document).ready(function(){

  $("#scan").on('click',function(){
      var id =$("#id").val();
      $.ajax({
               type: "POST",
               url: "getdata.php",
               data: {id: id},
               success: function(data){
               $('.results').append(data);
              }
      });

    });

  });
</code>```

Good luck

Body:
I am trying to get details of products to be displayed on my webpage in a specific format by submitting an id number through a form. But no data is being displayed on submitting the query. I want the latest retrieved data to be appended below the already existing data on the same page from where the form was submitted.

This is my home.php :

<?php
    ob_start();
    session_start();
    require_once 'dbconnect.php';
    // if session is not set this will redirect to login page
    if( !isset($_SESSION['user']) )
    {
        header("Location: index.php");
        exit;
    }
    // select loggedin users detail
    $res=mysqli_query($conn, "SELECT * FROM users WHERE userId=".$_SESSION['user']);
    $userRow=mysqli_fetch_array($res);
?>
<!DOCTYPE html>

        <meta charset="utf-8" />
        <title> ShopNGo </title>
        <link rel="stylesheet" type="text/css" href="style.css">
        <link rel="stylesheet" href="assets/css/bootstrap.min.css" type="text/css"  />
        <link rel="stylesheet" href="style.css" type="text/css" />

         Hi' <?php echo $userRow['userEmail']; ?>
         Sign Out

                <form name="products" method="POST" action="">

                    <input type="submit" name="scan" id="scan" value="SCAN">

                    <input type="text" name="id" id="id">
                </form>

<?php ob_end_flush(); ?>

This is my getdata.php :

$query = "SELECT name, price, img FROM product WHERE id = $_POST[id]";
$result = mysqli_query($conn, $query);
if(mysqli_num_rows($result) > 0)
{
    while($row = mysqli_fetch_assoc($result))
    {
        $element = "

";
        $element .= "";
        $element .= "
";
        $element .= $row["name"];
        $element .= "
";
        $element .= $row["price"];
        $element .= "

";
    }
}
echo $element;

This is dbconnect.php

<?php
    // this will avoid mysql_connect() deprecation error.
    error_reporting( ~E_DEPRECATED & ~E_NOTICE );
    // but I strongly suggest you to use PDO or MySQLi.

    $servername = "localhost";
    $username = "#usernasme";
    $password = "#password";
    $dbname = "#dbname";

    $conn = mysqli_connect($servername, $username, $password, $dbname);

    if ( !$conn )
    {
        die("Connection failed : " . mysqli_error());
    }
?>

FYI - I am using a php script that maintains a user login session that connects to a database and keeps a user logged in until he signs out. Is there by any an interference between the two scripts: one that maintains user sessions and another that accesses database for getting product details. Thanks in advance.

Body:
You are not sending any data via ajax;
I'm supposing that you'have included jquery correctly;
 Then try this

$(document).ready(function(){

  $("#scan").on('click',function(){
      var id =$("#id").val();
      $.ajax({
               type: "POST",
               url: "getdata.php",
               data: {id: id},
               success: function(data){
               $('.results').append(data);
              }
      });

    });

  });

Good luck


问:
naudio Midi input - filter e.MidiEvent to just data2 parameter?
Writing an app that takes MIDI input using naudio. Managed to get midi input going and outputting fine to the console, but to use the data I need to be able to isolate parts of the data. My code is

```<code>    void midiIn_MessageReceived(object sender, MidiInMessageEventArgs e)
    {
        Console.WriteLine(e.MidiEvent);
    }
</code>```

which writes the following line to the console.

```<code>0 ControlChange Ch: 1 Controller 48 Value 51
</code>```

This is fine but how do I only get data2 (the value) to then pass on to something? I could do something awful like slice it up as a string but this is probably not the way forward...

答:
You have to get the MIDI message from the message information:

```<code>void midiIn_MessageReceived(object sender, MidiInMessageEventArgs e)
{
    MidiEvent me = e.MidiEvent;
</code>```

Then you have to check for the correct message type:

```<code>    ControlChangeEvent cce = me as ControlChangeEvent;
    if (cce != null) {
</code>```

And handle it:

```<code>        Console.WriteLine(cce.ControllerValue);
    }
}
</code>```

Body:
Writing an app that takes MIDI input using naudio. Managed to get midi input going and outputting fine to the console, but to use the data I need to be able to isolate parts of the data. My code is

    void midiIn_MessageReceived(object sender, MidiInMessageEventArgs e)
    {
        Console.WriteLine(e.MidiEvent);
    }

which writes the following line to the console.

0 ControlChange Ch: 1 Controller 48 Value 51

This is fine but how do I only get data2 (the value) to then pass on to something? I could do something awful like slice it up as a string but this is probably not the way forward...

Body:
You have to get the MIDI message from the message information:

void midiIn_MessageReceived(object sender, MidiInMessageEventArgs e)
{
    MidiEvent me = e.MidiEvent;

Then you have to check for the correct message type:

    ControlChangeEvent cce = me as ControlChangeEvent;
    if (cce != null) {

And handle it:

        Console.WriteLine(cce.ControllerValue);
    }
}


问:
How do I call a text file to be used in my python terminal script
I wrote a binary decoder in python but i'm having trouble getting the text file through to it.

```<code>"""

Date :28/3/17
File Name:binary_to_string.py

"""

import sys

def binary_to_str(binary_string):
    """
    This function take a binary string as argument and convert to string
    :param binary_string: string in 0 or 1 from
    :return:
    """
    bits = 8  # initialize bit to 8 means by default we are assuming  8 bit binary
    # checking  for backslash if we found first 8 bit give backslash then we reassign  bit to 7
    if ord(chr(int(binary_string[:8], 2))) == 145:
        bits = 7

    result_string = ''
    # iterate all group of 7 or 8 character in binary string based on bits
    # and append to result string
    for i in range(0, len(binary_string), bits):
        result_string += chr(int(binary_string[i:i + bits], 2))
    return result_string

def read_file(file_name):
    """
    This function takes file name as input and read file line by line and
    append to binary_str and return it
    :param file_name:
    :return:
    """
    binary_str = ''
    with open(file_name, 'r') as f:
        for line in f:
            binary_str += line.strip()
    return binary_str

if __name__ == '__main__':
    input_file = sys.argv[1]
    print(binary_to_str(read_file(input_file)))
</code>```

I am trying to pass in a text file with the binary message:

```<code>100100011001011101100110110011011110100000101011111011111110010110110011001000100001
</code>```

Which is in a text file binary1.txt located in my pythonpractice folder along with my binary_to_string.py file.

The errors i receive from the terminal are as follows:

```<code>bthib@bthib-cyberstorm ~ $ cd pythonpractice

bthib@bthib-cyberstorm ~/pythonpractice $ python ./binary_to_string.py > binary1.txt

/usr/bin/python: can't find '__main__' module in './binary_to_string.py'
</code>```

答:
Error// bash: ./binary_to_strong.py: No such file or directory :
Have you give a directory in your python script to call ? </p>

<p>It possible to use a file object to pass the binary value you want to the textfile </p>

Body:
I wrote a binary decoder in python but i'm having trouble getting the text file through to it.

"""

Date :28/3/17
File Name:binary_to_string.py

"""

import sys

def binary_to_str(binary_string):
    """
    This function take a binary string as argument and convert to string
    :param binary_string: string in 0 or 1 from
    :return:
    """
    bits = 8  # initialize bit to 8 means by default we are assuming  8 bit binary
    # checking  for backslash if we found first 8 bit give backslash then we reassign  bit to 7
    if ord(chr(int(binary_string[:8], 2))) == 145:
        bits = 7

    result_string = ''
    # iterate all group of 7 or 8 character in binary string based on bits
    # and append to result string
    for i in range(0, len(binary_string), bits):
        result_string += chr(int(binary_string[i:i + bits], 2))
    return result_string

def read_file(file_name):
    """
    This function takes file name as input and read file line by line and
    append to binary_str and return it
    :param file_name:
    :return:
    """
    binary_str = ''
    with open(file_name, 'r') as f:
        for line in f:
            binary_str += line.strip()
    return binary_str

if __name__ == '__main__':
    input_file = sys.argv[1]
    print(binary_to_str(read_file(input_file)))

I am trying to pass in a text file with the binary message:

100100011001011101100110110011011110100000101011111011111110010110110011001000100001

Which is in a text file binary1.txt located in my pythonpractice folder along with my binary_to_string.py file.

The errors i receive from the terminal are as follows:

bthib@bthib-cyberstorm ~ $ cd pythonpractice

bthib@bthib-cyberstorm ~/pythonpractice $ python ./binary_to_string.py > binary1.txt

/usr/bin/python: can't find '__main__' module in './binary_to_string.py'

Body:
Error// bash: ./binary_to_strong.py: No such file or directory :
Have you give a directory in your python script to call ?

It possible to use a file object to pass the binary value you want to the textfile


问:
How to select and delete columns with duplicate name in pandas DataFrame
I have a huge DataFrame, where some columns have the same names. When I try to pick a column that exists twice, (eg del df['col name']  or df2=df['col name']) I get an error. What can I do?

答:
The following function removes columns with dublicate names and keeps only one. Not exactly what you asked for, but you can use snips of it to solve your problem. The idea is to return the index numbers and then you can adress the specific column indices directly. The indices are unique while the column names aren't

```<code>def remove_multiples(df,varname):
    """
    makes a copy of the first column of all columns with the same name,
    deletes all columns with that name and inserts the first column again
    """
    from copy import deepcopy
    dfout = deepcopy(df)
    if (varname in dfout.columns):
        tmp = dfout.iloc[:, min([i for i,x in enumerate(dfout.columns == varname) if x])]
        del dfout[varname]
        dfout[varname] = tmp
    return dfout
</code>```

where

```<code>[i for i,x in enumerate(dfout.columns == varname) if x]
</code>```

is the part you need

Body:
The following function removes columns with dublicate names and keeps only one. Not exactly what you asked for, but you can use snips of it to solve your problem. The idea is to return the index numbers and then you can adress the specific column indices directly. The indices are unique while the column names aren't

def remove_multiples(df,varname):
    """
    makes a copy of the first column of all columns with the same name,
    deletes all columns with that name and inserts the first column again
    """
    from copy import deepcopy
    dfout = deepcopy(df)
    if (varname in dfout.columns):
        tmp = dfout.iloc[:, min([i for i,x in enumerate(dfout.columns == varname) if x])]
        del dfout[varname]
        dfout[varname] = tmp
    return dfout

where

[i for i,x in enumerate(dfout.columns == varname) if x]

is the part you need


问:
Sort a String Array containing Numbers in linq
i have following string array which contain numbers
string[] arr = { "3", "1", "6", "10", "5", "13" };
if i do arr.OrderBy(x=>x) i am getting following result
1
10
13
3
5
6
expected result(in array):
1
3
5
6
10
13
 Any one have better and simple solution.

答:
That happens because you do a string comparison - you should change that to a int comparison

```<code>string[] arr = { "3", "1", "6", "10", "5", "13" };
var result = arr.OrderBy(int.Parse).ToArray();
</code>```

Body:
That happens because you do a string comparison - you should change that to a int comparison

string[] arr = { "3", "1", "6", "10", "5", "13" };
var result = arr.OrderBy(int.Parse).ToArray();


问:
How to change/add dependencies in Gradle 3?
The following lines are in a Gradle plugin:

```<code>project.configurations.compile.incoming.resolutionResult.allComponents.findAll { ..}
//...
Dependency dependency = project.dependencies.add('packaged', dependencyDescription)
</code>```

Applying this plugin works in Gradle 2, but fails in Gradle 3 with:

Failed to apply plugin [id 'test']

A problem occurred configuring project ':my-project'.

Cannot change dependencies of configuration ':my-project:packaged' after it has been included in
dependency resolution.

Removing the 2nd line, the error disappears in Gradle 3.
Now I would like to know the time & place which is valid in Gradle 3 to update the configuration. Reading the Gradle 3 manual i could not find an answer.

答:
It looks like incoming.resolutionResult from  the line

```<code>project.configurations.compile.incoming.resolutionResult.allComponents.findAll {..}
</code>```

is triggering dependency resolution so any modification to the dependencies after that causes the error.

The resolution can be eliminated by doing a copy and reading from it instead.

```<code>project.configurations.compile.copyRecursive().incoming.resolutionResult.allComponents.findAll {..}
</code>```

Body:
The following lines are in a Gradle plugin:

project.configurations.compile.incoming.resolutionResult.allComponents.findAll { ..}
//...
Dependency dependency = project.dependencies.add('packaged', dependencyDescription)

Applying this plugin works in Gradle 2, but fails in Gradle 3 with:

Failed to apply plugin [id 'test']

A problem occurred configuring project ':my-project'.

Cannot change dependencies of configuration ':my-project:packaged' after it has been included in
dependency resolution.

Removing the 2nd line, the error disappears in Gradle 3.
Now I would like to know the time & place which is valid in Gradle 3 to update the configuration. Reading the Gradle 3 manual i could not find an answer.

Body:
It looks like incoming.resolutionResult from  the line

project.configurations.compile.incoming.resolutionResult.allComponents.findAll {..}

is triggering dependency resolution so any modification to the dependencies after that causes the error.

The resolution can be eliminated by doing a copy and reading from it instead.

project.configurations.compile.copyRecursive().incoming.resolutionResult.allComponents.findAll {..}


问:
javascript focus search form on keydown ? (question mark)
How do I focus search form input field when these two keys are pressed using Javascript?

shift + / will generate the ?

So basically, on keydown for question mark, the search form gets autofocus.

Here is my current bootstrap 3 search form code:

```<code><form class="navbar-form navbar-right" role="form" method="post" action="{$WEB_ROOT}/knowledgebase.php?action=search">
    <div class="form-group">
        <input id="inputMessage" class="form-control" placeholder="Search website.com" type="text" name="search">
    </div>
    <button type="submit" class="btn btn-default"></button>
</form>
</code>```

答:
This works, but maybe you advise more clean solution?

```<code><script type="text/javascript">
$(document).keyup('keyup', function(event){
    if(event.which === 191) {
        $('#inputMessage').focus();
    }
});
</script>
</code>```

Maybe it shouldn't be keyup or perhaps the focus is not best. Whatcha think? I'm looking for the absolute superior way to achieve results.

Body:
How do I focus search form input field when these two keys are pressed using Javascript?

shift + / will generate the ?

So basically, on keydown for question mark, the search form gets autofocus.

Here is my current bootstrap 3 search form code:

<form class="navbar-form navbar-right" role="form" method="post" action="{$WEB_ROOT}/knowledgebase.php?action=search">

        <input id="inputMessage" class="form-control" placeholder="Search website.com" type="text" name="search">

    <button type="submit" class="btn btn-default"></button>
</form>

Body:
This works, but maybe you advise more clean solution?

<script type="text/javascript">
$(document).keyup('keyup', function(event){
    if(event.which === 191) {
        $('#inputMessage').focus();
    }
});
</script>

Maybe it shouldn't be keyup or perhaps the focus is not best. Whatcha think? I'm looking for the absolute superior way to achieve results.


问:
Contact form 7 will not email form due to it thinks its SPAM
I have  a client that has upgraded wordpress to 3.7.1. Contact Form 7 now reports all forms as SPAM.  I have WP-Mail installed and all was working before.  Any ideas on how to fix this.  Does anyone know where in the plugin code the form is getting marked as spam

Thanks

答:
I think this issue happens when we use 3rd party service like sparkpost for sending email or something like that. I tried to check code base how cf7 check spam and found  contact-form-7\includes

then submission.php file, check the code near or search with keyword "spam()"

```<code>elseif ( $this->spam() ) { // Spam!
        $this->status = 'spam';
        $this->response = $contact_form->message( 'spam' );
}
</code>```

I think besides the wordpress core blacklist checking it also check the sender domain name and bla bla and mark any valid form submission as spam. So I made the spam checking commented.

This is not a permanent solution but it will help for now.

Body:
I think this issue happens when we use 3rd party service like sparkpost for sending email or something like that. I tried to check code base how cf7 check spam and found  contact-form-7\includes

then submission.php file, check the code near or search with keyword "spam()"

elseif ( $this->spam() ) { // Spam!
        $this->status = 'spam';
        $this->response = $contact_form->message( 'spam' );
}

I think besides the wordpress core blacklist checking it also check the sender domain name and bla bla and mark any valid form submission as spam. So I made the spam checking commented.

This is not a permanent solution but it will help for now.


问:
Working with both http and https
I don't know much about working with .htaccess files. I've tried researching. So, maybe someone could help me out on here. I want to allow https and http at the same time. Let me explain.

http is working but a website on HTTPS is giving me a error in the console

XMLHttpRequest cannot load https://domain1.com/data.json. The 'Access-Control-Allow-Origin' header has a value 'https://www.domain1.coms' that is not equal to the supplied origin. Origin 'https://www.domain1.com' is therefore not allowed access.

If I change the "http" to "https" it works for the https website but then the http website doesn't work.  How do I allow both at the same time?

I hope that made any sense to you guys! Thank you for any help!

Here is my code:

```<code><IfModule mod_headers.c>
    SetEnvIf Origin "http(s)?://(www\.)?(domain.com|domain2.com|domain3.com|domain4.com|domain5.com)$" AccessControlAllowOrigin=$0$1
    Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
    Header set Access-Control-Allow-Credentials true
</IfModule>
</code>```

答:
Well, there are ways first is by creating virtual host. To do this neeed to make change http conf file.

```<code><VirtualHost *:80>
ServerName 'http://www.domain1.com'
DocumentRoot /var/www/your-domain-root
</VirtualHost>

<VirtualHost *:443>
DocumentRoot /var/www/your-domain-root
ServerName 'https://www.domain1.com'
SSLEngine On
SSLOptions +StrictRequire
SSLCertificateFile /path/to/server.crt
SSLCertificateKeyFile /path/to/server.key
SSLProtocol TLSv1
</VirtualHost>
</code>```

Secondly, we can do this using htaccess. In htaccess we can use 301 redirects. Website in ssl(http://) will be our base website and non ssl(http://) website will be secondary. Redirect all requests from http:// to https://. For redirecting you can use 301 redirects or mod_rewrite any.

Let me know if it was helpful.

Title: Working with both http and https

Body:
I don't know much about working with .htaccess files. I've tried researching. So, maybe someone could help me out on here. I want to allow https and http at the same time. Let me explain.

http is working but a website on HTTPS is giving me a error in the console

XMLHttpRequest cannot load https://domain1.com/data.json. The 'Access-Control-Allow-Origin' header has a value 'https://www.domain1.coms' that is not equal to the supplied origin. Origin 'https://www.domain1.com' is therefore not allowed access.

If I change the "http" to "https" it works for the https website but then the http website doesn't work.  How do I allow both at the same time?

I hope that made any sense to you guys! Thank you for any help!

Here is my code:

<IfModule mod_headers.c>
    SetEnvIf Origin "http(s)?://(www\.)?(domain.com|domain2.com|domain3.com|domain4.com|domain5.com)$" AccessControlAllowOrigin=$0$1
    Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
    Header set Access-Control-Allow-Credentials true
</IfModule>

Body:
Well, there are ways first is by creating virtual host. To do this neeed to make change http conf file.

<VirtualHost *:80>
ServerName 'http://www.domain1.com'
DocumentRoot /var/www/your-domain-root
</VirtualHost>

<VirtualHost *:443>
DocumentRoot /var/www/your-domain-root
ServerName 'https://www.domain1.com'
SSLEngine On
SSLOptions +StrictRequire
SSLCertificateFile /path/to/server.crt
SSLCertificateKeyFile /path/to/server.key
SSLProtocol TLSv1
</VirtualHost>

Secondly, we can do this using htaccess. In htaccess we can use 301 redirects. Website in ssl(http://) will be our base website and non ssl(http://) website will be secondary. Redirect all requests from http:// to https://. For redirecting you can use 301 redirects or mod_rewrite any.

Let me know if it was helpful.


问:
How to import multiple vCard VCF contact files into Outlook using Powershell?
How can I import multiple vCard VCF contact files into Outlook using Powershell ?

My script for create vcf is :

```<code>    # Création d'un fichier.vcf

New-Item C:\TEST\$($LastName)_$($Name).vcf -type file -force -value "
BEGIN:VCARD
VERSION:2.1
N;LANGUAGE=fr;CHARSET=utf-8:$($Agence)
FN;CHARSET=utf-8:$($LastName), $($Name)
ORG;CHARSET=utf-8:$($Company)
TITLE;CHARSET=utf-8:$($Title)
TEL;WORK;VOICE:$($WorkNum)
TEL;WORK;VOICE:$($WorkNum2)
TEL;CELL;VOICE:$($MobNum)
LABEL;WORK;PREF;CHARSET=utf-8;ENCODING=QUOTED-PRINTABLE:$($WorkAdress)
X-MS-OL-DEFAULT-POSTAL-ADDRESS:1
EMAIL;CHARSET=utf-8;PREF;INTERNET:$($Email)
X-MS-IMADDRESS;CHARSET=utf-8:$($Email)
PHOTO;TYPE=JPEG;ENCODING=BASE64:$($encodedImage)

X-MS-OL-DESIGN;CHARSET=utf-8:<card xmlns='http://schemas.microsoft.com/office/outlook/12/electronicbusinesscards' ver='1.0' layout='left' bgcolor='ffffff'><img xmlns='' align='fit' area='16' use='cardpicture'/><fld xmlns='' prop='name' align='left' dir='ltr' style='b' color='000000' size='10'/><fld xmlns='' prop='org' align='left' dir='ltr' color='000000' size='8'/><fld xmlns='' prop='blank' size='8'/><fld xmlns=' prop='telwork' align='left' dir='ltr' color='d48d2a' size='8'><label align='right' color='626262'>Bureau</label></fld><fld xmlns='' prop='telhome' align='left' dir='ltr' color='d48d2a' size='8'><label align='right' color='626262'>Domicile</label></fld><fld xmlns='' prop='email' align='left' dir='ltr' color='d48d2a' size='8'/><fld xmlns='' prop='addrwork' align='left' dir='ltr' color='000000' size='8'/><fld xmlns='' prop='im' align='left' dir='ltr' color='000000' size='8'><label align='right' color='626262'>Mess. instant.</label></fld><fld xmlns='' prop='blank' size='8'/><fld xmlns='' prop='blank' size='8'/><fld xmlns='' prop='blank' size='8'/><fld xmlns='' prop='blank' size='8'/><fld xmlns=' prop='blank' size='8'/><fld xmlns='' prop='blank' size='8'/><fld xmlns='' prop='blank' size='8'/><fld xmlns='' prop='blank' size='8'/></card>
END:VCARD"`
</code>```

答:
A couple of options:

I. Outlook Object Model - call Namespace.OpenSharedItem (it supports MSG, vCard, and iCal formats) and pass the VCF file name. Outlook will return an instance of the ContactItem object that you can save or move to any folder.

II. If using Redemption (I am its author) is an option, it supports vCard format (among a dozen or so other formats, vCard included) by the Import method (exposed by the RDOMail and objects derived from it, such as RDOContactItem).

```<code>set Session = CreateObject("Redemption.RDOSession")
Session.MAPIOBJECT = Application.Session.MAPIOBJECT 'or you can use Logon, LogonHostedExchangeMailbox, etc.
set Contact = Session.GetDefaultFolder(olFolderContacts).Items.Add
Contact.Import "c:\Temp\test.vcf ", olVCard
Contact.Save
</code>```

Body:
How can I import multiple vCard VCF contact files into Outlook using Powershell ?

My script for create vcf is :

    # Création d'un fichier.vcf

New-Item C:\TEST\$($LastName)_$($Name).vcf -type file -force -value "
BEGIN:VCARD
VERSION:2.1
N;LANGUAGE=fr;CHARSET=utf-8:$($Agence)
FN;CHARSET=utf-8:$($LastName), $($Name)
ORG;CHARSET=utf-8:$($Company)
TITLE;CHARSET=utf-8:$($Title)
TEL;WORK;VOICE:$($WorkNum)
TEL;WORK;VOICE:$($WorkNum2)
TEL;CELL;VOICE:$($MobNum)
LABEL;WORK;PREF;CHARSET=utf-8;ENCODING=QUOTED-PRINTABLE:$($WorkAdress)
X-MS-OL-DEFAULT-POSTAL-ADDRESS:1
EMAIL;CHARSET=utf-8;PREF;INTERNET:$($Email)
X-MS-IMADDRESS;CHARSET=utf-8:$($Email)
PHOTO;TYPE=JPEG;ENCODING=BASE64:$($encodedImage)

X-MS-OL-DESIGN;CHARSET=utf-8:<card xmlns='http://schemas.microsoft.com/office/outlook/12/electronicbusinesscards' ver='1.0' layout='left' bgcolor='ffffff'><fld xmlns='' prop='name' align='left' dir='ltr' style='b' color='000000' size='10'/><fld xmlns='' prop='org' align='left' dir='ltr' color='000000' size='8'/><fld xmlns='' prop='blank' size='8'/><fld xmlns=' prop='telwork' align='left' dir='ltr' color='d48d2a' size='8'>Bureau</fld><fld xmlns='' prop='telhome' align='left' dir='ltr' color='d48d2a' size='8'>Domicile</fld><fld xmlns='' prop='email' align='left' dir='ltr' color='d48d2a' size='8'/><fld xmlns='' prop='addrwork' align='left' dir='ltr' color='000000' size='8'/><fld xmlns='' prop='im' align='left' dir='ltr' color='000000' size='8'>Mess. instant.</fld><fld xmlns='' prop='blank' size='8'/><fld xmlns='' prop='blank' size='8'/><fld xmlns='' prop='blank' size='8'/><fld xmlns='' prop='blank' size='8'/><fld xmlns=' prop='blank' size='8'/><fld xmlns='' prop='blank' size='8'/><fld xmlns='' prop='blank' size='8'/><fld xmlns='' prop='blank' size='8'/></card>
END:VCARD"`

Body:
A couple of options:

I. Outlook Object Model - call Namespace.OpenSharedItem (it supports MSG, vCard, and iCal formats) and pass the VCF file name. Outlook will return an instance of the ContactItem object that you can save or move to any folder.

II. If using Redemption (I am its author) is an option, it supports vCard format (among a dozen or so other formats, vCard included) by the Import method (exposed by the RDOMail and objects derived from it, such as RDOContactItem).

set Session = CreateObject("Redemption.RDOSession")
Session.MAPIOBJECT = Application.Session.MAPIOBJECT 'or you can use Logon, LogonHostedExchangeMailbox, etc.
set Contact = Session.GetDefaultFolder(olFolderContacts).Items.Add
Contact.Import "c:\Temp\test.vcf ", olVCard
Contact.Save


问:
Reference alias (calculated in SELECT) in WHERE clause
```<code>SELECT (InvoiceTotal - PaymentTotal - CreditTotal) AS BalanceDue
FROM Invoices
WHERE BalanceDue > 0 --error
</code>```

The calculated value BalanceDue that is set as a variable in the list of selected columns cannot be used in the WHERE clause.

Is there a way that it can? In this related question (Using a variable in MySQL Select Statment in a Where Clause), it seems like the answer would be, actually, no, you would just write out the calculation (and perform that calculation in the query) twice, none of which is satisfactory.

答:
You can do this using cross apply

```<code>SELECT c.BalanceDue AS BalanceDue
FROM Invoices
cross apply (select (InvoiceTotal - PaymentTotal - CreditTotal) as BalanceDue) as c
WHERE  c.BalanceDue  > 0;
</code>```

Body:
SELECT (InvoiceTotal - PaymentTotal - CreditTotal) AS BalanceDue
FROM Invoices
WHERE BalanceDue > 0 --error

The calculated value BalanceDue that is set as a variable in the list of selected columns cannot be used in the WHERE clause.

Is there a way that it can? In this related question (Using a variable in MySQL Select Statment in a Where Clause), it seems like the answer would be, actually, no, you would just write out the calculation (and perform that calculation in the query) twice, none of which is satisfactory.

Body:
You can do this using cross apply

SELECT c.BalanceDue AS BalanceDue
FROM Invoices
cross apply (select (InvoiceTotal - PaymentTotal - CreditTotal) as BalanceDue) as c
WHERE  c.BalanceDue  > 0;


问:
Cannot read property of undefined when using interpolation
I have put an effort before asking this question to search and make sure this question is not duplicated, but I didn't find anything similar to my issue.

I am newbie to Angular 2, and my component class is like below:

import {Component} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';

@Component({
 selector: 'pm-products',
 templateUrl: 'app/products/product-list.component.html'
})

export class ProductListComponent{
pageTitle: string = 'Product List';
products: any[] = [
    {
        "productId": 1,
        "productName": "Leaf Rake",
        "productCode": "GDN-0011",
        "releaseDate": "March 19, 2016",
        "description": "Leaf rake with 48-inch wooden handle.",
        "price": 19.95,
        "starRating": 3.2,
        "imageUrl": "SOME URL"
    },
    {
        "productId": 2,
        "productName": "Garden Cart",
        "productCode": "GDN-0023",
        "releaseDate": "March 18, 2016",
        "description": "15 gallon capacity rolling garden cart",
        "price": 32.99,
        "starRating": 4.2,
        "imageUrl": "SOME URL"
    }

    ];
}
```

<p>And below code is my view:</p>

<pre class="lang-js prettyprint-override"><code><div class='table-responsive'>
    <table class='table'
        *ngIf='products && products.length'>
        <thead>
            <tr>
                <th>
                    <button class='btn btn-primary'>
                        Show Image
                    </button>
                </th>

                <th>Product</th>
                <th>Code</th>
                <th>Available</th>
                <th>Price</th>
                <th>5 Star Rating</th>
            </tr>
        </thead>
        <tbody>
            <tr *ngFor='let product of products'></tr>
            <td></td>
            <td>{{ product.productName }}</td>
            <td>{{ product.productCode }}</td>
            <td>{{ product.releaseDate }}</td>
            <td>{{ product.price }}</td>
            <td>{{ product.starRating }}</td>

        </tbody>
    </table>

</div>
</code>```

When I run this code I get an error saying "Error in app/products/product-list.component.html:38:16 caused by: Cannot read property 'productName' of undefined", and "Cannot read property 'productName' of undefined"

Using the interpolation in my view, my expectation is to see the products object properties values within the  tags.

答:
Use Angular safe navigation operator to check nested properties' path. Try this:</p>

```<code><tbody>
    <tr *ngFor='let product of products'>
        <td></td>
        <td>{{ product?.productName }}</td>
        <td>{{ product?.productCode }}</td>
        <td>{{ product?.releaseDate }}</td>
        <td>{{ product?.price }}</td>
        <td>{{ product?.starRating }}</td>
     </tr>
</tbody>
</code>```

Body:
I have put an effort before asking this question to search and make sure this question is not duplicated, but I didn't find anything similar to my issue.

I am newbie to Angular 2, and my component class is like below:

import {Component} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';

@Component({
 selector: 'pm-products',
 templateUrl: 'app/products/product-list.component.html'
})

export class ProductListComponent{
pageTitle: string = 'Product List';
products: any[] = [
    {
        "productId": 1,
        "productName": "Leaf Rake",
        "productCode": "GDN-0011",
        "releaseDate": "March 19, 2016",
        "description": "Leaf rake with 48-inch wooden handle.",
        "price": 19.95,
        "starRating": 3.2,
        "imageUrl": "SOME URL"
    },
    {
        "productId": 2,
        "productName": "Garden Cart",
        "productCode": "GDN-0023",
        "releaseDate": "March 18, 2016",
        "description": "15 gallon capacity rolling garden cart",
        "price": 32.99,
        "starRating": 4.2,
        "imageUrl": "SOME URL"
    }

    ];
}

And below code is my view:

                    <button class='btn btn-primary'>
                        Show Image
                    </button>

                Product
                Code
                Available
                Price
                5 Star Rating

            {{ product.productName }}
            {{ product.productCode }}
            {{ product.releaseDate }}
            {{ product.price }}
            {{ product.starRating }}

When I run this code I get an error saying "Error in app/products/product-list.component.html:38:16 caused by: Cannot read property 'productName' of undefined", and "Cannot read property 'productName' of undefined"

Using the interpolation in my view, my expectation is to see the products object properties values within the  tags.

Body:
Use Angular safe navigation operator to check nested properties' path. Try this:

<tbody>
    <tr *ngFor='let product of products'>
        <td></td>
        <td>{{ product?.productName }}</td>
        <td>{{ product?.productCode }}</td>
        <td>{{ product?.releaseDate }}</td>
        <td>{{ product?.price }}</td>
        <td>{{ product?.starRating }}</td>
     </tr>
</tbody>


问:
Git push origin master returns Error cannot spawn ... why?
I'm trying to use GitHub for the first time, but after many issues trying to get the authentication right, I've managed to authenticate with git@github.com and created a repo, but when i try "git push origin master" i get the following error:

```<code>$ git push origin master
error: cannot spawn : No such file or directory
fatal: unable to fork
</code>```

I cant  find any reason for the error or any explanation in the trouble shooting pages, can anyone suggest why it may be that I get that error.

I have already specified/added the remote path as follows:

```<code>$ git remote add origin git@github.com:christopherdebeer/yUML-Diagram.git
</code>```

please help.

Also this is all on a windows 7 machine running mysysgit (1.7.0.2) and using git bash.

re: Issue 313, a space in the GIT_SSH variable, cant be the problem mine is as follows:

```<code>$GIT_SSH="c:/putty/plink.exe"
</code>```

答:
I had same problem.
I changed my remote link from:

```<code>git@github.com:Prathapnagaraj/trydjango18.git
</code>```

to url-link:

```<code>https://github.com/Prathapnagaraj/trydjango18
</code>```

then it worked fine.

Body:
I'm trying to use GitHub for the first time, but after many issues trying to get the authentication right, I've managed to authenticate with git@github.com and created a repo, but when i try "git push origin master" i get the following error:

$ git push origin master
error: cannot spawn : No such file or directory
fatal: unable to fork

I cant  find any reason for the error or any explanation in the trouble shooting pages, can anyone suggest why it may be that I get that error.

I have already specified/added the remote path as follows:

$ git remote add origin git@github.com:christopherdebeer/yUML-Diagram.git

please help.

Also this is all on a windows 7 machine running mysysgit (1.7.0.2) and using git bash.

re: Issue 313, a space in the GIT_SSH variable, cant be the problem mine is as follows:

$GIT_SSH="c:/putty/plink.exe"

Body:
I had same problem.
I changed my remote link from:

git@github.com:Prathapnagaraj/trydjango18.git

to url-link:

https://github.com/Prathapnagaraj/trydjango18

then it worked fine.


问:
Is WebRtc library provide snapshot features?
I have to snapshot the live streaming video using webrtc. How can I snap the view?</p>

答: Just use canvas and video tags and context.drawImage. For a detailed tutorial please see https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API/Taking_still_photos


问:
awk command in unix - inserting records in to oracle
I am trying to generate insert statements in unix shell script and execute it using sqlplus command. I wrote the below code  .

```<code>    awk 'BEGIN { for (i = 1; i < 3;  i++)
printf "INSERT INTO EMPLOYEE VALUES(%s,%d,%d);\n","\047TEST-FROM-UNIX\047",$i,$i}'| sqlplus -s username/passwrd
</code>```

Is there any other good practice to do the insertion from unix ?

It generates the output

```<code>INSERT INTO EMPLOYEE VALUES('TEST-FROM-UNIX',0,0);

INSERT INTO EMPLOYEE VALUES('TEST-FROM-UNIX',0,0);
</code>```

But the required output is

```<code>INSERT INTO EMPLOYEE VALUES('TEST-FROM-UNIX',1,1);

INSERT INTO EMPLOYEE VALUES('TEST-FROM-UNIX',2,2);
</code>```

Could some one please tell, What change in the above code will achieve this ?  Thanks for your time..

答:
Drop the $ with i :

```<code> awk 'BEGIN { for (i = 1; i < 3;  i++)
 printf "INSERT INTO EMPLOYEE VALUES(%s,%d,%d);\n","\047TEST-FROM-UNIX\047",i,i}'
</code>```

If you want to do it with variable max value then you have to create a script file with this code :

```<code>awk -v rows=$1 'BEGIN { for (i = 1; i < rows;  i++)
printf "INSERT INTO EMPLOYEE VALUES(%s,%d,%d);\n","\047TEST-FROM-UNIX\047",i,i}'
</code>```

Body:
I am trying to generate insert statements in unix shell script and execute it using sqlplus command. I wrote the below code  .

    awk 'BEGIN { for (i = 1; i < 3;  i++)
printf "INSERT INTO EMPLOYEE VALUES(%s,%d,%d);\n","\047TEST-FROM-UNIX\047",$i,$i}'| sqlplus -s username/passwrd

Is there any other good practice to do the insertion from unix ?

It generates the output

INSERT INTO EMPLOYEE VALUES('TEST-FROM-UNIX',0,0);

INSERT INTO EMPLOYEE VALUES('TEST-FROM-UNIX',0,0);

But the required output is

INSERT INTO EMPLOYEE VALUES('TEST-FROM-UNIX',1,1);

INSERT INTO EMPLOYEE VALUES('TEST-FROM-UNIX',2,2);

Could some one please tell, What change in the above code will achieve this ?  Thanks for your time..

Body:
Drop the $ with i :

 awk 'BEGIN { for (i = 1; i < 3;  i++)
 printf "INSERT INTO EMPLOYEE VALUES(%s,%d,%d);\n","\047TEST-FROM-UNIX\047",i,i}'

If you want to do it with variable max value then you have to create a script file with this code :

awk -v rows=$1 'BEGIN { for (i = 1; i < rows;  i++)
printf "INSERT INTO EMPLOYEE VALUES(%s,%d,%d);\n","\047TEST-FROM-UNIX\047",i,i}'


问:
RegisterClassEx Fails as Invalid Parameter - C++
A call to RegisterClassEx in my application is failing with error code 87, "The parameter is incorrect."

```<code>memset( &m_wcx, 0, sizeof(WNDCLASSEX) );

m_wcx.cbSize = sizeof(WNDCLASSEX);  // size of structure
m_wcx.style = WS_ICONIC;            // initially minimized
m_wcx.lpfnWndProc = &WndProc;       // points to window procedure
m_wcx.cbClsExtra = 0;               // no extra class memory
m_wcx.cbWndExtra = 0;               // no extra window memory
m_wcx.hInstance = m_hInstance;      // handle to instance
m_wcx.hIcon = ::LoadIcon( NULL, IDI_APPLICATION ); // default app icon
m_wcx.hCursor = ::LoadCursor( NULL, IDC_ARROW ); // standard arrow cursor
m_wcx.hbrBackground = NULL;         // no background to paint
m_wcx.lpszMenuName = NULL;          // no menu resource
m_wcx.lpszClassName = _pwcWindowClass; // name of window class
m_wcx.hIconSm = NULL;               // search system resources for sm icon

m_atom = ::RegisterClassEx( &m_wcx );

if ( m_atom == 0 )
{
    TRACE(_T("CNotifyWindow::CNotifyWindow : Failed to register window class.\r\n\tError: %d\r\n\tFile: %s\r\n\tLine: %d\r\n"), ::GetLastError(), __WFILE__, __LINE__);
    THROW(::GetLastError());
}
</code>```

Does anyone know what I'm doing wrong?  Thanks.

答:
The style member of the WNDCLASSEX structure accepts class styles, not window styles. In other words, you can't make all windows of that class initially minimized that way.

You should pass WS_ICONIC in the dwStyle argument to CreateWindow() or CreateWindowEx() instead.

Body:
A call to RegisterClassEx in my application is failing with error code 87, "The parameter is incorrect."

memset( &m_wcx, 0, sizeof(WNDCLASSEX) );

m_wcx.cbSize = sizeof(WNDCLASSEX);  // size of structure
m_wcx.style = WS_ICONIC;            // initially minimized
m_wcx.lpfnWndProc = &WndProc;       // points to window procedure
m_wcx.cbClsExtra = 0;               // no extra class memory
m_wcx.cbWndExtra = 0;               // no extra window memory
m_wcx.hInstance = m_hInstance;      // handle to instance
m_wcx.hIcon = ::LoadIcon( NULL, IDI_APPLICATION ); // default app icon
m_wcx.hCursor = ::LoadCursor( NULL, IDC_ARROW ); // standard arrow cursor
m_wcx.hbrBackground = NULL;         // no background to paint
m_wcx.lpszMenuName = NULL;          // no menu resource
m_wcx.lpszClassName = _pwcWindowClass; // name of window class
m_wcx.hIconSm = NULL;               // search system resources for sm icon

m_atom = ::RegisterClassEx( &m_wcx );

if ( m_atom == 0 )
{
    TRACE(_T("CNotifyWindow::CNotifyWindow : Failed to register window class.\r\n\tError: %d\r\n\tFile: %s\r\n\tLine: %d\r\n"), ::GetLastError(), __WFILE__, __LINE__);
    THROW(::GetLastError());
}

Does anyone know what I'm doing wrong?  Thanks.


问:
ORA -00909 //sql statement ignored ...procedure created with compilation errors
```<code>create or replace procedure Pupdate(
peno in emp.empno%type,
psal in emp.sal%type,
pcomm in emp.comm%type)
IS
BEGIN
UPDATE emp SET sal=sal+psal, comm=NVL(comm)+pcomm WHERE empno=peno;
END Pupdate;
/
</code>```

The stored procedure takes the sal and comm from user and updates it into the emp table.

答:
```<code> create or replace procedure Pupdate(
peno in emp.empno%type,
psal in emp.sal%type,
pcomm in emp.comm%type)
IS
BEGIN
UPDATE emp SET sal=sal+psal, comm=NVL(comm,0)+nvl(pcomm,0) WHERE empno=peno;
END Pupdate;
/
</code>```

Just try this. NVL will be like NVL(column_name,value_if_null).

Body:
create or replace procedure Pupdate(
peno in emp.empno%type,
psal in emp.sal%type,
pcomm in emp.comm%type)
IS
BEGIN
UPDATE emp SET sal=sal+psal, comm=NVL(comm)+pcomm WHERE empno=peno;
END Pupdate;
/

The stored procedure takes the sal and comm from user and updates it into the emp table.

Body:
 create or replace procedure Pupdate(
peno in emp.empno%type,
psal in emp.sal%type,
pcomm in emp.comm%type)
IS
BEGIN
UPDATE emp SET sal=sal+psal, comm=NVL(comm,0)+nvl(pcomm,0) WHERE empno=peno;
END Pupdate;
/

Just try this. NVL will be like NVL(column_name,value_if_null).


问:
mkdir doesn't do path expansion
So I have folder aa

```<code>$ mkdir aa
</code>```

and path expansion for ls command works like this:

```<code>$ ls -la a*
total 0
drwxr-xr-x 1 a a 0 Mar 29 08:41 ./
drwxr-xr-x 1 a a 0 Dec 31  1979 ../
$ ls -la a?
total 0
drwxr-xr-x 1 a a 0 Mar 29 08:41 ./
drwxr-xr-x 1 a a 0 Dec 31  1979 ../
</code>```

But "the same" for mkdir shows an error:

```<code>$ mkdir a*/bb
mkdir: cannot create directory 'a*/bb': No such file or directory
$ mkdir a?/bb
mkdir: cannot create directory 'a?/bb': No such file or directory
</code>```

Where can I read why this difference in behavior happens and is there simple trick to let mkdir be "smarter" for behavior like in ls?

答:
This does not work, since wildcard expansion is done before the argument is passed to mkdir. bash tries to expand a*/bb, doesn't find a match and tells you so. mkdir is not even invoked here. You can also try e.g.

```<code>echo a*/bb
</code>```

or as you did before

```<code>ls -la a*/bb
</code>```

Both commands will give you the same error message.

Title: mkdir doesn't do path expansion

Body:
So I have folder aa

$ mkdir aa

and path expansion for ls command works like this:

$ ls -la a*
total 0
drwxr-xr-x 1 a a 0 Mar 29 08:41 ./
drwxr-xr-x 1 a a 0 Dec 31  1979 ../
$ ls -la a?
total 0
drwxr-xr-x 1 a a 0 Mar 29 08:41 ./
drwxr-xr-x 1 a a 0 Dec 31  1979 ../

But "the same" for mkdir shows an error:

$ mkdir a*/bb
mkdir: cannot create directory 'a*/bb': No such file or directory
$ mkdir a?/bb
mkdir: cannot create directory 'a?/bb': No such file or directory

Where can I read why this difference in behavior happens and is there simple trick to let mkdir be "smarter" for behavior like in ls?

Body:
This does not work, since wildcard expansion is done before the argument is passed to mkdir. bash tries to expand a*/bb, doesn't find a match and tells you so. mkdir is not even invoked here. You can also try e.g.

echo a*/bb

or as you did before

ls -la a*/bb

Both commands will give you the same error message.


答:
try </p>

```<code>$(document).on('keypress',function(e){
   if(e.keyCode == 63 ) {
      $("#inputMessage").focus()
   }
});
</code>```

Title: javascript focus search form on keydown ? (question mark)

Body:
How do I focus search form input field when these two keys are pressed using Javascript?

shift + / will generate the ?

So basically, on keydown for question mark, the search form gets autofocus.

Here is my current bootstrap 3 search form code:

<form class="navbar-form navbar-right" role="form" method="post" action="{$WEB_ROOT}/knowledgebase.php?action=search">

        <input id="inputMessage" class="form-control" placeholder="Search website.com" type="text" name="search">

    <button type="submit" class="btn btn-default"></button>
</form>

Body:
try

$(document).on('keypress',function(e){
   if(e.keyCode == 63 ) {
      $("#inputMessage").focus()
   }
});


问:
How to compare hours with numbers in excel?
I am making a task sheet for my students and I have written the following code:

```<code>=IF(J35-K35>5,"Task 1",IF(J35-K35>3,"Task 2",IF(J35-K35>2,"Task 3", IF(J35-K35>0,"Task 4",IF(K35-J35<1,"Task 5",IF(K35-J35<3,"task 6",IF(K35-J35>3,"Task 7")))))))
</code>```

The cell K35 contains "Total hours worked" and
The cell J35 contains  "Total hours required".
Their format is in [h]:mm

The problem I am facing here is that it is showing me output for only 2 conditions - for the one which is greater than 0 (Task 4) and the other which is less than 1 (task 5). None of the other conditions are getting executed. I need a way in which I can compare hours with numbers.
How can I solve this problem?

答:
If the cells contain times, the calculation J35-K35 will return a number between 0 and 1 for a positive value, between -1 and 0 for a negative value. The formula will use the underlying values, not what they will look like if formatted as time.

The value of one hour, formatted as general is 0.041666667. You can either use that and its multiples in your formula or multiply the result of the subtraction by 24 to arrive at numbers where the part before the decimal point is the number of hours, so your formula could be

```<code>=IF((J35-K35)*24>5,"Task 1",IF((J35-K35)*24>3,"Task 2",IF((J35-K35)*24>2,"Task 3", IF((J35-K35)*24>0,"Task 4",IF((K35-J35)*24<1,"Task 5",IF((K35-J35)*24<3,"task 6",IF((K35-J35)*24>3,"Task 7")))))))
</code>```

Body:
I am making a task sheet for my students and I have written the following code:

=IF(J35-K35>5,"Task 1",IF(J35-K35>3,"Task 2",IF(J35-K35>2,"Task 3", IF(J35-K35>0,"Task 4",IF(K35-J35<1,"Task 5",IF(K35-J35<3,"task 6",IF(K35-J35>3,"Task 7")))))))

The cell K35 contains "Total hours worked" and
The cell J35 contains  "Total hours required".
Their format is in [h]:mm

The problem I am facing here is that it is showing me output for only 2 conditions - for the one which is greater than 0 (Task 4) and the other which is less than 1 (task 5). None of the other conditions are getting executed. I need a way in which I can compare hours with numbers.
How can I solve this problem?

Body:
If the cells contain times, the calculation J35-K35 will return a number between 0 and 1 for a positive value, between -1 and 0 for a negative value. The formula will use the underlying values, not what they will look like if formatted as time.

The value of one hour, formatted as general is 0.041666667. You can either use that and its multiples in your formula or multiply the result of the subtraction by 24 to arrive at numbers where the part before the decimal point is the number of hours, so your formula could be

=IF((J35-K35)*24>5,"Task 1",IF((J35-K35)*24>3,"Task 2",IF((J35-K35)*24>2,"Task 3", IF((J35-K35)*24>0,"Task 4",IF((K35-J35)*24<1,"Task 5",IF((K35-J35)*24<3,"task 6",IF((K35-J35)*24>3,"Task 7")))))))