问:
Inconsistent representation of tuples?
Assume we've made the following assignment:

```<code>x = (1, 2, (3, 'John', 4), 'Hi')
</code>```

Why does x[0:1] gives me (1,) but x[0:-1] gives (1, 2, (3, 'John', 4))? Why is there no comma after (3, 'John', 4)?

答: When ever you are working on a tuple and there is a single element it ends with a comma like in your first case (1,). As in the second case (1, 2, (3, 'John', 4)) there is more than one element, it does not end with a comma.</p>

Title: Inconsistent representation of tuples?

Body:
Assume we've made the following assignment:

x = (1, 2, (3, 'John', 4), 'Hi')

Why does x[0:1] gives me (1,) but x[0:-1] gives (1, 2, (3, 'John', 4))? Why is there no comma after (3, 'John', 4)?


来源: stackexchange

问:
SQL multiple group by, aggregate by first group
I Currently have written an sql query like this:

```<code>SELECT   a, b, count(id) / ????
FROM     X
group by a, b
</code>```

Please pay attention to the ????? in the code above.
There are two groups in group by. Namely by columns a and b.

What I intend to do is to divide the (1) count of items in the second group (b) to the (2) count of items in the first group (a).

count(id) accomplishes (1). But I don't know what to write for (2).

P.S.: However I know It is possible to replace "????" with another complex select query, but I want to learn if there is a simpler way to aggregate items of first Group by.

Update:
Sample data:

```<code>id       a           b
______________________
1       'A'         'G'
2       'A'         'H'
3       'A'         'H'
4       'B'         'G'
5       'B'         'G'
6       'B'         'K'
7       'B'         'K'
</code>```

results:

```<code>a           b          [unnamed]
________________________________
'A'         'G'        0.33333
'A'         'H'        0.66667
'B'         'G'        0.5
'B'         'K'        0.5
</code>```

The third column is the percentage of columns with values as in column b relative to values in column a.

Thank you.

答:
```<code>select A.a, B.b, a.num, b.num, CAST(b.num as float) / cast(a.num as float)
from
(select a, count(*) as num
from @table
group by a) as A
join
(select a, b, count(*) as num
from @table
group by a, b) as B on A.a = B.a
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I Currently have written an sql query like this:

SELECT   a, b, count(id) / ????
FROM     X
group by a, b

Please pay attention to the ????? in the code above.
There are two groups in group by. Namely by columns a and b.

What I intend to do is to divide the (1) count of items in the second group (b) to the (2) count of items in the first group (a).

count(id) accomplishes (1). But I don't know what to write for (2).

P.S.: However I know It is possible to replace "????" with another complex select query, but I want to learn if there is a simpler way to aggregate items of first Group by.

Update:
Sample data:

id       a           b
______________________
1       'A'         'G'
2       'A'         'H'
3       'A'         'H'
4       'B'         'G'
5       'B'         'G'
6       'B'         'K'
7       'B'         'K'

results:

a           b          [unnamed]
________________________________
'A'         'G'        0.33333
'A'         'H'        0.66667
'B'         'G'        0.5
'B'         'K'        0.5

The third column is the percentage of columns with values as in column b relative to values in column a.

Thank you.


问:
SVG hovers with fallbacks
What is the bestpractice, when I need to have SVG images with SVG hovers with fallbacks?

I mean SVG images with PNG fallbacks (normal, reaponsive 2x, 3x), and change them on hover to other SVG images with PNG fallbacks?

Is it better to use  or <picture> + <source /> +  tag with jQuery (or vanilla, but I already use jQuery), or to have it all in CSS as backgrounds? If jQuery, does it mean swapping srcsets? If CSS, how do I best include @2x and @3x image versions?

Also, how does the used method affect preloading of the hovers? It would surely be much better without blinking.

So far I have this, I need to change them on hover to 1hov.svg, 1hov.png, 1hov@2x.png, 1hov@3x.png

```<code><a href="#">
 <picture>
  <source type="image/svg+xml" srcset="logos/1.svg">
  <img src="logos/1.png" srcset="logos/1@2x.png 2x, logos/1@3x.png 3x" alt="logo">
 </picture>
</a>
</code>```

答:
Here is a HTML + jQuery solution I found. It swaps the src and sourcesets to their hover alternatives. Includes the hovers preloading.

HTML

```<code>        <a href="#" target="_blank">
            <picture>
                <source type="image/svg+xml" srcset="logos/1.svg" data-swap-srcset="logos/1hov.svg">
                <img src="logos/1.png"  data-swap-src="logos/1hov.png"
srcset="logos/1@2x.png 2x, logos/1@3x.png 3x" data-swap-srcset="logos/1hov@2x.png 2x, logos/1hov@3x.png 3x" alt="logo">
            </picture>
        </a>
</code>```

jQuery

```<code>//preload hovers
$("source[data-swap-src]").each(function(){
    $('<img/>')[0].src = $(this).attr("data-swap-src");
});
$("img[data-swap-src]").each(function(){
    $('<img/>')[0].src = $(this).attr("data-swap-src");
    $('<img/>')[0].srcset = $(this).attr("data-swap-srcset");
});

$("a").hover(function(){
   var newone = $(this).find("img").attr("data-swap-src");
   $(this).find("img").attr("data-swap-src", $(this).find("img").attr("src"));
   $(this).find("img").attr("src", newone);
   newone = $(this).find("img").attr("data-swap-srcset");
   $(this).find("img").attr("data-swap-srcset", $(this).find("img").attr("srcset"));
   $(this).find("img").attr("srcset", newone);
   newone = $(this).find("source").attr("data-swap-srcset");
   $(this).find("source").attr("data-swap-srcset", $(this).find("source").attr("srcset"));
   $(this).find("source").attr("srcset", newone);
 }
);
</code>```

Title: SVG hovers with fallbacks

Body:
What is the bestpractice, when I need to have SVG images with SVG hovers with fallbacks?

I mean SVG images with PNG fallbacks (normal, reaponsive 2x, 3x), and change them on hover to other SVG images with PNG fallbacks?

Is it better to use  or <picture> + <source /> +  tag with jQuery (or vanilla, but I already use jQuery), or to have it all in CSS as backgrounds? If jQuery, does it mean swapping srcsets? If CSS, how do I best include @2x and @3x image versions?

Also, how does the used method affect preloading of the hovers? It would surely be much better without blinking.

So far I have this, I need to change them on hover to 1hov.svg, 1hov.png, 1hov@2x.png, 1hov@3x.png

 <picture>
  <source type="image/svg+xml" srcset="logos/1.svg">

 </picture>

Body:
Here is a HTML + jQuery solution I found. It swaps the src and sourcesets to their hover alternatives. Includes the hovers preloading.

HTML

        <a href="#" target="_blank">
            <picture>
                <source type="image/svg+xml" srcset="logos/1.svg" data-swap-srcset="logos/1hov.svg">
                <img src="logos/1.png"  data-swap-src="logos/1hov.png"
srcset="logos/1@2x.png 2x, logos/1@3x.png 3x" data-swap-srcset="logos/1hov@2x.png 2x, logos/1hov@3x.png 3x" alt="logo">
            </picture>
        </a>

jQuery

//preload hovers
$("source[data-swap-src]").each(function(){
    $('<img/>')[0].src = $(this).attr("data-swap-src");
});
$("img[data-swap-src]").each(function(){
    $('<img/>')[0].src = $(this).attr("data-swap-src");
    $('<img/>')[0].srcset = $(this).attr("data-swap-srcset");
});

$("a").hover(function(){
   var newone = $(this).find("img").attr("data-swap-src");
   $(this).find("img").attr("data-swap-src", $(this).find("img").attr("src"));
   $(this).find("img").attr("src", newone);
   newone = $(this).find("img").attr("data-swap-srcset");
   $(this).find("img").attr("data-swap-srcset", $(this).find("img").attr("srcset"));
   $(this).find("img").attr("srcset", newone);
   newone = $(this).find("source").attr("data-swap-srcset");
   $(this).find("source").attr("data-swap-srcset", $(this).find("source").attr("srcset"));
   $(this).find("source").attr("srcset", newone);
 }
);


问:
link href only works in chrome
Im making a button that opens a link (web site), but the problem is that it only works on chrome!!  why??
link here!

here the simple html code>

```<code> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
   <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
<title>HTML and CSS Rounded Corner Button Generated By iWebToolsOnline.com</title>
<link href="./style.css" rel="stylesheet" type="text/css" />
<style href>a {text-decoration: none} </style>
 </head>
  <body>
<h3> </h3>
<button class="rounded">
  <a href="http://www.iwebtoolsonline.com/rss-feed-icon-generator">
  <span>Save</span>
  </a>
</button>
 <br/><br/>

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

CSS

```<code>button {
 border: 0 none;
 cursor: pointer;
 font-weight: bold;
 padding: 0 15px 0 0;
 text-align: center;
 height: 40px;
 line-height: 40px;
 width: auto;
 }

 button.rounded {
 background: transparent url( btn_right.png ) no-repeat scroll right top;
 clear: left;
 font-family: "Kristen ITC";
 font-size: 36px;

  }

  button span {
  display: block;
  padding: 0 0 0 15px;
  position: relative;
  white-space: nowrap;
  height: 40px;
  line-height: 40px;
   }

  button.rounded span {
  background: transparent url( btn_left.png ) no-repeat scroll left top;
  color: #FFFFFF;
  }

  button.rounded:hover {
  background-position: 100% -40px;
  }

  button.rounded:hover span {
  background-position: 0% -40px;
  }

  button::-moz-focus-inner {
  border: none;
  }
</code>```

You can find the link from the generator I used for the button in the link Im trying to go to, the generator doesn't give the code for the link so I just used href in the button, I this not done properly??
what else could be the problem?

Thanks a lot!

答:
Do it like this:

```<code>  <a href="http://www.iwebtoolsonline.com/rss-feed-icon-generator">
  <button class="rounded">Save</button>
  </a>
</code>```

But this wont work in IE6 or 7 (you will need to emulate it with JS (JQuery example)) :

```<code>$("a button").click(function() {
   window.location.href = $(this).parent().attr("href");
});
</code>```

