问:
Print null or transparent label in Gnuplot
I would like to place a few graphs beside each other horizontally. The issue is only the one at the middle should have an xlabel.

On implementing that, the other graphs appear to start a bit below on merging all the images together. I have tried to change the color of xlabel, but it hasn't been working on epslatex. Neither supplying a null value worked ("").

```<code>set format "$%g$"
set terminal epslatex size 5.25,4.2 color standalone
set output "count.tex"

unset key
set yrange [0:18]
set xrange [0:18]
set cbrange [0:1400]
unset colorbox
set ylabel "Species 2 ----->"
set xlabel "Species 1 ----->" tc rgb "white"

plot 'combine.txt' u 1:2:3 with points pointtype 7 pointsize 3 palette
</code>```

Please help me regarding this.

答:
I found a workaround regarding this. A space could be printed instead.</p>

```<code>set encoding iso_8859_1
set xlabel "\240"
</code>```

Body:
I would like to place a few graphs beside each other horizontally. The issue is only the one at the middle should have an xlabel.

On implementing that, the other graphs appear to start a bit below on merging all the images together. I have tried to change the color of xlabel, but it hasn't been working on epslatex. Neither supplying a null value worked ("").

set format "$%g$"
set terminal epslatex size 5.25,4.2 color standalone
set output "count.tex"

unset key
set yrange [0:18]
set xrange [0:18]
set cbrange [0:1400]
unset colorbox
set ylabel "Species 2 ----->"
set xlabel "Species 1 ----->" tc rgb "white"

plot 'combine.txt' u 1:2:3 with points pointtype 7 pointsize 3 palette

Please help me regarding this.

Body:
I found a workaround regarding this. A space could be printed instead.

set encoding iso_8859_1
set xlabel "\240"


来源: stackexchange

问:
Cannot send image in server?
I am not able to send image  file to server using library alamofire. I am having issue with sending image file dynamically.The filename is shown in the server but image is blank.How can this be solved?

Image code

```<code> let parameters = [
                "name": name_txt.text! as String,
                "address": address_txt.text! as String,
                "district": website_txt!.text! as String,
                "country": establishment_txt.text! as String,

            ]

            Alamofire.upload(multipartFormData: { multipartFormData in
                if let imageData = UIImageJPEGRepresentation(self.logo_holder.image!, 1) {
                    multipartFormData.append(imageData, withName: "logo", fileName: "file.png", mimeType: "image/png")
                }

                for (key, value) in parameters {
                    multipartFormData.append((value.data(using: .utf8))!, withName: key)
                }}, to: "http://www.myeducationhunt.com/api/v1/schools", method: .post, headers: ["Authorization": "auth_token"],
                    encodingCompletion: { encodingResult in
                        switch encodingResult {
                        case .success(let upload, _, _):
                            upload.response { [weak self] response in
                                guard self != nil else {
                                    return
                                }
                                debugPrint(response)
                            }
                        case .failure(let encodingError):
                            print("errorss:\(encodingError)")
                        }
            })
</code>```

i am able to receive image filename but image gone blank.How can this
  be solved?

答:
you can try this

```<code>let parameters = [

               "name": name_txt.text! as String,

               "address": address_txt.text! as String,

               "district": website_txt!.text! as String,

               "country": establishment_txt.text! as String

           ]

        Alamofire.upload(multipartFormData: { multipartFormData in

               if let imageData = UIImageJPEGRepresentation(self.logo_holder.image!, 0.5) {

                   multipartFormData.append(imageData, withName: "image", fileName: "image.jpeg", mimeType: "file/jpeg")

                   print("imgdatas",imageData)

               }

               for (key, value) in parameters {

                   multipartFormData.append((value.data(using: .utf8))!, withName: key)

               }}, to: "http://www.myeducationhunt.com/api/v1/schools", method: .post, headers: ["Authorization": "auth_token"],

                   encodingCompletion: { encodingResult in

                       switch encodingResult {

                       case .success(let upload, _, _):

                           upload.response { [weak self] response in

                               guard self != nil else {

                                   return

                               }

                               debugPrint(response)

                           }

                       case .failure(let encodingError):

                           print("errorss:\(encodingError)")

                       }

           })
</code>```

ContentLicense: CC BY-SA 3.0

Title: Cannot send image in server?

Body:
I am not able to send image  file to server using library alamofire. I am having issue with sending image file dynamically.The filename is shown in the server but image is blank.How can this be solved?

Image code

 let parameters = [
                "name": name_txt.text! as String,
                "address": address_txt.text! as String,
                "district": website_txt!.text! as String,
                "country": establishment_txt.text! as String,

            ]

            Alamofire.upload(multipartFormData: { multipartFormData in
                if let imageData = UIImageJPEGRepresentation(self.logo_holder.image!, 1) {
                    multipartFormData.append(imageData, withName: "logo", fileName: "file.png", mimeType: "image/png")
                }

                for (key, value) in parameters {
                    multipartFormData.append((value.data(using: .utf8))!, withName: key)
                }}, to: "http://www.myeducationhunt.com/api/v1/schools", method: .post, headers: ["Authorization": "auth_token"],
                    encodingCompletion: { encodingResult in
                        switch encodingResult {
                        case .success(let upload, _, _):
                            upload.response { [weak self] response in
                                guard self != nil else {
                                    return
                                }
                                debugPrint(response)
                            }
                        case .failure(let encodingError):
                            print("errorss:\(encodingError)")
                        }
            })

i am able to receive image filename but image gone blank.How can this
  be solved?

Body:
you can try this

let parameters = [

               "name": name_txt.text! as String,

               "address": address_txt.text! as String,

               "district": website_txt!.text! as String,

               "country": establishment_txt.text! as String

           ]

        Alamofire.upload(multipartFormData: { multipartFormData in

               if let imageData = UIImageJPEGRepresentation(self.logo_holder.image!, 0.5) {

                   multipartFormData.append(imageData, withName: "image", fileName: "image.jpeg", mimeType: "file/jpeg")

                   print("imgdatas",imageData)

               }

               for (key, value) in parameters {

                   multipartFormData.append((value.data(using: .utf8))!, withName: key)

               }}, to: "http://www.myeducationhunt.com/api/v1/schools", method: .post, headers: ["Authorization": "auth_token"],

                   encodingCompletion: { encodingResult in

                       switch encodingResult {

                       case .success(let upload, _, _):

                           upload.response { [weak self] response in

                               guard self != nil else {

                                   return

                               }

                               debugPrint(response)

                           }

                       case .failure(let encodingError):

                           print("errorss:\(encodingError)")

                       }

           })


问:
What would be a simple regular expression for password check during signup?
What I want to do is just check when the user is signing up that whether the password entered is at least 6 characters and has no space in it. Thats pretty much it. What would be a regex that I could use in Java Pattern Matcher classes for this purpose?

Thanks for your help guys.

答:
Pattern Matcher is a little overhead there, you can use the following:</p>

