问:
Swift Filter and Map over array of structs
I may have this really wrong. Noob. I've recreated what I'm doing in a playground type environment here. Basically the sender is a slider within a UITableView of other sliders. The myData is the underlying data. I want to perform a calculation to all the items of the underlying data EXCEPT the one which corresponds to the sender item. I have no idea if my closure syntax is correct. This is the first time I'm creating one.

```<code>// sender comes over as a struct
struct myStruct {
    var tag: Int = 0
    var value: Float = 0
}
let sender = myStruct(tag: 1, value: 199)

// some vars for the calculation
let globalTotal: Float = 597
let globalAnotherTotal: Float = 0

// an array of data structs
struct myDataStruct {
    var name: String = ""
    var value: Float = 0
}
var myData: [myDataStruct] = []
myData.append(myDataStruct(name: "Tom", value: 45.0))
myData.append(myDataStruct(name: "Dick", value: 16.4))
myData.append(myDataStruct(name: "Harry", value: 12.3))

// a closure to do the calculation
var calcOtherVals: (Float, Float) -> (Float) = { (startVal, senderStartVal) in

    let remainingStartVals = globalTotal - senderStartVal
    let remainingNewVal = globalTotal - sender.value - globalAnotherTotal

    let endVal = ((startVal * (100 / remainingStartVals)) / 100) * remainingNewVal

    return endVal
}

// now need to perform calcOtherVals on all the .value floats in myData EXCEPT the element at position sender.tag hopefully using filter and map
</code>```

So basically I'm trying to use filter and map and the calcOtherVals closure to edit the array of structs in place. I can do this with conditionals and loops and calcOtherVals as a function no problem. Just hoping to do it more elegantly.

QUESTION: As in the code comment, I need to perform calcOtherVals on all the .value floats in myData EXCEPT the element at position sender.tag. How?

答:
```<code>myData.enumerated().flatMap { (index, element) in return index != sender.tag ? calcOtherVals (element.value) : nil }
</code>```

Few bits of swift magic here. Firstly enumerate() returns an array of tuples containing the element, and the index of said element.

Next flatMap(). This is essentially map but it ignores any transform that resolves to nil. Great for converting from an optional array to a flat array, and also great if you wish to do a map+filter operation such as this.

-- Updated --

If you're comfortable with implicit arguments, you can reduce it further:

```<code>myData.enumerated().flatMap { $0.offset != sender.tag ? calcOtherVals ($0.element.value) : nil }
</code>```

Body:
I may have this really wrong. Noob. I've recreated what I'm doing in a playground type environment here. Basically the sender is a slider within a UITableView of other sliders. The myData is the underlying data. I want to perform a calculation to all the items of the underlying data EXCEPT the one which corresponds to the sender item. I have no idea if my closure syntax is correct. This is the first time I'm creating one.

// sender comes over as a struct
struct myStruct {
    var tag: Int = 0
    var value: Float = 0
}
let sender = myStruct(tag: 1, value: 199)

// some vars for the calculation
let globalTotal: Float = 597
let globalAnotherTotal: Float = 0

// an array of data structs
struct myDataStruct {
    var name: String = ""
    var value: Float = 0
}
var myData: [myDataStruct] = []
myData.append(myDataStruct(name: "Tom", value: 45.0))
myData.append(myDataStruct(name: "Dick", value: 16.4))
myData.append(myDataStruct(name: "Harry", value: 12.3))

// a closure to do the calculation
var calcOtherVals: (Float, Float) -> (Float) = { (startVal, senderStartVal) in

    let remainingStartVals = globalTotal - senderStartVal
    let remainingNewVal = globalTotal - sender.value - globalAnotherTotal

    let endVal = ((startVal * (100 / remainingStartVals)) / 100) * remainingNewVal

    return endVal
}

// now need to perform calcOtherVals on all the .value floats in myData EXCEPT the element at position sender.tag hopefully using filter and map

So basically I'm trying to use filter and map and the calcOtherVals closure to edit the array of structs in place. I can do this with conditionals and loops and calcOtherVals as a function no problem. Just hoping to do it more elegantly.

QUESTION: As in the code comment, I need to perform calcOtherVals on all the .value floats in myData EXCEPT the element at position sender.tag. How?

Body:
myData.enumerated().flatMap { (index, element) in return index != sender.tag ? calcOtherVals (element.value) : nil }

Few bits of swift magic here. Firstly enumerate() returns an array of tuples containing the element, and the index of said element.

Next flatMap(). This is essentially map but it ignores any transform that resolves to nil. Great for converting from an optional array to a flat array, and also great if you wish to do a map+filter operation such as this.

-- Updated --

If you're comfortable with implicit arguments, you can reduce it further:

myData.enumerated().flatMap { $0.offset != sender.tag ? calcOtherVals ($0.element.value) : nil }


来源: stackexchange

问:
3DES/DES encryption using the JCE - generating an acceptable key
I'm working on a project that requires 3DES encryption in Java. The issue is that I've been (and will continue to be) supplied with a 128-bit hex key like "0123456789ABCDEF0123456789ABCDEF". Conversion to bytes is no issue. What is the issue, however, is that the Java Cryptographic Extensions API will choke on this key, saying it is invalid. I gather that the MSB of each byte is merely a parity bit, so the JCE expects me to remove those (or so I think). In .NET, however, I can specify the key as supplied, and it quietly handles the encryption/decryption with no complaints.

Is there any way I can generate the kind of key the JCE expects from the kind of key I'm supplied?

I've found that the JCE allows you specify an 8-byte key for DES encryption, so I tried implementing 3DES as DES EDE using half of the supplied key. However, I'm still getting inconsistent results with .NET.

Here's the Java code:

```<code>import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.spec.IvParameterSpec;

public class Main{
    public static void main(String[] args) throws Exception {
        byte [] plain = "I eat fish every day".getBytes("utf-8");

        byte [] keyBytes = new byte [] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
            (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00
            };

        byte [] key2Bytes = new byte [] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
            (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x0  }; // actual keys replaced with dummies.

        SecretKey keySpec = new SecretKeySpec(keyBytes, "DES");
        SecretKey keySpec2 = new SecretKeySpec(key2Bytes, "DES");

        IvParameterSpec iv = new IvParameterSpec(new byte[8]);

        Cipher e_cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        Cipher cipher = Cipher.getInstance("DES/CBC/NoPadding");

        e_cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv);
        cipher.init(Cipher.DECRYPT_MODE, keySpec2, iv);

        byte [] cipherText = e_cipher.doFinal(plain);
        cipherText = cipher.doFinal(cipherText);
        cipherText = e_cipher.doFinal(cipherText);

        System.out.println("Ciphertext: " + new sun.misc.BASE64Encoder().encode(cipherText));
    }
}
</code>```

and here's the .NET code:

```<code>using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace EncryptionDemo
{
    class Program
    {
    public static void Main(string[] args)
    {
        Console.WriteLine("Hello World!");

        // TODO: Implement Functionality Here
        var plainBytes = Encoding.UTF8.GetBytes("I eat fish every day");
        var keyBytes = new byte [] { 0x00, 0x00, 0x00, 0x00,
         0x00, 0x00, 0x00, 0x00,
         0x00, 0x00, 0x00, 0x00,
         0x00,  0x00, 0x00, 0x00  };

        var tripleDES = TripleDESCryptoServiceProvider.Create();
        var transform = tripleDES.CreateEncryptor(keyBytes, new byte [8]);

        var memStream = new MemoryStream();
        var cStream = new CryptoStream(memStream, transform, CryptoStreamMode.Write);

        cStream.Write(plainBytes, 0, plainBytes.Length);
        cStream.FlushFinalBlock();

        //memStream.Position = 0;
        var cipherBytes = memStream.ToArray();

        Console.WriteLine("Ciphertext: " + Convert.ToBase64String(cipherBytes));

        Console.Write("Press any key to continue . . . ");
        Console.ReadKey(true);
    }
}
</code>```

Both produce different outputs (some characters in the Base64 string are the same)

答:
3DES keys are 192 bits long.

How are you creating the SecretKey instance? What error message to you get?

The Java code in your question is using DES, not "Triple DES". The algorithm name should be "DESede/CBC/PKCS5Padding". The code in your answer probably works because you got the algorithm right, not because you switched providers. The SunJCE provider in Java 6 will accept 128-bit keys (and use keying option 2). I am not sure about older versions.

ContentLicense: CC BY-SA 2.5

Body:
I'm working on a project that requires 3DES encryption in Java. The issue is that I've been (and will continue to be) supplied with a 128-bit hex key like "0123456789ABCDEF0123456789ABCDEF". Conversion to bytes is no issue. What is the issue, however, is that the Java Cryptographic Extensions API will choke on this key, saying it is invalid. I gather that the MSB of each byte is merely a parity bit, so the JCE expects me to remove those (or so I think). In .NET, however, I can specify the key as supplied, and it quietly handles the encryption/decryption with no complaints.

Is there any way I can generate the kind of key the JCE expects from the kind of key I'm supplied?

I've found that the JCE allows you specify an 8-byte key for DES encryption, so I tried implementing 3DES as DES EDE using half of the supplied key. However, I'm still getting inconsistent results with .NET.

Here's the Java code:

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.spec.IvParameterSpec;

public class Main{
    public static void main(String[] args) throws Exception {
        byte [] plain = "I eat fish every day".getBytes("utf-8");

        byte [] keyBytes = new byte [] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
            (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00
            };

        byte [] key2Bytes = new byte [] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
            (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x0  }; // actual keys replaced with dummies.

        SecretKey keySpec = new SecretKeySpec(keyBytes, "DES");
        SecretKey keySpec2 = new SecretKeySpec(key2Bytes, "DES");

        IvParameterSpec iv = new IvParameterSpec(new byte[8]);

        Cipher e_cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        Cipher cipher = Cipher.getInstance("DES/CBC/NoPadding");

        e_cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv);
        cipher.init(Cipher.DECRYPT_MODE, keySpec2, iv);

        byte [] cipherText = e_cipher.doFinal(plain);
        cipherText = cipher.doFinal(cipherText);
        cipherText = e_cipher.doFinal(cipherText);