But still in Firefox it will call twice that page (maybe it won't matter you). There is bug report about that (https://bugzilla.mozilla.org/show_bug.cgi?id=577035).

Just remember that having "BUTTON" inside "A" is against W3C standard recommendations.

ContentLicense: CC BY-SA 2.5

Title: link href only works in chrome

Body:
Im making a button that opens a link (web site), but the problem is that it only works on chrome!!  why??
link here!

here the simple html code>

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<title>HTML and CSS Rounded Corner Button Generated By iWebToolsOnline.com</title>
<link href="./style.css" rel="stylesheet" type="text/css" />

<button class="rounded">

  Save

</button>

CSS

button {
 border: 0 none;
 cursor: pointer;
 font-weight: bold;
 padding: 0 15px 0 0;
 text-align: center;
 height: 40px;
 line-height: 40px;
 width: auto;
 }

 button.rounded {
 background: transparent url( btn_right.png ) no-repeat scroll right top;
 clear: left;
 font-family: "Kristen ITC";
 font-size: 36px;

  }

  button span {
  display: block;
  padding: 0 0 0 15px;
  position: relative;
  white-space: nowrap;
  height: 40px;
  line-height: 40px;
   }

  button.rounded span {
  background: transparent url( btn_left.png ) no-repeat scroll left top;
  color: #FFFFFF;
  }

  button.rounded:hover {
  background-position: 100% -40px;
  }

  button.rounded:hover span {
  background-position: 0% -40px;
  }

  button::-moz-focus-inner {
  border: none;
  }

You can find the link from the generator I used for the button in the link Im trying to go to, the generator doesn't give the code for the link so I just used href in the button, I this not done properly??
what else could be the problem?

Thanks a lot!

Body:
Do it like this:

  <a href="http://www.iwebtoolsonline.com/rss-feed-icon-generator">
  <button class="rounded">Save</button>
  </a>

But this wont work in IE6 or 7 (you will need to emulate it with JS (JQuery example)) :

$("a button").click(function() {
   window.location.href = $(this).parent().attr("href");
});

But still in Firefox it will call twice that page (maybe it won't matter you). There is bug report about that (https://bugzilla.mozilla.org/show_bug.cgi?id=577035).

Just remember that having "BUTTON" inside "A" is against W3C standard recommendations.


问:
Chrome extension throwing error in console
My content script sends a message to background.js. In the callback handler for response, I had the last line as "alert(alrt_msg)". Upon executing code, I get the alert box, but after clicking "OK", the chrome console shows following in red:

```<code>Error in event handler for 'undefined': Cannot call method 'disconnect' of null TypeError: Cannot call method 'disconnect' of null
    at chromeHidden.Port.sendMessageImpl (miscellaneous_bindings:285:14)
    at chrome.Event.dispatch (event_bindings:237:41)
    at Object.chromeHidden.Port.dispatchOnMessage (miscellaneous_bindings:250:22)
</code>```

Its not much informative but intuitively I knew that this error is because some structure somewhere is garbage collected while user clicks on "OK". So I put my code as

window.setTimeout(function() { alert(alrt_msg); } , 1);

This made it work without above error. Still, after searching for documentation or google, I was not able to find the exact reason behind this. Can someone please explain whats going on and if documentation contains a specific way to do this?

答: I had same error. It was iMacros app. After I deleted it no error.</p>

Body:
My content script sends a message to background.js. In the callback handler for response, I had the last line as "alert(alrt_msg)". Upon executing code, I get the alert box, but after clicking "OK", the chrome console shows following in red:

Error in event handler for 'undefined': Cannot call method 'disconnect' of null TypeError: Cannot call method 'disconnect' of null
    at chromeHidden.Port.sendMessageImpl (miscellaneous_bindings:285:14)
    at chrome.Event.dispatch (event_bindings:237:41)
    at Object.chromeHidden.Port.dispatchOnMessage (miscellaneous_bindings:250:22)

Its not much informative but intuitively I knew that this error is because some structure somewhere is garbage collected while user clicks on "OK". So I put my code as

window.setTimeout(function() { alert(alrt_msg); } , 1);

This made it work without above error. Still, after searching for documentation or google, I was not able to find the exact reason behind this. Can someone please explain whats going on and if documentation contains a specific way to do this?


问:
Using MD5() in SELECT Query does not return results
I have this query in my Laravel PHP application, however, I found out that this problem primarily relates to MySQL rather than Laravel or PHP.  This is the query:

```<code>SELECT id FROM users WHERE MD5('email')='9e1af6d8046e217984ea76bf489a64eb' AND password_md5='f3617237ac21562663a40608a85ea38d';
</code>```

I'm only given the email's md5 hash as well as the password (also md5-hashed) and need to retrieve the user's id from the MySQL database. email in the database is not hashed, that's why I found that I need to MD5() it during the statement. However, the above query does not return any results when it should have returned one. Yes, I made sure that the hashes are properly input.

What I found when trying to tackle this problem was that SELECT MD5('users.email') does not return the same MD5 hash as the actual email address. I wonder whether I'm misusing the MD5() function or if MySQL adds anything to it so the hash is different from the one also calculated my PHP.

答:
Remove the quotes around email if it is a column identifier. You only need to use quotes for string literals.

```<code> SELECT id FROM users WHERE MD5(email)='9e1af6d8046e217984ea76bf489a64eb' AND password_md5='f3617237ac21562663a40608a85ea38d';
</code>```

Body:
I have this query in my Laravel PHP application, however, I found out that this problem primarily relates to MySQL rather than Laravel or PHP.  This is the query:

SELECT id FROM users WHERE MD5('email')='9e1af6d8046e217984ea76bf489a64eb' AND password_md5='f3617237ac21562663a40608a85ea38d';

I'm only given the email's md5 hash as well as the password (also md5-hashed) and need to retrieve the user's id from the MySQL database. email in the database is not hashed, that's why I found that I need to MD5() it during the statement. However, the above query does not return any results when it should have returned one. Yes, I made sure that the hashes are properly input.

What I found when trying to tackle this problem was that SELECT MD5('users.email') does not return the same MD5 hash as the actual email address. I wonder whether I'm misusing the MD5() function or if MySQL adds anything to it so the hash is different from the one also calculated my PHP.

Body:
Remove the quotes around email if it is a column identifier. You only need to use quotes for string literals.

 SELECT id FROM users WHERE MD5(email)='9e1af6d8046e217984ea76bf489a64eb' AND password_md5='f3617237ac21562663a40608a85ea38d';


问:
Method in child class doesn't get called by virtual function in parent class
In my application, I have several readers which read data out of .csv files. I want to structure them now by creating a parent class for those readers which have in common that they own the method getData(std::string filename). I wanted to do it by implementing a virtual method in the base class. The filename should be passed by the constructor.

main

```<code>int main()
{
    std::string filename = "file.csv";
    ChildReader1 reader = new ChildReader1(filename);
}
</code>```

ChildReader1.h

```<code>class ChildReader1: public ParentReader
    {
    public:
        ChildReader1(std::string filename)
            : ParentReader(filename)
        {

        };
        void getData(std::string filename)
        {
             //get the data here
        }
    };
</code>```

ParentReader.h

```<code>class ParentReader
    {
    public:
        ParentReader() {};
        ParentReader(std::string filename)
        {
            getData(filename);
        };
        ~ParentReader() {};

        virtual void getData(std::string filename) {};
    };
</code>```

At the moment, filename is passed to ParentReader but the getData(filename) opens the virtual method in ParentReader instead of the actual method in ChildReader 1. How can I solve that?

答:
As others have mentioned, you can't call a virtual method on a derived class in a base class constructor as the derived class is not ready yet.

One solution is to have a factory function on ChildReader1:

```<code>class ParentReader {
public:
  ParentReader(){};
  void initialize(const std::string& filename){
    getData(filename);
  };
  virtual ~ParentReader(){};
  virtual void getData(const std::string& /*filename*/) {
  };
};

class ChildReader1 : public ParentReader {
private:
  ChildReader1(){}
public:
  void getData(const std::string& /*filename*/) override {
    // get the data here
  }
  static std::unique_ptr<ChildReader1> create(const std::string &filename) {
    auto reader = std::unique_ptr<ChildReader1>(new ChildReader1);
    reader->initialize(filename);
    return reader;
  }
};

int main() {
  std::string filename = "file.csv";
  auto reader = ChildReader1::create(filename);
}
</code>```

The factory function creates a fully formed object and can then call virtual functions before returning. You can make the constructor of the object private to force callers to use your factory function.

To avoid code duplication between  derived classes you could introduce an intermediate CRTP class.

Body:
In my application, I have several readers which read data out of .csv files. I want to structure them now by creating a parent class for those readers which have in common that they own the method getData(std::string filename). I wanted to do it by implementing a virtual method in the base class. The filename should be passed by the constructor.

main

int main()
{
    std::string filename = "file.csv";
    ChildReader1 reader = new ChildReader1(filename);
}

ChildReader1.h

class ChildReader1: public ParentReader
    {
    public:
        ChildReader1(std::string filename)
            : ParentReader(filename)
        {

        };
        void getData(std::string filename)
        {
             //get the data here
        }
    };

ParentReader.h

class ParentReader
    {
    public:
        ParentReader() {};
        ParentReader(std::string filename)
        {
            getData(filename);
        };
        ~ParentReader() {};

        virtual void getData(std::string filename) {};
    };

At the moment, filename is passed to ParentReader but the getData(filename) opens the virtual method in ParentReader instead of the actual method in ChildReader 1. How can I solve that?

Body:
As others have mentioned, you can't call a virtual method on a derived class in a base class constructor as the derived class is not ready yet.

One solution is to have a factory function on ChildReader1:

class ParentReader {
public:
  ParentReader(){};
  void initialize(const std::string& filename){
    getData(filename);
  };
  virtual ~ParentReader(){};
  virtual void getData(const std::string& /*filename*/) {
  };
};

class ChildReader1 : public ParentReader {
private:
  ChildReader1(){}
public:
  void getData(const std::string& /*filename*/) override {
    // get the data here
  }
  static std::unique_ptr<ChildReader1> create(const std::string &filename) {
    auto reader = std::unique_ptr<ChildReader1>(new ChildReader1);
    reader->initialize(filename);
    return reader;
  }
};

int main() {
  std::string filename = "file.csv";
  auto reader = ChildReader1::create(filename);
}

The factory function creates a fully formed object and can then call virtual functions before returning. You can make the constructor of the object private to force callers to use your factory function.

To avoid code duplication between  derived classes you could introduce an intermediate CRTP class.


问:
FileProvider - IllegalArgumentException: Failed to find configured root
I'm trying to take a picture with camera, but I'm getting the following error:

```<code>FATAL EXCEPTION: main
Process: com.example.marek.myapplication, PID: 6747
java.lang.IllegalArgumentException: Failed to find configured root that contains /storage/emulated/0/Android/data/com.example.marek.myapplication/files/Pictures/JPEG_20170228_175633_470124220.jpg
    at android.support.v4.content.FileProvider$SimplePathStrategy.getUriForFile(FileProvider.java:711)
    at android.support.v4.content.FileProvider.getUriForFile(FileProvider.java:400)
    at com.example.marek.myapplication.MainActivity.dispatchTakePictureIntent(MainActivity.java:56)
    at com.example.marek.myapplication.MainActivity.access$100(MainActivity.java:22)
    at com.example.marek.myapplication.MainActivity$1.onClick(MainActivity.java:35)
</code>```

AndroidManifest.xml:

```<code><provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="com.example.marek.myapplication.fileprovider"
        android:enabled="true"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths" />
</provider>
</code>```

Java:

```<code>Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Ensure that there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        // Create the File where the photo should go
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
            Toast.makeText(getApplicationContext(), "Error while saving picture.", Toast.LENGTH_LONG).show();
        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            Uri photoURI = FileProvider.getUriForFile(this,
                    "com.example.marek.myapplication.fileprovider",
                    photoFile);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
        }
    }
</code>```

file_paths.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<paths>
    <files-path name="my_images" path="images/"/>
</paths>
</code>```

I was searching whole day about this error and trying to understand FileProvider, but I have no idea what this error message tries to tell me. If you want more info/code, write me in the comment.

答:
If you are using internal cache then use.</p>

```<code><paths xmlns:android="http://schemas.android.com/apk/res/android">
    <cache-path name="cache" path="/" />
</paths>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to take a picture with camera, but I'm getting the following error:

FATAL EXCEPTION: main
Process: com.example.marek.myapplication, PID: 6747
java.lang.IllegalArgumentException: Failed to find configured root that contains /storage/emulated/0/Android/data/com.example.marek.myapplication/files/Pictures/JPEG_20170228_175633_470124220.jpg
    at android.support.v4.content.FileProvider$SimplePathStrategy.getUriForFile(FileProvider.java:711)
    at android.support.v4.content.FileProvider.getUriForFile(FileProvider.java:400)
    at com.example.marek.myapplication.MainActivity.dispatchTakePictureIntent(MainActivity.java:56)
    at com.example.marek.myapplication.MainActivity.access$100(MainActivity.java:22)
    at com.example.marek.myapplication.MainActivity$1.onClick(MainActivity.java:35)

AndroidManifest.xml:

<provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="com.example.marek.myapplication.fileprovider"
        android:enabled="true"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths" />
</provider>

Java:

Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Ensure that there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        // Create the File where the photo should go
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
            Toast.makeText(getApplicationContext(), "Error while saving picture.", Toast.LENGTH_LONG).show();
        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            Uri photoURI = FileProvider.getUriForFile(this,
                    "com.example.marek.myapplication.fileprovider",
                    photoFile);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
        }
    }