```<code>String password = ...;
final int PASS_MIN_LEN = 6;
if (password.length >= PASS_MIN_LEN && password.indexOf(' ') < 0) {
 // proceed
} else {
 // error
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Pattern Matcher is a little overhead there, you can use the following:

String password = ...;
final int PASS_MIN_LEN = 6;
if (password.length >= PASS_MIN_LEN && password.indexOf(' ') < 0) {
 // proceed
} else {
 // error
}


问:
Python/Scrapy wait until complete
Trying to get a project I'm working on to wait on the results of the Scrapy crawls. Pretty new to Python but I'm learning quickly and I have liked it thus far. Here's my remedial function to refresh my crawls;

```<code>def refreshCrawls():
     os.system('rm JSON/*.json)

     os.system('scrapy crawl TeamGameResults -o JSON/TeamGameResults.json --nolog')
     #I do this same call for 4 other crawls also
</code>```

This function gets called in a for loop in my 'main function' while I'm parsing args:

```<code>for i in xrange(1,len(sys.argv)):
     arg = sys.argv[i]
     if arg == '-r':
          pprint('Refreshing Data...')
          refreshCrawls()
</code>```

This all works and does update the JSON files, however the rest of my application does not wait on this as I foolishly expected it to. Didn't really have a problem with this until I moved the app over to a Pi and now the poor little guy can't refresh soon enough, Any suggestions on how to resolve this?

My quick dirty answer says split it into a different automated script and just run it an hour or so before I run my automated 'main function,' or use a sleep timer but I'd rather go about this properly if there's some low hanging fruit that can solve this for me. I do like being able to enter the refresh arg in my command line.

答:
Instead of using os use subprocess:

```<code>from subprocess import Popen
import shlex

def refreshCrawls():
     os.system('rm JSON/*.json')
     cmd = shlex.split('scrapy crawl TeamGameResults -o JSON/TeamGameResults.json --nolog')
     p = Popen(cmd)
     #I do this same call for 4 other crawls also
     p.wait()

for i in xrange(1,len(sys.argv)):
     arg = sys.argv[i]
     if arg == '-r':
          pprint('Refreshing Data...')
          refreshCrawls()
</code>```

Title: Python/Scrapy wait until complete

Body:
Trying to get a project I'm working on to wait on the results of the Scrapy crawls. Pretty new to Python but I'm learning quickly and I have liked it thus far. Here's my remedial function to refresh my crawls;

def refreshCrawls():
     os.system('rm JSON/*.json)

     os.system('scrapy crawl TeamGameResults -o JSON/TeamGameResults.json --nolog')
     #I do this same call for 4 other crawls also

This function gets called in a for loop in my 'main function' while I'm parsing args:

for i in xrange(1,len(sys.argv)):
     arg = sys.argv[i]
     if arg == '-r':
          pprint('Refreshing Data...')
          refreshCrawls()

This all works and does update the JSON files, however the rest of my application does not wait on this as I foolishly expected it to. Didn't really have a problem with this until I moved the app over to a Pi and now the poor little guy can't refresh soon enough, Any suggestions on how to resolve this?

My quick dirty answer says split it into a different automated script and just run it an hour or so before I run my automated 'main function,' or use a sleep timer but I'd rather go about this properly if there's some low hanging fruit that can solve this for me. I do like being able to enter the refresh arg in my command line.

Body:
Instead of using os use subprocess:

from subprocess import Popen
import shlex

def refreshCrawls():
     os.system('rm JSON/*.json')
     cmd = shlex.split('scrapy crawl TeamGameResults -o JSON/TeamGameResults.json --nolog')
     p = Popen(cmd)
     #I do this same call for 4 other crawls also
     p.wait()

for i in xrange(1,len(sys.argv)):
     arg = sys.argv[i]
     if arg == '-r':
          pprint('Refreshing Data...')
          refreshCrawls()


问:
All com.android.support libraries must use the exact same version specification
After updating to android studio 2.3 I got this error message.
I know it's just a hint as the app run normally but it's really strange.

All com.android.support libraries must use the exact same version specification (mixing versions can lead to runtime crashes). Found versions 25.1.1, 24.0.0. Examples include com.android.support:animated-vector-drawable:25.1.1 and com.android.support:mediarouter-v7:24.0.0

my gradle:

```<code>dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    testCompile 'junit:junit:4.12'

    compile 'com.android.support:appcompat-v7:25.1.1'
    compile 'com.android.support:support-v4:25.1.1'
    compile 'com.android.support:design:25.1.1'
    compile 'com.android.support:recyclerview-v7:25.1.1'
    compile 'com.android.support:cardview-v7:25.1.1'
    compile 'com.google.android.gms:play-services-maps:10.2.0'
    compile 'com.google.android.gms:play-services:10.2.0'

    compile 'io.reactivex.rxjava2:rxjava:2.0.1'
    compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
    compile 'com.jakewharton:butterknife:8.4.0'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0'
    compile 'com.blankj:utilcode:1.3.6'
    compile 'com.orhanobut:logger:1.15'
    compile 'com.facebook.stetho:stetho:1.4.2'

    provided 'com.google.auto.value:auto-value:1.2'
    annotationProcessor 'com.google.auto.value:auto-value:1.2'
    annotationProcessor 'com.ryanharter.auto.value:auto-value-parcel:0.2.5'

    compile 'com.mikepenz:iconics-core:2.8.2@aar'
    compile('com.mikepenz:materialdrawer:5.8.1@aar') { transitive = true }
    compile 'com.mikepenz:google-material-typeface:2.2.0.3.original@aar'
    compile 'me.zhanghai.android.materialprogressbar:library:1.3.0'
    compile 'com.github.GrenderG:Toasty:1.1.1'
    compile 'com.github.CymChad:BaseRecyclerViewAdapterHelper:2.8.0'
    compile 'com.github.MAXDeliveryNG:slideview:1.0.0'

    compile 'com.facebook.fresco:fresco:1.0.1'
    compile 'com.github.bumptech.glide:glide:3.7.0'

    compile 'com.google.maps.android:android-maps-utils:0.4.4'
    compile 'com.github.jd-alexander:library:1.1.0'
}
</code>```

答:
I had to add the following lines in gradle to remove the error</p>

```<code>compile 'com.android.support:animated-vector-drawable:25.2.0'
compile 'com.android.support:preference-v7:25.2.0'
compile 'com.android.support:customtabs:25.2.0'
compile 'com.android.support:cardview-v7:25.2.0'
</code>```

Body:
After updating to android studio 2.3 I got this error message.
I know it's just a hint as the app run normally but it's really strange.

All com.android.support libraries must use the exact same version specification (mixing versions can lead to runtime crashes). Found versions 25.1.1, 24.0.0. Examples include com.android.support:animated-vector-drawable:25.1.1 and com.android.support:mediarouter-v7:24.0.0

my gradle:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    testCompile 'junit:junit:4.12'

    compile 'com.android.support:appcompat-v7:25.1.1'
    compile 'com.android.support:support-v4:25.1.1'
    compile 'com.android.support:design:25.1.1'
    compile 'com.android.support:recyclerview-v7:25.1.1'
    compile 'com.android.support:cardview-v7:25.1.1'
    compile 'com.google.android.gms:play-services-maps:10.2.0'
    compile 'com.google.android.gms:play-services:10.2.0'

    compile 'io.reactivex.rxjava2:rxjava:2.0.1'
    compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
    compile 'com.jakewharton:butterknife:8.4.0'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0'
    compile 'com.blankj:utilcode:1.3.6'
    compile 'com.orhanobut:logger:1.15'
    compile 'com.facebook.stetho:stetho:1.4.2'

    provided 'com.google.auto.value:auto-value:1.2'
    annotationProcessor 'com.google.auto.value:auto-value:1.2'
    annotationProcessor 'com.ryanharter.auto.value:auto-value-parcel:0.2.5'

    compile 'com.mikepenz:iconics-core:2.8.2@aar'
    compile('com.mikepenz:materialdrawer:5.8.1@aar') { transitive = true }
    compile 'com.mikepenz:google-material-typeface:2.2.0.3.original@aar'
    compile 'me.zhanghai.android.materialprogressbar:library:1.3.0'
    compile 'com.github.GrenderG:Toasty:1.1.1'
    compile 'com.github.CymChad:BaseRecyclerViewAdapterHelper:2.8.0'
    compile 'com.github.MAXDeliveryNG:slideview:1.0.0'

    compile 'com.facebook.fresco:fresco:1.0.1'
    compile 'com.github.bumptech.glide:glide:3.7.0'

    compile 'com.google.maps.android:android-maps-utils:0.4.4'
    compile 'com.github.jd-alexander:library:1.1.0'
}

Body:
I had to add the following lines in gradle to remove the error

compile 'com.android.support:animated-vector-drawable:25.2.0'
compile 'com.android.support:preference-v7:25.2.0'
compile 'com.android.support:customtabs:25.2.0'
compile 'com.android.support:cardview-v7:25.2.0'


问:
How to resize NSTextView according to its content?
I am trying to set an attributed string within NSTextView. I want to increase its height based on its content, initially it is set to some default value.

So I tried this method:

I set content in NSTextView. When we set some content in NSTextView its size automatically increases. So I increased height of its super view that is NSScrollView to its height, but NSScrollView is not getting completely resized, it is showing scroller on right.

```<code>float xCoordinate = 15.0;

[xContentViewScroller setFrame:NSMakeRect(xCoordinate, 0.0, 560.0, 10.0)];

[[xContentView textStorage] setAttributedString:xContents];

float xContentViewScrollerHeight = [xfContentView frame].size.height + 2;

[xContentViewScroller setFrame:NSMakeRect(xCoordinate, 0.0, 560.0, xContentViewScrollerHeight)];
</code>```

Can anyone suggest me some way or method to resolve this issue. By doing google search I found that in UITextView there is contentSize method which can get size of its content, I tried to find similar method in NSTextView but could not get any success :(

答:
```<code>NSTextView *textView = [[NSTextView alloc] init];
textView.font = [NSFont systemFontOfSize:[NSFont systemFontSize]];
textView.string = @"Lorem ipsum";

[textView.layoutManager ensureLayoutForTextContainer:textView.textContainer];

textView.frame = [textView.layoutManager usedRectForTextContainer:textView.textContainer];
</code>```

Body:
I am trying to set an attributed string within NSTextView. I want to increase its height based on its content, initially it is set to some default value.

So I tried this method:

I set content in NSTextView. When we set some content in NSTextView its size automatically increases. So I increased height of its super view that is NSScrollView to its height, but NSScrollView is not getting completely resized, it is showing scroller on right.

float xCoordinate = 15.0;

[xContentViewScroller setFrame:NSMakeRect(xCoordinate, 0.0, 560.0, 10.0)];

[[xContentView textStorage] setAttributedString:xContents];

float xContentViewScrollerHeight = [xfContentView frame].size.height + 2;

[xContentViewScroller setFrame:NSMakeRect(xCoordinate, 0.0, 560.0, xContentViewScrollerHeight)];

Can anyone suggest me some way or method to resolve this issue. By doing google search I found that in UITextView there is contentSize method which can get size of its content, I tried to find similar method in NSTextView but could not get any success :(


问:
Edit existing items in a Wordpress theme
I've created a homepage, that simply has a sentence as the content

I've edited the settings so that this the front page of the website.

However, given the theme that I am using, when I go to the home page, this is what I see

I can see the content of my home page at the very bottom, but before that, there is a slider and a couple of blocks (that presumably come with the theme).

I'd like to know either how to remove these default blocks, or edit them myself to include links to other pages.

Also, as you can probably tell, I am very new to Wordpress. Are there any good documentations for beginners that would teach me how to create pages, edit and customize them so that I can have control over the whole page (as a regular website)?

答:
I think you should edit by the php file, so if u don't know PHP start here.

Go to : menu > appereance > editor.

Here u see all the files you need. The file you should edit change with the theme.. so go through the code.

Maybe, it's under header.php


问:
AES encryption, InvalidKeyException: Unsupported key size: 6 bytes?
I am trying to encrypt a string as follows

```<code>public class AES256Cipher {
static byte[] ivBytes = new byte[]{0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76};
static String EncryptionKey = "abc123";

public static byte[] encrypt(String plainText)
        throws java.io.UnsupportedEncodingException,
        NoSuchAlgorithmException,
        NoSuchPaddingException,
        InvalidKeyException,
        InvalidAlgorithmParameterException,
        IllegalBlockSizeException,
        BadPaddingException {
    byte[] keyBytes = EncryptionKey.getBytes("UTF-8");

    AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
    SecretKeySpec newKey = new SecretKeySpec(keyBytes, "AES");
    Cipher cipher = null;
    cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, newKey, ivSpec);
    byte[] cipherData = cipher.doFinal(plainText.getBytes("UTF-8"));
    Log.e("cipher", Base64.encodeToString(cipherData, Base64.DEFAULT));
    return cipher.doFinal(plainText.getBytes("UTF-8"));
}
}
</code>```

I am getting this exception

```<code>java.security.InvalidKeyException: Unsupported key size: 6 bytes
at com.android.org.conscrypt.OpenSSLCipher$EVP_CIPHER$AES.checkSupportedKeySize(OpenSSLCipher.java:686)
at com.android.org.conscrypt.OpenSSLCipher.checkAndSetEncodedKey(OpenSSLCipher.java:442)
at com.android.org.conscrypt.OpenSSLCipher.engineInit(OpenSSLCipher.java:272)
at javax.crypto.Cipher.tryTransformWithProvider(Cipher.java:608)
at javax.crypto.Cipher.tryCombinations(Cipher.java:532)
at javax.crypto.Cipher.getSpi(Cipher.java:437)
at javax.crypto.Cipher.init(Cipher.java:909)
at javax.crypto.Cipher.init(Cipher.java:859)
at com.vfirst.util.netwrok.AES256Cipher.encrypt(AES256Cipher.java:36)
at com.vfirst.LoginActivity.onCreate(LoginActivity.java:61)
at android.app.Activity.performCreate(Activity.java:6321)
</code>```

String to encrypt

```<code>AES256Cipher.encrypt("12345");
</code>```

答:
AES allows 128, 192 and 256 bit of key length.
In other words 16, 24 or 32 byte.

Body:
I am trying to encrypt a string as follows

public class AES256Cipher {
static byte[] ivBytes = new byte[]{0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76};
static String EncryptionKey = "abc123";

public static byte[] encrypt(String plainText)
        throws java.io.UnsupportedEncodingException,
        NoSuchAlgorithmException,
        NoSuchPaddingException,
        InvalidKeyException,
        InvalidAlgorithmParameterException,
        IllegalBlockSizeException,
        BadPaddingException {
    byte[] keyBytes = EncryptionKey.getBytes("UTF-8");

    AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
    SecretKeySpec newKey = new SecretKeySpec(keyBytes, "AES");
    Cipher cipher = null;
    cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, newKey, ivSpec);
    byte[] cipherData = cipher.doFinal(plainText.getBytes("UTF-8"));
    Log.e("cipher", Base64.encodeToString(cipherData, Base64.DEFAULT));
    return cipher.doFinal(plainText.getBytes("UTF-8"));
}
}

I am getting this exception

java.security.InvalidKeyException: Unsupported key size: 6 bytes
at com.android.org.conscrypt.OpenSSLCipher$EVP_CIPHER$AES.checkSupportedKeySize(OpenSSLCipher.java:686)
at com.android.org.conscrypt.OpenSSLCipher.checkAndSetEncodedKey(OpenSSLCipher.java:442)
at com.android.org.conscrypt.OpenSSLCipher.engineInit(OpenSSLCipher.java:272)
at javax.crypto.Cipher.tryTransformWithProvider(Cipher.java:608)
at javax.crypto.Cipher.tryCombinations(Cipher.java:532)
at javax.crypto.Cipher.getSpi(Cipher.java:437)
at javax.crypto.Cipher.init(Cipher.java:909)
at javax.crypto.Cipher.init(Cipher.java:859)
at com.vfirst.util.netwrok.AES256Cipher.encrypt(AES256Cipher.java:36)
at com.vfirst.LoginActivity.onCreate(LoginActivity.java:61)
at android.app.Activity.performCreate(Activity.java:6321)

String to encrypt

AES256Cipher.encrypt("12345");


问:
Convert time in hh:mm:ss AM(PM) format (sql)
How do I convert time :  ' 8:02:24 AM ' into ' 08:02:24 AM ' so that all the time in a particular column is of fixed length.

I tried using different style values in convert function but couldn't get my desired result.

答:
Below sample code will add 0 based on the hour part length (1 or 2).</p>

```<code>declare @hour char(2)
    declare @time varchar(20)='8:02:24 PM'
    select @hour=substring(@time,1,charindex(':',@time)-1)
    if len(@hour)=1
    begin
       set @hour='0'+@hour
       set @time=@hour+substring(@time,charindex(':',@time),10)
    end
    select @time