        System.out.println("Ciphertext: " + new sun.misc.BASE64Encoder().encode(cipherText));
    }
}

and here's the .NET code:

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace EncryptionDemo
{
    class Program
    {
    public static void Main(string[] args)
    {
        Console.WriteLine("Hello World!");

        // TODO: Implement Functionality Here
        var plainBytes = Encoding.UTF8.GetBytes("I eat fish every day");
        var keyBytes = new byte [] { 0x00, 0x00, 0x00, 0x00,
         0x00, 0x00, 0x00, 0x00,
         0x00, 0x00, 0x00, 0x00,
         0x00,  0x00, 0x00, 0x00  };

        var tripleDES = TripleDESCryptoServiceProvider.Create();
        var transform = tripleDES.CreateEncryptor(keyBytes, new byte [8]);

        var memStream = new MemoryStream();
        var cStream = new CryptoStream(memStream, transform, CryptoStreamMode.Write);

        cStream.Write(plainBytes, 0, plainBytes.Length);
        cStream.FlushFinalBlock();

        //memStream.Position = 0;
        var cipherBytes = memStream.ToArray();

        Console.WriteLine("Ciphertext: " + Convert.ToBase64String(cipherBytes));

        Console.Write("Press any key to continue . . . ");
        Console.ReadKey(true);
    }
}

Both produce different outputs (some characters in the Base64 string are the same)


问:
Numeric keyboard with decimal
I´m building an app with equations and I have used a numeric keyboard but I want to have a decimal slot on it. The default is only numbers. How do you add a decimal input on that keyboard?

This is the code I use to get the numeric keyboard

```<code>.keyboardType = UIKeyboardType.NumberPad
</code>```

答: In storyboard go to Attribute Inspector. There you can change keyboard type.You can check here</p>

ContentLicense: CC BY-SA 4.0

Title: Numeric keyboard with decimal

Body:
I´m building an app with equations and I have used a numeric keyboard but I want to have a decimal slot on it. The default is only numbers. How do you add a decimal input on that keyboard?

This is the code I use to get the numeric keyboard

.keyboardType = UIKeyboardType.NumberPad

ContentLicense: CC BY-SA 3.0


问:
temporal dead zone (ES6) doesnt seem to work
Below is my code:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

</head>
<body>
<h1 id="message"></h1>

<script src="traceur/traceur.js"></script>
<script src="traceur/BrowserSystem.js"></script>
<script src="traceur/bootstrap.js"></script>
<script type="module">

    var x = 'outer scope';
    (function() {
        console.log(x); //Expected undefined, got undefined ! this is as expected.
        var x = 'inner scope';
    }());

    //same as above, but changed to var to let and x to y
    let y = 'outer scope';
    (function() {
        console.log(y); //Was expecting ReferenceError here, but got undefined. WTF ??!!!
        let y = 'inner scope';
    }());

</script>

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

Its seems the temporal drop zone (TDZ) in es6 should throw a referenceError in case the let-var is used before it is declared.

However, in this example, I am getting undefined for let.
Where am i going wrong?

Been at this problem for a long time and wasted a day on this. (Any pointers would be very help). I am using Chrome v58.

v58 has es6 compatibility as per https://kangax.github.io/compat-table/es6/ under current browser).

I stripped off the traceur part and posted on babel-try it out, and got the same result.

Am wondering why is it not working in my chrome v58. Maybe it requires something else too??

答:
You are using Traceur, which does not support TDZ for let/const. It will convert let to var - making the TDZ behaviour for let identical to your var example. Run the same code in an ES6-compatible environment and you'll see the expected result:

var x = 'outer scope';
(function() {
    console.log(x);
    var x = 'inner scope';
}());

let y = 'outer scope';
(function() {
    console.log(y);
    let y = 'inner scope';
}());```

Body:
Below is my code:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>

Its seems the temporal drop zone (TDZ) in es6 should throw a referenceError in case the let-var is used before it is declared.

However, in this example, I am getting undefined for let.
Where am i going wrong?

Been at this problem for a long time and wasted a day on this. (Any pointers would be very help). I am using Chrome v58.

v58 has es6 compatibility as per https://kangax.github.io/compat-table/es6/ under current browser).

I stripped off the traceur part and posted on babel-try it out, and got the same result.

Am wondering why is it not working in my chrome v58. Maybe it requires something else too??


问:
Prevention to Cross Site Scripting
I have received one vulnerability effects detail from Acunetix-scan Vulnerability scan.

```<code>**Request URL**
http://www.example.co/brands/tom-ford-2692.aspx,Gender.Women
</code>```

Attack details
    URL encoded GET input Gender.Women was set to F"onmouseover=9QJ0(9526)"
    The input is reflected inside a tag parameter between double quotes.

I am new for this and have no idea how to recover my site from this vulnerability.

Any reply will be appreciated

答: before rendering any string from user input into HTML page do HTMLEncode(userInputString)</p>

Title: Prevention to Cross Site Scripting

Body:
I have received one vulnerability effects detail from Acunetix-scan Vulnerability scan.

**Request URL**
http://www.example.co/brands/tom-ford-2692.aspx,Gender.Women

Attack details
    URL encoded GET input Gender.Women was set to F"onmouseover=9QJ0(9526)"
    The input is reflected inside a tag parameter between double quotes.

I am new for this and have no idea how to recover my site from this vulnerability.

Any reply will be appreciated


问:
Capitalise the first letter of every word as user types unless user insists on lower case
I am working on the script where I want the first letter and the letter after a space to be capitalized. If a word follows a hyphen (-), it should not be capitalized until and unless a space follows after the hyphen (-). If the user wants to lower case the first letter of any word, it should work dynamically.

This I achieved using the below script.

The challenge here is, that it should be possible for the user to change the uppercased letter to a lower case while typing

I am not able to achieve that feature.

Example:

If the user types "hello world", the output will be "Hello World", and if the user wants to lower case the letter "W"  from the word "World" by deleting the letter "W" and retyping the letter "w", the expected result should be "Hello world".

$.fn.capitalize = function() {
  $.each(this, function() {
    var split = this.value.split(' ');
    for (var i = 0, len = split.length; i < len; i++) {
      split[i] = split[i].charAt(0).toUpperCase() + split[i].slice(1);
    }
    this.value = split.join(' ');
  });
  return this;
};

$('textarea').on('keyup', function() {
  $(this).capitalize();
}).capitalize();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<textarea></textarea></code>```

答:
The difficulty will be in determining whether the user "corrects" an uppercase back to a lowercase equivalent or is making changes with other intentions. For instance, what if the user continues to change other characters of the original word, should the first letter be converted to upper case again? This, and many other scenarios, may lead to unexpected results for the user.

I would suggest an alternative, where you wait for the user to type a white space, and then capitalise the first letter of only the word that precedes that white space. Then, if the user goes back and makes it a lower case again, it will stay like that. The user must type a space (or newline, or tab) to trigger the automatic capitalisation again on the preceding word.

Here is how that would work:

$.fn.capitalize = function() {
    $.each(this, function() {
        var pos = this.selectionStart,
            s = this.value,
            i = s.lastIndexOf(' ', pos-1)+1;
        // Don't do anything if text is selected
        if (this.selectionEnd !== pos) return;
        // Uppercase first character of word
        this.value = s.substr(0, i) + s.charAt(i).toUpperCase() + s.substr(i+1);
        // Restore caret position
        this.selectionStart = this.selectionEnd = pos;
    });
    return this;
};

$('textarea').on('keypress', function(e) {
    if (' \n\r\t'.indexOf(String.fromCharCode(e.which)) > -1) {
        $(this).capitalize();
    }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>textarea { width: 100% }</code>```

<textarea></textarea>```

Body:
I am working on the script where I want the first letter and the letter after a space to be capitalized. If a word follows a hyphen (-), it should not be capitalized until and unless a space follows after the hyphen (-). If the user wants to lower case the first letter of any word, it should work dynamically.

This I achieved using the below script.

The challenge here is, that it should be possible for the user to change the uppercased letter to a lower case while typing

I am not able to achieve that feature.

Example:

If the user types "hello world", the output will be "Hello World", and if the user wants to lower case the letter "W"  from the word "World" by deleting the letter "W" and retyping the letter "w", the expected result should be "Hello world".

$.fn.capitalize = function() {
  $.each(this, function() {
    var split = this.value.split(' ');
    for (var i = 0, len = split.length; i < len; i++) {
      split[i] = split[i].charAt(0).toUpperCase() + split[i].slice(1);
    }
    this.value = split.join(' ');
  });
  return this;
};

$('textarea').on('keyup', function() {
  $(this).capitalize();
}).capitalize();

<textarea></textarea>

Body:
The difficulty will be in determining whether the user "corrects" an uppercase back to a lowercase equivalent or is making changes with other intentions. For instance, what if the user continues to change other characters of the original word, should the first letter be converted to upper case again? This, and many other scenarios, may lead to unexpected results for the user.

I would suggest an alternative, where you wait for the user to type a white space, and then capitalise the first letter of only the word that precedes that white space. Then, if the user goes back and makes it a lower case again, it will stay like that. The user must type a space (or newline, or tab) to trigger the automatic capitalisation again on the preceding word.

Here is how that would work:

$.fn.capitalize = function() {
    $.each(this, function() {
        var pos = this.selectionStart,
            s = this.value,
            i = s.lastIndexOf(' ', pos-1)+1;
        // Don't do anything if text is selected
        if (this.selectionEnd !== pos) return;
        // Uppercase first character of word
        this.value = s.substr(0, i) + s.charAt(i).toUpperCase() + s.substr(i+1);
        // Restore caret position
        this.selectionStart = this.selectionEnd = pos;
    });
    return this;
};

$('textarea').on('keypress', function(e) {
    if (' \n\r\t'.indexOf(String.fromCharCode(e.which)) > -1) {
        $(this).capitalize();
    }
});

textarea { width: 100% }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea></textarea>


问:
Swift 3 : Core data "data: <fault>" issue
I'm saving the data without any warning, but when I try to get data, I'll get nothing. I don't get what the problem is. I'll check my array and it's giving this warning :

```<code><Sepet: 0x60000028ab40> (entity: Sepet; id: 0xd000000000240000 <x-coredata://5CDE7285-D461-44FD-AA49-DC6C5A61A9D8/Sepet/p9> ; data: <fault>)]
</code>```

This is my code for saving Core Data :

```<code>@IBAction func addToCardAction(_ sender: UIButton) {
        let cell = sender.superview?.superview as! SiparisVerTableViewCell

        if cell.countLabel.text == "0"{
            print("0'dan büyük olmalı")
        }else{

            let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

            let task = Sepet(context: context)
            task.menuimage = "turk-telekom"
            task.details = cell.detailsTextView.text!

            if cell.detailTextField.text == ""{
                task.customerDetails = "Açıklama yok."
            }else{
                task.customerDetails = cell.detailTextField.text!
            }

            task.count = cell.countLabel.text!
            task.price = cell.priceLabel.text!

            print(cell.menuImageView, cell.detailsTextView.text, cell.detailTextField.text, cell.countLabel.text, cell.priceLabel.text)
            // Save the data to coredata
            print("saved")
            (UIApplication.shared.delegate as! AppDelegate).saveContext()
        }
    }
</code>```

And this is the code for getting the data and tableView implementation :

```<code>func getData() {
    do {
        sepetContents = try context.fetch(Sepet.fetchRequest())
        print(sepetContents)
    }
    catch {
        print("Fetching Failed")
    }
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "sepetCell", for: indexPath) as! SepetTableViewCell
    let sepetim = sepetContents[indexPath.row]

    if let image = sepetim.menuimage, let details = sepetim.details, let customerDetails = sepetim.customerDetails, let price = sepetim.price, let count = sepetim.count {
        cell.menuImageView?.image = UIImage(named: image)
        cell.detailsTextView.text = details
        cell.customerDetailsLabel.text = customerDetails
        cell.priceLabel.text = price
        cell.countLabel.text = count
    }

    return cell
}
</code>```

答:
Fault is nothing bad, it just means that the whole object wasn't loaded from core data, only the basic metadata, this is an optimization measure. Whenever you access properties you need, they will be loaded automatically.

You can of course preload relationships by parametrizing fetch request if you know you gotta need the properties anyway.

What exactly doesn't work? If your problem is that the object doesn't print fully in the debugger, it is unfortunately how it is, LLDB doesn't unfault objects.

Body:
I'm saving the data without any warning, but when I try to get data, I'll get nothing. I don't get what the problem is. I'll check my array and it's giving this warning :

<Sepet: 0x60000028ab40> (entity: Sepet; id: 0xd000000000240000 <x-coredata://5CDE7285-D461-44FD-AA49-DC6C5A61A9D8/Sepet/p9> ; data: <fault>)]

This is my code for saving Core Data :

@IBAction func addToCardAction(_ sender: UIButton) {
        let cell = sender.superview?.superview as! SiparisVerTableViewCell

        if cell.countLabel.text == "0"{
            print("0'dan büyük olmalı")
        }else{

            let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

            let task = Sepet(context: context)
            task.menuimage = "turk-telekom"
            task.details = cell.detailsTextView.text!

            if cell.detailTextField.text == ""{
                task.customerDetails = "Açıklama yok."
            }else{
                task.customerDetails = cell.detailTextField.text!
            }

            task.count = cell.countLabel.text!
            task.price = cell.priceLabel.text!

            print(cell.menuImageView, cell.detailsTextView.text, cell.detailTextField.text, cell.countLabel.text, cell.priceLabel.text)
            // Save the data to coredata
            print("saved")
            (UIApplication.shared.delegate as! AppDelegate).saveContext()
        }
    }

And this is the code for getting the data and tableView implementation :

func getData() {
    do {
        sepetContents = try context.fetch(Sepet.fetchRequest())
        print(sepetContents)
    }
    catch {
        print("Fetching Failed")
    }
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "sepetCell", for: indexPath) as! SepetTableViewCell
    let sepetim = sepetContents[indexPath.row]

    if let image = sepetim.menuimage, let details = sepetim.details, let customerDetails = sepetim.customerDetails, let price = sepetim.price, let count = sepetim.count {
        cell.menuImageView?.image = UIImage(named: image)
        cell.detailsTextView.text = details
        cell.customerDetailsLabel.text = customerDetails
        cell.priceLabel.text = price
        cell.countLabel.text = count
    }

    return cell
}


问:
set selected value select2 from database with icon flags
i'm doing edit profile page i've problem with select2 for country. i'm using html and php. below is my code for jquery.

```<code>function formatCountry (country) {

            if (!country.id) { return country.text; }
            var $country = $(
                '<span class="flag-icon flag-icon-'+ country.id.toLowerCase() +' flag-icon-squared"></span>' +
                '<span class="flag-text">'+ country.text+"</span>"
            );
            return $country;
        };

        $("[name='country']").select2({
            placeholder: "Select a country",
            templateResult: formatCountry,
            data: isoCountries

        });
        $("#country").val('<?php echo  $profile_fields[11]["value"];?>').trigger('change');
</code>```

My code only display country name.how to add icon flag? output my code

答:
i add templateSelection

$("[name='country']").select2({
                placeholder: "Select a country",
                templateResult: formatCountry,
                templateSelection: formatCountry,
                data: isoCountries,
                id: '<?php echo  $profile_fields[11]["value"];?>'
            });

Body:
i'm doing edit profile page i've problem with select2 for country. i'm using html and php. below is my code for jquery.

function formatCountry (country) {

            if (!country.id) { return country.text; }
            var $country = $(
                '' +
                ''+ country.text+""
            );
            return $country;
        };

        $("[name='country']").select2({
            placeholder: "Select a country",
            templateResult: formatCountry,
            data: isoCountries

        });
        $("#country").val('<?php echo  $profile_fields[11]["value"];?>').trigger('change');

My code only display country name.how to add icon flag? output my code


问:
Staying on no branch after pulling and switching to a branch
I'm trying to switch another branch but I keep staying on a detached head or no branch.

What I tried:

Switch/Checkout:

Getting:

But if I want to commit, I'm still on no branch:

And if I try to pull this branch instead:

I'm getting:

And I'm still on no branch...

How can I actually go back to the portalGraphs branch?

答:
I haven't used those lousy GUI's for git.

The problem you're facing is the detached head. What you need to do is to checkout the branch. In your case checkout the master.

```<code>git checkout master
</code>```

or below command this will checkout the former branch you checked out.

```<code>git checkout -
</code>```

Detached head means you are no longer on a branch, you have checked out a single commit in the history.

After checking out the branch then you can switch to your branch.

Body:
I haven't used those lousy GUI's for git.

The problem you're facing is the detached head. What you need to do is to checkout the branch. In your case checkout the master.

git checkout master

or below command this will checkout the former branch you checked out.

git checkout -

Detached head means you are no longer on a branch, you have checked out a single commit in the history.

After checking out the branch then you can switch to your branch.


问:
yield throws KotlinNullPointerException in buildSequence for maven projects
I'm looking into coroutines in Kotlin, starting with Fibonacci sequence like this:

```<code>import kotlin.coroutines.experimental.buildSequence

fun main(args: Array<String>) {
    val fibo = buildSequence {
        yield(0)

        var a = 0
        var b = 1

        while (true) {
            yield(b)
            b = a + b
            a = b - a
        }
    }

    fibo.take(5).forEach { println(it) }
}
</code>```

I'm using IntelliJ IDEA, when the above code runs in a project created by New Project -> Kotlin -> Kotlin(JVM), it's working fine.

When the code runs in a project of Maven, created from archetype org.jetbrains.kotlin:kotlin-archetype-jvm kotlin-archetype-jvm:1.1.2-4 it throws KotlinNullPointerException.

Exception in thread "main" kotlin.KotlinNullPointerException  at
  kotlin.coroutines.experimental.SequenceBuilderIterator.yield(SequenceBuilder.kt:163)
    at com.github.fdudannychen.HelloKt$main$fibo$1.doResume(Hello.kt:7)
    at
  kotlin.coroutines.experimental.jvm.internal.CoroutineImpl.resume(CoroutineImpl.kt:54)
    at
  kotlin.coroutines.experimental.SequenceBuilderIterator.hasNext(SequenceBuilder.kt:128)
    at kotlin.sequences.TakeSequence$iterator$1.hasNext(Sequences.kt:348)
    at com.github.fdudannychen.HelloKt.main(Hello.kt:22)

Steps in this article don't help to fix the issue. I don't know why it's not working. Am I missing something?

答: The problem was reported in KT-18026 and was marked fixed for Kotlin version 1.1.2-5

Body:
I'm looking into coroutines in Kotlin, starting with Fibonacci sequence like this:

import kotlin.coroutines.experimental.buildSequence

fun main(args: Array<String>) {
    val fibo = buildSequence {
        yield(0)

        var a = 0
        var b = 1

        while (true) {
            yield(b)
            b = a + b
            a = b - a
        }
    }

    fibo.take(5).forEach { println(it) }
}

I'm using IntelliJ IDEA, when the above code runs in a project created by New Project -> Kotlin -> Kotlin(JVM), it's working fine.

When the code runs in a project of Maven, created from archetype org.jetbrains.kotlin:kotlin-archetype-jvm kotlin-archetype-jvm:1.1.2-4 it throws KotlinNullPointerException.

Exception in thread "main" kotlin.KotlinNullPointerException  at
  kotlin.coroutines.experimental.SequenceBuilderIterator.yield(SequenceBuilder.kt:163)
    at com.github.fdudannychen.HelloKt$main$fibo$1.doResume(Hello.kt:7)
    at
  kotlin.coroutines.experimental.jvm.internal.CoroutineImpl.resume(CoroutineImpl.kt:54)
    at
  kotlin.coroutines.experimental.SequenceBuilderIterator.hasNext(SequenceBuilder.kt:128)
    at kotlin.sequences.TakeSequence$iterator$1.hasNext(Sequences.kt:348)
    at com.github.fdudannychen.HelloKt.main(Hello.kt:22)

Steps in this article don't help to fix the issue. I don't know why it's not working. Am I missing something?


问:
ajax request getting HTTP status code 403
I already create POST method in Spring and I want consume with AJAX POST but I found an error.

My code is:

Controller Spring:

```<code>@PostMapping(value={"/tesinsert"}, consumes={"application/json"})
@ResponseStatus(HttpStatus.CREATED)
public ResponseEntity<?> insert(@RequestBody KasusEntity user) throws Exception {
    Map result = new HashMap();
    userService.insertTabel(user);
    return new ResponseEntity<>(result, HttpStatus.CREATED);
}
</code>```

Javascript:

```<code>var data = {
        "kodekasus":5,
        "nama":"baru",
        "isdelete":1,
        "createdby":"hahaa",
        "createddate":null,
        "updatedby":"hihii",
        "updateddate":null
};

    var url = "http://localhost:8089/SpringNew/tesinsert";

    $.ajax({
        type: 'POST',
        url: url,
        dataType: 'json',
        data: JSON.stringify(data),
        success: function(data) {
            console.log('sukses: '+data);
        },
        error: function(error){
            console.log('gagal: '+error);
        }
        ,
        headers: {
            Accept : "application/json",
            "Content-Type": "application/json;charset=UTF-8"
            }
    });
</code>```

How can I solve this problem?

How to finding error source? in javascript or spring?

答:
HTTP status code 403 means access forbidded or denied

So May be your application is not permitted to request to the endpoint with the credential you are trying.

May be some security things blocks your request. You have find that, it should be in Spring (i mean in your application server)

Body:
I already create POST method in Spring and I want consume with AJAX POST but I found an error.

My code is:

Controller Spring:

@PostMapping(value={"/tesinsert"}, consumes={"application/json"})
@ResponseStatus(HttpStatus.CREATED)
public ResponseEntity<?> insert(@RequestBody KasusEntity user) throws Exception {
    Map result = new HashMap();
    userService.insertTabel(user);
    return new ResponseEntity<>(result, HttpStatus.CREATED);
}

Javascript:

var data = {
        "kodekasus":5,
        "nama":"baru",
        "isdelete":1,
        "createdby":"hahaa",
        "createddate":null,
        "updatedby":"hihii",
        "updateddate":null
};

    var url = "http://localhost:8089/SpringNew/tesinsert";

    $.ajax({
        type: 'POST',
        url: url,
        dataType: 'json',
        data: JSON.stringify(data),
        success: function(data) {
            console.log('sukses: '+data);
        },
        error: function(error){
            console.log('gagal: '+error);
        }
        ,
        headers: {
            Accept : "application/json",
            "Content-Type": "application/json;charset=UTF-8"
            }
    });

How can I solve this problem?

How to finding error source? in javascript or spring?


问:
Removing dynamically an element from a list
My question can looks a bit weird and easy, but I can't find a satisfying answer. I want to iterate on a list, and remove elements from it. The problem happens when there is one element left in the list after a deletion: the loop will not iterate on the last element, just as if the list was empty.

I am using a for .. in .. like in the following example:

```<code>def test_remove(self):
    """Test to remove all values from a list."""
    test = [4, 5]
    [test.remove(i) for i in test]
    print test
</code>```

I am getting the following output:

```<code>[5]
</code>```

Does it mean that iterating like I am doing on a list doesn't dynamically resize the list when an element is deleted (same thing is happening using for i in range()) ? Or it is just because i am simply reaching i = len, and so I can't go further ?

I could always cheat and check when the len is equal to 1 but I would like to understand if there is a more beautiful way to do this.

Thank you very much.

答:
Use:

```<code>for (Iterator<String> iter = list.listIterator(); iter.hasNext(); ){
    String a = iter.next();
    if (...) {
        iter.remove();
        }
    }
</code>```

Use the code as above; it will work. It worked for me in removing all elements from the list.

Body:
My question can looks a bit weird and easy, but I can't find a satisfying answer. I want to iterate on a list, and remove elements from it. The problem happens when there is one element left in the list after a deletion: the loop will not iterate on the last element, just as if the list was empty.

I am using a for .. in .. like in the following example:

def test_remove(self):
    """Test to remove all values from a list."""
    test = [4, 5]
    [test.remove(i) for i in test]
    print test

I am getting the following output:

[5]

Does it mean that iterating like I am doing on a list doesn't dynamically resize the list when an element is deleted (same thing is happening using for i in range()) ? Or it is just because i am simply reaching i = len, and so I can't go further ?

I could always cheat and check when the len is equal to 1 but I would like to understand if there is a more beautiful way to do this.

Thank you very much.

Body:
Use:

for (Iterator<String> iter = list.listIterator(); iter.hasNext(); ){
    String a = iter.next();
    if (...) {
        iter.remove();
        }
    }

Use the code as above; it will work. It worked for me in removing all elements from the list.


问:
Uncaught SyntaxError: missing ) after argument list - Other answers did not solve it
My SO search tells me that this error occurs when you have an extra bracket, or another formatting error (source, source etc.). But I have gone through my code snippet again and again, and haven't been able to spot any such problem. But I am still getting the error:

```<code>Uncaught SyntaxError: missing ) after argument list
</code>```

Following is my script. The question is why I am getting this error, and how to resolve this.

```<code><?php

$(document).ready(function() {
    alert("scripts.js detected");//check

    alert($("input#theInput").val());//check

    /*
    *
    */
    $("form#theInputForm").submit(function(event) {
        event.preventDefault();

        if ($("input#theInput").val() == '') {
            alert("Please enter a the value.");
        } else {

            $(".inputFormWrapper").css("height") = "10vh";
            $(".otherSectionWrapper").show();

            var theEntered = $("input#theInput").val();

            $.ajax(
                url: "get_the_data_two.php",
                method: "get",
                data: {
                    theFromUser: theEntered
                },
                success: function(otherData, textStatus, jqXHR) {

                    alert(otherData);//check

                },
                error: function(jqXHR, textStatus, errorThrown) {
                    alert("textStatus: " + textStatus + " \nerrorThrown: " + errorThrown);//check
                }
            );

        }

    });

});

?>
</code>```

答:
Two things :: Assignment of height is not proper and ajax syntax.

Your else part should be as follows:

```<code>{
    $(".inputFormWrapper").css("height","100px");
    $(".responseSectionWrapper").css("height","90px");

    var tmsiEntered = $("input#tmsiInput").val();

    $.ajax({
        url: "get_auth_data_two.php",
        method: "get",
        data: {
            tmsiFromUser: tmsiEntered
        },
        success: function(responseData, textStatus, jqXHR) {

            alert(responseData);//check

        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert("textStatus: " + textStatus + " \nerrorThrown: " + errorThrown);//check
        }
    });

}
</code>```

When in doubt, check the API: http://api.jquery.com/css/

Body:
My SO search tells me that this error occurs when you have an extra bracket, or another formatting error (source, source etc.). But I have gone through my code snippet again and again, and haven't been able to spot any such problem. But I am still getting the error:

Uncaught SyntaxError: missing ) after argument list

Following is my script. The question is why I am getting this error, and how to resolve this.

<?php

$(document).ready(function() {
    alert("scripts.js detected");//check

    alert($("input#theInput").val());//check

    /*
    *
    */
    $("form#theInputForm").submit(function(event) {
        event.preventDefault();

        if ($("input#theInput").val() == '') {
            alert("Please enter a the value.");
        } else {

            $(".inputFormWrapper").css("height") = "10vh";
            $(".otherSectionWrapper").show();

            var theEntered = $("input#theInput").val();

            $.ajax(
                url: "get_the_data_two.php",
                method: "get",
                data: {
                    theFromUser: theEntered
                },
                success: function(otherData, textStatus, jqXHR) {

                    alert(otherData);//check

                },
                error: function(jqXHR, textStatus, errorThrown) {
                    alert("textStatus: " + textStatus + " \nerrorThrown: " + errorThrown);//check
                }
            );

        }

    });

});

?>

Body:
Two things :: Assignment of height is not proper and ajax syntax.

Your else part should be as follows:

{
    $(".inputFormWrapper").css("height","100px");
    $(".responseSectionWrapper").css("height","90px");

    var tmsiEntered = $("input#tmsiInput").val();

    $.ajax({
        url: "get_auth_data_two.php",
        method: "get",
        data: {
            tmsiFromUser: tmsiEntered
        },
        success: function(responseData, textStatus, jqXHR) {

            alert(responseData);//check

        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert("textStatus: " + textStatus + " \nerrorThrown: " + errorThrown);//check
        }
    });

}

When in doubt, check the API: http://api.jquery.com/css/


问:
git p4 sync changelist interval
My goal is to sync the repository from p4 using an interval of changelists so that the first changelist version of the repository would be considered as an initial commit.
So I used the following command:

```<code>git p4 clone //path-to-project@cl1,cl2
</code>```

where cl1 and cl2 are numbers of mentioned changelists.

And when it finished, the files, that were created before the cl1 were not in the HEAD.

The problem, as I see it, is that before syncing changes in the given range, p4 task does not sync to cl1 version of the repo, and applies commits to the empty repository.

Is it a bug or my misunderstanding of how git p4 should work? And how should I do this correctly?

UPD: The reason I need changelist interval is that there is a problem with the p4 database and I can't checkout changelists before one point in the past. And I would like to migrate to git with all accessible history.

答:
I think that, apart from the special import just the head revision default option, the @cl1,cl2 options only import the changelists, not the state of the repository at those changelists.

I think you'll have to do @all to get the complete history. Or alter git-p4 to do what you want.

Title: git p4 sync changelist interval

Body:
My goal is to sync the repository from p4 using an interval of changelists so that the first changelist version of the repository would be considered as an initial commit.
So I used the following command:

git p4 clone //path-to-project@cl1,cl2

where cl1 and cl2 are numbers of mentioned changelists.

And when it finished, the files, that were created before the cl1 were not in the HEAD.

The problem, as I see it, is that before syncing changes in the given range, p4 task does not sync to cl1 version of the repo, and applies commits to the empty repository.

Is it a bug or my misunderstanding of how git p4 should work? And how should I do this correctly?

UPD: The reason I need changelist interval is that there is a problem with the p4 database and I can't checkout changelists before one point in the past. And I would like to migrate to git with all accessible history.


问:
_temporary directory is not getting deleted from output location when mapreduce job is completed
I am parsing a data in order to get some sense out of it through MapReduce job. The parsed data comes in form of batches. It is further loaded to hive external table through spark streaming job. This is a real time process. Now an unusual event was faced by me today as a _temporary directory got created in output location, due to which loading into hive table failed as a directory can't be loaded into hive table. It happened only once and rest of the jobs are running fine. Please refer the screenshot.

_temporary directory further contains task IDs as sub-directories which are empty. Can anyone please help in resolving this so that it could be avoided in future.

答: _temporary directory is created when there are some tasks yet to complete, there may be few data yet to move its actual location from its temporary location. The task may showed as completed in web UI but the data movement is yet to be completed. Once this process is completed there would be only _SUCCESS file. You can check this by monitoring the size of the _temporary directory.This would be gradually reducing.   </p>


问:
Obfuscated NuGet Packages and Deployment considerations
This has been a major confusion and a consideration for deployment.

I have a portable class library (that targets Mono and Xamarin platforms) and it has a dependency licensing library as well. In order to protect tampering of the licensing library I am considering to get it obfuscated.

My question here is:

If a NuGet library is obfuscated, will it cause trouble for other projects referencing the library. Say for instance in Windows Store apps or even Android apps? Will their app be rejected from these stores due to the usage of an obfuscated library?

I have heard that obfuscated libraries may add pdb packages as a workaround. Will that suffice?

Any input or suggestion on this is much appreciated.

答:
If you develop a library, and obfuscate it private part (not a visible interface, that people use to communicate with your library) I don't see a problem for other developers to use your library.

You can submit an application with the obfuscated library to Windows/Andorid stores. They indeed scan your code, but did that in a more intelligent way (in assembler calls level, rather than plain code)


问:
kafka how to implement exactly-once message delivery logic with topic/partition/offset
I manage to get the topic/partition/offset in method annotated with @KafkaListener,  but how can i use these data to implement a exactly-once consumer logic ?

I'm using ConcurrentKafkaListenerContainerFactory with setting of concurrenc=4, and set the  AckMode to MANUAL.
My current way is using redis to dedup:
I use topic:partition as redis key, offset as its value, then compare the coming offset with the value in redis, if the offset is newer(greater) than redis one, then go on the business logic, else I ignore the  message. finally commit the offset(ack.acknowledge())

but this way not work, for example, if the rebalance happen before ack.acknowledge() finish, then it came out this error :org.apache.kafka.clients.consumer.CommitFailedException,

and after rebalancing , the original partition is assigned to another thread, which cause the same message will be consume twice.

so in one word, how to design a logic that can make each kafka message delivery exactly-once ?

答:
Kafka does not support exactly once yet. It will be available in the 0.11.0.0 release : https://issues.apache.org/jira/browse/KAFKA-4923
This release is planned for 14 June 2017, so you can wait or build this complex logic yourself ;-)</p>