file_paths.xml

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <files-path name="my_images" path="images/"/>
</paths>

I was searching whole day about this error and trying to understand FileProvider, but I have no idea what this error message tries to tell me. If you want more info/code, write me in the comment.

Body:
If you are using internal cache then use.

<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <cache-path name="cache" path="/" />
</paths>


问:
Change input text value in before submitting form
I'm trying to change the value of my input text field before submitting the form using jQuery like this:

```<code><form actions="http://test.com/" method="GET">
 <input name="test" id="autocompleteform" type="text"/>
</form>
<script>
$('#form-customer-attr-new').submit(function(e) {
    var value = $("#autocompleteform").val();
    value = value.substr(0, value.indexOf(' '));
    if (!isNan(value) && !empty(value)) {
        $("#autocompleteform").val(value);
        alert($("#autocompleteform").val());
        return true;
    } else {
        alert("Invalid Postcode");
        return false;
    }
});
</script>
</code>```

when i alert the value of the input file, it's showing the new value, but when the form submitten, the paramether in url still showing the old value of the input, for example:

```<code> old_input_value = "1234 justice spoiler message";
 new_input_value = "1234";
 the_url_after_form_submit_now = "http://test.com?test=1234+justice+spoiler+message";
 the_url_after_form_submit_should_be ="http://test.com?test=1234";
</code>```

答:
```<code><form id="form-customer-attr-new" action="" method="get">
 <input name="test" id="autocompleteform" type="text" value=""/>
</form>

<script>
$('#form-customer-attr-new').submit(function(e) {
    var value = $("#autocompleteform").val();
    value = value.substr(0, value.indexOf(' '));

    if (!isNaN(value) && value!='') {
        $("#autocompleteform").val(value);
        alert($("#autocompleteform").val());
        return true;
    } else {
        alert("Invalid Postcode");
        return false;
    }
});
</script>
</code>```

Body:
I'm trying to change the value of my input text field before submitting the form using jQuery like this:

<form actions="http://test.com/" method="GET">
 <input name="test" id="autocompleteform" type="text"/>
</form>

when i alert the value of the input file, it's showing the new value, but when the form submitten, the paramether in url still showing the old value of the input, for example:

 old_input_value = "1234 justice spoiler message";
 new_input_value = "1234";
 the_url_after_form_submit_now = "http://test.com?test=1234+justice+spoiler+message";
 the_url_after_form_submit_should_be ="http://test.com?test=1234";


问:
How to turn off Git warnings "LF will be replaced by CRLF"?
I am working on Windows, but may also work on Unix, so I don't need to store Windows line endings. I just want to suppress the warning.

I found these related Stack Overflow questions:

With Git, how do I turn off the "LF will be replaced by CRLF" warning

git, whitespace errors, squelching and autocrlf, the definitive answers

I tried the following:

git config core.whitespace cr-at-eol false

git config core.whitespace cr-at-eol true

git config core.whitespace cr-at-eol nowarn
```

But these don't seem to do anything. Does anyone know how to turn off the warnings?

答:
I'm also developing on windows and Because our servers are powered by Linux and all the code has to base on Linux I have preferred to change all my files to LF instead of CRLF.

from git command line:

```<code>git config --global core.autocrlf false
</code>```

i'm working with intellij idea so it's quite easy:

1)    File --> settings --> editor --> code style: (for any new file will
  be created)

a.    Scheme : default

b.    Line separator: unix and os x (\n)

2)    mark the root of the project --> file --> line separator --> LF
  unix and os x (\n) (for exist files)

Remark: you can also use apps like dos2unix.exe or some other scripts.

than I did using my command line: (you can do this also from the idea)

```<code>git commit -m "bla bla"
git add .
git push origin master
</code>```

since then, I didn't got those warnings

Body:
I am working on Windows, but may also work on Unix, so I don't need to store Windows line endings. I just want to suppress the warning.

I found these related Stack Overflow questions:

With Git, how do I turn off the "LF will be replaced by CRLF" warning

git, whitespace errors, squelching and autocrlf, the definitive answers

I tried the following:

git config core.whitespace cr-at-eol false

git config core.whitespace cr-at-eol true

git config core.whitespace cr-at-eol nowarn

But these don't seem to do anything. Does anyone know how to turn off the warnings?

Body:
I'm also developing on windows and Because our servers are powered by Linux and all the code has to base on Linux I have preferred to change all my files to LF instead of CRLF.

from git command line:

git config --global core.autocrlf false

i'm working with intellij idea so it's quite easy:

1)    File --> settings --> editor --> code style: (for any new file will
  be created)

a.    Scheme : default

b.    Line separator: unix and os x (\n)

2)    mark the root of the project --> file --> line separator --> LF
  unix and os x (\n) (for exist files)

Remark: you can also use apps like dos2unix.exe or some other scripts.

than I did using my command line: (you can do this also from the idea)

git commit -m "bla bla"
git add .
git push origin master

since then, I didn't got those warnings


问:
No local JVM's were detected, not even the jvm running this instance of java mission control
I'm new at Java, and I've just recently installed it and set the environmental variables.

But when I try to compile something, it says:

```<code>javac: file not found: BoleanTest.java
Usage: javac <options> <source files>
use -help for a list of possible options
</code>```

And when I open JVM it says:

No local JVM's were detected, not even the jvm running this instance of java mission control.

Help please, thank you.

(A photo of the error as shown on the screen)

答:
In command prompt the currently active folder is C:\Program Files\Notepad++
However your file is created on your Desktop (C:\Users\Alban Selmanaj\Desktop\BoleanTest.java).

As a starting point try the following command before attempting to run javac:

```<code> cd %USERPROFILE%\Desktop
</code>```

Please confirm if it helps or not.

Body:
I'm new at Java, and I've just recently installed it and set the environmental variables.

But when I try to compile something, it says:

javac: file not found: BoleanTest.java
Usage: javac <options> <source files>
use -help for a list of possible options

And when I open JVM it says:

No local JVM's were detected, not even the jvm running this instance of java mission control.

Help please, thank you.

(A photo of the error as shown on the screen)

Body:
In command prompt the currently active folder is C:\Program Files\Notepad++
However your file is created on your Desktop (C:\Users\Alban Selmanaj\Desktop\BoleanTest.java).

As a starting point try the following command before attempting to run javac:

 cd %USERPROFILE%\Desktop

Please confirm if it helps or not.


问:
Provide default arguments for subscript operator and function call operator
In the following code, I have provided default arguments for array subscript operator.

```<code>struct st
{
    int operator[](int x = 0)
    {
        // code here
    }
};
</code>```

But, compiler generated an error :

```<code>error: 'int st::operator[](int)' cannot have default arguments
     int operator[](int x = 0)
</code>```

But, If I provide default arguments for function call operator.

```<code>struct st
{
    int operator()(int x = 0)
    {
        // code here
    }
};
</code>```

It's working fine.

So, I have a questions:

Why doesn't allowed default arguments for the array subscript operator?

Why does allowed default arguments for the function call operator?

答:
The operators (both overloading of user-defined-types and for inbuilt types) are intended to let people use notations familiar from mathematics, logic and general usage (though << and >> have seen double-service as streaming operators, and notational compromises had to be made given the limited characters near-universally available on computers).  To turn around and allow variations on the intuitive, familiar notations (such as implied arguments) seems counter-productive.

operator() is different though in that it's there to abstract away differences between "calling" (through) an object and calling a hard-coded function - it needs to support default arguments to do that properly.

Body:
In the following code, I have provided default arguments for array subscript operator.

struct st
{
    int operator[](int x = 0)
    {
        // code here
    }
};

But, compiler generated an error :

error: 'int st::operator[](int)' cannot have default arguments
     int operator[](int x = 0)

But, If I provide default arguments for function call operator.

struct st
{
    int operator()(int x = 0)
    {
        // code here
    }
};

It's working fine.

So, I have a questions:

Why doesn't allowed default arguments for the array subscript operator?

Why does allowed default arguments for the function call operator?


问:
Autofac Singleton Decorator constructed multiple times
i'm trying to create a simple in-memory caching mechanism for some services. I'm using the Decorator pattern, creating a cached version of the service that decorates the concrete implementation of it.
By using Autofac i will register the cache decorator as SingleInstance() in order to be sure that the data stays in memory.

```<code> builder.RegisterDecorator<IBackendOperatorServiceProxy>(
      (c, inner) =>  new CachedBackendOperatorServiceProxy(inner),
      fromKey: "BackendOperatorService")
      .SingleInstance();