</code>```

Body:
Below sample code will add 0 based on the hour part length (1 or 2).

declare @hour char(2)
    declare @time varchar(20)='8:02:24 PM'
    select @hour=substring(@time,1,charindex(':',@time)-1)
    if len(@hour)=1
    begin
       set @hour='0'+@hour
       set @time=@hour+substring(@time,charindex(':',@time),10)
    end
    select @time


问:
knockout.js initialize viewmodel from another viewmodel
This is my code

Viewmodel 1

```<code>function AppViewModel() {
var self = this;
self.boardtext = ko.observable();
self.board = ko.observableArray([
    { boardname: 'Board' },
    { boardname: 'Board' },
    { boardname: 'Board' }
]);

self.addboard = function () {
    self.board.push({ boardname: self.boardtext() });
    // initialize ListModal to zero
};

self.removeboard = function () {
    self.board.remove(this);
}
</code>```

}

Viewmodel 2

```<code> var initialData = [];

var ListModal = function (lists) {
    var self = this;
    self.cardtext = ko.observable();
    self.lists = ko.observableArray(ko.utils.arrayMap(lists, function (list) {
        return { listname: list.listname, cardlists: ko.observableArray(list.cardlists), showRenderTimes: ko.observable(false) };
    }));

};

ko.applyBindings(new AppViewModel(), document.getElementById("container1"));
ko.applyBindings(new ListModal(initialData), document.getElementById("container2"));
</code>```

As soon as i press addboard how can i set my ListModal to zero?

答:
If you want to re-initialize listModal, try to wrap those 2 viewmodels in 1 viewmodel so that they can relate to each other. And then you can do the following:</p>

```<code>var initialData = [];

var ListModal = function (lists) {
  var self = this;
  self.cardtext = ko.observable();
  self.lists = ko.observableArray(ko.utils.arrayMap(lists, function (list) {
    return { listname: list.listname, cardlists: ko.observableArray(list.cardlists), showRenderTimes: ko.observable(false) };
  }));
}

function AppViewModel(parent) {
  var self = this;

  // this will keep the object of ViewModel
  self.parentObject = parent;

  self.boardtext = ko.observable();
  self.board = ko.observableArray([
    { boardname: 'Board' },
    { boardname: 'Board' },
    { boardname: 'Board' }
  ]);

  self.addboard = function () {
    self.board.push({ boardname: self.boardtext() });

    // re-initialize listModal
    self.parentObject.listModal(new ListModal(initialData));
  };

  self.removeboard = function () {
    self.board.remove(this);
  };
}

function ViewModel() {
  var self = this;
  self.appViewModel = ko.observable(new AppViewModel(self));
  self.listModal = ko.observable(new ListModal(initialData));
}

// provide another div which wrap container 1 and 2 together
ko.applyBindings(new ViewModel(), document.getElementById("container1And2"));
</code>```

Body:
This is my code

Viewmodel 1

function AppViewModel() {
var self = this;
self.boardtext = ko.observable();
self.board = ko.observableArray([
    { boardname: 'Board' },
    { boardname: 'Board' },
    { boardname: 'Board' }
]);

self.addboard = function () {
    self.board.push({ boardname: self.boardtext() });
    // initialize ListModal to zero
};

self.removeboard = function () {
    self.board.remove(this);
}

}

Viewmodel 2

 var initialData = [];

var ListModal = function (lists) {
    var self = this;
    self.cardtext = ko.observable();
    self.lists = ko.observableArray(ko.utils.arrayMap(lists, function (list) {
        return { listname: list.listname, cardlists: ko.observableArray(list.cardlists), showRenderTimes: ko.observable(false) };
    }));

};

ko.applyBindings(new AppViewModel(), document.getElementById("container1"));
ko.applyBindings(new ListModal(initialData), document.getElementById("container2"));

As soon as i press addboard how can i set my ListModal to zero?

Body:
If you want to re-initialize listModal, try to wrap those 2 viewmodels in 1 viewmodel so that they can relate to each other. And then you can do the following:

var initialData = [];

var ListModal = function (lists) {
  var self = this;
  self.cardtext = ko.observable();
  self.lists = ko.observableArray(ko.utils.arrayMap(lists, function (list) {
    return { listname: list.listname, cardlists: ko.observableArray(list.cardlists), showRenderTimes: ko.observable(false) };
  }));
}

function AppViewModel(parent) {
  var self = this;

  // this will keep the object of ViewModel
  self.parentObject = parent;

  self.boardtext = ko.observable();
  self.board = ko.observableArray([
    { boardname: 'Board' },
    { boardname: 'Board' },
    { boardname: 'Board' }
  ]);

  self.addboard = function () {
    self.board.push({ boardname: self.boardtext() });

    // re-initialize listModal
    self.parentObject.listModal(new ListModal(initialData));
  };

  self.removeboard = function () {
    self.board.remove(this);
  };
}

function ViewModel() {
  var self = this;
  self.appViewModel = ko.observable(new AppViewModel(self));
  self.listModal = ko.observable(new ListModal(initialData));
}

// provide another div which wrap container 1 and 2 together
ko.applyBindings(new ViewModel(), document.getElementById("container1And2"));


问:
Mercurial.Net pullCommand using authorization
I am trying to pull code changes from Mercurial using Mercurial.NET library. I get an authorization exception and do not obtain any results, below is the code.

```<code>Repository repository = new Repository(@"D:\sandeep\work\20Dec2016");

PullCommand pullcommand = new PullCommand();
repository.Pull(pullcommand);
</code>```

This is my code, is there a way, I can specify my credentials (username and password) for authentication in order to pull the recent changes?

答:
I could achieve the result with the below code and help from Lasse V. Karlsen</p>

```<code>Repository repository = new Repository(@"D:\sandeep\Work\20Dec2016");
pullCommand.WithConfigurationOverride("auth", "x.prefix", "*");
pullCommand.WithConfigurationOverride("auth", "x.username", "ssk");
pullCommand.WithConfigurationOverride("auth", "x.password", "ssk");
repository.Pull(pullCommand);
</code>```

Body:
I am trying to pull code changes from Mercurial using Mercurial.NET library. I get an authorization exception and do not obtain any results, below is the code.

Repository repository = new Repository(@"D:\sandeep\work\20Dec2016");

PullCommand pullcommand = new PullCommand();
repository.Pull(pullcommand);

This is my code, is there a way, I can specify my credentials (username and password) for authentication in order to pull the recent changes?

Body:
I could achieve the result with the below code and help from Lasse V. Karlsen

Repository repository = new Repository(@"D:\sandeep\Work\20Dec2016");
pullCommand.WithConfigurationOverride("auth", "x.prefix", "*");
pullCommand.WithConfigurationOverride("auth", "x.username", "ssk");
pullCommand.WithConfigurationOverride("auth", "x.password", "ssk");
repository.Pull(pullCommand);


问:
How can i load a function again once more content has been added via jquery?
I am using this zoom image script to load thumbs into larger images:
http://www.eyecon.ro/zoomimage/#implement

The trouble is i'm loading the gallery after the page is loaded using jquery load (code below):

```<code>//Remove tab info and add gallery
 $(".more").click(function () {
  var $gallery = $(this).closest('.tab').find('.gallery'),
  cat = $(this).attr('href').split('cat=')[1];

  if ($gallery.is(':empty')) {
   $gallery.load('/public/themes/lbd/js/imagegallery.php', {'cat': cat}, function(){
    $(this).fadeIn();
   });
  }

  $gallery.siblings().fadeOut(function(){
   $gallery.fadeIn();
  });
  return false;
 });
</code>```

The trouble is this script creates the gallery on the fly so the code below won't work

```<code><script type="text/javascript">
    $(document).ready(function() {
        $('a.customGal').zoomimage();
    });
</script>
</code>```

How can i work in the code above to run once the gallery is loaded the so function completes?

I have tried to add the $('a.customGal').zoomimage(); within .load but it doesn't work still.

答:
If I understand your problem correctly, you're trying to create a gallery out of a.customGals, but your code isn't working because these anchors don't exist at page load. They're loaded from the .click.

If that is right, I believe this should work:

```<code>$gallery.load('/public/themes/lbd/js/imagegallery.php', {'cat': cat}, function(){
    $(this).fadeIn(function(){
        $('a.customGal').zoomimage();
    });
});
</code>```

That will call your plugin after the HTML has been appended to your page and has finished animating.

Body:
I am using this zoom image script to load thumbs into larger images:
http://www.eyecon.ro/zoomimage/#implement

The trouble is i'm loading the gallery after the page is loaded using jquery load (code below):

//Remove tab info and add gallery
 $(".more").click(function () {
  var $gallery = $(this).closest('.tab').find('.gallery'),
  cat = $(this).attr('href').split('cat=')[1];

  if ($gallery.is(':empty')) {
   $gallery.load('/public/themes/lbd/js/imagegallery.php', {'cat': cat}, function(){
    $(this).fadeIn();
   });
  }

  $gallery.siblings().fadeOut(function(){
   $gallery.fadeIn();
  });
  return false;
 });

The trouble is this script creates the gallery on the fly so the code below won't work

How can i work in the code above to run once the gallery is loaded the so function completes?

I have tried to add the $('a.customGal').zoomimage(); within .load but it doesn't work still.

Body:
If I understand your problem correctly, you're trying to create a gallery out of a.customGals, but your code isn't working because these anchors don't exist at page load. They're loaded from the .click.

If that is right, I believe this should work:

$gallery.load('/public/themes/lbd/js/imagegallery.php', {'cat': cat}, function(){
    $(this).fadeIn(function(){
        $('a.customGal').zoomimage();
    });
});

That will call your plugin after the HTML has been appended to your page and has finished animating.


问:
C++ equivalent of fgets for reading from popen
I need to process some data from standard output. Here is the code I am using:

```<code>FILE* in;
in = popen("ls -a", "r");
char line[256]
while (fgets(line, sizeof(line), in) != NULL) {
    // do something with line
}
</code>```

Which works fine but there is a problem if the line is longer than 256 bytes. So now I tried the following but it is not a good solution:

```<code>FILE* in;
in = popen("ls -a", "r");
char line[100000000] // Wow
while (fgets(line, sizeof(line), in) != NULL) {
    // do something with line
}
</code>```

How do I use c++ to avoid having to specify the line size? I.e. be able to handle a line of any length?

Edit, getline doesn't work! :=[[

```<code>FILE *in;
std::string line;
while(std::getline(in, line))
{
   // Says no matching function =((((
}
</code>```

答:
A C++ solution would use std::string instead of char[], std::getline instead of fgets(), and input streams instead of FILE *.

The one problem is the POSIX function popen() -- for which various C++ alternatives exist, among others...

PStreams

```<code>#include "pstream.h"
#include <string>
#include <iostream>

int main()
{
    redi::ipstream is("ls -a");
    std::string line;
    while (std::getline(is, line))
    {
        std::cout << line << std::endl;
    }
}
</code>```

Boost.Process (as of 1.64 "officially" part of Boost.org)

```<code>#include "boost/process.hpp"
#include <string>
#include <vector>
#include <iostream>

int main()
{
    boost::process::context ctx;
    ctx.stdout_behavior = boost::process::capture_stream();

    std::string exe( "ls" );
    std::vector< std::string > args;
    args.push_back( "-a" );

    boost::process::child c = boost::process::launch( exe, args, ctx);

    boost::process::pistream &is = c.get_stdout();

    std::string line;
    while (std::getline(is, line))
    {
        std::cout << line << std::endl;
    }
}
</code>```

Body:
I need to process some data from standard output. Here is the code I am using:

FILE* in;
in = popen("ls -a", "r");
char line[256]
while (fgets(line, sizeof(line), in) != NULL) {
    // do something with line
}

Which works fine but there is a problem if the line is longer than 256 bytes. So now I tried the following but it is not a good solution:

FILE* in;
in = popen("ls -a", "r");
char line[100000000] // Wow
while (fgets(line, sizeof(line), in) != NULL) {
    // do something with line
}

How do I use c++ to avoid having to specify the line size? I.e. be able to handle a line of any length?

Edit, getline doesn't work! :=[[

FILE *in;
std::string line;
while(std::getline(in, line))
{
   // Says no matching function =((((
}

Body:
A C++ solution would use std::string instead of char[], std::getline instead of fgets(), and input streams instead of FILE *.

The one problem is the POSIX function popen() -- for which various C++ alternatives exist, among others...

PStreams

#include "pstream.h"
#include <string>
#include <iostream>

int main()
{
    redi::ipstream is("ls -a");
    std::string line;
    while (std::getline(is, line))
    {
        std::cout << line << std::endl;
    }
}

Boost.Process (as of 1.64 "officially" part of Boost.org)

#include "boost/process.hpp"
#include <string>
#include <vector>
#include <iostream>

int main()
{
    boost::process::context ctx;
    ctx.stdout_behavior = boost::process::capture_stream();

    std::string exe( "ls" );
    std::vector< std::string > args;
    args.push_back( "-a" );

    boost::process::child c = boost::process::launch( exe, args, ctx);

    boost::process::pistream &is = c.get_stdout();

    std::string line;
    while (std::getline(is, line))
    {
        std::cout << line << std::endl;
    }
}


问:
how to delete root tag in xml C#
hi following XML is my input XML

```<code><?xml version="1.0" encoding="utf-8"?>
      <units xmlns="http://www.elsevier.com/xml/ani/ani" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ce="http://www.elsevier.com/xml/ani/common" xsi:schemaLocation="http://www.elsevier.com/xml/ani/ani http://www.elsevier.com/xml/ani/ani512-input-CAR.xsd">
<unit type="journal" xmlns="">
<unit-info>
  <timestamp>2017-01-08T02:03:14Z</timestamp>
  <order-id>12535892</order-id>
  <parcel-id>none</parcel-id>
  <unit-id>4756202</unit-id>
</unit-info>
<unit-content>
  <bibrecord>
    <item-info>
      <status state="new" stage="S300" />
    </item-info>
    <head>
      <citation-info>
        <citation-type code="jo" />
        <citation-language xmllang="ENG" />
        <abstract-language xmllang="ENG" />
        <author-keywords>
          <author-keyword>Stroke</author-keyword>
          <author-keyword> cerebral ischaemia</author-keyword>
          <author-keyword> Neuro-protection</author-keyword>
          <author-keyword> Neuro-protective agents</author-keyword>
        </author-keywords>
      </citation-info>
      <citation-title xmllang="ENG" original="y">
        <titletext>PATHOGENESIS AND NEURO-PROTECTIVE AGENTS OF STROKE</titletext>
      </citation-title>
      <abstracts>
        <abstract>
          <cepara>ABSTRACT: Stroke remains worlds second leading cause of mortality; and globally most frequent cause of long-lasting disabilities. The ischaemic pathophysiologic cascade leading to neuronal damage consists of peri-infarct depolarization, excitotoxicity, inflammation, oxidative stress, and apoptosis. Despite plethora of experimental evidences and advancement into the development of treatments, clinical treatment of acute stroke still remains challenging. Neuro-protective agents, as novel therapeutic strategy confer neuro-protection by targeting the pathophysiologic mechanism of stroke. The aim of this review is discussion of summary of the literature on stroke pathophysiology, current preclinical research findings of neuroprotective agents in stroke and possible factors that were responsible for the failure of these agents to translate in human stroke therapies.</cepara>
        </abstract>
      </abstracts>
      <correspondence>
        <person>
          <ceinitials>M.</ceinitials>
          <cesurname>Mubarak</cesurname>
        </person>
        <affiliation>
          <organization> Bayero University Kano</organization>
          <organization> Nigeria. Email: mubarakmahmad@yahoo.com</organization>
        </affiliation>
      </correspondence>
      <root>
        <author Seq="0">
          <Inital>A.El</Inital>
          <Surname>Khattabi</Surname>
          <Givenname>Abdelkrim</Givenname>
        </author>
      </root>
    </head>
  </bibrecord>
</unit-content>
</code>```

from this xml i need to delete root tag alone but i need all child element

```<code>        <author Seq="0">
          <Inital>A.El</Inital>
          <Surname>Khattabi</Surname>
          <Givenname>Abdelkrim</Givenname>
        </author>
</code>```

how to delete root tag alone. For this i followed following code

```<code>  XDocument CarXML = new XDocument();
        CarXML.Add(Root);
        CarXML.Descendants("root").Remove();
        CarXML.Save(@"CAR.XML");
</code>```

But this code delete all xml tag. How to delete root element alone.  i need child element

答:
```<code>CarXML.ReplaceNodes(CarXML.Descendants("author").FirstOrDefault());
</code>```

This replaces the whole content of the XML with the first descendant named author.

Title: how to delete root tag in xml C#

Body:
hi following XML is my input XML

<?xml version="1.0" encoding="utf-8"?>
      <units xmlns="http://www.elsevier.com/xml/ani/ani" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ce="http://www.elsevier.com/xml/ani/common" xsi:schemaLocation="http://www.elsevier.com/xml/ani/ani http://www.elsevier.com/xml/ani/ani512-input-CAR.xsd">
<unit type="journal" xmlns="">
<unit-info>
  <timestamp>2017-01-08T02:03:14Z</timestamp>
  <order-id>12535892</order-id>
  <parcel-id>none</parcel-id>
  <unit-id>4756202</unit-id>
</unit-info>
<unit-content>
  <bibrecord>
    <item-info>
      <status state="new" stage="S300" />
    </item-info>

      <citation-info>
        <citation-type code="jo" />
        <citation-language xmllang="ENG" />
        <abstract-language xmllang="ENG" />
        <author-keywords>
          <author-keyword>Stroke</author-keyword>
          <author-keyword> cerebral ischaemia</author-keyword>
          <author-keyword> Neuro-protection</author-keyword>
          <author-keyword> Neuro-protective agents</author-keyword>
        </author-keywords>
      </citation-info>
      <citation-title xmllang="ENG" original="y">
        <titletext>PATHOGENESIS AND NEURO-PROTECTIVE AGENTS OF STROKE</titletext>
      </citation-title>
      <abstracts>
        <abstract>
          <cepara>ABSTRACT: Stroke remains worlds second leading cause of mortality; and globally most frequent cause of long-lasting disabilities. The ischaemic pathophysiologic cascade leading to neuronal damage consists of peri-infarct depolarization, excitotoxicity, inflammation, oxidative stress, and apoptosis. Despite plethora of experimental evidences and advancement into the development of treatments, clinical treatment of acute stroke still remains challenging. Neuro-protective agents, as novel therapeutic strategy confer neuro-protection by targeting the pathophysiologic mechanism of stroke. The aim of this review is discussion of summary of the literature on stroke pathophysiology, current preclinical research findings of neuroprotective agents in stroke and possible factors that were responsible for the failure of these agents to translate in human stroke therapies.</cepara>
        </abstract>
      </abstracts>
      <correspondence>
        <person>
          <ceinitials>M.</ceinitials>
          <cesurname>Mubarak</cesurname>
        </person>
        <affiliation>
          <organization> Bayero University Kano</organization>
          <organization> Nigeria. Email: mubarakmahmad@yahoo.com</organization>
        </affiliation>
      </correspondence>
      <root>
        <author Seq="0">
          <Inital>A.El</Inital>
          <Surname>Khattabi</Surname>
          <Givenname>Abdelkrim</Givenname>
        </author>
      </root>

  </bibrecord>
</unit-content>

from this xml i need to delete root tag alone but i need all child element

        <author Seq="0">
          <Inital>A.El</Inital>
          <Surname>Khattabi</Surname>
          <Givenname>Abdelkrim</Givenname>
        </author>

how to delete root tag alone. For this i followed following code

  XDocument CarXML = new XDocument();
        CarXML.Add(Root);
        CarXML.Descendants("root").Remove();
        CarXML.Save(@"CAR.XML");

But this code delete all xml tag. How to delete root element alone.  i need child element

Body:
CarXML.ReplaceNodes(CarXML.Descendants("author").FirstOrDefault());

This replaces the whole content of the XML with the first descendant named author.


问:
PDF file printing on client side using javascript
I am trying to print a pdf file on the client side using javascript. My javascript code is as below

```<code>function doit() {
    var win = document.getElementById("pdf");
    var frm = document.getElementById("pdf").contentWindow;
    frm.print();
    win.print();
}
</code>```

The problem is that frm is always null and win does not have a function of print

My pdf element is as below

```<code><iframe id="pdf" name="pdf" src="C:\My_P.pdf"></iframe>
</code>```

I am calling the function from c# as below

```<code>ClientScript.RegisterStartupScript(this.GetType(), "Print", "doit();", true);
</code>```

Really struggling. Please help

答:
The solution to your problem is to call print function after Iframe has been loaded, you may not need to call it from server using RegisterStartupScript

```<code><iframe id="pdf" name="pdf" src="C:\My_P.pdf"
     onload="doit();"></iframe>
</code>```

Another problem seems to be src path C:\My_P.pdf,  I frame is expecting a url to display content. refer Iframe

To mitigate this, create a directory e.g. MyResource within your asp.net project and copy your pdf to this directory and change src="/MyResource/My_P.pdf". Your pdf should be a accessible to browser then only Iframe can load it.

Body:
I am trying to print a pdf file on the client side using javascript. My javascript code is as below

function doit() {
    var win = document.getElementById("pdf");
    var frm = document.getElementById("pdf").contentWindow;
    frm.print();
    win.print();
}

The problem is that frm is always null and win does not have a function of print

My pdf element is as below

I am calling the function from c# as below

ClientScript.RegisterStartupScript(this.GetType(), "Print", "doit();", true);

Really struggling. Please help

Body:
The solution to your problem is to call print function after Iframe has been loaded, you may not need to call it from server using RegisterStartupScript

<iframe id="pdf" name="pdf" src="C:\My_P.pdf"
     onload="doit();"></iframe>

Another problem seems to be src path C:\My_P.pdf,  I frame is expecting a url to display content. refer Iframe

To mitigate this, create a directory e.g. MyResource within your asp.net project and copy your pdf to this directory and change src="/MyResource/My_P.pdf". Your pdf should be a accessible to browser then only Iframe can load it.


问:
How to return colour of point in scatterplot Python
Is there a way to obtain the colour (or a simple yes/no answer if colour is present) from the x, y coordinates of a matplotlib scatterplot?

Basically I want to give a coordinate (x, y) and know if there is a coloured circle at that position in my plot.

Any help will be appreciated.

答:
To determine if there is a scatter circle at a position (xi,yi) is not straight forward. The problem is that (xi,yi) are given in data coordinates, while the circle is drawn as a circle in display coordinates. This means that the circle in display coordinates might acutally be an ellipse in data coordinates, when the axis scaling is different for x and y axis.

Matplotlib contains some functionality to determine if a point given in display coordinates is within the extent of an artist. I order to use this, the canvas first has to be drawn. One might then simulate a mouse event at the position (xi,yi) and detect if it hits any artist from the scatter. The respective color can then be retrieved.

```<code>import numpy as np; np.random.seed(0)
import matplotlib.pyplot as plt
import matplotlib.backend_bases

x = np.random.rayleigh(size=10)
y = np.random.normal(size=10)
c = np.random.rand(10)

fig, ax = plt.subplots()
sc = ax.scatter(x,y,c=c, s=49, picker=True)

fig.canvas.draw()

def color_at_pos(xi,yi):
    xi, yi = ax.transData.transform((xi,yi))
    me = matplotlib.backend_bases.LocationEvent("no", fig.canvas, xi, yi)
    cont, ind = sc.contains(me)
    return sc.cmap(sc.norm(sc.get_array()[ind["ind"]]))

col = color_at_pos(1.25931,0.145889)
print col
col = color_at_pos(0.7,0.7)
print col

plt.show()
</code>```

Here the first point (1.25931,0.145889) is actuall within two circles, so two colors are printed, while the second point is not in any circle and an empty array is printed.

Body:
To determine if there is a scatter circle at a position (xi,yi) is not straight forward. The problem is that (xi,yi) are given in data coordinates, while the circle is drawn as a circle in display coordinates. This means that the circle in display coordinates might acutally be an ellipse in data coordinates, when the axis scaling is different for x and y axis.

Matplotlib contains some functionality to determine if a point given in display coordinates is within the extent of an artist. I order to use this, the canvas first has to be drawn. One might then simulate a mouse event at the position (xi,yi) and detect if it hits any artist from the scatter. The respective color can then be retrieved.

import numpy as np; np.random.seed(0)
import matplotlib.pyplot as plt
import matplotlib.backend_bases

x = np.random.rayleigh(size=10)
y = np.random.normal(size=10)
c = np.random.rand(10)

fig, ax = plt.subplots()
sc = ax.scatter(x,y,c=c, s=49, picker=True)

fig.canvas.draw()

def color_at_pos(xi,yi):
    xi, yi = ax.transData.transform((xi,yi))
    me = matplotlib.backend_bases.LocationEvent("no", fig.canvas, xi, yi)
    cont, ind = sc.contains(me)
    return sc.cmap(sc.norm(sc.get_array()[ind["ind"]]))

col = color_at_pos(1.25931,0.145889)
print col
col = color_at_pos(0.7,0.7)
print col

plt.show()

Here the first point (1.25931,0.145889) is actuall within two circles, so two colors are printed, while the second point is not in any circle and an empty array is printed.


问:
Cannot edit EditText in AlertDialog
I am trying to get a value from the user the first time the app is opened. I am inflating an AlertDialog to get the value from the user. I am not able to input any text into the EditText, eventhough I can see the cursor blinking.

The code in MainActivity

```<code>SharedPreferences sharedPreferences = getSharedPreferences("hasRunBefore", 0);
        boolean hasRun = sharedPreferences.getBoolean("hasRun", false);
        if (!hasRun) {
            SharedPreferences.Editor edit = sharedPreferences.edit();
            edit.putBoolean("hasRun", true);

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            LayoutInflater layoutInflater = LayoutInflater.from(this);
            final View dialogView = layoutInflater.inflate(R.layout.alertdialog, null);
            final EditText editText = (EditText) dialogView.findViewById(R.id.alert_dialog_editText);
            builder.setView(dialogView)
                    .setPositiveButton("Okay", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            editText.requestFocus();
                            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                            imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
                            regNum = editText.getText().toString();
                        }
                    })
                    .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    });
            builder.show();
            edit.putString("registerNumber", regNum);
            edit.apply();
            TextView textView = (TextView) findViewById(R.id.regNum_textView);
            textView.setText(regNum);
        } else {
            //code if the app HAS run before
            TextView textView = (TextView) findViewById(R.id.regNum_textView);
            textView.setText(regNum);
        }