问:
Alphabetical sort using elasticsearch
I wounder if there any way or setting to perform an alphabetical sort in elasticsearch. I've got a field and I want to perform sort in descending order over it. Elastic performs it lexicographically. What I get:

```<code>Company name
Customer name
company address
</code>```

What I want to get:

```<code>Company name
company address
Customer name
</code>```

I found that I can create a custom analyser, but maybe there can be a better option?

答:
use multifields to index the text field as lowercased keyword with fielddata true where you can sort.

```<code>{
  "settings": {
    "analysis": {
      "analyzer": {
        "keyword_lowercase": {
          "tokenizer": "keyword",
          "filter": ["lowercase"]
        }
      }
    }
  },
  "mappings": {
    "my_type": {
      "properties": {
        "text": {
          "type": "text",
          "fields": {
            "raw": {
              "type":     "text",
              "analyzer": "keyword_lowercase",
              "fielddata": true
            }
          }
        }
      }
    }
  }
}
</code>```

Query

```<code>{
  "sort": [
    {
      "text.raw": {
        "order": "asc"
      }
    }
  ]
}
</code>```

Title: Alphabetical sort using elasticsearch

Body:
I wounder if there any way or setting to perform an alphabetical sort in elasticsearch. I've got a field and I want to perform sort in descending order over it. Elastic performs it lexicographically. What I get:

Company name
Customer name
company address

What I want to get:

Company name
company address
Customer name

I found that I can create a custom analyser, but maybe there can be a better option?

Body:
use multifields to index the text field as lowercased keyword with fielddata true where you can sort.

{
  "settings": {
    "analysis": {
      "analyzer": {
        "keyword_lowercase": {
          "tokenizer": "keyword",
          "filter": ["lowercase"]
        }
      }
    }
  },
  "mappings": {
    "my_type": {
      "properties": {
        "text": {
          "type": "text",
          "fields": {
            "raw": {
              "type":     "text",
              "analyzer": "keyword_lowercase",
              "fielddata": true
            }
          }
        }
      }
    }
  }
}

Query

{
  "sort": [
    {
      "text.raw": {
        "order": "asc"
      }
    }
  ]
}


问:
Linq to SQL anonymous types return null
I have a query that returns multiple result sets. But if one of the results is null, then nothing is returned. Is it possible to recover the data even if this result set is null?

Example:

```<code>from u in Units
select new
{
    Unit = u,
    AgreementType = from at in AgreementTypes
                    select new { at },
    OptionRightsType = from ortp in OptionRightsTypes
                       select new { ortp }
}
</code>```

In this example, if Unit is null, then no records are returned. Is it possible to recover the other result sets even if unit is null?