</code>```

and i will register the concrete implementation as

```<code> builder.RegisterType<BackendOperatorServiceProxy>().Named<IBackendOperatorServiceProxy>("BackendOperatorService");
</code>```

The problem that i'm having is that when resolved in the webApi controller, this singleton decorator is always recreated (once per request).

I have (hopefully) correctly set-up the owin pipeline for autofac (in fact the service gets injected in the BL class called by the controller).

I really can't understand a possible reason for an issue like this. I've used SIngleInstance() different times with different projects and it always worked without issues.
To further "investigate" this i've also created a fake class registered as singleton and injected it in the same controller as the decorator. It works as expected, creating just a single instance of the fake class.
For completeness, i've registered this fake one as:

```<code>builder.Register<Foo>(c => new Foo(c.ResolveNamed<IBackendOperatorServiceProxy>("BackendOperatorService"))).AsImplementedInterfaces().SingleInstance();
</code>```

And this is the constructor of the Cached (Decorator) service:

```<code>public CachedBackendOperatorServiceProxy(IBackendOperatorServiceProxy decoratedServiceImplementation)
{
  _decoratedServiceImplementation = decoratedServiceImplementation ?? throw new ArgumentNullException(nameof(decoratedServiceImplementation));
  _cachedElements = new Dictionary<string, CachedOperatorDto>();
}
</code>```

Is there any problem or something that i'm missing with decorators and SIngleInstances?

答: Thanks to Evk, the easiest solution is to just stick to "manual" decorator registration as RegisterDecorator (as reported in the link provided in comments) should be used when you need to decorate multiple implementations, not a single one as i was trying to do. </p>

Body:
i'm trying to create a simple in-memory caching mechanism for some services. I'm using the Decorator pattern, creating a cached version of the service that decorates the concrete implementation of it.
By using Autofac i will register the cache decorator as SingleInstance() in order to be sure that the data stays in memory.

 builder.RegisterDecorator<IBackendOperatorServiceProxy>(
      (c, inner) =>  new CachedBackendOperatorServiceProxy(inner),
      fromKey: "BackendOperatorService")
      .SingleInstance();

and i will register the concrete implementation as

 builder.RegisterType<BackendOperatorServiceProxy>().Named<IBackendOperatorServiceProxy>("BackendOperatorService");

The problem that i'm having is that when resolved in the webApi controller, this singleton decorator is always recreated (once per request).

I have (hopefully) correctly set-up the owin pipeline for autofac (in fact the service gets injected in the BL class called by the controller).

I really can't understand a possible reason for an issue like this. I've used SIngleInstance() different times with different projects and it always worked without issues.
To further "investigate" this i've also created a fake class registered as singleton and injected it in the same controller as the decorator. It works as expected, creating just a single instance of the fake class.
For completeness, i've registered this fake one as:

builder.Register<Foo>(c => new Foo(c.ResolveNamed<IBackendOperatorServiceProxy>("BackendOperatorService"))).AsImplementedInterfaces().SingleInstance();

And this is the constructor of the Cached (Decorator) service:

public CachedBackendOperatorServiceProxy(IBackendOperatorServiceProxy decoratedServiceImplementation)
{
  _decoratedServiceImplementation = decoratedServiceImplementation ?? throw new ArgumentNullException(nameof(decoratedServiceImplementation));
  _cachedElements = new Dictionary<string, CachedOperatorDto>();
}

Is there any problem or something that i'm missing with decorators and SIngleInstances?


问:
How to restrict processing to specified number of cores in spark standalone
We have tried using various combinations of settings - but mpstat is showing that all or most cpu's are always being used (on a single 8 core system)

Following have been tried:

set master to:

```<code>local[2]
</code>```

send in

```<code>conf.set("spark.cores.max","2")
</code>```

in the spark configuration

Also using

```<code>--total-executor-cores 2
</code>```

and

```<code>--executor-cores 2
</code>```

In all cases

```<code>mpstat -A
</code>```

shows that all of the CPU's are being used - and not just by the master.

So I am at a loss presently.  We do need to limit the usage to a specified number of cpu's.

答: Apparently spark standalone ignores the spark.cores.max setting. That setting does work in yarn.

Body:
We have tried using various combinations of settings - but mpstat is showing that all or most cpu's are always being used (on a single 8 core system)

Following have been tried:

set master to:

local[2]

send in

conf.set("spark.cores.max","2")

in the spark configuration

Also using

--total-executor-cores 2

and

--executor-cores 2

In all cases

mpstat -A

shows that all of the CPU's are being used - and not just by the master.

So I am at a loss presently.  We do need to limit the usage to a specified number of cpu's.


问:
java.sql.SQLException : Operation not allowed after ResultSet closed
Can anyone point me in the write direction to solve the error: SQLException: Operation not allowed after ResultSet closed

Here is the code i believe the error occurs in

```<code>Statement stmt = con.createStatement();
String query1 = "";
String query2 = "";

int candidateNo = 42;

query1 = "SELECT * FROM Candidates WHERE CandidateNo = "+ candidateNo;
ResultSet rs = stmt.executeQuery(query1);
//If query can be completed then display name and prompt to continue
if(rs.next()){
    query2 = "SELECT * FROM Achieved WHERE CandidateNo = " + candidateNo;
    ResultSet ts = stmt.executeQuery(query2);
}
</code>```

I have tried using resultset rs = null; to create the variable but the error still occurs

答:
You are iterating over the ResultSet bound to a Statement , then while iterating, you are using the exact same Statement object to issue a new query and get and iterate over another ResultSet .

This won't work as long as you are not done with the processing of the first ResultSet, so consider using a distinct Statement object for your second query .

Body:
Can anyone point me in the write direction to solve the error: SQLException: Operation not allowed after ResultSet closed

Here is the code i believe the error occurs in

Statement stmt = con.createStatement();
String query1 = "";
String query2 = "";

int candidateNo = 42;

query1 = "SELECT * FROM Candidates WHERE CandidateNo = "+ candidateNo;
ResultSet rs = stmt.executeQuery(query1);
//If query can be completed then display name and prompt to continue
if(rs.next()){
    query2 = "SELECT * FROM Achieved WHERE CandidateNo = " + candidateNo;
    ResultSet ts = stmt.executeQuery(query2);
}

I have tried using resultset rs = null; to create the variable but the error still occurs


问:
Python - Organisation of 3 subplots with matplotlib
I try to generate 3 subplots for my figure. It seems work but it is not perfectly aligned. How to have the same width between the figure at the bottom et the figures at below?

```<code>plt.close()
fig = plt.figure()

ax1 = plt.subplot(211)
ax1.plot(cycles,np.asarray(df_int),'wo',label='')
ax1.plot(cycles,np.asarray(df_proj),'k+',label='')
ax1.legend(loc=2)
#ax1.subplots_adjust(left=0.15)
ax1.set_ylim(0.001,0.004)

ax2 = plt.subplot(223)
i2=ax2.imshow(c,cmap=plt.cm.hot, vmin=-5, vmax=5);#plt.colorbar();plt.clim(-5,5)
cb2=plt.colorbar(i2,ax=ax2,ticks=[-5,0,5],fraction=0.046, pad=0.04,format='%.2f')
cb2.ax.tick_params(labelsize=12)

ax3 = plt.subplot(224)
i3=ax3.imshow(residue_proj,cmap=plt.cm.hot, vmin=-5, vmax=5);#plt.colorbar();plt.clim(-5,5);
cb3=plt.colorbar(i3,ax=ax3,ticks=[-5,0,5],fraction=0.046, pad=0.04,format='%.2f')
cb3.ax.tick_params(labelsize=12)

plt.savefig('test.png', dpi=500,  bbox_inches='tight', pad_inches=0.1)
#plt.show()
</code>```

答:
The same as the above answer can be done with a figure object like so:</p>

```<code>import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

# Create 2x2 sub plots
gs = gridspec.GridSpec(2, 2)

fig = plt.figure()
ax1 = fig.add_subplot(gs[0, 0]) # row 0, col 0
ax1.plot([0,1])

ax2 = fig.add_subplot(gs[0, 1]) # row 0, col 1
ax2.plot([0,1])

ax3 = fig.add_subplot(gs[1, :]) # row 1, span all columns
ax3.plot([0,1])
</code>```

Body:
I try to generate 3 subplots for my figure. It seems work but it is not perfectly aligned. How to have the same width between the figure at the bottom et the figures at below?

plt.close()
fig = plt.figure()

ax1 = plt.subplot(211)
ax1.plot(cycles,np.asarray(df_int),'wo',label='')
ax1.plot(cycles,np.asarray(df_proj),'k+',label='')
ax1.legend(loc=2)
#ax1.subplots_adjust(left=0.15)
ax1.set_ylim(0.001,0.004)

ax2 = plt.subplot(223)
i2=ax2.imshow(c,cmap=plt.cm.hot, vmin=-5, vmax=5);#plt.colorbar();plt.clim(-5,5)
cb2=plt.colorbar(i2,ax=ax2,ticks=[-5,0,5],fraction=0.046, pad=0.04,format='%.2f')
cb2.ax.tick_params(labelsize=12)

ax3 = plt.subplot(224)
i3=ax3.imshow(residue_proj,cmap=plt.cm.hot, vmin=-5, vmax=5);#plt.colorbar();plt.clim(-5,5);
cb3=plt.colorbar(i3,ax=ax3,ticks=[-5,0,5],fraction=0.046, pad=0.04,format='%.2f')
cb3.ax.tick_params(labelsize=12)

plt.savefig('test.png', dpi=500,  bbox_inches='tight', pad_inches=0.1)
#plt.show()

Body:
The same as the above answer can be done with a figure object like so:

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

# Create 2x2 sub plots
gs = gridspec.GridSpec(2, 2)

fig = plt.figure()
ax1 = fig.add_subplot(gs[0, 0]) # row 0, col 0
ax1.plot([0,1])

ax2 = fig.add_subplot(gs[0, 1]) # row 0, col 1
ax2.plot([0,1])

ax3 = fig.add_subplot(gs[1, :]) # row 1, span all columns
ax3.plot([0,1])


问:
using web fonts?
I did read somewhere that using web fonts is not a good idea as it makes the web pages to load slow or can cause any other problems, is it true? Is the use of web font not recommended generally? Thanks for your thoughts.</p>

答: This should help: http://socialcompare.com/en/comparison/comparison-of-web-fonts-solutions-7d0b3w9</p>

Title: using web fonts?


问:
What is react-native component doing when the component is in background
What is react-native component doing when the component is in background?

And What will react-native do when component re-active to foreground?

Like Page A navigate to Page B.
And Page B back to Page A.What happened to A and B?

Is there any ui update like onResume on Android or something?

Edit:

I have a TabNavagation with four tab.One of the tabs renders an Android UI Component which is a custom frameLayout(a listview is in the frameLayout).

When the frameLayout first rendered, the listview position is not correct(position is -4 item height).But when I navigate to a child page and goback, I found that the frameLayout is correct now and does't enter any android lifecycle.

So I'm wondering is it doing something background?

答:
After debug many many times, I found that it is the react-navigation.

Four tabs in homepage with bottom tabbar.When I enter a child page with navigationOptions:{header:null}, the bottom bar is gone. And when I goback from the child page, the bottom bar has back meanwhile and the whole view has corrected.Seems the whole view is re-draw?So I called view.requestLayout() in createViewInstance().So the final result is the view need to requestLayout manual.

UPDATE:
answer top is not totally correct.The final problem is the custom view should measure self in its requestLayout.
I found the answer in https://github.com/facebook/react-native/issues/4990

```<code>@Override
public void requestLayout() {
    super.requestLayout();
    post(measureAndLayout);
}

private final Runnable measureAndLayout = new Runnable() {
    @Override
    public void run() {
        measure(MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.EXACTLY),
                MeasureSpec.makeMeasureSpec(getHeight(), MeasureSpec.EXACTLY));
        layout(getLeft(), getTop(), getRight(), getBottom());
    }
};
</code>```

And thanks for your answers.@bennygenel  @Jouke

Body:
After debug many many times, I found that it is the react-navigation.

Four tabs in homepage with bottom tabbar.When I enter a child page with navigationOptions:{header:null}, the bottom bar is gone. And when I goback from the child page, the bottom bar has back meanwhile and the whole view has corrected.Seems the whole view is re-draw?So I called view.requestLayout() in createViewInstance().So the final result is the view need to requestLayout manual.

UPDATE:
answer top is not totally correct.The final problem is the custom view should measure self in its requestLayout.
I found the answer in https://github.com/facebook/react-native/issues/4990

@Override
public void requestLayout() {
    super.requestLayout();
    post(measureAndLayout);
}

private final Runnable measureAndLayout = new Runnable() {
    @Override
    public void run() {
        measure(MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.EXACTLY),
                MeasureSpec.makeMeasureSpec(getHeight(), MeasureSpec.EXACTLY));
        layout(getLeft(), getTop(), getRight(), getBottom());
    }
};

And thanks for your answers.@bennygenel  @Jouke


问:
Flex: how to apply styles to text child
Given the following HTML snippet...

```<code><div class="container">
  Hello, World!