</code>```

The layout file is

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/alertDialog"
    >

    <TextView
        android:id="@+id/alert_dialog_textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enter Your Register Number"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="33dp" />

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/alert_dialog_editText"
        android:hint="Type your register number here"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:layout_below="@+id/alert_dialog_textview"
         />

</RelativeLayout>
</code>```

What am I doing wrong?

答:
Try this code:</p>

```<code>// get yourView.xml view
                LayoutInflater li = LayoutInflater.from(context);
                View promptsView = li.inflate(R.layout.yourView, null);

                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                        context);

                // set prompts.xml to alertdialog builder
                alertDialogBuilder.setView(promptsView);

                final EditText userInput = (EditText) promptsView
                        .findViewById(R.id.editTextDialogUserInput);

                // set dialog message
                alertDialogBuilder
                    .setCancelable(false)
                    .setPositiveButton("OK",
                      new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,int id) {
                        // get user input and set it to result
                        // edit text
                        result.setText(userInput.getText());
                        }
                      })
                    .setNegativeButton("Cancel",
                      new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,int id) {
                        dialog.cancel();
                        }
                      });

                // create alert dialog
                AlertDialog alertDialog = alertDialogBuilder.create();

                // show it
                alertDialog.show();
</code>```

Title: Cannot edit EditText in AlertDialog