UPDATE

Example:

```<code>from u in Units
where u.Id == 1000
select new
{
    Unit = u,
    AgreementType = from at in AgreementTypes
                    select new { at },
    OptionRightsType = from ortp in OptionRightsTypes
                       select new { ortp }
}
</code>```

In the above example, I would exist the result to recover three IQueryable types, Unit, AgreementType, OptionRightsType.

This is the case, but if the query does not find a unit with id equal to 1000, then it returns null.

Can I still recover the AgreementType and OptionRightsType types when the unit return no records?

UPDATE 2

What I am trying to do is:

```<code>from u in Units
where u.Id == 1000
select new
{
    Unit = u
}
</code>```

and

```<code>from at in AgreementTypes
           select new
           {
               at,
               OptionRightsType = from ortp in OptionRightsTypes
                                  select new { ortp }
            }
</code>```

Two completely separate queries.

I just thought that I could join them together as the second query just pulls static data back

答:
What it sounds like you need is this:

```<code>var unit = Units.Where(u => u.Id == 1000).FirstOrDefault();
var agreementTypes = AgreementTypes.ToArray();
var optionRightsTypes = OptionRightsTypes.ToArray();
</code>```

Don't worry about network calls until you know you have an actual problem with the speed of the calls.

Title: Linq to SQL anonymous types return null

Body:
I have a query that returns multiple result sets. But if one of the results is null, then nothing is returned. Is it possible to recover the data even if this result set is null?

Example:

from u in Units
select new
{
    Unit = u,
    AgreementType = from at in AgreementTypes
                    select new { at },
    OptionRightsType = from ortp in OptionRightsTypes
                       select new { ortp }
}

In this example, if Unit is null, then no records are returned. Is it possible to recover the other result sets even if unit is null?

UPDATE

Example:

from u in Units
where u.Id == 1000
select new
{
    Unit = u,
    AgreementType = from at in AgreementTypes
                    select new { at },
    OptionRightsType = from ortp in OptionRightsTypes
                       select new { ortp }
}

In the above example, I would exist the result to recover three IQueryable types, Unit, AgreementType, OptionRightsType.

This is the case, but if the query does not find a unit with id equal to 1000, then it returns null.

Can I still recover the AgreementType and OptionRightsType types when the unit return no records?

UPDATE 2

What I am trying to do is:

from u in Units
where u.Id == 1000
select new
{
    Unit = u
}

and

from at in AgreementTypes
           select new
           {
               at,
               OptionRightsType = from ortp in OptionRightsTypes
                                  select new { ortp }
            }

Two completely separate queries.

I just thought that I could join them together as the second query just pulls static data back

Body:
What it sounds like you need is this:

var unit = Units.Where(u => u.Id == 1000).FirstOrDefault();
var agreementTypes = AgreementTypes.ToArray();
var optionRightsTypes = OptionRightsTypes.ToArray();

Don't worry about network calls until you know you have an actual problem with the speed of the calls.


问:
VBA Copy a pivot table and rename
I am working on the following code in Excel VBA. I copied a pivot table to L8 and want to rename this pivot table to "PivotTable00". However error message "Object Doesn't support this property or method" when it goes to the second line here.

Is there a way to fix it? Many thanks.

```<code>wsPvtTbl.PivotTables("PivotTable1").TableRange2.Copy Destination:=wsPvtTbl.Range("L8")
wsPvtTbl.Range("L8").Activate
ActiveCell.pivotTable.Name = "PivotTable00"
</code>```