</div>
</code>```

... I want to achieve a layout like this...

```<code>+----------------------------------------------------+
| x | Hello, World!                              | y |
+----------------------------------------------------+
</code>```

... using flexbox layout and without changing the HTML structure.

My SCSS looks something like this:

```<code>.container {
    display: flex;
    flex-direction: row;
    justify-content: space-between;

    &:before {
        content: 'x';
    }

    &:after {
        content: 'x';
    }
}
</code>```

which nearly does the right thing, except that the text content is horizontally centered instead of flush left.

Normally I would simply apply flex-grow: 1 to the content that I wish to have at full width, but in this case there simply is no content node.

So, how can I make the text content grow? Thanks!

答:
In a case like this, where the text is not wrapped in its own element, Flexbox create an anonymous wrapper, which one can't target using CSS.

One solution is to drop the justify-content and use auto margins instead, on the ::after pseudo element, shown below, another is to position the first pseudo ::before absolute.

Note, as flex-direction: row; is the default, you can omit it.

Stack snippet

.container {
  display: flex;
}

.container:before {
  content: 'x';
}

.container:after {
  content: 'x';
  margin-left: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  Hello, World!
</div></code>```

Title: Flex: how to apply styles to text child

Body:
Given the following HTML snippet...

  Hello, World!

... I want to achieve a layout like this...

+----------------------------------------------------+
| x | Hello, World!                              | y |
+----------------------------------------------------+

... using flexbox layout and without changing the HTML structure.

My SCSS looks something like this:

.container {
    display: flex;
    flex-direction: row;
    justify-content: space-between;

    &:before {
        content: 'x';
    }

    &:after {
        content: 'x';
    }
}

which nearly does the right thing, except that the text content is horizontally centered instead of flush left.

Normally I would simply apply flex-grow: 1 to the content that I wish to have at full width, but in this case there simply is no content node.

So, how can I make the text content grow? Thanks!

Body:
In a case like this, where the text is not wrapped in its own element, Flexbox create an anonymous wrapper, which one can't target using CSS.

One solution is to drop the justify-content and use auto margins instead, on the ::after pseudo element, shown below, another is to position the first pseudo ::before absolute.

Note, as flex-direction: row; is the default, you can omit it.

Stack snippet

.container {
  display: flex;
}

.container:before {
  content: 'x';
}

.container:after {
  content: 'x';
  margin-left: auto;
}

<div class="container">
  Hello, World!
</div>


问:
Haskell list of int tuples to string
I'm trying to write out my list of tuples from:

```<code>[(8,7),(5,6),(3,3),(9,4),(5,4)]
</code>```

to:

```<code>8 7 5 6 3 3 9 4 5 4
</code>```

this is how far i've come:
(Updated)

```<code>showTuples :: Board -> String
showTuples = unwords . fmap show . concatMap (\(x,y) -> [x,y])
</code>```

I know i'm suppose to map this function to all elements of my list but i can't seem to get it right.

(UPDATE)
It worked, still having problems with the quotation marks though

also type of Board is:

```<code>type Board = [(Int,Int)]
</code>```

答:
Using pattern matching:</p>

```<code>type Board = [(Int, Int)]

showTuples :: Board -> String
showTuples [] = ""
showTuples (x:[]) = show(fst(x)) ++ " " ++ show(snd(x))
showTuples (x:xs) = show(fst(x)) ++ " " ++ show(snd(x)) ++ " " ++ showTuples xs

main :: IO ()
main = putStrLn . showTuples $ [(8, 7), (5, 6), (3, 3), (9, 4), (5, 4)] -- 8 7 5 6 3 3 9 4 5 4
</code>```

Title: Haskell list of int tuples to string

Body:
I'm trying to write out my list of tuples from:

[(8,7),(5,6),(3,3),(9,4),(5,4)]

to:

8 7 5 6 3 3 9 4 5 4

this is how far i've come:
(Updated)

showTuples :: Board -> String
showTuples = unwords . fmap show . concatMap (\(x,y) -> [x,y])

I know i'm suppose to map this function to all elements of my list but i can't seem to get it right.

(UPDATE)
It worked, still having problems with the quotation marks though

also type of Board is:

type Board = [(Int,Int)]

Body:
Using pattern matching:

type Board = [(Int, Int)]

showTuples :: Board -> String
showTuples [] = ""
showTuples (x:[]) = show(fst(x)) ++ " " ++ show(snd(x))
showTuples (x:xs) = show(fst(x)) ++ " " ++ show(snd(x)) ++ " " ++ showTuples xs

main :: IO ()
main = putStrLn . showTuples $ [(8, 7), (5, 6), (3, 3), (9, 4), (5, 4)] -- 8 7 5 6 3 3 9 4 5 4


问:
Sort a dictionary by a custom order
This refers to

Sort a list by a custom order

I will go for a similar example... I have a dictionary containing users

```<code>public class UserInfo
{
    public string Name { get; set; }

    public string Location { get; set; }
}
</code>```

the data:

```<code>private Dictionary<string, UserInfo> users = new Dictionary<string, UserInfo>(); // id + user
</code>```

and a list of possible locations

```<code>        private string[] locations = {
            "europe",
            "america",
            "asia",
            "africa"
        };
</code>```

how can I order this dictionary by these locations?

There should be the output

// ... all europeans

// ... all americans

// ... all asians

// ... all africans

when calling

```<code>    Dictionary<string, UserInfo> sortedUsers = ; // Sorting the dict "users" by locations

    foreach (KeyValuePair<string, UserInfo> info in sortedUsers)
    {
        Console.WriteLine("L: " + info.Value.Location + " N: " + info.Value.Name);
    }
</code>```

答:
Dictionary isn't an ICollection, you'll cannot use OrderBy(), but if you convert to list, you can instanciate an IComparer function  :

```<code>private class SortCustom : IComparer
{
   private static string[] locations = {
        "europe",
        "america",
        "asia",
        "africa"
    };
   int IComparer.Compare(UserInfo a, UserInfo b)
   {
      return
           Array.FindIndex(locations, row => row == a.Value.Location).CompareTo(
           Array.FindIndex(locations, row => row == b.Value.Location));
   }
}
</code>```

Called by :

```<code>sortedUsers.OrderBy(x => x, new SortCustom());
</code>```

Title: Sort a dictionary by a custom order

Body:
This refers to

Sort a list by a custom order

I will go for a similar example... I have a dictionary containing users

public class UserInfo
{
    public string Name { get; set; }

    public string Location { get; set; }
}

the data:

private Dictionary<string, UserInfo> users = new Dictionary<string, UserInfo>(); // id + user

and a list of possible locations

        private string[] locations = {
            "europe",
            "america",
            "asia",
            "africa"
        };

how can I order this dictionary by these locations?

There should be the output

// ... all europeans

// ... all americans

// ... all asians

// ... all africans

when calling

    Dictionary<string, UserInfo> sortedUsers = ; // Sorting the dict "users" by locations

    foreach (KeyValuePair<string, UserInfo> info in sortedUsers)
    {
        Console.WriteLine("L: " + info.Value.Location + " N: " + info.Value.Name);
    }

Body:
Dictionary isn't an ICollection, you'll cannot use OrderBy(), but if you convert to list, you can instanciate an IComparer function  :

private class SortCustom : IComparer
{
   private static string[] locations = {
        "europe",
        "america",
        "asia",
        "africa"
    };
   int IComparer.Compare(UserInfo a, UserInfo b)
   {
      return
           Array.FindIndex(locations, row => row == a.Value.Location).CompareTo(
           Array.FindIndex(locations, row => row == b.Value.Location));
   }
}

Called by :

sortedUsers.OrderBy(x => x, new SortCustom());


问:
WinForms: Is there a concept of associating a label with a textbox?
I'm using Visual Studio 2010 with C#.  Is there a concept in Windows Forms development of somehow linking a label with is text box?  Something so that they move together as a unit?  In the ASP.NET world, there is the AssociatedControlId property of the label control.  I also think I remember MS Access form designer having some way of associating (or linking) labels with controls.  Does this feature even exist in Visual Studio world?

If not, how do you group labels with controls such that if you move a text box you don't have to manually move the label also?

答:
No there is not - at least with the out of the box controls. If you want this you could achieve it with a user control. </p>

<p>In general the winforms is not line driven in the same way as HTML is. </p>

Body:
No there is not - at least with the out of the box controls. If you want this you could achieve it with a user control.

In general the winforms is not line driven in the same way as HTML is.


答:
You can use margin-left: auto on :after instead.

.container {
  display: flex;
  align-items: center;
  border: 1px solid black;
}

.container:after {
  content: 'y';
  margin-left: auto;
  padding: 5px;
}