Body:
I am trying to get a value from the user the first time the app is opened. I am inflating an AlertDialog to get the value from the user. I am not able to input any text into the EditText, eventhough I can see the cursor blinking.

The code in MainActivity

SharedPreferences sharedPreferences = getSharedPreferences("hasRunBefore", 0);
        boolean hasRun = sharedPreferences.getBoolean("hasRun", false);
        if (!hasRun) {
            SharedPreferences.Editor edit = sharedPreferences.edit();
            edit.putBoolean("hasRun", true);

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            LayoutInflater layoutInflater = LayoutInflater.from(this);
            final View dialogView = layoutInflater.inflate(R.layout.alertdialog, null);
            final EditText editText = (EditText) dialogView.findViewById(R.id.alert_dialog_editText);
            builder.setView(dialogView)
                    .setPositiveButton("Okay", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            editText.requestFocus();
                            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                            imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
                            regNum = editText.getText().toString();
                        }
                    })
                    .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    });
            builder.show();
            edit.putString("registerNumber", regNum);
            edit.apply();
            TextView textView = (TextView) findViewById(R.id.regNum_textView);
            textView.setText(regNum);
        } else {
            //code if the app HAS run before
            TextView textView = (TextView) findViewById(R.id.regNum_textView);
            textView.setText(regNum);
        }

The layout file is

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/alertDialog"
    >

    <TextView
        android:id="@+id/alert_dialog_textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enter Your Register Number"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="33dp" />

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/alert_dialog_editText"
        android:hint="Type your register number here"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:layout_below="@+id/alert_dialog_textview"
         />

</RelativeLayout>

What am I doing wrong?

Body:
Try this code:

// get yourView.xml view
                LayoutInflater li = LayoutInflater.from(context);
                View promptsView = li.inflate(R.layout.yourView, null);

                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                        context);

                // set prompts.xml to alertdialog builder
                alertDialogBuilder.setView(promptsView);

                final EditText userInput = (EditText) promptsView
                        .findViewById(R.id.editTextDialogUserInput);

                // set dialog message
                alertDialogBuilder
                    .setCancelable(false)
                    .setPositiveButton("OK",
                      new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,int id) {
                        // get user input and set it to result
                        // edit text
                        result.setText(userInput.getText());
                        }
                      })
                    .setNegativeButton("Cancel",
                      new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,int id) {
                        dialog.cancel();
                        }
                      });

                // create alert dialog
                AlertDialog alertDialog = alertDialogBuilder.create();

                // show it
                alertDialog.show();


问:
Writing array a new python file
I have 10 files in a folder. I want to make an array with no of folder and multiply with a variable. As I am new in programming, I am not sure how to perform this. Will it be fine to perform like this,

```<code>import numpy as np
folder=/home/foldername/
startfile=[0]
endfile=[9]
x=[0.5]
for i in range(startfile,endfile):
    newarray=[i+x]
    i+=1
    print(newarray)
</code>```

it is expected to print

```<code>newarray=[0.5,1.5,2.5,3.5,4.5,5.5,6.5,7.5,8.5,9.5]
</code>```

答:
A much simpler way to get the array you want is

```<code>>>> newarray = [x + 0.5 for x in range(1, 10)]
>>> newarray
[1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5]
</code>```

As it stands what you are trying to do instead has several mistakes.

First, range expects integers, but you give it lists:

```<code>>>> startfile=[0]
>>> endfile=[9]
>>> for i in range(startfile,endfile):
...   print i

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: range() integer end argument expected, got list.
</code>```

[0] is a list containing 0; just make startfile = 0, and likewise for endfile

```<code>>>> startfile=0
>>> endfile=9
>>> for i in range(startfile,endfile):
...   print i
...
0
1
2
3
4
5
6
7
8
</code>```

Notice this go up to but not including 9.

Now, you have i+=1 in your loop, I suspect because you want tomake sure it gets incremented, but the for loop does that for you.

Finally, you have newarray=[i+x], which will reset newarray each time round the loop. If you want to append things to a loop, do just that.

```<code>>>> newarray = []
>>> for i in range(startfile,endfile):
...   newarray.append(i + 0.5)
...
>>> newarray
[0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5]
</code>```

Again, note you probably want endfile to be one larger.

ContentLicense: CC BY-SA 4.0

Title: Writing array a new python file

Body:
I have 10 files in a folder. I want to make an array with no of folder and multiply with a variable. As I am new in programming, I am not sure how to perform this. Will it be fine to perform like this,

import numpy as np
folder=/home/foldername/
startfile=[0]
endfile=[9]
x=[0.5]
for i in range(startfile,endfile):
    newarray=[i+x]
    i+=1
    print(newarray)

it is expected to print

newarray=[0.5,1.5,2.5,3.5,4.5,5.5,6.5,7.5,8.5,9.5]

Body:
A much simpler way to get the array you want is

>>> newarray = [x + 0.5 for x in range(1, 10)]
>>> newarray
[1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5]

As it stands what you are trying to do instead has several mistakes.

First, range expects integers, but you give it lists:

>>> startfile=[0]
>>> endfile=[9]
>>> for i in range(startfile,endfile):
...   print i

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: range() integer end argument expected, got list.

[0] is a list containing 0; just make startfile = 0, and likewise for endfile

>>> startfile=0
>>> endfile=9
>>> for i in range(startfile,endfile):
...   print i
...
0
1
2
3
4
5
6
7
8

Notice this go up to but not including 9.