答:
Instead of using Activate and ActiveCell (which only slows down your code's run-time), you can use the fact that the latest PivotTable that is pasted, gets the first index of the PivotTables in wsPvtTbl worksheet, try:

```<code>wsPvtTbl.PivotTables("PivotTable1").TableRange2.Copy Destination:=wsPvtTbl.Range("L8")
wsPvtTbl.PivotTables(1).Name = "PivotTable00"
</code>```

Title: VBA Copy a pivot table and rename

Body:
I am working on the following code in Excel VBA. I copied a pivot table to L8 and want to rename this pivot table to "PivotTable00". However error message "Object Doesn't support this property or method" when it goes to the second line here.

Is there a way to fix it? Many thanks.

wsPvtTbl.PivotTables("PivotTable1").TableRange2.Copy Destination:=wsPvtTbl.Range("L8")
wsPvtTbl.Range("L8").Activate
ActiveCell.pivotTable.Name = "PivotTable00"

Body:
Instead of using Activate and ActiveCell (which only slows down your code's run-time), you can use the fact that the latest PivotTable that is pasted, gets the first index of the PivotTables in wsPvtTbl worksheet, try:

wsPvtTbl.PivotTables("PivotTable1").TableRange2.Copy Destination:=wsPvtTbl.Range("L8")
wsPvtTbl.PivotTables(1).Name = "PivotTable00"


问:
How to get a list of all available packet names in Node.js JavaScript Client for MySQL?
Where may I read a list of all available packets to select which ones I need for a debug array (here)?

debug: Prints protocol details to stdout. Can be true/false or an array of packet type names that should be printed. (Default: false)

They mentioned the option in docs but forgot to supply any link or a list of available packet names.

答:
Ok, I found it. A name of a file references a packet name (I hope):

https://github.com/mysqljs/mysql/tree/master/lib/protocol/packets

This is how it may be implemented in an app:

```<code>module.exports = {
    'development': {
        host: 'your-db-host.com',
        port: 3306,
        database: 'your-db-name',
        dialect: 'mysql',
        user: 'username',
        password: 'userpassword',
        connectionLimit: 10,

        // or an array of packet type names that should be printed.
        debug: ['ComQueryPacket', 'OkPacket', 'ComQueryPacket', 'ResultSetHeaderPacket', 'ErrorPacket'],
    },
}
</code>```

Body:
Ok, I found it. A name of a file references a packet name (I hope):

https://github.com/mysqljs/mysql/tree/master/lib/protocol/packets

This is how it may be implemented in an app:

module.exports = {
    'development': {
        host: 'your-db-host.com',
        port: 3306,
        database: 'your-db-name',
        dialect: 'mysql',
        user: 'username',
        password: 'userpassword',
        connectionLimit: 10,

        // or an array of packet type names that should be printed.
        debug: ['ComQueryPacket', 'OkPacket', 'ComQueryPacket', 'ResultSetHeaderPacket', 'ErrorPacket'],
    },
}


问:
How to throw exception while converting from JsonStr to PojoClassObj if any key/value is missing in the JsonStr?
I tried using @NotNull annotation but it did not work. If any field is missing in the JsonString, it gives null(String) or zero(int). But what I want is if any field is missing in the JsonStr defined in the class should throw an exception.

Add: My PojoClass may have object reference or multilevel object reference. I am using Gson for the conversion of the String to obj.
for more clarification, I have added my code below:

JsonStr:

```<code>{
   "name":"John",
   "id":1,
   "roll":100,
   "c":{
      "city":"Dhaka",
      "school":"B. govt. School"
   }
}
</code>```

Code:

```<code>public class C {

    private String city;
    private String school;

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getSchool() {
        return school;
    }

    public void setSchool(String school) {
        this.school = school;
    }

}
</code>```

ClassB:

```<code>public class B {

    private String name;
    private int id;
    @NotNull
    private int roll;
    private C c;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getRoll() {
        return roll;
    }

    public void setRoll(int roll) {
        this.roll = roll;
    }

    public C getC() {
        return c;
    }

    public void setC(C c) {
        this.c = c;
    }

}
</code>```

MainClass:

```<code>try {
                B obj = new B();
                String str = "{\"name\":\"John\",\"id\":1,\"c\":{\"city\":\"dhaka\",\"school\":\"school\"}}";
                obj = gson.fromJson(str, B.class);

            } catch (RuntimeException e) {
                 System.out.println("exception Message");

            }
</code>```

For the field roll, I used @NotNull to throw an exception if that field is not present in the JsonStr but it gives 0 value without throwing any exception.

How can I implement that?

Please don't say this is duplicate, because I have seen these questions:

GSON throwing null pointer exception when a field is missing in json [duplicate]

What is a NullPointerException, and how do I fix it?

答:
@NotNull is not a part of Gson, and it cannot handle it by default (unless you add support yourself). Also, nullability-check annotations should not be applied to primitives fields -- generally speaking it makes not much sense. Also, the default int fields values are 0, and Gson does not check if a particular field was read from a JSON document. However, you can easily implement it if you:

slightly change your mapping by changing the primitive int to its nullable wrapper Integer;

implement a custom post-processing validation type adapter.

For example,

final class Person {

    final String name = null;

    final int id = Integer.valueOf(0); // final primitive fields are inlined by javac

    @NotNull
    final Integer roll = null;

    @SerializedName("c")
    final Location location = null;

}
```

<pre class="lang-java prettyprint-override"><code>final class Location {

    final String city = null;

    final String school = null;

}
</code>```

The next step is just creating your own type adapter to check the nullable fields.

final class NotNullTypeAdapterFactory
        implements TypeAdapterFactory {

    // The type adapter factory holds no state, so no need to instantiate it multiple times
    private static final TypeAdapterFactory notNullTypeAdapterFactory = new NotNullTypeAdapterFactory();

    private NotNullTypeAdapterFactory() {
    }

    static TypeAdapterFactory getNotNullTypeAdapterFactory() {
        return notNullTypeAdapterFactory;
    }

    @Override
    public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> typeToken) {
        final Collection<Field> notNullFields = getNotNullFields(typeToken.getRawType());
        // If no @NotNull fields found, then just tell Gson to pick the next best type adapter
        if ( notNullFields.isEmpty() ) {
            return null;
        }
        // If there's at least one @NotNull field, get the original type adapter
        final TypeAdapter<T> delegateTypeAdapter = gson.getDelegateAdapter(this, typeToken);
        return new TypeAdapter<T>() {
            @Override
            public void write(final JsonWriter out, final T value)
                    throws IOException {
                delegateTypeAdapter.write(out, value);
            }

            @Override
            public T read(final JsonReader in)
                    throws IOException {
                try {
                    // Read the value ...
                    final T value = delegateTypeAdapter.read(in);
                    // ... and make some post-processing
                    for ( final Field f : notNullFields ) {
                        if ( f.get(value) == null ) {
                            throw new MalformedJsonException(f + " has no value");
                        }
                    }
                    return value;
                } catch ( final IllegalAccessException ex ) {
                    throw new IOException(ex);
                }
            }
        };
    }

    private static Collection<Field> getNotNullFields(final Class<?> clazz) {
        // Primitive types and java.lang.Object do not have @NotNull
        if ( clazz.isPrimitive() || clazz == Object.class ) {
            return emptyList();
        }
        // Scan the whole hierarchy from the bottom subclass to the top superclass (except java.lang.Object we mentioned above)
        final Collection<Field> notNullFields = new ArrayList<>();
        for ( Class<?> c = clazz; c != Object.class; c = c.getSuperclass() ) {
            for ( final Field f : c.getDeclaredFields() ) {
                if ( f.isAnnotationPresent(NotNull.class) ) {
                    // Don't forget to make private fields accessible
                    f.setAccessible(true);
                    notNullFields.add(f);
                }
            }
        }
        return notNullFields;
    }

}
```

<p>Test (uses some Google Guava and custom resource readers):</p>

<pre class="lang-java prettyprint-override"><code>private static final Gson gson = new GsonBuilder()
        .registerTypeAdapterFactory(getNotNullTypeAdapterFactory())
        .create();

public static void main(final String... args)
        throws IOException {
    for ( final String resourceName : ImmutableList.of("file-with-roll.json", "file-without-roll.json") ) {
        System.out.println("Deserializing " + resourceName);
        try ( final JsonReader jsonReader = getPackageResourceJsonReader(Q44362030.class, resourceName) ) {
            try {
                final Person person = gson.fromJson(jsonReader, Person.class);
                System.out.println(person.name + " " + person.roll);
            } catch ( final Exception ex ) {
                System.out.println("FAILED! " + ex.getMessage());
            }
        }
    }
}
</code>```

Output:

Deserializing file-with-roll.json

  John 100

  Deserializing file-without-roll.json

  FAILED! com.google.gson.stream.MalformedJsonException: final java.lang.Integer q44362030.Person.roll has no value

Similarly, you can create your another TypeAdapter to check all fields automatically not even needing @NotNull, but this needs a more complicated implementation.

Body:
I tried using @NotNull annotation but it did not work. If any field is missing in the JsonString, it gives null(String) or zero(int). But what I want is if any field is missing in the JsonStr defined in the class should throw an exception.

Add: My PojoClass may have object reference or multilevel object reference. I am using Gson for the conversion of the String to obj.
for more clarification, I have added my code below:

JsonStr:

{
   "name":"John",
   "id":1,
   "roll":100,
   "c":{
      "city":"Dhaka",
      "school":"B. govt. School"
   }
}

Code:

public class C {

    private String city;
    private String school;

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getSchool() {
        return school;
    }

    public void setSchool(String school) {
        this.school = school;
    }

}

ClassB:

public class B {

    private String name;
    private int id;
    @NotNull
    private int roll;
    private C c;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getRoll() {
        return roll;
    }

    public void setRoll(int roll) {
        this.roll = roll;
    }

    public C getC() {
        return c;
    }

    public void setC(C c) {
        this.c = c;
    }

}

MainClass:

try {
                B obj = new B();
                String str = "{\"name\":\"John\",\"id\":1,\"c\":{\"city\":\"dhaka\",\"school\":\"school\"}}";
                obj = gson.fromJson(str, B.class);

            } catch (RuntimeException e) {
                 System.out.println("exception Message");

            }

For the field roll, I used @NotNull to throw an exception if that field is not present in the JsonStr but it gives 0 value without throwing any exception.

How can I implement that?

Please don't say this is duplicate, because I have seen these questions:

GSON throwing null pointer exception when a field is missing in json [duplicate]

What is a NullPointerException, and how do I fix it?

Body:
@NotNull is not a part of Gson, and it cannot handle it by default (unless you add support yourself). Also, nullability-check annotations should not be applied to primitives fields -- generally speaking it makes not much sense. Also, the default int fields values are 0, and Gson does not check if a particular field was read from a JSON document. However, you can easily implement it if you:

slightly change your mapping by changing the primitive int to its nullable wrapper Integer;

implement a custom post-processing validation type adapter.

For example,

final class Person {

    final String name = null;

    final int id = Integer.valueOf(0); // final primitive fields are inlined by javac

    @NotNull
    final Integer roll = null;

    @SerializedName("c")
    final Location location = null;

}

final class Location {

    final String city = null;

    final String school = null;

}

The next step is just creating your own type adapter to check the nullable fields.

final class NotNullTypeAdapterFactory
        implements TypeAdapterFactory {

    // The type adapter factory holds no state, so no need to instantiate it multiple times
    private static final TypeAdapterFactory notNullTypeAdapterFactory = new NotNullTypeAdapterFactory();

    private NotNullTypeAdapterFactory() {
    }

    static TypeAdapterFactory getNotNullTypeAdapterFactory() {
        return notNullTypeAdapterFactory;
    }

    @Override
    public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> typeToken) {
        final Collection<Field> notNullFields = getNotNullFields(typeToken.getRawType());
        // If no @NotNull fields found, then just tell Gson to pick the next best type adapter
        if ( notNullFields.isEmpty() ) {
            return null;
        }
        // If there's at least one @NotNull field, get the original type adapter
        final TypeAdapter<T> delegateTypeAdapter = gson.getDelegateAdapter(this, typeToken);
        return new TypeAdapter<T>() {
            @Override
            public void write(final JsonWriter out, final T value)
                    throws IOException {
                delegateTypeAdapter.write(out, value);
            }

            @Override
            public T read(final JsonReader in)
                    throws IOException {
                try {
                    // Read the value ...
                    final T value = delegateTypeAdapter.read(in);
                    // ... and make some post-processing
                    for ( final Field f : notNullFields ) {
                        if ( f.get(value) == null ) {
                            throw new MalformedJsonException(f + " has no value");
                        }
                    }
                    return value;
                } catch ( final IllegalAccessException ex ) {
                    throw new IOException(ex);
                }
            }
        };
    }

    private static Collection<Field> getNotNullFields(final Class<?> clazz) {
        // Primitive types and java.lang.Object do not have @NotNull
        if ( clazz.isPrimitive() || clazz == Object.class ) {
            return emptyList();
        }
        // Scan the whole hierarchy from the bottom subclass to the top superclass (except java.lang.Object we mentioned above)
        final Collection<Field> notNullFields = new ArrayList<>();
        for ( Class<?> c = clazz; c != Object.class; c = c.getSuperclass() ) {
            for ( final Field f : c.getDeclaredFields() ) {
                if ( f.isAnnotationPresent(NotNull.class) ) {
                    // Don't forget to make private fields accessible
                    f.setAccessible(true);
                    notNullFields.add(f);
                }
            }
        }
        return notNullFields;
    }

}