.container:before {
  content: 'x';
  padding: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  Hello, World!
</div></code>```

Title: Flex: how to apply styles to text child

Body:
You can use margin-left: auto on :after instead.

.container {
  display: flex;
  align-items: center;
  border: 1px solid black;
}

.container:after {
  content: 'y';
  margin-left: auto;
  padding: 5px;
}

.container:before {
  content: 'x';
  padding: 5px;
}

<div class="container">
  Hello, World!
</div>


答:
You might solve your issue with a factory:</p>

```<code>class ParentReader
{
public:
    virtual ~ParentReader() = default
    virtual void getData(const std::string& filename) = 0;
};

template <typename T, typename ... Ts>
std::unique_ptr<T> MakeReader(const std::string& filename, Ts&&... args)
{
    static_assert(std::is_base_of<ParentReader, T>::value, "!");
    auto res = std::make_unique<T>(std::forward<Ts>(args)...);
    res->getData(filename);
    return res;
}
</code>```

Title: Method in child class doesn't get called by virtual function in parent class

Body:
In my application, I have several readers which read data out of .csv files. I want to structure them now by creating a parent class for those readers which have in common that they own the method getData(std::string filename). I wanted to do it by implementing a virtual method in the base class. The filename should be passed by the constructor.

main

int main()
{
    std::string filename = "file.csv";
    ChildReader1 reader = new ChildReader1(filename);
}

ChildReader1.h

class ChildReader1: public ParentReader
    {
    public:
        ChildReader1(std::string filename)
            : ParentReader(filename)
        {

        };
        void getData(std::string filename)
        {
             //get the data here
        }
    };

ParentReader.h

class ParentReader
    {
    public:
        ParentReader() {};
        ParentReader(std::string filename)
        {
            getData(filename);
        };
        ~ParentReader() {};

        virtual void getData(std::string filename) {};
    };

At the moment, filename is passed to ParentReader but the getData(filename) opens the virtual method in ParentReader instead of the actual method in ChildReader 1. How can I solve that?

Body:
You might solve your issue with a factory:

class ParentReader
{
public:
    virtual ~ParentReader() = default
    virtual void getData(const std::string& filename) = 0;
};

template <typename T, typename ... Ts>
std::unique_ptr<T> MakeReader(const std::string& filename, Ts&&... args)
{
    static_assert(std::is_base_of<ParentReader, T>::value, "!");
    auto res = std::make_unique<T>(std::forward<Ts>(args)...);
    res->getData(filename);
    return res;
}


问:
Is it possible to insert a column in a database table automatically using a variable in PHP?
I am trying to insert a column in a database table automatically using a variable.

I have a table named tbl_category, I want to let the user choose the sub category field by their own choice. So, from the dashboard, the user will insert 3/4 (or how many fields they would like to create) sub category fields.

I will take this value as $insert_sub_cat_count. So, when this info will hit the function named function save_category_info($data), the function will receive the value $insert_sub_cat_count as $data.

After that, this info have to implement in the table tbl_category and add 3/4 fields automatically according to the value $data.

If the user inputs 2, this will insert two columns automatically:

If the user inputs 3, this will insert 3 columns:

Is this possible? I don't know how to extend columns automatically or if there's any other way to do so.

答:
This is a bad idea from the very start. As Raymond Nijland said above ("the same column names with increment are a SQL anti pattern.. you should check table normalization instead"), you shouldn't allow users to create columns with their desired name in your database. You should have the following tables:

```<code>user - id, name
categories - id, id_user, name
subcategories - id, id_category, id_user, name
</code>```

So you will be able to link the category and subcategory to the user that created it. You don't need to create a separate column for each user.
If you're worried about speed you should add index for the subcategories table, for the column: id_user. In this way the search will work fast enough.

Body:
This is a bad idea from the very start. As Raymond Nijland said above ("the same column names with increment are a SQL anti pattern.. you should check table normalization instead"), you shouldn't allow users to create columns with their desired name in your database. You should have the following tables:

user - id, name
categories - id, id_user, name
subcategories - id, id_category, id_user, name

So you will be able to link the category and subcategory to the user that created it. You don't need to create a separate column for each user.
If you're worried about speed you should add index for the subcategories table, for the column: id_user. In this way the search will work fast enough.


问:
How to test iOS Core Bluetooth project in Macbook?
I want to learn CB (Core Bluetooth) framework in iOS. Any practical example or links from where I could understand this deeply?</p>

答:
Basic BLE swift lang tutorial for beginners :

http://www.kevinhoyt.com/2016/05/20/the-12-steps-of-bluetooth-swift/

follows above link, it's best link for learn core bluetooth with swift lang.

Must be require iOS device which supported Bluetooth 4.0 and later version. BLE not supported in simulator(Xcode).


问:
Execute a shell command with python variables
I had script on bash where I generated username, password, ssh-key for user.
Part for creating of ssh-key:

```<code>su $user -c "ssh-keygen -f /home/$user/.ssh/id_rsa -t rsa -b 4096 -N ''"
</code>```

How can I do the same in Python with os.system? I tried this:

```<code>os.system('su %s -c "ssh-keygen -f /home/%s/.ssh/id_rsa -t rsa -b 4096 -N ''"', user)
TypeError: system() takes at most 1 argument (2 given)
</code>```

Also I tried:

```<code>os.system('su user -c "ssh-keygen -f /home/user/.ssh/id_rsa -t rsa -b 4096 -N ''"')
</code>```

Of course, it doesn't work either.

答:
Use the subprocess module:

```<code>import subprocess
username = 'user'
result, err = subprocess.Popen(
            'su %s -c "ssh-keygen -f /home/%s/.ssh/id_rsa -t rsa -b 4096 -N ''"' % (username, username),
            stdout=subprocess.PIPE,
            shell=True
          ).communicate()
if err:
    print('Something went wrong')
else:
    print(result)
</code>```

Edit: this is the 'fast' way to do that, you should't use shell=True if you can't control the input since it allows code execution as said here

Body:
I had script on bash where I generated username, password, ssh-key for user.
Part for creating of ssh-key:

su $user -c "ssh-keygen -f /home/$user/.ssh/id_rsa -t rsa -b 4096 -N ''"

How can I do the same in Python with os.system? I tried this:

os.system('su %s -c "ssh-keygen -f /home/%s/.ssh/id_rsa -t rsa -b 4096 -N ''"', user)
TypeError: system() takes at most 1 argument (2 given)

Also I tried:

os.system('su user -c "ssh-keygen -f /home/user/.ssh/id_rsa -t rsa -b 4096 -N ''"')

Of course, it doesn't work either.

Body:
Use the subprocess module:

import subprocess
username = 'user'
result, err = subprocess.Popen(
            'su %s -c "ssh-keygen -f /home/%s/.ssh/id_rsa -t rsa -b 4096 -N ''"' % (username, username),
            stdout=subprocess.PIPE,
            shell=True
          ).communicate()
if err:
    print('Something went wrong')
else:
    print(result)

Edit: this is the 'fast' way to do that, you should't use shell=True if you can't control the input since it allows code execution as said here


问:
Difference between Software and Hardware Interrupts
I have recently started working on ARM Cortex Microcontrollers. While reading different articles over Internet, I usually found 2 common terms as Software Interrupt and Hardware Interrupt.
What is the actual difference in both? Can you explain with an example?</p>

答:
Hardware interrupts are generated by physical signals, either from within the microcontroller itself (e.g. as part of a bus controller) or from an external GPIO configured as an interrupt. These interrupts are usually related to interactions with hardware external to the microcontroller, e.g. SPI or I2C bus interrupts generated when an event occurs on the bus. These hardware interrupts are usually configured via a combination of control registers, which specify hardware behaviour, and interrupt masking, which allows certain interrupts to be enabled or disabled at any point in time. Internal hardware events such as power events, timers, etc. also trigger interrupts.

Software interrupts are generated by instructions executed by the microcontroller. For example, on x86 platforms you can use an INT3 instruction to raise a TRAP interrupt for debugging purposes. Software interrupts are commonly used as a way to switch privilege levels, e.g. with syscalls, since code running in a low-privilege mode can trigger an interrupt which executes in a high-privilege mode, which can then dispatch the syscall request appropriately.

In both cases, interrupt handlers are generally configured using an interrupt vector table. Interrupt vectors are simply pointers to functions that handle each interrupt. The table usually exists at a fixed memory location in the microcontroller's flash or ROM space, but in many situations the interrupt table location can be configured as part of the programming process. Generally, each interrupt type is given a number which corresponds to its index in the interrupt table, so you know where to put each individual handler's vector.


问:
Working with decimals in Ruby on Rails 3
I'm trying to calculate the average net price of a product. I have, in my Product model :total_sold and :total_net_revenue. Doing straight division in the method seems to always result in 0. I resorted to using BigDecimal as I figured that was the problem ... but with my latest iteration of the code below, I'm still getting zero when the answer comes out to a decimal.

```<code>def avg_price
  BigDecimal(total_sold.to_s) / (BigDecimal(total_net_revenue.to_s) / 100)
end
</code>```

Net revenue is in cents, which is why I divide by 100. Can someone point out what I'm doing wrong or should do?

答:
You need to convert your values that are in whole cents (integers) to floats (numbers with decimals) so that the math will result in a floating number instead of an integer.

So in general it works like this:

```<code>some_integer.to_f / some_other_integer.to_f  # returns a float
</code>```

Body:
I'm trying to calculate the average net price of a product. I have, in my Product model :total_sold and :total_net_revenue. Doing straight division in the method seems to always result in 0. I resorted to using BigDecimal as I figured that was the problem ... but with my latest iteration of the code below, I'm still getting zero when the answer comes out to a decimal.

def avg_price
  BigDecimal(total_sold.to_s) / (BigDecimal(total_net_revenue.to_s) / 100)
end

Net revenue is in cents, which is why I divide by 100. Can someone point out what I'm doing wrong or should do?

Body:
You need to convert your values that are in whole cents (integers) to floats (numbers with decimals) so that the math will result in a floating number instead of an integer.

So in general it works like this:

some_integer.to_f / some_other_integer.to_f  # returns a float


问:
register custom config namespace for Symfony MicroKernel
I have an app with a MicroKernel and would like to use Symfony's TreeBuilder with a custom config because the app will be quite generic and I would like to have as much as possible configured externally. My problem is, I can't get my custom namespace registered for symfony:

```<code>There is no extension able to load the configuration for "research"
(in /var/www/html/src/app/config/config.yml). Looked for
namespace "research", found "framework", "twig",
"sensio_framework_extra", "web_profiler"
</code>```

I have this Configuration class:

```<code><?php
namespace App\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

class Configuration implements ConfigurationInterface
{
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode    = $treeBuilder->root('research');

        // @formatter:off
        $rootNode
            ->children()
                ->arrayNode('questions')
                    ->children()
                        ->integerNode('client_id')->end()
                        ->scalarNode('client_secret')->end()
                    ->end()
                ->end()// twitter
            ->end();
        // @formatter:on

        return $treeBuilder;
    }
}
</code>```

and my AppExtension:

```<code><?php
namespace App\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\DependencyInjection\ConfigurableExtension;

class AppExtension extends ConfigurableExtension
{
    // note that this method is called loadInternal and not load
    protected function loadInternal(array $mergedConfig, ContainerBuilder $container)
    {
        dump($mergedConfig);
    }

    public function getAlias()
    {
        return 'research';
    }
}
</code>```

In my AppKernel class, I'm initializing the extension like this and as a result I also get an output from the dump($mergedConfig) call in my AppExtension from my original research.yml

```<code><?php
namespace App;

use App\DependencyInjection\AppExtension;
use Doctrine\Common\Annotations\AnnotationRegistry;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Routing\RouteCollectionBuilder;
use Symfony\Component\Yaml\Exception\ParseException;
use Symfony\Component\Yaml\Yaml;

$loader = require __DIR__ . '/../vendor/autoload.php';

// auto-load annotations
AnnotationRegistry::registerLoader(array($loader, 'loadClass'));

/**
 * Class AppKernel
 */
class AppKernel extends Kernel
{
    use MicroKernelTrait;

    ...

    protected function configureContainer(ContainerBuilder $c, LoaderInterface $loader)
    {
        $researchConfig = Yaml::parse(file_get_contents(__DIR__ . '/config/research.yml'));
        $appExtension = new AppExtension();
        $appExtension->load(researchConfig, $c);

        $loader->load(__DIR__ . '/config/config.yml');
    }

    ...
}
</code>```

nevertheless, when my config.yml looks like this, I get the error mentioned above:

```<code>framework:
    secret: S0ME_SUPER_SECRET
    profiler: { only_exceptions: false }

research:
    questions:
       client_id: 2342323423
       clent_secret: mysecret