Now, you have i+=1 in your loop, I suspect because you want tomake sure it gets incremented, but the for loop does that for you.

Finally, you have newarray=[i+x], which will reset newarray each time round the loop. If you want to append things to a loop, do just that.

>>> newarray = []
>>> for i in range(startfile,endfile):
...   newarray.append(i + 0.5)
...
>>> newarray
[0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5]

Again, note you probably want endfile to be one larger.


问:
Content sent through jQuery ajax is getting cut off
I am trying to send html via jQuery's $.ajax() method, and then dump the html into a new .html file, but the content is getting cut off for some reason.

I have set up a test case:

```<code><html>

<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script >
$(document).ready(function(){
      var contents = $('html').html();
      var filename = "test/000.html";
      $.ajax({
         type: "POST",
         url: "/file.php",
         data: "content="+contents+"&fn="+filename,
         dataType: "html",
         success: function(msg, ts, xh){
             console.log(msg);
             console.log(ts);
             console.log(xh);
             alert("success");
         },
         processData: false,
         error: function(X, textStatus, error){
             alert("Error saving... please try again now.")
         }
     });
});
</script>

</head>

<body>

<div id="rteContainer" class="dev">
  <div id="textEditor">
    <form>
    <textarea name="balh" id="balh" rows="25" cols="103"></textarea>
    <input type="button" id="updateContent" value="Update Changes">
    <input type="button" id="closeEditor" value="Close Without Saving">
    </form>
  </div>
</div>

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

the file.php file is:

```<code><?php
header("Content-type:text/html;charset:UTF-8");
$content = "<html>".stripslashes(urldecode($_POST["content"]))."</html>";
$dump_file = $_POST["fn"];
$fp = fopen($dump_file, 'w');
fclose($fp);
echo $content;
?>
</code>```

Why is is getting cut off? I'm guessing it's come encoding problem, but I can't figure this out.

答:
Your script is dying of embarrassment at the massive security hole in it.

Never, ever, write into a file where the filename is a form parameter without validating the filename first.  Even a novice hacker could use this script to overwrite any file on your system that the webserver has access to.

In your Ajax call, pass a { } style array of key value pairs in the data parameter, don't concatenate the variables with ampersands yourself:

```<code>data: { content: contents,
        fn: filename }
</code>```

Oh, and you're never actually writing the content into the dumpfile, so whatever file 'fn' points at will just get truncated.

Hope that helps...

Body:
I am trying to send html via jQuery's $.ajax() method, and then dump the html into a new .html file, but the content is getting cut off for some reason.

I have set up a test case:

    <form>
    <textarea name="balh" id="balh" rows="25" cols="103"></textarea>
    <input type="button" id="updateContent" value="Update Changes">
    <input type="button" id="closeEditor" value="Close Without Saving">
    </form>

the file.php file is:

<?php
header("Content-type:text/html;charset:UTF-8");
$content = "".stripslashes(urldecode($_POST["content"]))."";
$dump_file = $_POST["fn"];
$fp = fopen($dump_file, 'w');
fclose($fp);
echo $content;
?>

Why is is getting cut off? I'm guessing it's come encoding problem, but I can't figure this out.

Body:
Your script is dying of embarrassment at the massive security hole in it.

Never, ever, write into a file where the filename is a form parameter without validating the filename first.  Even a novice hacker could use this script to overwrite any file on your system that the webserver has access to.

In your Ajax call, pass a { } style array of key value pairs in the data parameter, don't concatenate the variables with ampersands yourself:

data: { content: contents,
        fn: filename }

Oh, and you're never actually writing the content into the dumpfile, so whatever file 'fn' points at will just get truncated.

Hope that helps...


问:
Running a diffent code for each block of file
I have an output file from some numeric calculation. The output file looks like

aa ab ac ad ae   ┐

  ba bb bc bd be   ┘  Block of 5 strings

  0.5 1.2 0.3 aaa bbb  ┐

  0.2 8.2 3.3 ccc ddd  ┃ Block of 3 float + 2 string

  0.5 1.3 0.6 eee ggg  ┘

  0.11  0.444  0.333 0.777 0.88  ┐

  0.41  0.544  0.313 0.797 0.01 ┃

  0.11  0.447  0.333 0.777 0.88 ┃  Block of 6 float

  0.17  0.444  0.333 0.787 0.03 ┃

  0.11  0.444  0.333 0.777 0.88 ┘

which means, it forms block of some patterns. What I want to do is to read this file, and do some stuff for each block seperately.

For the simplest approach, I wrote the code like

```<code>file = open("myfile", "r")
for i, line in enumerate(file):
    if i <= 1:
        # do some stuff 1.
    elif 1< i <=4 :
        # do some stuff 2
    elif 4 < i :
        # do some stuff 3
file.close()
</code>```

and specify the line number manually whenever I run the program. The problem is that the line number of output file varies from file to file (but the pattern is same), and before I check it manually by eye, I don't know how long each block will be. What is the efficient approach handling this problem?

The size of each file is about 100~1000MB, and each contains about 500000~ 5000000 lines.

Body:
I have an output file from some numeric calculation. The output file looks like

aa ab ac ad ae   ┐

  ba bb bc bd be   ┘  Block of 5 strings

  0.5 1.2 0.3 aaa bbb  ┐

  0.2 8.2 3.3 ccc ddd  ┃ Block of 3 float + 2 string

  0.5 1.3 0.6 eee ggg  ┘

  0.11  0.444  0.333 0.777 0.88  ┐

  0.41  0.544  0.313 0.797 0.01 ┃

  0.11  0.447  0.333 0.777 0.88 ┃  Block of 6 float

  0.17  0.444  0.333 0.787 0.03 ┃

  0.11  0.444  0.333 0.777 0.88 ┘

which means, it forms block of some patterns. What I want to do is to read this file, and do some stuff for each block seperately.

For the simplest approach, I wrote the code like

file = open("myfile", "r")
for i, line in enumerate(file):
    if i <= 1:
        # do some stuff 1.
    elif 1< i <=4 :
        # do some stuff 2
    elif 4 < i :
        # do some stuff 3
file.close()

and specify the line number manually whenever I run the program. The problem is that the line number of output file varies from file to file (but the pattern is same), and before I check it manually by eye, I don't know how long each block will be. What is the efficient approach handling this problem?

The size of each file is about 100~1000MB, and each contains about 500000~ 5000000 lines.

Body:
Here is another approach:

a = '''aa ab ac ad ae
ba bb bc bd be
0.5 1.2 0.3 aaa bbb
0.2 8.2 3.3 ccc ddd
0.5 1.3 0.6 eee ggg
0.11 0.444 0.333 0.777 0.88
0.41 0.544 0.313 0.797 0.01
0.11 0.447 0.333 0.777 0.88
0.17 0.444 0.333 0.787 0.03
0.11 0.444 0.333 0.777 0.88'''

for line in a.split('\n'):
    if line[0].isalpha():
        print 'Group1'
    elif line[0].isdigit() and line[-1].isalpha():
        print 'Group2'
    elif line[0].isdigit() and line[-1].isdigit():
        print 'Group3'


问:
Get html input type value in lightning JS controller
I am stuck with one issue regarding lightning components, I am using

<input type="date" aura.id="Wellness Visit" class="inpText" format="MM/dd/yyyy" value="{!v.visitDate}" /> element

Calendar is appearing but not able to get the value in controller.

```<code>var inputDate = component.find("Wellness Visit").get("v.value");
console.log('*****inputDate****'+inputDate);
</code>```

Getting undefined in the log

Please suggest any other way i can get the html elament value.

Thanks in advance!

答:
Thanks @chinmayahd,

Finally i got the solution here,

enter link description here

Check answer given by Boog, i am using

You can check the following screenshot.

Body:
I am stuck with one issue regarding lightning components, I am using

<input type="date" aura.id="Wellness Visit" class="inpText" format="MM/dd/yyyy" value="{!v.visitDate}" /> element

Calendar is appearing but not able to get the value in controller.

var inputDate = component.find("Wellness Visit").get("v.value");
console.log('*****inputDate****'+inputDate);

Getting undefined in the log

Please suggest any other way i can get the html elament value.

Thanks in advance!


问:
How to overcome IO Error 13 in Python when running script using qBittorrent
I download a lot of linux ISOs torrents from the internet. I have made my own little python script that will send a notification to my iPhone about the details of the torrent that has finished downloading. Sends me the name, label and size of the torrent.

I use a python library called Pushbullet.py to send the notifications to my phone.

```<code>import os , sys, string, time, random
from datetime import datetime
from os import linesep
from pushbullet import Pushbullet

#Random Sys.Argv replacements
names = ['ubuntu-16.04.1-desktop-amd64.iso', 'Kali-Linux', 'Linux-Mind', 'dog', 'Arch-Linux']
labels = ['Movie', 'TV Show', 'Music', 'Program' ,'Game', 'eBook']
sizes = ['5000000000', '2000000000', '777758998000']
name_rand = (random.choice(names))
label_rand = (random.choice(labels))
sizes_rand = (random.choice(sizes))

#System arguments passed from qBittorrent to this script. This usually should be sys.argv[1-3] but changed for this case.
torrent_name = name_rand
torrent_category = label_rand
torrent_size = sizes_rand

qbittorrent_byte = Decimal(torrent_size)
mebibyte_divisor = Decimal(1048576)
mebibyte_value = qbittorrent_byte / mebibyte_divisor
mebibyte_string = str(round(mebibyte_value,2))

#Pushbullet Config
pb = Pushbullet("API-KEY")
iPhone = pb.devices[0]

t = time.localtime()
date_run = time.asctime(t)

#Pushbullet message templates
pb_title = torrent_category + " Download Completed"
pb_message = "Torrent: " + torrent_name + "\n" + "Size: " + mebibyte_string + " MB" + "\n" + "Label: " + torrent_category + "\n" + "Run on: " + date_run
pb_debug = date_run + "\n" + "Torrent: " + torrent_name + "\n" + "Size: " + mebibyte_string + " MB" + "\n" + "Label: " + torrent_category

def Send_Push():
    push = iPhone.push_note(pb_title, pb_message)
    print "PUSH sent successfully"

def write_file():
    file = open("debug.txt", "a")
    pb_message_debug = date_run + "\n" + "Torrent: " + torrent_name + "\n" + "Size: " + mebibyte_string + " MB" + "\n" + "Label: " + torrent_category
    file.write(pb_message_debug + "\n")
    file.close()