Test (uses some Google Guava and custom resource readers):

private static final Gson gson = new GsonBuilder()
        .registerTypeAdapterFactory(getNotNullTypeAdapterFactory())
        .create();

public static void main(final String... args)
        throws IOException {
    for ( final String resourceName : ImmutableList.of("file-with-roll.json", "file-without-roll.json") ) {
        System.out.println("Deserializing " + resourceName);
        try ( final JsonReader jsonReader = getPackageResourceJsonReader(Q44362030.class, resourceName) ) {
            try {
                final Person person = gson.fromJson(jsonReader, Person.class);
                System.out.println(person.name + " " + person.roll);
            } catch ( final Exception ex ) {
                System.out.println("FAILED! " + ex.getMessage());
            }
        }
    }
}

Output:

Deserializing file-with-roll.json

  John 100

  Deserializing file-without-roll.json

  FAILED! com.google.gson.stream.MalformedJsonException: final java.lang.Integer q44362030.Person.roll has no value

Similarly, you can create your another TypeAdapter to check all fields automatically not even needing @NotNull, but this needs a more complicated implementation.


问:
python how to get proper distance value out of scipy condensed distance matrix
I am using python 2.7 with scipy to calculate a distance matrix for an array.

I don't get how to find the wanted distance values in the returned condensed matrix.

See example

```<code>from scipy.spatial.distance import pdist
import numpy as np

a = np.array([[1],[4],[0],[5]])
print a
print pdist(a)
</code>```

will print

```<code>[ 3.  1.  4.  4.  1.  5.]
</code>```

I found here that the ij entry in the condensed matrix should store the distance between the i and j entries where ithread wondering if they mean ij as i*j or str.join(i,j) e.g 1,2 -> 2 or 12.

I can't find a consistent way to know the wanted index.

see my example, you should expect that all of the distances from entry 0 to anywhere else will be stored in entry 0 if the first option is valid.

can anyone shed some light on how can i extract my wanted distance from entry x to entry y? which index am i looking for?

Thanks!

答:
This vector is in condensed form. It enumerates all pairs of indices in a natural order (in your example 0,1 0,2 0,3 0,4 1,2 1,3 1,4 2,3 2,4 ) and yields the distance between the elements at these array entries.

There is also the squareform function, which transforms the condensed form into a square matrix form (and vice versa). The square matrix form is exactly what you expect, i.e. at entry ij (row i, column j), it stores the distance between the i-th and j-th entry. For example, if you add print squareform(d) at the end of you code, the output will be:

```<code>array([[ 0.,  3.,  1.,  4.],
       [ 3.,  0.,  4.,  1.],
       [ 1.,  4.,  0.,  5.],
       [ 4.,  1.,  5.,  0.]])
</code>```

Body:
I am using python 2.7 with scipy to calculate a distance matrix for an array.

I don't get how to find the wanted distance values in the returned condensed matrix.

See example

from scipy.spatial.distance import pdist
import numpy as np

a = np.array([[1],[4],[0],[5]])
print a
print pdist(a)

will print

[ 3.  1.  4.  4.  1.  5.]

I found here that the ij entry in the condensed matrix should store the distance between the i and j entries where ithread wondering if they mean ij as i*j or str.join(i,j) e.g 1,2 -> 2 or 12.

I can't find a consistent way to know the wanted index.

see my example, you should expect that all of the distances from entry 0 to anywhere else will be stored in entry 0 if the first option is valid.

can anyone shed some light on how can i extract my wanted distance from entry x to entry y? which index am i looking for?

Thanks!

Body:
This vector is in condensed form. It enumerates all pairs of indices in a natural order (in your example 0,1 0,2 0,3 0,4 1,2 1,3 1,4 2,3 2,4 ) and yields the distance between the elements at these array entries.

There is also the squareform function, which transforms the condensed form into a square matrix form (and vice versa). The square matrix form is exactly what you expect, i.e. at entry ij (row i, column j), it stores the distance between the i-th and j-th entry. For example, if you add print squareform(d) at the end of you code, the output will be:

array([[ 0.,  3.,  1.,  4.],
       [ 3.,  0.,  4.,  1.],
       [ 1.,  4.,  0.,  5.],
       [ 4.,  1.,  5.,  0.]])


问:
Insert arbitrary text and modify NodeArrays in the TypeScript compiler API
```<code>// Input
class Foo {
    templateString = 'some value';
}

// Output
import __LIB__ from '@scope/lib/path/to/lib';

class Foo {
    templateString = (function compiledTemplate(deps) {
        // ...
        return result;
    })({lib: __LIB__});
}
</code>```

In fact, I have two questions:

How to create AST-fragment from string?

How to add import?