</code>```

so what do I need to do, to actually register my namespace research so I can properly overwrite it? Or does it have to an external vendor bundle?

答:
You get the error because you dont register a bundle and so symfony doesnt know the bundle config namespace.

I cant say how you could fix this with your approach but i would suggest to make a AppBundle instead of the App and register AppBundle in public function registerBundles().

See f.E. in some boilerplates like https://github.com/ikoene/symfony-micro.

Alternativly you could try to set up your project with the new symfony Flex.

This already uses MicroKernel, is bundleless and also supports latest stable symfony version (sf3.3).

https://symfony.com/doc/current/setup/flex.html#using-symfony-flex-in-new-applications

So no need to build something off the track yourself.

Body:
I have an app with a MicroKernel and would like to use Symfony's TreeBuilder with a custom config because the app will be quite generic and I would like to have as much as possible configured externally. My problem is, I can't get my custom namespace registered for symfony:

There is no extension able to load the configuration for "research"
(in /var/www/html/src/app/config/config.yml). Looked for
namespace "research", found "framework", "twig",
"sensio_framework_extra", "web_profiler"

I have this Configuration class:

<?php
namespace App\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

class Configuration implements ConfigurationInterface
{
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode    = $treeBuilder->root('research');

        // @formatter:off
        $rootNode
            ->children()
                ->arrayNode('questions')
                    ->children()
                        ->integerNode('client_id')->end()
                        ->scalarNode('client_secret')->end()
                    ->end()
                ->end()// twitter
            ->end();
        // @formatter:on

        return $treeBuilder;
    }
}

and my AppExtension:

<?php
namespace App\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\DependencyInjection\ConfigurableExtension;

class AppExtension extends ConfigurableExtension
{
    // note that this method is called loadInternal and not load
    protected function loadInternal(array $mergedConfig, ContainerBuilder $container)
    {
        dump($mergedConfig);
    }

    public function getAlias()
    {
        return 'research';
    }
}

In my AppKernel class, I'm initializing the extension like this and as a result I also get an output from the dump($mergedConfig) call in my AppExtension from my original research.yml

<?php
namespace App;

use App\DependencyInjection\AppExtension;
use Doctrine\Common\Annotations\AnnotationRegistry;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Routing\RouteCollectionBuilder;
use Symfony\Component\Yaml\Exception\ParseException;
use Symfony\Component\Yaml\Yaml;

$loader = require __DIR__ . '/../vendor/autoload.php';

// auto-load annotations
AnnotationRegistry::registerLoader(array($loader, 'loadClass'));

/**
 * Class AppKernel
 */
class AppKernel extends Kernel
{
    use MicroKernelTrait;

    ...

    protected function configureContainer(ContainerBuilder $c, LoaderInterface $loader)
    {
        $researchConfig = Yaml::parse(file_get_contents(__DIR__ . '/config/research.yml'));
        $appExtension = new AppExtension();
        $appExtension->load(researchConfig, $c);

        $loader->load(__DIR__ . '/config/config.yml');
    }

    ...
}

nevertheless, when my config.yml looks like this, I get the error mentioned above:

framework:
    secret: S0ME_SUPER_SECRET
    profiler: { only_exceptions: false }

research:
    questions:
       client_id: 2342323423
       clent_secret: mysecret

so what do I need to do, to actually register my namespace research so I can properly overwrite it? Or does it have to an external vendor bundle?


问:
Eclipse Angular IDE project creation fails and has wrong node version
I'm on a mac. I just installed Angular IDE (eclipse) and when I try to create a new Angular project it fails. I can run the same commands from the terminal and it works. I'm using node 8.9.1 and npm 5.5.1 outside the IDE, but can't find where to tell the plugin to use that version.</p>

```<code>Node.js version:    v9.1.0
NPM version:        5.5.1
npm install @angular/cli@1.4.9
npm WARN npm npm does not support Node.js v9.1.0
npm WARN npm You should probably upgrade to a newer version of node as we
npm WARN npm can't make any promises that npm will work with this version.
npm WARN npm Supported releases of Node.js are the latest release of 4, 6, 7, 8.
npm WARN npm You can find the latest version at https://nodejs.org/
WARNING: You are likely using a version of node-tar or npm that is incompatible with this version of Node.js.
Please use either the version of npm that is bundled with Node.js, or a version of npm (> 5.5.1 or < 5.4.0) or node-tar (> 4.0.1) that is compatible with Node.js 9 and above.
/Users/bobsmith/.webclipse/nodejs/9.1.0/bin/node[4666]: ../src/node_zlib.cc:437:static void node::(anonymous namespace)::ZCtx::Init(const FunctionCallbackInfo<v8::Value> &): Assertion `args.Length() == 7 && "init(windowBits, level, memLevel, strategy, writeResult, writeCallback," " dictionary)"' failed.
 1: node::Abort() [/Users/bobsmith/.webclipse/nodejs/9.1.0/bin/node]
 2: node::(anonymous namespace)::DomainEnter(node::Environment*, v8::Local<v8::Object>) [/Users/bobsmith/.webclipse/nodejs/9.1.0/bin/node]
 3: node::(anonymous namespace)::ZCtx::Init(v8::FunctionCallbackInfo<v8::Value> const&) [/Users/bobsmith/.webclipse/nodejs/9.1.0/bin/node]
 4: v8::internal::FunctionCallbackArguments::Call(void (*)(v8::FunctionCallbackInfo<v8::Value> const&)) [/Users/bobsmith/.webclipse/nodejs/9.1.0/bin/node]
 5: v8::internal::MaybeHandle<v8::internal::Object> v8::internal::(anonymous namespace)::HandleApiCallHelper<false>(v8::internal::Isolate*, v8::internal::Handle<v8::internal::HeapObject>, v8::internal::Handle<v8::internal::HeapObject>, v8::internal::Handle<v8::internal::FunctionTemplateInfo>, v8::internal::Handle<v8::internal::Object>, v8::internal::BuiltinArguments) [/Users/bobsmith/.webclipse/nodejs/9.1.0/bin/node]
 6: v8::internal::Builtin_Impl_HandleApiCall(v8::internal::BuiltinArguments, v8::internal::Isolate*) [/Users/bobsmith/.webclipse/nodejs/9.1.0/bin/node]
 7: 0x337a5df842fd
/Users/bobsmith/.webclipse/npm/5.5.1/bin/npm: line 14:  4666 Abort trap: 6           node "$basedir/../bin/npm-cli.js" "$@"
</code>```

答: First, try to execute outside the IDE the line "npm install @angular/cli@1.4.9", later in the IDE, you need to create the project with the same versions for node, npm, en angular cli that you have installed in your machine.</p>

Body:
I'm on a mac. I just installed Angular IDE (eclipse) and when I try to create a new Angular project it fails. I can run the same commands from the terminal and it works. I'm using node 8.9.1 and npm 5.5.1 outside the IDE, but can't find where to tell the plugin to use that version.

Node.js version:    v9.1.0
NPM version:        5.5.1
npm install @angular/cli@1.4.9
npm WARN npm npm does not support Node.js v9.1.0
npm WARN npm You should probably upgrade to a newer version of node as we
npm WARN npm can't make any promises that npm will work with this version.
npm WARN npm Supported releases of Node.js are the latest release of 4, 6, 7, 8.
npm WARN npm You can find the latest version at https://nodejs.org/
WARNING: You are likely using a version of node-tar or npm that is incompatible with this version of Node.js.
Please use either the version of npm that is bundled with Node.js, or a version of npm (> 5.5.1 or < 5.4.0) or node-tar (> 4.0.1) that is compatible with Node.js 9 and above.
/Users/bobsmith/.webclipse/nodejs/9.1.0/bin/node[4666]: ../src/node_zlib.cc:437:static void node::(anonymous namespace)::ZCtx::Init(const FunctionCallbackInfo<v8::Value> &): Assertion `args.Length() == 7 && "init(windowBits, level, memLevel, strategy, writeResult, writeCallback," " dictionary)"' failed.
 1: node::Abort() [/Users/bobsmith/.webclipse/nodejs/9.1.0/bin/node]
 2: node::(anonymous namespace)::DomainEnter(node::Environment*, v8::Local<v8::Object>) [/Users/bobsmith/.webclipse/nodejs/9.1.0/bin/node]
 3: node::(anonymous namespace)::ZCtx::Init(v8::FunctionCallbackInfo<v8::Value> const&) [/Users/bobsmith/.webclipse/nodejs/9.1.0/bin/node]
 4: v8::internal::FunctionCallbackArguments::Call(void (*)(v8::FunctionCallbackInfo<v8::Value> const&)) [/Users/bobsmith/.webclipse/nodejs/9.1.0/bin/node]
 5: v8::internal::MaybeHandle<v8::internal::Object> v8::internal::(anonymous namespace)::HandleApiCallHelper<false>(v8::internal::Isolate*, v8::internal::Handle<v8::internal::HeapObject>, v8::internal::Handle<v8::internal::HeapObject>, v8::internal::Handle<v8::internal::FunctionTemplateInfo>, v8::internal::Handle<v8::internal::Object>, v8::internal::BuiltinArguments) [/Users/bobsmith/.webclipse/nodejs/9.1.0/bin/node]
 6: v8::internal::Builtin_Impl_HandleApiCall(v8::internal::BuiltinArguments, v8::internal::Isolate*) [/Users/bobsmith/.webclipse/nodejs/9.1.0/bin/node]
 7: 0x337a5df842fd
/Users/bobsmith/.webclipse/npm/5.5.1/bin/npm: line 14:  4666 Abort trap: 6           node "$basedir/../bin/npm-cli.js" "$@"


问:
OpenCV Error: (-215)size.width>0 && size.height>0 in function imshow
I am trying to make a face tracker that combines Haar Cascade Classification with Lucas Kanade good feature detection. However, I keep getting an error that I cannot figure out what it means nor how to solve it.

Can anyone help me here?

Error:

```<code>line 110, in <module>
cv2.imshow('frame',img)
error: /build/buildd/opencv-2.4.8+dfsg1/modules/highgui/src/window.cpp:269:
error: (-215)size.width>0 && size.height>0 in function imshow
</code>```

Code:

```<code>from matplotlib import pyplot as plt
import numpy as np

import cv2

face_classifier = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_default.xml')

cap = cv2.VideoCapture(0)

# params for ShiTomasi corner detection
feature_params = dict( maxCorners = 200,
                       qualityLevel = 0.01,
                       minDistance = 10,
                       blockSize = 7 )

# Parameters for lucas kanade optical flow
lk_params = dict( winSize  = (15,15),
                  maxLevel = 2,
                  criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03))

# Create some random colors
color = np.random.randint(0,255,(100,3))

# Take first frame and find corners in it
ret, old_frame = cap.read()

cv2.imshow('Old_Frame', old_frame)
cv2.waitKey(0)
old_gray = cv2.cvtColor(old_frame, cv2.COLOR_BGR2GRAY)
restart = True
#while restart == True:
face = face_classifier.detectMultiScale(old_gray, 1.2, 4)

if len(face) == 0:
    print "This is empty"

for (x,y,w,h) in face:
    focused_face = old_frame[y: y+h, x: x+w]

cv2.imshow('Old_Frame', old_frame)

face_gray = cv2.cvtColor(old_frame,cv2.COLOR_BGR2GRAY)

gray = cv2.cvtColor(focused_face,cv2.COLOR_BGR2GRAY)

corners_t = cv2.goodFeaturesToTrack(gray, mask = None, **feature_params)
corners = np.int0(corners_t)

print corners

for i in corners:
    ix,iy = i.ravel()
    cv2.circle(focused_face,(ix,iy),3,255,-1)
    cv2.circle(old_frame,(x+ix,y+iy),3,255,-1)

plt.imshow(old_frame),plt.show()

# Create a mask image for drawing purposes
mask = np.zeros_like(old_frame)