Send_Push()
write_file()
</code>```

This script can be used to send test messages to my phone. When I save this file to the desktop and run it using CMD, it sends the message to my phone and even write the debug.txt file as it is supposed to.

But when I try to configure qBittorrent to run the script whenever a download has finished, it sends the message to my phone, but does not append to the debug.txt file.

Whenever I try to run the script using the CMD, it totally works. Sends the message to my phone and appends to debug.txt

It is my theory that qBittorrent is why I am getting IO Error 13 Permission Denied..

Help a guy out? Open to any changes..

答:
The problem most probably is that you are specifying the path of the debug.txt file relatively. The following line will create a file in the current working directory named debug.txt.

```<code>file = open("debug.txt", "a")
</code>```

If your torrent app runs the script using a working directory that you don't have write access to by default (e.g. your programs folder), you will get a permission denied error.

Try to change the path to something absolute (a location where you have write access, e.g. your home folder):

```<code>file = open(r"C:\users\your_username_here\debug.txt", "a")
</code>```

This should fix the issue.

Body:
I download a lot of linux ISOs torrents from the internet. I have made my own little python script that will send a notification to my iPhone about the details of the torrent that has finished downloading. Sends me the name, label and size of the torrent.

I use a python library called Pushbullet.py to send the notifications to my phone.

import os , sys, string, time, random
from datetime import datetime
from os import linesep
from pushbullet import Pushbullet

#Random Sys.Argv replacements
names = ['ubuntu-16.04.1-desktop-amd64.iso', 'Kali-Linux', 'Linux-Mind', 'dog', 'Arch-Linux']
labels = ['Movie', 'TV Show', 'Music', 'Program' ,'Game', 'eBook']
sizes = ['5000000000', '2000000000', '777758998000']
name_rand = (random.choice(names))
label_rand = (random.choice(labels))
sizes_rand = (random.choice(sizes))

#System arguments passed from qBittorrent to this script. This usually should be sys.argv[1-3] but changed for this case.
torrent_name = name_rand
torrent_category = label_rand
torrent_size = sizes_rand

qbittorrent_byte = Decimal(torrent_size)
mebibyte_divisor = Decimal(1048576)
mebibyte_value = qbittorrent_byte / mebibyte_divisor
mebibyte_string = str(round(mebibyte_value,2))

#Pushbullet Config
pb = Pushbullet("API-KEY")
iPhone = pb.devices[0]

t = time.localtime()
date_run = time.asctime(t)

#Pushbullet message templates
pb_title = torrent_category + " Download Completed"
pb_message = "Torrent: " + torrent_name + "\n" + "Size: " + mebibyte_string + " MB" + "\n" + "Label: " + torrent_category + "\n" + "Run on: " + date_run
pb_debug = date_run + "\n" + "Torrent: " + torrent_name + "\n" + "Size: " + mebibyte_string + " MB" + "\n" + "Label: " + torrent_category

def Send_Push():
    push = iPhone.push_note(pb_title, pb_message)
    print "PUSH sent successfully"

def write_file():
    file = open("debug.txt", "a")
    pb_message_debug = date_run + "\n" + "Torrent: " + torrent_name + "\n" + "Size: " + mebibyte_string + " MB" + "\n" + "Label: " + torrent_category
    file.write(pb_message_debug + "\n")
    file.close()

Send_Push()
write_file()

This script can be used to send test messages to my phone. When I save this file to the desktop and run it using CMD, it sends the message to my phone and even write the debug.txt file as it is supposed to.

But when I try to configure qBittorrent to run the script whenever a download has finished, it sends the message to my phone, but does not append to the debug.txt file.

Whenever I try to run the script using the CMD, it totally works. Sends the message to my phone and appends to debug.txt

It is my theory that qBittorrent is why I am getting IO Error 13 Permission Denied..

Help a guy out? Open to any changes..

Body:
The problem most probably is that you are specifying the path of the debug.txt file relatively. The following line will create a file in the current working directory named debug.txt.

file = open("debug.txt", "a")

If your torrent app runs the script using a working directory that you don't have write access to by default (e.g. your programs folder), you will get a permission denied error.

Try to change the path to something absolute (a location where you have write access, e.g. your home folder):

file = open(r"C:\users\your_username_here\debug.txt", "a")

This should fix the issue.


问:
Memcpy takes the same time as memset
I want to measure memory bandwidth using memcpy. I modified the code from this answer:why vectorizing the loop does not have performance improvement which used memset to measure the bandwidth. The problem is that memcpy is only slighly slower than memset when I expect it to be about two times slower since it operations on twice the memory.

More specifically, I run over 1 GB arrays a and b (allocated will calloc) 100 times with the following operations.

```<code>operation             time(s)
-----------------------------
memset(a,0xff,LEN)    3.7
memcpy(a,b,LEN)       3.9
a[j] += b[j]          9.4
memcpy(a,b,LEN)       3.8
</code>```

Notice that memcpy is only slightly slower then memset. The operations a[j] += b[j] (where j goes over [0,LEN)) should take three times longer than memcpy because it operates on three times as much data.  However it's only about 2.5 as slow as memset.

Then I initialized b to zero with memset(b,0,LEN) and test again:

```<code>operation             time(s)
-----------------------------
memcpy(a,b,LEN)       8.2
a[j] += b[j]          11.5
</code>```

Now we see that memcpy is about twice as slow as memset and a[j] += b[j] is about thrice as slow as memset like I expect.

At the very least I would have expected that before memset(b,0,LEN) that memcpy would be slower because the of lazy allocation (first touch) on the first of the 100 iterations.

Why do I only get the time I expect after memset(b,0,LEN)?

test.c

```<code>#include <time.h>
#include <string.h>
#include <stdio.h>

void tests(char *a, char *b, const int LEN){
    clock_t time0, time1;
    time0 = clock();
    for (int i = 0; i < 100; i++) memset(a,0xff,LEN);
    time1 = clock();
    printf("%f\n", (double)(time1 - time0) / CLOCKS_PER_SEC);

    time0 = clock();
    for (int i = 0; i < 100; i++) memcpy(a,b,LEN);
    time1 = clock();
    printf("%f\n", (double)(time1 - time0) / CLOCKS_PER_SEC);

    time0 = clock();
    for (int i = 0; i < 100; i++) for(int j=0; j<LEN; j++) a[j] += b[j];
    time1 = clock();
    printf("%f\n", (double)(time1 - time0) / CLOCKS_PER_SEC);

    time0 = clock();
    for (int i = 0; i < 100; i++) memcpy(a,b,LEN);
    time1 = clock();
    printf("%f\n", (double)(time1 - time0) / CLOCKS_PER_SEC);

    memset(b,0,LEN);
    time0 = clock();
    for (int i = 0; i < 100; i++) memcpy(a,b,LEN);
    time1 = clock();
    printf("%f\n", (double)(time1 - time0) / CLOCKS_PER_SEC);

    time0 = clock();
    for (int i = 0; i < 100; i++) for(int j=0; j<LEN; j++) a[j] += b[j];
    time1 = clock();
    printf("%f\n", (double)(time1 - time0) / CLOCKS_PER_SEC);
}
</code>```

main.c

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

int tests(char *a, char *b, const int LEN);

int main(void) {
    const int LEN = 1 << 30;    //  1GB
    char *a = (char*)calloc(LEN,1);
    char *b = (char*)calloc(LEN,1);
    tests(a, b, LEN);
}
</code>```

Compile with (gcc 6.2) gcc -O3 test.c main.c. Clang 3.8 gives essentially the same result.

Test system: i7-6700HQ@2.60GHz (Skylake), 32 GB DDR4, Ubuntu 16.10. On my Haswell system the bandwidths make sense before memset(b,0,LEN) i.e. I only see a problem on my Skylake system.

I first discovered this issue from the a[j] += b[k] operations in this answer which was overestimating the bandwidth.

I came up with a simpler test

```<code>#include <time.h>
#include <string.h>
#include <stdio.h>

void __attribute__ ((noinline))  foo(char *a, char *b, const int LEN) {
  for (int i = 0; i < 100; i++) for(int j=0; j<LEN; j++) a[j] += b[j];
}

void tests(char *a, char *b, const int LEN) {
    foo(a, b, LEN);
    memset(b,0,LEN);
    foo(a, b, LEN);
}
</code>```

This outputs.

```<code>9.472976
12.728426
</code>```

However, if I do memset(b,1,LEN) in main after calloc (see below) then it outputs

```<code>12.5
12.5
</code>```

This leads me to to think this is a OS allocation issue and not a compiler issue.

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

int tests(char *a, char *b, const int LEN);

int main(void) {
    const int LEN = 1 << 30;    //  1GB
    char *a = (char*)calloc(LEN,1);
    char *b = (char*)calloc(LEN,1);
    //GCC optimizes memset(b,0,LEN) away after calloc but Clang does not.
    memset(b,1,LEN);
    tests(a, b, LEN);
}
</code>```

答:
Your b array probably was not written after mmap-ing (huge allocation requests with malloc/calloc are usually converted into mmap). And whole array was mmaped to single read-only "zero page" (part of COW mechanism). Reading zeroes from single page is faster than reading from many pages, as single page will be kept in the cache and in TLB. This explains why test before memset(0) was faster:

This outputs.  9.472976 12.728426

However, if I do memset(b,1,LEN) in main after calloc (see below) then it outputs: 12.5 12.5

And more about gcc's malloc+memset / calloc+memset optimization into calloc (expanded from my comment)

```<code>//GCC optimizes memset(b,0,LEN) away after calloc but Clang does not.
</code>```

This optimization was proposed in https://gcc.gnu.org/bugzilla/show_bug.cgi?id=57742 (tree-optimization PR57742) at 2013-06-27 by Marc Glisse (https://stackoverflow.com/users/1918193?) as planned for 4.9/5.0 version of GCC:

memset(malloc(n),0,n) -> calloc(n,1)

calloc can sometimes be significantly faster than malloc+bzero because it has special knowledge that some memory is already zero. When other optimizations simplify some code to malloc+memset(0), it would thus be nice to replace it with calloc. Sadly, I don't think there is a way to do a similar optimization in C++ with new, which is where such code most easily appears (creating std::vector(10000) for instance). And there would also be the complication there that the size of the memset would be a bit smaller than that of the malloc (using calloc would still be fine, but it gets harder to know if it is an improvement).

Implemented at 2014-06-24 (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=57742#c15) - https://gcc.gnu.org/viewcvs/gcc?view=revision&revision=211956 (also https://patchwork.ozlabs.org/patch/325357/)

tree-ssa-strlen.c ...
  (handle_builtin_malloc, handle_builtin_memset): New functions.

The current code in gcc/tree-ssa-strlen.c https://github.com/gcc-mirror/gcc/blob/7a31ada4c400351a35ab65f8dc0357e7c88805d5/gcc/tree-ssa-strlen.c#L1889 - if memset(0) get pointer from malloc or calloc, it will convert malloc into calloc and then memset(0) will be removed:

```<code>/* Handle a call to memset.
   After a call to calloc, memset(,0,) is unnecessary.
   memset(malloc(n),0,n) is calloc(n,1).  */
static bool
handle_builtin_memset (gimple_stmt_iterator *gsi)
 ...
  if (code1 == BUILT_IN_CALLOC)
    /* Not touching stmt1 */ ;
  else if (code1 == BUILT_IN_MALLOC
       && operand_equal_p (gimple_call_arg (stmt1, 0), size, 0))
    {
      gimple_stmt_iterator gsi1 = gsi_for_stmt (stmt1);
      update_gimple_call (&gsi1, builtin_decl_implicit (BUILT_IN_CALLOC), 2,
              size, build_one_cst (size_type_node));
      si1->length = build_int_cst (size_type_node, 0);
      si1->stmt = gsi_stmt (gsi1);
    }
</code>```

This was discussed in gcc-patches mailing list in Mar 1, 2014 - Jul 15, 2014 with subject "calloc = malloc + memset"

https://gcc.gnu.org/ml/gcc-patches/2014-02/msg01693.html

https://gcc.gnu.org/ml/gcc-patches/2014-03/threads.html#00009

https://gcc.gnu.org/ml/gcc-patches/2014-04/threads.html#00817

https://gcc.gnu.org/ml/gcc-patches/2014-05/msg01392.html

https://gcc.gnu.org/ml/gcc-patches/2014-06/threads.html#00234

https://gcc.gnu.org/ml/gcc-patches/2014-07/threads.html#01059

with notable comment from Andi Kleen (http://halobates.de/blog/, https://github.com/andikleen): https://gcc.gnu.org/ml/gcc-patches/2014-06/msg01818.html

FWIW i believe the transformation will break a large variety of micro
  benchmarks.

calloc internally knows that memory fresh from the OS is zeroed. But
  the memory may not be faulted in yet.

memset always faults in the memory.

So if you have some test like

```<code>   buf = malloc(...)
   memset(buf, ...)
   start = get_time();
   ... do something with buf
   end = get_time()