P.S. I tried various methods createSourceFile and ts.createImportDeclaration, but they all lead to this or that error: [

答:
To add in arbitrary text, the best way I know of is to use createIdentifier with the string you want to insert.

To add in an import statement, remember that you're updating the tree without mutating the original.

The ts.visitEachChild API takes a nodesVisitor parameter which specially operates on NodeArrays. Usually, if you don't pass a nodesVisitor in, it will operate on each Node in the NodeArray using the first callback you pass for the visitor parameter, but here you specially want to operate on the full node array.

In your case, you're interested in a SourceFile's statements (which is a NodeArray<Statement>. You can create the import with createImportDeclaration, and update the SourceFile by passing in a nodesVisitor like the following:

```<code>function addImport(statements: ts.NodeArray<ts.Statement>) {
    const importStatement = ts.createImportStatement(/*...*/);
    return ts.createNodeArray([importStatement, ...statements]);
}

visitEachChild(
    sourceFile,
    /*replace this with something that controls traversal*/ x => x,
    context,
    addImport);
</code>```

Body:
// Input
class Foo {
    templateString = 'some value';
}

// Output
import __LIB__ from '@scope/lib/path/to/lib';

class Foo {
    templateString = (function compiledTemplate(deps) {
        // ...
        return result;
    })({lib: __LIB__});
}

In fact, I have two questions:

How to create AST-fragment from string?

How to add import?

P.S. I tried various methods createSourceFile and ts.createImportDeclaration, but they all lead to this or that error: [

Body:
To add in arbitrary text, the best way I know of is to use createIdentifier with the string you want to insert.

To add in an import statement, remember that you're updating the tree without mutating the original.

The ts.visitEachChild API takes a nodesVisitor parameter which specially operates on NodeArrays. Usually, if you don't pass a nodesVisitor in, it will operate on each Node in the NodeArray using the first callback you pass for the visitor parameter, but here you specially want to operate on the full node array.

In your case, you're interested in a SourceFile's statements (which is a NodeArray<Statement>. You can create the import with createImportDeclaration, and update the SourceFile by passing in a nodesVisitor like the following:

function addImport(statements: ts.NodeArray<ts.Statement>) {
    const importStatement = ts.createImportStatement(/*...*/);
    return ts.createNodeArray([importStatement, ...statements]);
}

visitEachChild(
    sourceFile,
    /*replace this with something that controls traversal*/ x => x,
    context,
    addImport);


问:
How can I save the position of a Drag and Drop image after refreshing the page
I want to do with this is that, whenever im going to drag and resize the images it will save the position or it will still remain if im going to refresh the page. How can I solve that?</p>

答:
Store your positions in localStorage on event of onbeforeunload this is called before page is refreshed.

The localStorage property allows you to access a local Storage object.
  localStorage is similar to sessionStorage. The only difference is
  that, while data stored in localStorage has no expiration time, data
  stored in sessionStorage gets cleared when the browsing session
  ends—that is, when the browser is closed.

```<code>localStorage.setItem('somekey',JSON.stringify(positionData));
// stringify if your data is an object.
</code>```

and then on load of page reposition them by reading the values from the localStorage

```<code>var data = localStorage.getItem('somekey',positionData);
if(data) var position = JSON.parse(data); // parse string to get object
else{
    //Do normal logic
}
</code>```

Body:
Store your positions in localStorage on event of onbeforeunload this is called before page is refreshed.

The localStorage property allows you to access a local Storage object.
  localStorage is similar to sessionStorage. The only difference is
  that, while data stored in localStorage has no expiration time, data
  stored in sessionStorage gets cleared when the browsing session
  ends—that is, when the browser is closed.

localStorage.setItem('somekey',JSON.stringify(positionData));
// stringify if your data is an object.

and then on load of page reposition them by reading the values from the localStorage

var data = localStorage.getItem('somekey',positionData);
if(data) var position = JSON.parse(data); // parse string to get object
else{
    //Do normal logic
}


问:
Zorder specification in matplotlib patch collections?
I am trying to plot a series of rectangles and circles, with the circles in the foreground.

According to the following post, I have to set the zorder argument:
Patches I add to my graph are not opaque with alpha=1. Why?

This works fine when I plot all the circles individually, but not when I try to place a series of circles into a collection and add the collection, i.e.

```<code>fig,ax=plt.subplots(1)
p_fancy = FancyBboxPatch((1,1),
                         0.5, 0.5,
                         boxstyle="round,pad=0.1",
                         fc='beige',
                         ec='None', zorder=1)
ax.add_patch(p_fancy)
ax.set_xlim([0,2])
ax.set_ylim([0,2])
circ=patches.Circle ((1,1), 0.2, zorder=10)
ax.add_patch(circ)
</code>```

works fine:

while

```<code>fig,ax=plt.subplots(1)
p_fancy = FancyBboxPatch((1,1),
                         0.5, 0.5,
                         boxstyle="round,pad=0.1",
                         fc='beige',
                         ec='None', zorder=1)
ax.add_patch(p_fancy)
ax.set_xlim([0.,2])
ax.set_ylim([0.,2])
circ=[]
circ.append(patches.Circle ((1,1), 0.2, zorder=10))
coll=PatchCollection(circ)
ax.add_collection(coll)
</code>```

does not:

Is there a reason, or does zorder work differently with patch collections in ways that I don't understand?

答:
In the second case you want the PatchCollection to have a defined zorder, not the members of the PatchCollection. Thus, you need to specify zorder for the collection.

```<code>circ=[]
circ.append(Circle ((1,1), 0.2))
coll=PatchCollection(circ, zorder=10)
ax.add_collection(coll)
</code>```

Body:
I am trying to plot a series of rectangles and circles, with the circles in the foreground.

According to the following post, I have to set the zorder argument:
Patches I add to my graph are not opaque with alpha=1. Why?

This works fine when I plot all the circles individually, but not when I try to place a series of circles into a collection and add the collection, i.e.

fig,ax=plt.subplots(1)
p_fancy = FancyBboxPatch((1,1),
                         0.5, 0.5,
                         boxstyle="round,pad=0.1",
                         fc='beige',
                         ec='None', zorder=1)
ax.add_patch(p_fancy)
ax.set_xlim([0,2])
ax.set_ylim([0,2])
circ=patches.Circle ((1,1), 0.2, zorder=10)
ax.add_patch(circ)

works fine:

while

fig,ax=plt.subplots(1)
p_fancy = FancyBboxPatch((1,1),
                         0.5, 0.5,
                         boxstyle="round,pad=0.1",
                         fc='beige',
                         ec='None', zorder=1)
ax.add_patch(p_fancy)
ax.set_xlim([0.,2])
ax.set_ylim([0.,2])
circ=[]
circ.append(patches.Circle ((1,1), 0.2, zorder=10))
coll=PatchCollection(circ)
ax.add_collection(coll)

does not:

Is there a reason, or does zorder work differently with patch collections in ways that I don't understand?

Body:
In the second case you want the PatchCollection to have a defined zorder, not the members of the PatchCollection. Thus, you need to specify zorder for the collection.

circ=[]
circ.append(Circle ((1,1), 0.2))
coll=PatchCollection(circ, zorder=10)
ax.add_collection(coll)


问:
Error in receiving JSON object from API
I am making an http request from ionic app(Angular4) and receiving a response in form of a Js object, but on receiving i am getting some error.

This is the object which i am receiving from API

```<code>{"up_votes":"1","down_votes":"0"}
</code>```

using http.get to receive data in app, home.ts

```<code>..
public vote_response:any={};
...
this.http.get(this.baseURI+'votesNum.php?'+this.question.question_id)
        .subscribe(result =>{this.vote_response = result.json();});
</code>```

this is the error which i am receiving:

```<code>ERROR SyntaxError: Unexpected token < in JSON at position 0
    at JSON.parse (<anonymous>)
    at Response.Body.json (http.es5.js:800)
    at MapSubscriber.project (forum-quest-details.ts:44)
    at MapSubscriber._next (map.js:77)
    at MapSubscriber.Subscriber.next (Subscriber.js:89)
    at XMLHttpRequest.onLoad (http.es5.js:1229)
    at t.invokeTask (polyfills.js:3)
    at Object.onInvokeTask (core.es5.js:4119)
    at t.invokeTask (polyfills.js:3)
    at r.runTask (polyfills.js:3)
</code>```

Can anyone help me solve this issue.

答:
```<code>this.vote_response = result.json();
</code>```

Replace this one with console.log(result) and take the data and check with some online JSON validation site  (https://jsonlint.com) to see if the data is valid JSON. You might be getting HTML body instead of JSON.

To response as JSON:

```<code>header('Content-Type: application/json');
echo  json_encode(array('up_votes'=>$up_votes, 'down_votes'=> $down_votes ));
</code>```

Title: Error in receiving JSON object from API

Body:
I am making an http request from ionic app(Angular4) and receiving a response in form of a Js object, but on receiving i am getting some error.

This is the object which i am receiving from API

{"up_votes":"1","down_votes":"0"}

using http.get to receive data in app, home.ts

..
public vote_response:any={};
...
this.http.get(this.baseURI+'votesNum.php?'+this.question.question_id)
        .subscribe(result =>{this.vote_response = result.json();});

this is the error which i am receiving:

ERROR SyntaxError: Unexpected token < in JSON at position 0
    at JSON.parse (<anonymous>)
    at Response.Body.json (http.es5.js:800)
    at MapSubscriber.project (forum-quest-details.ts:44)
    at MapSubscriber._next (map.js:77)
    at MapSubscriber.Subscriber.next (Subscriber.js:89)
    at XMLHttpRequest.onLoad (http.es5.js:1229)
    at t.invokeTask (polyfills.js:3)
    at Object.onInvokeTask (core.es5.js:4119)
    at t.invokeTask (polyfills.js:3)
    at r.runTask (polyfills.js:3)

Can anyone help me solve this issue.

Body:
this.vote_response = result.json();

Replace this one with console.log(result) and take the data and check with some online JSON validation site  (https://jsonlint.com) to see if the data is valid JSON. You might be getting HTML body instead of JSON.

To response as JSON:

header('Content-Type: application/json');
echo  json_encode(array('up_votes'=>$up_votes, 'down_votes'=> $down_votes ));


问:
Android Room - Get the id of new inserted row with auto-generate
This is how I am inserting data into database using Room Persistence Library:

Entity:

```<code>@Entity
class User {
    @PrimaryKey(autoGenerate = true)
    public int id;
    //...
}
</code>```

Data access object:

```<code>@Dao
public interface UserDao{
    @Insert(onConflict = IGNORE)
    void insertUser(User user);
    //...
}
</code>```

Is it possible to return the id of User once the insertion is completed in the above method itself without writing a separate select query?

答:
Based on the documentation here (below the code snippet)

A method annotated with the @Insert annotation can return:

long for single insert operation

long[] or Long[] or List<Long> for multiple insert operations

void if you don't care about the inserted id(s)

Body:
This is how I am inserting data into database using Room Persistence Library:

Entity:

@Entity
class User {
    @PrimaryKey(autoGenerate = true)
    public int id;
    //...
}

Data access object:

@Dao
public interface UserDao{
    @Insert(onConflict = IGNORE)
    void insertUser(User user);
    //...
}

Is it possible to return the id of User once the insertion is completed in the above method itself without writing a separate select query?


问:
Multiplying 2 matrix using VBS
I would just like to know why this returns an "Expected end of statement" whenever I call the function multiply_matrix(matrixA, matrixB) and feed it with matrixA (3x3 matrix), and matrixB(3x3 matrix).
The error is always at "Next k".

This is the code of the function.

```<code>Function multiply_matrix(matrixA, matrixB)

    dim answer_matrix(3,3)

    for i=0 to UBound(matrixA,1)

        for j=0 to UBound(matrixB,2)

            sum = 0

            for k=0 to UBound(matrixB,1)

                sum = sum +  ( matrixA(i,k) * matrixB(k,j) )

            next k

            answer_matrix(i,j) = sum

        next j

    next i

    multiply_matrix = answer_matrix

End Function
</code>```

答: Other Basic dialects allow variable names after the Next, VBScript doesn't.

Title: Multiplying 2 matrix using VBS

Body:
I would just like to know why this returns an "Expected end of statement" whenever I call the function multiply_matrix(matrixA, matrixB) and feed it with matrixA (3x3 matrix), and matrixB(3x3 matrix).
The error is always at "Next k".

This is the code of the function.

Function multiply_matrix(matrixA, matrixB)

    dim answer_matrix(3,3)

    for i=0 to UBound(matrixA,1)

        for j=0 to UBound(matrixB,2)

            sum = 0

            for k=0 to UBound(matrixB,1)

                sum = sum +  ( matrixA(i,k) * matrixB(k,j) )

            next k

            answer_matrix(i,j) = sum

        next j

    next i

    multiply_matrix = answer_matrix

End Function