while(1):
    ret,frame = cap.read()
    frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # calculate optical flow
    p1, st, err = cv2.calcOpticalFlowPyrLK(old_gray, frame_gray, corners_t, None, **lk_params)

    # Select good points
    good_new = p1[st==1]
    good_old = corners_t[st==1]

    # draw the tracks
    print "COLORING TIME!"
    for i,(new,old) in enumerate(zip(good_new,good_old)):
        print i
        print color[i]
        a,b = new.ravel()
        c,d = old.ravel()
        mask = cv2.line(mask, (a,b),(c,d), color[i].tolist(), 2)
        frame = cv2.circle(frame,(a, b),5,color[i].tolist(),-1)
        if i == 99:
            break
    img = cv2.add(frame,mask)

    cv2.imshow('frame',img)
    k = cv2.waitKey(30) & 0xff
    if k == 27:
        break

    # Now update the previous frame and previous points
    old_gray = frame_gray.copy()
    p0 = good_new.reshape(-1,1,2)

cv2.destroyAllWindows()
cap.release()
</code>```

答:
I use ssh to connect to remote server and have python code execute cv2.VideoCapture(0) to capture remote webcam, then encounter this error message:

error: (-215)size.width>0 && size.height>0 in function imshow

Finally, I have to grant access to /dev/video0 (which is my webcam device) with my user account and the error message was gone. Use usermod to add user into group video

```<code>usermod -a -G video user
</code>```

Body:
I am trying to make a face tracker that combines Haar Cascade Classification with Lucas Kanade good feature detection. However, I keep getting an error that I cannot figure out what it means nor how to solve it.

Can anyone help me here?

Error:

line 110, in <module>
cv2.imshow('frame',img)
error: /build/buildd/opencv-2.4.8+dfsg1/modules/highgui/src/window.cpp:269:
error: (-215)size.width>0 && size.height>0 in function imshow

Code:

from matplotlib import pyplot as plt
import numpy as np

import cv2

face_classifier = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_default.xml')

cap = cv2.VideoCapture(0)

# params for ShiTomasi corner detection
feature_params = dict( maxCorners = 200,
                       qualityLevel = 0.01,
                       minDistance = 10,
                       blockSize = 7 )

# Parameters for lucas kanade optical flow
lk_params = dict( winSize  = (15,15),
                  maxLevel = 2,
                  criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03))

# Create some random colors
color = np.random.randint(0,255,(100,3))

# Take first frame and find corners in it
ret, old_frame = cap.read()

cv2.imshow('Old_Frame', old_frame)
cv2.waitKey(0)
old_gray = cv2.cvtColor(old_frame, cv2.COLOR_BGR2GRAY)
restart = True
#while restart == True:
face = face_classifier.detectMultiScale(old_gray, 1.2, 4)

if len(face) == 0:
    print "This is empty"

for (x,y,w,h) in face:
    focused_face = old_frame[y: y+h, x: x+w]

cv2.imshow('Old_Frame', old_frame)

face_gray = cv2.cvtColor(old_frame,cv2.COLOR_BGR2GRAY)

gray = cv2.cvtColor(focused_face,cv2.COLOR_BGR2GRAY)

corners_t = cv2.goodFeaturesToTrack(gray, mask = None, **feature_params)
corners = np.int0(corners_t)

print corners

for i in corners:
    ix,iy = i.ravel()
    cv2.circle(focused_face,(ix,iy),3,255,-1)
    cv2.circle(old_frame,(x+ix,y+iy),3,255,-1)

plt.imshow(old_frame),plt.show()

# Create a mask image for drawing purposes
mask = np.zeros_like(old_frame)

while(1):
    ret,frame = cap.read()
    frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # calculate optical flow
    p1, st, err = cv2.calcOpticalFlowPyrLK(old_gray, frame_gray, corners_t, None, **lk_params)

    # Select good points
    good_new = p1[st==1]
    good_old = corners_t[st==1]

    # draw the tracks
    print "COLORING TIME!"
    for i,(new,old) in enumerate(zip(good_new,good_old)):
        print i
        print color[i]
        a,b = new.ravel()
        c,d = old.ravel()
        mask = cv2.line(mask, (a,b),(c,d), color[i].tolist(), 2)
        frame = cv2.circle(frame,(a, b),5,color[i].tolist(),-1)
        if i == 99:
            break
    img = cv2.add(frame,mask)

    cv2.imshow('frame',img)
    k = cv2.waitKey(30) & 0xff
    if k == 27:
        break

    # Now update the previous frame and previous points
    old_gray = frame_gray.copy()
    p0 = good_new.reshape(-1,1,2)

cv2.destroyAllWindows()
cap.release()

Body:
I use ssh to connect to remote server and have python code execute cv2.VideoCapture(0) to capture remote webcam, then encounter this error message:

error: (-215)size.width>0 && size.height>0 in function imshow

Finally, I have to grant access to /dev/video0 (which is my webcam device) with my user account and the error message was gone. Use usermod to add user into group video

usermod -a -G video user


问:
Error: "The SqlParameter is already contained by another SqlParameterCollection" when adding a Parameter
I have a few similar functions that interact with my SQL server (selects, calls to stored procdures etc.) and all work with the exception of the one below.  Each SqlConnection is contained within a using block with the SqlCommand also contained within a using block.

This code is failing when attempting to add the @LastUpdated parameter. I've tried some suggestions I've seen in other posts: cmd.Parameters.Clear(), wrapping in using, etc., but no luck. A few posts with the same error were resolved when duplicate attempts to set the same parameter where found. It's possible I'm missing that but I've looked over this for a few hours, even cleaned the glasses. Any direction would be appreciated.

```<code>private void _AddCartItem(bool hasEventInCart, _EventCart cartContents, ref int cartItemId)
{
    using (SqlConnection sqlConnection = new SqlConnection(_striMISConnection))
    {
        sqlConnection.Open();

        using (SqlCommand cmd = sqlConnection.CreateCommand())
        {
            SqlParameter param = new SqlParameter();
            cmd.Parameters.Clear();

            // add/update CartItem
            if (hasEventInCart)
            {
                // Update item
                cmd.CommandText = "SProc2Insert @CartItemId, @ID, 'Event', @Created, @LastUpdated";
                param.ParameterName = "@CartItemId";
                param.Value = cartItemId;
                cmd.Parameters.Add(param);
            }
            else
            {
                // add item
                cmd.CommandText = "SProc2Update @ID, 'Event', @Created, @LastUpdated";
            }

            cmd.CommandType = CommandType.Text;

            param.ParameterName = "@Created";
            param.Value = DateTime.Now.ToString();
            cmd.Parameters.Add(param);

            param.ParameterName = "@LastUpdated";
            param.Value = DateTime.Now.ToString();
            **cmd.Parameters.Add(param);**

            param.ParameterName = "@ID";
            param.Value = this.ID;
            cmd.Parameters.Add(param);

            if (hasEventInCart)
            {
                cmd.ExecuteNonQuery(); // do the update
            }
            else
            {
                cartItemId = (int)cmd.ExecuteScalar();

                foreach (var currentCartEvent in cartContents.CartEvents)
                {
                    if (currentCartEvent.EventCode == this.EventCode)
                    {
                        currentCartEvent.CartItemID = cartItemId;
                    }
                }
            }
            cmd.Parameters.Clear();
        }
    }
}
</code>```

答:
I had the same problem, you can solve it with the code below:

```<code>if (SqlParams != null && SqlParams.Count > 0)
{
    foreach (SqlParameter spp in SqlParams )
    {
        SqlParameter nameParam = new SqlParameter(spp.ParameterName, spp.SqlValue);

        mycmd.Parameters.Add(nameParam);
    }
}
</code>```

Body:
I have a few similar functions that interact with my SQL server (selects, calls to stored procdures etc.) and all work with the exception of the one below.  Each SqlConnection is contained within a using block with the SqlCommand also contained within a using block.

This code is failing when attempting to add the @LastUpdated parameter. I've tried some suggestions I've seen in other posts: cmd.Parameters.Clear(), wrapping in using, etc., but no luck. A few posts with the same error were resolved when duplicate attempts to set the same parameter where found. It's possible I'm missing that but I've looked over this for a few hours, even cleaned the glasses. Any direction would be appreciated.

private void _AddCartItem(bool hasEventInCart, _EventCart cartContents, ref int cartItemId)
{
    using (SqlConnection sqlConnection = new SqlConnection(_striMISConnection))
    {
        sqlConnection.Open();

        using (SqlCommand cmd = sqlConnection.CreateCommand())
        {
            SqlParameter param = new SqlParameter();
            cmd.Parameters.Clear();

            // add/update CartItem
            if (hasEventInCart)
            {
                // Update item
                cmd.CommandText = "SProc2Insert @CartItemId, @ID, 'Event', @Created, @LastUpdated";
                param.ParameterName = "@CartItemId";
                param.Value = cartItemId;
                cmd.Parameters.Add(param);
            }
            else
            {
                // add item
                cmd.CommandText = "SProc2Update @ID, 'Event', @Created, @LastUpdated";
            }

            cmd.CommandType = CommandType.Text;

            param.ParameterName = "@Created";
            param.Value = DateTime.Now.ToString();
            cmd.Parameters.Add(param);

            param.ParameterName = "@LastUpdated";
            param.Value = DateTime.Now.ToString();
            **cmd.Parameters.Add(param);**

            param.ParameterName = "@ID";
            param.Value = this.ID;
            cmd.Parameters.Add(param);

            if (hasEventInCart)
            {
                cmd.ExecuteNonQuery(); // do the update
            }
            else
            {
                cartItemId = (int)cmd.ExecuteScalar();

                foreach (var currentCartEvent in cartContents.CartEvents)
                {
                    if (currentCartEvent.EventCode == this.EventCode)
                    {
                        currentCartEvent.CartItemID = cartItemId;
                    }
                }
            }
            cmd.Parameters.Clear();
        }
    }
}

Body:
I had the same problem, you can solve it with the code below:

if (SqlParams != null && SqlParams.Count > 0)
{
    foreach (SqlParameter spp in SqlParams )
    {
        SqlParameter nameParam = new SqlParameter(spp.ParameterName, spp.SqlValue);

        mycmd.Parameters.Add(nameParam);
    }
}


问:
Chef PEM file invalid or mis-named?
My sytem username is myuser but I'm trying to bootstrap machines with a chef-validator.pem and then a blah.pem file, and getting the following error message:

```<code>ERROR: Failed to authenticate to https://mychef01 as blah with key
/etc/chef/blah.pem.
Response: Invalid signature for user or client 'blah'
</code>```

Does this mean that the blah.pem file is invalid, or does it mean that it needs to match my system username (so, myuser.pem)? Either way, what is the root problem and what is the fix?

答:
I've gotten the same issue. In my case I was generating the key from the left sidebar and getting the same issue. But when I clicked in the user line "Gear"(action column), and then clicked in reset key to download it again (and place it poperly in the .chef directory), then it worked fine.

Other thing that may happened is that your .pem file is not correctly referenced in the knife.rb file

Hope that helps

Title: Chef PEM file invalid or mis-named?

Body:
My sytem username is myuser but I'm trying to bootstrap machines with a chef-validator.pem and then a blah.pem file, and getting the following error message:

ERROR: Failed to authenticate to https://mychef01 as blah with key
/etc/chef/blah.pem.
Response: Invalid signature for user or client 'blah'

Does this mean that the blah.pem file is invalid, or does it mean that it needs to match my system username (so, myuser.pem)? Either way, what is the root problem and what is the fix?