</code>```

Now the times will be completely off because the measured times
  includes the page faults.

Marc replied "Good point. I guess working around compiler optimizations is part of the game for micro benchmarks, and their authors would be disappointed if the compiler didn't mess it up regularly in new and entertaining ways ;-)" and Andi asked: "I would prefer to not do it. I'm not sure it has a lot of benefit. If you want to keep it please make sure there is an easy way to turn it off."

Marc shows how to turn this optimization off: https://gcc.gnu.org/ml/gcc-patches/2014-06/msg01834.html

Any of these flags works:

-fdisable-tree-strlen

-fno-builtin-malloc

-fno-builtin-memset (assuming you wrote 'memset' explicitly in your code)

-fno-builtin

-ffreestanding

-O1

-Os

In the code, you can hide that the pointer passed to memset is the
  one returned by malloc by storing it in a volatile variable, or
  any other trick to hide from the compiler that we are doing
  memset(malloc(n),0,n).

Title: Memcpy takes the same time as memset

Body:
I want to measure memory bandwidth using memcpy. I modified the code from this answer:why vectorizing the loop does not have performance improvement which used memset to measure the bandwidth. The problem is that memcpy is only slighly slower than memset when I expect it to be about two times slower since it operations on twice the memory.

More specifically, I run over 1 GB arrays a and b (allocated will calloc) 100 times with the following operations.

operation             time(s)
-----------------------------
memset(a,0xff,LEN)    3.7
memcpy(a,b,LEN)       3.9
a[j] += b[j]          9.4
memcpy(a,b,LEN)       3.8

Notice that memcpy is only slightly slower then memset. The operations a[j] += b[j] (where j goes over [0,LEN)) should take three times longer than memcpy because it operates on three times as much data.  However it's only about 2.5 as slow as memset.

Then I initialized b to zero with memset(b,0,LEN) and test again:

operation             time(s)
-----------------------------
memcpy(a,b,LEN)       8.2
a[j] += b[j]          11.5

Now we see that memcpy is about twice as slow as memset and a[j] += b[j] is about thrice as slow as memset like I expect.

At the very least I would have expected that before memset(b,0,LEN) that memcpy would be slower because the of lazy allocation (first touch) on the first of the 100 iterations.

Why do I only get the time I expect after memset(b,0,LEN)?

test.c

#include <time.h>
#include <string.h>
#include <stdio.h>

void tests(char *a, char *b, const int LEN){
    clock_t time0, time1;
    time0 = clock();
    for (int i = 0; i < 100; i++) memset(a,0xff,LEN);
    time1 = clock();
    printf("%f\n", (double)(time1 - time0) / CLOCKS_PER_SEC);

    time0 = clock();
    for (int i = 0; i < 100; i++) memcpy(a,b,LEN);
    time1 = clock();
    printf("%f\n", (double)(time1 - time0) / CLOCKS_PER_SEC);

    time0 = clock();
    for (int i = 0; i < 100; i++) for(int j=0; j<LEN; j++) a[j] += b[j];
    time1 = clock();
    printf("%f\n", (double)(time1 - time0) / CLOCKS_PER_SEC);

    time0 = clock();
    for (int i = 0; i < 100; i++) memcpy(a,b,LEN);
    time1 = clock();
    printf("%f\n", (double)(time1 - time0) / CLOCKS_PER_SEC);

    memset(b,0,LEN);
    time0 = clock();
    for (int i = 0; i < 100; i++) memcpy(a,b,LEN);
    time1 = clock();
    printf("%f\n", (double)(time1 - time0) / CLOCKS_PER_SEC);

    time0 = clock();
    for (int i = 0; i < 100; i++) for(int j=0; j<LEN; j++) a[j] += b[j];
    time1 = clock();
    printf("%f\n", (double)(time1 - time0) / CLOCKS_PER_SEC);
}

main.c

#include <stdlib.h>

int tests(char *a, char *b, const int LEN);

int main(void) {
    const int LEN = 1 << 30;    //  1GB
    char *a = (char*)calloc(LEN,1);
    char *b = (char*)calloc(LEN,1);
    tests(a, b, LEN);
}

Compile with (gcc 6.2) gcc -O3 test.c main.c. Clang 3.8 gives essentially the same result.

Test system: i7-6700HQ@2.60GHz (Skylake), 32 GB DDR4, Ubuntu 16.10. On my Haswell system the bandwidths make sense before memset(b,0,LEN) i.e. I only see a problem on my Skylake system.

I first discovered this issue from the a[j] += b[k] operations in this answer which was overestimating the bandwidth.

I came up with a simpler test

#include <time.h>
#include <string.h>
#include <stdio.h>

void __attribute__ ((noinline))  foo(char *a, char *b, const int LEN) {
  for (int i = 0; i < 100; i++) for(int j=0; j<LEN; j++) a[j] += b[j];
}

void tests(char *a, char *b, const int LEN) {
    foo(a, b, LEN);
    memset(b,0,LEN);
    foo(a, b, LEN);
}

This outputs.

9.472976
12.728426

However, if I do memset(b,1,LEN) in main after calloc (see below) then it outputs

12.5
12.5

This leads me to to think this is a OS allocation issue and not a compiler issue.

#include <stdlib.h>

int tests(char *a, char *b, const int LEN);

int main(void) {
    const int LEN = 1 << 30;    //  1GB
    char *a = (char*)calloc(LEN,1);
    char *b = (char*)calloc(LEN,1);
    //GCC optimizes memset(b,0,LEN) away after calloc but Clang does not.
    memset(b,1,LEN);
    tests(a, b, LEN);
}

Body:
Your b array probably was not written after mmap-ing (huge allocation requests with malloc/calloc are usually converted into mmap). And whole array was mmaped to single read-only "zero page" (part of COW mechanism). Reading zeroes from single page is faster than reading from many pages, as single page will be kept in the cache and in TLB. This explains why test before memset(0) was faster:

This outputs.  9.472976 12.728426

However, if I do memset(b,1,LEN) in main after calloc (see below) then it outputs: 12.5 12.5

And more about gcc's malloc+memset / calloc+memset optimization into calloc (expanded from my comment)

//GCC optimizes memset(b,0,LEN) away after calloc but Clang does not.

This optimization was proposed in https://gcc.gnu.org/bugzilla/show_bug.cgi?id=57742 (tree-optimization PR57742) at 2013-06-27 by Marc Glisse (https://stackoverflow.com/users/1918193?) as planned for 4.9/5.0 version of GCC:

memset(malloc(n),0,n) -> calloc(n,1)

calloc can sometimes be significantly faster than malloc+bzero because it has special knowledge that some memory is already zero. When other optimizations simplify some code to malloc+memset(0), it would thus be nice to replace it with calloc. Sadly, I don't think there is a way to do a similar optimization in C++ with new, which is where such code most easily appears (creating std::vector(10000) for instance). And there would also be the complication there that the size of the memset would be a bit smaller than that of the malloc (using calloc would still be fine, but it gets harder to know if it is an improvement).

Implemented at 2014-06-24 (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=57742#c15) - https://gcc.gnu.org/viewcvs/gcc?view=revision&revision=211956 (also https://patchwork.ozlabs.org/patch/325357/)

tree-ssa-strlen.c ...
  (handle_builtin_malloc, handle_builtin_memset): New functions.

The current code in gcc/tree-ssa-strlen.c https://github.com/gcc-mirror/gcc/blob/7a31ada4c400351a35ab65f8dc0357e7c88805d5/gcc/tree-ssa-strlen.c#L1889 - if memset(0) get pointer from malloc or calloc, it will convert malloc into calloc and then memset(0) will be removed:

/* Handle a call to memset.
   After a call to calloc, memset(,0,) is unnecessary.
   memset(malloc(n),0,n) is calloc(n,1).  */
static bool
handle_builtin_memset (gimple_stmt_iterator *gsi)
 ...
  if (code1 == BUILT_IN_CALLOC)
    /* Not touching stmt1 */ ;
  else if (code1 == BUILT_IN_MALLOC
       && operand_equal_p (gimple_call_arg (stmt1, 0), size, 0))
    {
      gimple_stmt_iterator gsi1 = gsi_for_stmt (stmt1);
      update_gimple_call (&gsi1, builtin_decl_implicit (BUILT_IN_CALLOC), 2,
              size, build_one_cst (size_type_node));
      si1->length = build_int_cst (size_type_node, 0);
      si1->stmt = gsi_stmt (gsi1);
    }

This was discussed in gcc-patches mailing list in Mar 1, 2014 - Jul 15, 2014 with subject "calloc = malloc + memset"

https://gcc.gnu.org/ml/gcc-patches/2014-02/msg01693.html

https://gcc.gnu.org/ml/gcc-patches/2014-03/threads.html#00009

https://gcc.gnu.org/ml/gcc-patches/2014-04/threads.html#00817

https://gcc.gnu.org/ml/gcc-patches/2014-05/msg01392.html

https://gcc.gnu.org/ml/gcc-patches/2014-06/threads.html#00234

https://gcc.gnu.org/ml/gcc-patches/2014-07/threads.html#01059

with notable comment from Andi Kleen (http://halobates.de/blog/, https://github.com/andikleen): https://gcc.gnu.org/ml/gcc-patches/2014-06/msg01818.html

FWIW i believe the transformation will break a large variety of micro
  benchmarks.

calloc internally knows that memory fresh from the OS is zeroed. But
  the memory may not be faulted in yet.

memset always faults in the memory.

So if you have some test like

   buf = malloc(...)
   memset(buf, ...)
   start = get_time();
   ... do something with buf
   end = get_time()

Now the times will be completely off because the measured times
  includes the page faults.

Marc replied "Good point. I guess working around compiler optimizations is part of the game for micro benchmarks, and their authors would be disappointed if the compiler didn't mess it up regularly in new and entertaining ways ;-)" and Andi asked: "I would prefer to not do it. I'm not sure it has a lot of benefit. If you want to keep it please make sure there is an easy way to turn it off."

Marc shows how to turn this optimization off: https://gcc.gnu.org/ml/gcc-patches/2014-06/msg01834.html

Any of these flags works:

-fdisable-tree-strlen

-fno-builtin-malloc

-fno-builtin-memset (assuming you wrote 'memset' explicitly in your code)

-fno-builtin

-ffreestanding

-O1

-Os

In the code, you can hide that the pointer passed to memset is the
  one returned by malloc by storing it in a volatile variable, or
  any other trick to hide from the compiler that we are doing
  memset(malloc(n),0,n).


问:
What would be a simple regular expression for password check during signup?
What I want to do is just check when the user is signing up that whether the password entered is at least 6 characters and has no space in it. Thats pretty much it. What would be a regex that I could use in Java Pattern Matcher classes for this purpose?

Thanks for your help guys.

答:
```<code>^[^ ]{6,}$
</code>```

This will match the whole string ^...$ and ignore spaces [^ ] for 6 or more chars {6,}

Body:
^[^ ]{6,}$

This will match the whole string ^...$ and ignore spaces [^ ] for 6 or more chars {6,}