问:
Swift: how can I add an image to another image?
Will you please direct me to right path of how to select another transparent picture and add it over to another picture?

Transparent pictures like: a clown nose, hat, cap, earrings, mustache, glasses etc.

Its exist in several applications but i cant find any Swift sample about this.

Thanks for your help.

答:
I have a nice function on an UIImage extension:

```<code>extension UIImage {

    static func imageByMergingImages(topImage: UIImage, bottomImage: UIImage, scaleForTop: CGFloat = 1.0) -> UIImage {
        let size = bottomImage.size
        let container = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        UIGraphicsBeginImageContextWithOptions(size, false, 2.0)
        UIGraphicsGetCurrentContext()!.interpolationQuality = .high
        bottomImage.draw(in: container)

        let topWidth = size.width / scaleForTop
        let topHeight = size.height / scaleForTop
        let topX = (size.width / 2.0) - (topWidth / 2.0)
        let topY = (size.height / 2.0) - (topHeight / 2.0)

        topImage.draw(in: CGRect(x: topX, y: topY, width: topWidth, height: topHeight), blendMode: .normal, alpha: 1.0)

        return UIGraphicsGetImageFromCurrentImageContext()!
    }

}
</code>```

So you can call in this way:

```<code>let image = UIImage.imageByMergingImages(topImage: top, bottomImage: bottom)
</code>```

For your specific case, considering that you want to add many overlays over an image, you should have a function like this:

```<code>extension UIImage {

    func imageOverlayingImages(_ images: [UIImage], scalingBy factors: [CGFloat]? = nil) -> UIImage {
        let size = self.size
        let container = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        UIGraphicsBeginImageContextWithOptions(size, false, 2.0)
        UIGraphicsGetCurrentContext()!.interpolationQuality = .high

        self.draw(in: container)

        let scaleFactors = factors ?? [CGFloat](repeating: 1.0, count: images.count)

        for (image, scaleFactor) in zip(images, scaleFactors) {
            let topWidth = size.width / scaleFactor
            let topHeight = size.height / scaleFactor
            let topX = (size.width / 2.0) - (topWidth / 2.0)
            let topY = (size.height / 2.0) - (topHeight / 2.0)

            image.draw(in: CGRect(x: topX, y: topY, width: topWidth, height: topHeight), blendMode: .normal, alpha: 1.0)
        }
        return UIGraphicsGetImageFromCurrentImageContext()!
    }

}
</code>```

Then you can compose your final image in this way:

```<code>var imageClownFace = UIImage(named: "clown_face")!
imageClownFace = imageClownFace.imageOverlayingImages([imageNose, imageHat, imageCap])
</code>```

Body:
I have a nice function on an UIImage extension:

extension UIImage {

    static func imageByMergingImages(topImage: UIImage, bottomImage: UIImage, scaleForTop: CGFloat = 1.0) -> UIImage {
        let size = bottomImage.size
        let container = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        UIGraphicsBeginImageContextWithOptions(size, false, 2.0)
        UIGraphicsGetCurrentContext()!.interpolationQuality = .high
        bottomImage.draw(in: container)

        let topWidth = size.width / scaleForTop
        let topHeight = size.height / scaleForTop
        let topX = (size.width / 2.0) - (topWidth / 2.0)
        let topY = (size.height / 2.0) - (topHeight / 2.0)

        topImage.draw(in: CGRect(x: topX, y: topY, width: topWidth, height: topHeight), blendMode: .normal, alpha: 1.0)

        return UIGraphicsGetImageFromCurrentImageContext()!
    }

}

So you can call in this way:

let image = UIImage.imageByMergingImages(topImage: top, bottomImage: bottom)

For your specific case, considering that you want to add many overlays over an image, you should have a function like this:

extension UIImage {

    func imageOverlayingImages(_ images: [UIImage], scalingBy factors: [CGFloat]? = nil) -> UIImage {
        let size = self.size
        let container = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        UIGraphicsBeginImageContextWithOptions(size, false, 2.0)
        UIGraphicsGetCurrentContext()!.interpolationQuality = .high

        self.draw(in: container)

        let scaleFactors = factors ?? [CGFloat](repeating: 1.0, count: images.count)

        for (image, scaleFactor) in zip(images, scaleFactors) {
            let topWidth = size.width / scaleFactor
            let topHeight = size.height / scaleFactor
            let topX = (size.width / 2.0) - (topWidth / 2.0)
            let topY = (size.height / 2.0) - (topHeight / 2.0)

            image.draw(in: CGRect(x: topX, y: topY, width: topWidth, height: topHeight), blendMode: .normal, alpha: 1.0)
        }
        return UIGraphicsGetImageFromCurrentImageContext()!
    }

}

Then you can compose your final image in this way:

var imageClownFace = UIImage(named: "clown_face")!
imageClownFace = imageClownFace.imageOverlayingImages([imageNose, imageHat, imageCap])


来源: stackexchange

问:
Encrypt RSA/ECB/OAEPWithSHA-256AndMGF1Padding Swift
I am going to say in advance i don't know too much about cryptography (Basics only). I am trying to Implement a Credential OpenHome Service and I want to encrypt a password to send it to the device.

The device provides a function written in C that returns a public key String that looks like that:

```<code>MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCzjFGuEKD0uWxzb47oRbiSP2uDwVJPeWU7m9VXi626V6lameTzdtwj2eYVZTIAsAW7yW4or2skn7oHqFG4GvhMzgMwoQjKFxeCPPFXRSotnt26AN1DhvFJp3V/d+MpmkzI07iWcD5eNe4EVNK9GSE4JOEHhJ/JYBVMiu04XE5aqwIDAQAB
</code>```

The Android implementation has been already done and the specs given are

RSA/ECB/OAEPWithSHA-256AndMGF1Padding

also there is a web site that gives "instructions" when encrypting

http://wiki.openhome.org/wiki/Av:Developer:CredentialsService

I have tried so far these libraries:

SwiftyRSA, Heimdall, SwCrypt

I really thing that one of my main failures are I don't understand what I have, what do I need and finally how to achieve it using swift.

ideally at the end i will have a functions like

```<code>func encryptMessage(message:String, whithPublicKey key:String)->String
</code>```

thank you very much.

答:
After a long research i have just implemented my own solution rather than using libraries and not understanding what was going on. It is always good to know what happens and it this case it is not rocket science.

On iOS if you want to encrypt/decrypt you need to use a key stored on the keychain. If, in my case, i have been given the public key i can import it and also I can do the same with the private key. Please see my HelperClass Here.

Then, and from only from iOS 10, you can call this 2 methods for encrypting and decrypting

```<code>        let error:UnsafeMutablePointer<Unmanaged<CFError>?>? = nil
        let plainData = "A Plain text...".data(using: .utf8)
        if let encryptedMessageData:Data = SecKeyCreateEncryptedData(publicSecKey, .rsaEncryptionOAEPSHA256, plainData! as CFData,error) as Data?{
            print("We have an encrypted message")

            let encryptedMessageSigned = encryptedMessageData.map { Int8(bitPattern: $0) }
            print(encryptedMessageSigned)

            if let decryptedMessage:Data = SecKeyCreateDecryptedData(privateSecKey, .rsaEncryptionOAEPSHA256, encryptedMessageData as CFData,error) as Data?{
                print("We have an decrypted message \(String.init(data: decryptedMessage, encoding: .utf8)!)")
            }
            else{
                print("Error decrypting")
            }

        }
        else{
            print("Error encrypting")
        }
</code>```

Also, if you want before iOS 10 you have the functions:

```<code>func SecKeyEncrypt(_ key: SecKey,
             _ padding: SecPadding,
             _ plainText: UnsafePointer<UInt8>,
             _ plainTextLen: Int,
             _ cipherText: UnsafeMutablePointer<UInt8>,
             _ cipherTextLen: UnsafeMutablePointer<Int>) -> OSStatus
</code>```

And

```<code>func SecKeyDecrypt(_ key: SecKey,
             _ padding: SecPadding,
             _ cipherText: UnsafePointer<UInt8>,
             _ cipherTextLen: Int,
             _ plainText: UnsafeMutablePointer<UInt8>,
             _ plainTextLen: UnsafeMutablePointer<Int>) -> OSStatus
</code>```

But these give less options and They are quite resticted.

Worth mentioning that my public and private key where generate on android using

```<code>public static String createStringFromPublicKey(Key key) throws Exception {
  X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(key.getEncoded());
  return new String(Base64.encode(x509EncodedKeySpec.getEncoded(), Base64.NO_WRAP), "UTF-8");
}
</code>```

and

```<code>public static String createStringFromPrivateKey(Key key) throws Exception {
  PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(key.getEncoded());
  return new String(Base64.encode(pkcs8EncodedKeySpec.getEncoded(), Base64.NO_WRAP), "UTF-8");
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am going to say in advance i don't know too much about cryptography (Basics only). I am trying to Implement a Credential OpenHome Service and I want to encrypt a password to send it to the device.

The device provides a function written in C that returns a public key String that looks like that:

MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCzjFGuEKD0uWxzb47oRbiSP2uDwVJPeWU7m9VXi626V6lameTzdtwj2eYVZTIAsAW7yW4or2skn7oHqFG4GvhMzgMwoQjKFxeCPPFXRSotnt26AN1DhvFJp3V/d+MpmkzI07iWcD5eNe4EVNK9GSE4JOEHhJ/JYBVMiu04XE5aqwIDAQAB

The Android implementation has been already done and the specs given are

RSA/ECB/OAEPWithSHA-256AndMGF1Padding

also there is a web site that gives "instructions" when encrypting

http://wiki.openhome.org/wiki/Av:Developer:CredentialsService

I have tried so far these libraries:

SwiftyRSA, Heimdall, SwCrypt

I really thing that one of my main failures are I don't understand what I have, what do I need and finally how to achieve it using swift.

ideally at the end i will have a functions like

func encryptMessage(message:String, whithPublicKey key:String)->String

thank you very much.

Body:
After a long research i have just implemented my own solution rather than using libraries and not understanding what was going on. It is always good to know what happens and it this case it is not rocket science.

On iOS if you want to encrypt/decrypt you need to use a key stored on the keychain. If, in my case, i have been given the public key i can import it and also I can do the same with the private key. Please see my HelperClass Here.

Then, and from only from iOS 10, you can call this 2 methods for encrypting and decrypting

        let error:UnsafeMutablePointer<Unmanaged<CFError>?>? = nil
        let plainData = "A Plain text...".data(using: .utf8)
        if let encryptedMessageData:Data = SecKeyCreateEncryptedData(publicSecKey, .rsaEncryptionOAEPSHA256, plainData! as CFData,error) as Data?{
            print("We have an encrypted message")

            let encryptedMessageSigned = encryptedMessageData.map { Int8(bitPattern: $0) }
            print(encryptedMessageSigned)

            if let decryptedMessage:Data = SecKeyCreateDecryptedData(privateSecKey, .rsaEncryptionOAEPSHA256, encryptedMessageData as CFData,error) as Data?{
                print("We have an decrypted message \(String.init(data: decryptedMessage, encoding: .utf8)!)")
            }
            else{
                print("Error decrypting")
            }

        }
        else{
            print("Error encrypting")
        }

Also, if you want before iOS 10 you have the functions:

func SecKeyEncrypt(_ key: SecKey,
             _ padding: SecPadding,
             _ plainText: UnsafePointer<UInt8>,
             _ plainTextLen: Int,
             _ cipherText: UnsafeMutablePointer<UInt8>,
             _ cipherTextLen: UnsafeMutablePointer<Int>) -> OSStatus

And

func SecKeyDecrypt(_ key: SecKey,
             _ padding: SecPadding,
             _ cipherText: UnsafePointer<UInt8>,
             _ cipherTextLen: Int,
             _ plainText: UnsafeMutablePointer<UInt8>,
             _ plainTextLen: UnsafeMutablePointer<Int>) -> OSStatus

But these give less options and They are quite resticted.

Worth mentioning that my public and private key where generate on android using

public static String createStringFromPublicKey(Key key) throws Exception {
  X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(key.getEncoded());
  return new String(Base64.encode(x509EncodedKeySpec.getEncoded(), Base64.NO_WRAP), "UTF-8");
}

and

public static String createStringFromPrivateKey(Key key) throws Exception {
  PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(key.getEncoded());
  return new String(Base64.encode(pkcs8EncodedKeySpec.getEncoded(), Base64.NO_WRAP), "UTF-8");
}

ContentLicense: CC BY-SA 4.0


问:
How to clean the deleted deployments history in Firebase Hosting?
I've been using Firebase Hosting for few months now.
The deployment history is quite handy with the possibility to rollback to a previous version.

The problem is, it is not always necessary to keep every previous versions. So I've deleted quite a lot of the previous deployments I made.

My problem is that all those deployments with the "deleted" status are still visible in my deployment list, making the list unnecessary long.

So, do you know a way to purge the list of all the "deleted" deployment ?

答:
No you need to delete them one by one. May be in future they add this feature.

Meanwhile you can track the issue here


问:
Change button style in Sweet alert
I am using SweetAlert Dialog for android.

https://github.com/pedant/sweet-alert-dialog

In the success dialog, I want to remove to the OK Button and Change its style. Please explain how can I remove the OK button.

I am calling method on button click

```<code>new SweetAlertDialog(this, SweetAlertDialog.SUCCESS_TYPE)
    .setTitleText("Good job!")
    .setContentText("You clicked the button!")
    .show();
</code>```

答:
You can change colors from color.xml to hex values you want;</p>

```<code>    <color name="blue_btn_bg_pressed_color">#96BFD2</color>
    <color name="blue_btn_bg_color">#AEDEF4</color>
    <color name="button_text_color">#FFFFFF</color>
    <color name="error_stroke_color">#F27474</color>
    <color name="float_transparent">#00000000</color>
    <color name="gray_btn_bg_color">#D0D0D0</color>
    <color name="gray_btn_bg_pressed_color">#B6B6B6</color>
    <color name="material_blue_grey_80">#ff37474f</color>
    <color name="material_blue_grey_90">#ff263238</color>
    <color name="material_blue_grey_95">#ff21272b</color>
    <color name="material_deep_teal_20">#ff80cbc4</color>
    <color name="material_deep_teal_50">#ff009688</color>
    <color name="red_btn_bg_color">#DD6B55</color>
    <color name="red_btn_bg_pressed_color">#CD5B55</color>
    <color name="success_stroke_color">#A5DC86</color>
    <color name="sweet_dialog_bg_color">#FFFFFF</color>
    <color name="text_color">#575757</color>
    <color name="trans_success_stroke_color">#33A5DC86</color>
    <color name="warning_stroke_color">#F8BB86</color>
</code>```

Title: Change button style in Sweet alert

Body:
I am using SweetAlert Dialog for android.

https://github.com/pedant/sweet-alert-dialog

In the success dialog, I want to remove to the OK Button and Change its style. Please explain how can I remove the OK button.

I am calling method on button click

new SweetAlertDialog(this, SweetAlertDialog.SUCCESS_TYPE)
    .setTitleText("Good job!")
    .setContentText("You clicked the button!")
    .show();

Body:
You can change colors from color.xml to hex values you want;

    <color name="blue_btn_bg_pressed_color">#96BFD2</color>
    <color name="blue_btn_bg_color">#AEDEF4</color>
    <color name="button_text_color">#FFFFFF</color>
    <color name="error_stroke_color">#F27474</color>
    <color name="float_transparent">#00000000</color>
    <color name="gray_btn_bg_color">#D0D0D0</color>
    <color name="gray_btn_bg_pressed_color">#B6B6B6</color>
    <color name="material_blue_grey_80">#ff37474f</color>
    <color name="material_blue_grey_90">#ff263238</color>
    <color name="material_blue_grey_95">#ff21272b</color>
    <color name="material_deep_teal_20">#ff80cbc4</color>
    <color name="material_deep_teal_50">#ff009688</color>
    <color name="red_btn_bg_color">#DD6B55</color>
    <color name="red_btn_bg_pressed_color">#CD5B55</color>
    <color name="success_stroke_color">#A5DC86</color>
    <color name="sweet_dialog_bg_color">#FFFFFF</color>
    <color name="text_color">#575757</color>
    <color name="trans_success_stroke_color">#33A5DC86</color>
    <color name="warning_stroke_color">#F8BB86</color>


问:
Erlang Universal Binary Format? Anyone using it?
I recently stumbled upon this 2002 conference paper (Getting Erlang to talk to the outside world by Joe Armstrong) and I was wondering whether this is a standard that was ignored or if there was any adoption?

Should I focus on Apache Thrift for inter-platform communication? (whatever solution I choose will involve at least Erlang)

答:
I think the Hibari guys are using it.

https://github.com/ubf/ubf/

ContentLicense: CC BY-SA 2.5


问:
In Entity Framework Core, with one query, how do I select objects by the order of a parent object?
I'm working in Entity Framework Core 2.0, and I'm trying to do something like this. I want a list of all the classes taught by the oldest teacher. I tried to make the two requests into one query, but I couldn't make it work. Is there a concise way to make this one query?

```<code>private async Task<Teacher> GetOldestTeacher(int schoolId)
{
    using (var db = new SchoolContext())
    {
        return await db.Teacher
            .Where(t => t.SchoolId == schoolId)
            .OrderByDescending(t => t.DateOfBirth)
            .FirstAsync();
    }
}

public async Task<IEnumerable<Class>> GetOldestTeachersClasses(int schoolId)
{
    var oldestTeacher = await GetOldestTeacher(schoolId);
    using (var db = new SchoolContext())
    {
        return await db.Class
            .Where(c => c.TeacherId == oldestTeacher.Id && c.SchoolId == schoolId)
            .ToListAsync();
    }
}
</code>```

This isn't exactly my code, but it's close enough to what I'm shooting for. This works, but I'm looking to make it more efficient. Any help would be appreciated.

答:
Assuming there exists a navigation property called Classes in the Teacher class, you could do this:

```<code>public async Task<IEnumerable<Class>> GetOldestTeachersClasses(int schoolId)
{
    using (var db = new SchoolContext())
    {
        return await db.Teacher
            .Where(t => t.SchoolId == schoolId)
            .OrderByDescending(t => t.DateOfBirth)
            .Take(1)
            .SelectMany(t => t.Classes)
            .ToListAsync();
    }
}
</code>```

If you use First, you inevitably ask EF to immediately load the object into memory. Because of that, if you use that returned object to do the further parts of the query, you would actually be doing at least 2 roundtrips to the database and performing 2 queries instead of one despite in your C# code there being only one expression.

The trick here is that you filter the teachers just as you've already done, and instead of loading the first one using First(), you Take() the topmost one, according to the ordering requirements. The key difference is that Take will not actually load the object immediately - instead, it enables you to further specify the query which will be translated to one proper SQL query.

The reason for using SelectMany() is that semantically, there still can be more than one teachers as the Take() call actually returns an IQueryable<Teacher> object. But the semantics of your filter criteria ensures that in reality, there will only be 0 or 1 teacher, so collecting his/her classes using SelectMany will result in only his/her taught classes. You could also do the same by doing a Join as DevilSuichiro remarked in the comments.

However, make sure you verify the generated SQL. I personally don't yet have experience with EF Core 2.0 only with 1.x, which sometimes failed to translate rather trivial queries to proper SQL statements and instead performed a lot of work in my app. The last time I checked the 2.0 roadmap it was promised to significantly improve the translator, but I've written this code just from the top of my head so a proper verification is required.

Body:
I'm working in Entity Framework Core 2.0, and I'm trying to do something like this. I want a list of all the classes taught by the oldest teacher. I tried to make the two requests into one query, but I couldn't make it work. Is there a concise way to make this one query?

private async Task<Teacher> GetOldestTeacher(int schoolId)
{
    using (var db = new SchoolContext())
    {
        return await db.Teacher
            .Where(t => t.SchoolId == schoolId)
            .OrderByDescending(t => t.DateOfBirth)
            .FirstAsync();
    }
}

public async Task<IEnumerable<Class>> GetOldestTeachersClasses(int schoolId)
{
    var oldestTeacher = await GetOldestTeacher(schoolId);
    using (var db = new SchoolContext())
    {
        return await db.Class
            .Where(c => c.TeacherId == oldestTeacher.Id && c.SchoolId == schoolId)
            .ToListAsync();
    }
}

This isn't exactly my code, but it's close enough to what I'm shooting for. This works, but I'm looking to make it more efficient. Any help would be appreciated.

Body:
Assuming there exists a navigation property called Classes in the Teacher class, you could do this:

public async Task<IEnumerable<Class>> GetOldestTeachersClasses(int schoolId)
{
    using (var db = new SchoolContext())
    {
        return await db.Teacher
            .Where(t => t.SchoolId == schoolId)
            .OrderByDescending(t => t.DateOfBirth)
            .Take(1)
            .SelectMany(t => t.Classes)
            .ToListAsync();
    }
}

If you use First, you inevitably ask EF to immediately load the object into memory. Because of that, if you use that returned object to do the further parts of the query, you would actually be doing at least 2 roundtrips to the database and performing 2 queries instead of one despite in your C# code there being only one expression.

The trick here is that you filter the teachers just as you've already done, and instead of loading the first one using First(), you Take() the topmost one, according to the ordering requirements. The key difference is that Take will not actually load the object immediately - instead, it enables you to further specify the query which will be translated to one proper SQL query.

The reason for using SelectMany() is that semantically, there still can be more than one teachers as the Take() call actually returns an IQueryable<Teacher> object. But the semantics of your filter criteria ensures that in reality, there will only be 0 or 1 teacher, so collecting his/her classes using SelectMany will result in only his/her taught classes. You could also do the same by doing a Join as DevilSuichiro remarked in the comments.

However, make sure you verify the generated SQL. I personally don't yet have experience with EF Core 2.0 only with 1.x, which sometimes failed to translate rather trivial queries to proper SQL statements and instead performed a lot of work in my app. The last time I checked the 2.0 roadmap it was promised to significantly improve the translator, but I've written this code just from the top of my head so a proper verification is required.


问:
Pandas calling partial row data
I have the following data in a column:

```<code>Company Name
Company Name\Cortana Place\rBaton Rouge, LA 70815
Some Product Company\r1Highway 21\rMadis

df = pd.read_csv(csv_cropped_tabula, encoding = "ISO-8859-1")
</code>```

when I call df['Company Name'][0] or df['Company Name'][1]

I am getting back only following data

```<code>rBaton Rouge, LA 70815
r1Highway 21\rMadis
</code>```

I dont understand why is it bringing back the partial data not full line

```<code>Company Name\Cortana Place\rBaton Rouge, LA 70815
</code>```

答:
It's parsing the embedded commas as separators, it looks like you only have a single column so you can tell it to only load that column and pass lineterminator='\n':

```<code>In[86]:
t="""Company Name
Company Name\Cortana Place\rBaton Rouge, LA 70815 Some Product
Company\r1Highway 21\rMadi"""
df = pd.read_csv(io.StringIO(t), usecols=[0], lineterminator='\n')
df

Out[85]:
                                        Company Name
0  Company Name\Cortana Place\rBaton Rouge, LA 70...
1                         Company\r1Highway 21\rMadi
</code>```

Here I tell pandas to only load the first column usecols=[0], additionally it's reading the \r as carriage returns so we can override this and tell it to look specifically for \n as the line terminator

If we now look at the first row, we can see it's all there:

```<code>In[87]:
df['Company Name'].iloc[0]

Out[87]: 'Company Name\\Cortana Place\rBaton Rouge'
</code>```

Title: Pandas calling partial row data

Body:
I have the following data in a column:

Company Name
Company Name\Cortana Place\rBaton Rouge, LA 70815
Some Product Company\r1Highway 21\rMadis

df = pd.read_csv(csv_cropped_tabula, encoding = "ISO-8859-1")

when I call df['Company Name'][0] or df['Company Name'][1]

I am getting back only following data

rBaton Rouge, LA 70815
r1Highway 21\rMadis

I dont understand why is it bringing back the partial data not full line

Company Name\Cortana Place\rBaton Rouge, LA 70815

Body:
It's parsing the embedded commas as separators, it looks like you only have a single column so you can tell it to only load that column and pass lineterminator='\n':

In[86]:
t="""Company Name
Company Name\Cortana Place\rBaton Rouge, LA 70815 Some Product
Company\r1Highway 21\rMadi"""
df = pd.read_csv(io.StringIO(t), usecols=[0], lineterminator='\n')
df

Out[85]:
                                        Company Name
0  Company Name\Cortana Place\rBaton Rouge, LA 70...
1                         Company\r1Highway 21\rMadi

Here I tell pandas to only load the first column usecols=[0], additionally it's reading the \r as carriage returns so we can override this and tell it to look specifically for \n as the line terminator

If we now look at the first row, we can see it's all there:

In[87]:
df['Company Name'].iloc[0]

Out[87]: 'Company Name\\Cortana Place\rBaton Rouge'


问:
dequeueReusableCellWithIdentifier creates duplicate UITableviewcell

I am creating a page where I am using UITableView and UITableViewCell. The above shown photo is one UITableViewCell created programatically.

This UITableViewCell is getting created in cellForRowAtIndexPath where i am using tags for views and reusing views with tags whenever cellForRowAtIndexPath is called

------------------- Code for cell creation ---------------------------

```<code>NSString* reuseIdentifier = @"NameNCityCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];

    // Configure the cell...
    if (nil == cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
    }

    [self configureCell:cell withIndexPath: indexPath];
</code>```

In this UITableViewCell when we tap on city , A new controller is opened where I can select city which will reflect in the City Column in current viewcontroller.

Now The problem.

when I open the page with this cell, new cell is created but after tapping on the citycontroller and selecting city it comes to this previous controller and instead of using the same cell, it creates new . So its like one cell over another (Duplicates)

Now I again tap on citycontroller and select city, on selection when it comes to this VC and it uses the hidden view from the 2 views.

I need to know How should I do that so that two view are not created. I want to work with the same view.

Let me now if you need more details.

答:
Create custom cell Class like example

```<code>#import "JSCustomCell.h"
@implementation JSCustomCell
@synthesize descriptionLabel = _descriptionLabel;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // configure control(s)
        self.descriptionLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 10, 300, 30)];
        self.descriptionLabel.textColor = [UIColor blackColor];
        self.descriptionLabel.font = [UIFont fontWithName:@"Arial" size:12.0f];

        [self addSubview:self.descriptionLabel];
    }
    return self;
}
@end
</code>```

Then the main view controller

```<code>#import "JSViewController.h"
#import "JSCustomCell.h"
@interface JSViewController ()
@end
@implementation JSViewController {
    UITableView *tableView;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    // init table view
    tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    // must set delegate & dataSource, otherwise the the table will be empty and not responsive
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.backgroundColor = [UIColor cyanColor];
    // add to canvas
    [self.view addSubview:tableView];
}
#pragma mark - UITableViewDataSource
// number of section(s), now I assume there is only 1 section
- (NSInteger)numberOfSectionsInTableView:(UITableView *)theTableView
{
    return 1;
}
// number of row in the section, I assume there is only 1 row
- (NSInteger)tableView:(UITableView *)theTableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
// the cell will be returned to the tableView
- (UITableViewCell *)tableView:(UITableView *)theTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"HistoryCell";

    // Similar to UITableViewCell, but
    JSCustomCell *cell = (JSCustomCell *)[theTableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[JSCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    // Just want to test, so I hardcode the data
    cell.descriptionLabel.text = @"Testing";

    return cell;
}
#pragma mark - UITableViewDelegate
// when user tap the row, what action you want to perform
- (void)tableView:(UITableView *)theTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"selected %d row", indexPath.row);
}
@end
</code>```

Body:
I am creating a page where I am using UITableView and UITableViewCell. The above shown photo is one UITableViewCell created programatically.

This UITableViewCell is getting created in cellForRowAtIndexPath where i am using tags for views and reusing views with tags whenever cellForRowAtIndexPath is called

------------------- Code for cell creation ---------------------------

NSString* reuseIdentifier = @"NameNCityCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];

    // Configure the cell...
    if (nil == cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
    }

    [self configureCell:cell withIndexPath: indexPath];

In this UITableViewCell when we tap on city , A new controller is opened where I can select city which will reflect in the City Column in current viewcontroller.

Now The problem.

when I open the page with this cell, new cell is created but after tapping on the citycontroller and selecting city it comes to this previous controller and instead of using the same cell, it creates new . So its like one cell over another (Duplicates)

Now I again tap on citycontroller and select city, on selection when it comes to this VC and it uses the hidden view from the 2 views.

I need to know How should I do that so that two view are not created. I want to work with the same view.

Let me now if you need more details.

Body:
Create custom cell Class like example

#import "JSCustomCell.h"
@implementation JSCustomCell
@synthesize descriptionLabel = _descriptionLabel;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // configure control(s)
        self.descriptionLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 10, 300, 30)];
        self.descriptionLabel.textColor = [UIColor blackColor];
        self.descriptionLabel.font = [UIFont fontWithName:@"Arial" size:12.0f];

        [self addSubview:self.descriptionLabel];
    }
    return self;
}
@end

Then the main view controller

#import "JSViewController.h"
#import "JSCustomCell.h"
@interface JSViewController ()
@end
@implementation JSViewController {
    UITableView *tableView;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    // init table view
    tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    // must set delegate & dataSource, otherwise the the table will be empty and not responsive
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.backgroundColor = [UIColor cyanColor];
    // add to canvas
    [self.view addSubview:tableView];
}
#pragma mark - UITableViewDataSource
// number of section(s), now I assume there is only 1 section
- (NSInteger)numberOfSectionsInTableView:(UITableView *)theTableView
{
    return 1;
}
// number of row in the section, I assume there is only 1 row
- (NSInteger)tableView:(UITableView *)theTableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
// the cell will be returned to the tableView
- (UITableViewCell *)tableView:(UITableView *)theTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"HistoryCell";

    // Similar to UITableViewCell, but
    JSCustomCell *cell = (JSCustomCell *)[theTableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[JSCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    // Just want to test, so I hardcode the data
    cell.descriptionLabel.text = @"Testing";

    return cell;
}
#pragma mark - UITableViewDelegate
// when user tap the row, what action you want to perform
- (void)tableView:(UITableView *)theTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"selected %d row", indexPath.row);
}
@end


问:
Why am I getting an "undefined" entry when building a JSON response?
I tried the below code. The POSTMAN and console response is:

"undefined[object Object],[object Object],[object Object],[object
  Object],[object Object],[object Object],[object Object],[object
  Object],"

I want the correct JSON output:

```<code>    exports.getIssues = function(req, res) {
        console.log(filename + '>>get Issues>>');
        var response = {
            status: Boolean,
            message: String,
            data: String
        };
        var request = require('request');
        var username =
            const.username;
        var password =
            const.password;
        var options = {
            url: 'https://computenext.atlassian.net/rest/api/2/search?jql=status+%3D+Resolved+ORDER+BY+updated',
            auth: {
                username: username,
                password: password
            }
        };

        request(options, function(error, obj) {
            if (error) {
                response.message = appmsg.DATA_NT_FOUND;
                response.status = false;
                response.data = obj;
                res.send(response);
            } else {
                response.message = appmsg.DATA_FOUND;
                response.status = true;
                response.data = JSON.parse(obj.body);
                //res.send(response);
                var issueKey = response.data.issues;

                // var keyData = issueKey[0].key;
                // console.log(response.data.issues);
                // console.log(keyData);
                var output = [];
                for (var i = 0; i < issueKey.length; i++) {
                    var issue = issueKey[i].key;
                    //var key = [];
                    //key.push(issue);
                    console.log(issue);

                    var respon = {
                        status: Boolean,
                        message: String,
                        data: String
                    };
                    var request = require('request'),
                        username =
                        const.username,
                        password =
                        const.username,
                        url = "https://computenext.atlassian.net/rest/api/2/issue/" + issue,
                        auth = "Basic " + new Buffer(username + ":" + password).toString("base64");

                    //console.log(url);
                    request({
                        url: url,
                        headers: {
                            "Authorization": auth
                        }
                    }, function(err, object) {
                        if (object) {

                            var info = object;
                            output.push(info); // this is not working as ouput is undefined at this    point
                            //var pout = JSON.parse(output);
                            //console.log(info);
                            console.log("==============================================================================");
                            //console.log(output);
                            console.log("******************************************************************************");
                            if (issueKey.length === output.length) {
                                respon.message = appmsg.DATA_FOUND;
                                respon.status = true;
                                respon.data = output;
                                //console.log(output);
                                //res.send(respon);

                                var id = issueKey[0].id;
                                console.log(id);

                                var commitout = [];
                                for (var i = 0; i < issueKey.length; i++) {
                                    var commits = issueKey[i].id;
                                    console.log(commits);

                                    var request = require('request'),
                                        username =
                                        const.username,
                                        password =
                                        const.password,
                                        url = "https://computenext.atlassian.net/rest/dev-status/1.0/issue/detail?issueId=" + commits + "&applicationType=stash&dataType=repository",
                                        auth = "Basic " + new Buffer(username + ":" + password).toString("base64");

                                    //console.log(url);
                                    var test = [];
                                    request({
                                        url: url,
                                        headers: {
                                            "Authorization": auth
                                        }
                                    }, function(err, obj1) {
                                        if (obj1) {
                                            var info1 = obj1;
                                            commitout.push(info1);
                                            var resultdone = [];
                                            if (issueKey.length === commitout.length) {
                                                respon.message = appmsg.DATA_FOUND;
                                                respon.status = true;
                                                respon.data = commitout;
                                                // console.log(commitout);
                                                //var test = merge(output, commitout);
                                                //var text = output.body[0];

                                                resultdone.push = output + commitout;
                                                console.log(resultdone);
                                                res.send(resultdone);
                                            }
                                        }
                                    });
                                }

                            }
                        }

                    });

                }
            }

        });

    };
</code>```

答:
What are you trying to do here: resultdone.push = output + commitout;
This concatenates your arrays, hence the [object object]s. Also Why are you assigning it to resultdone.push? I think you actually want to call the method.

Try this instead:

```<code>resultdone.push(commitout.concat(output ))
</code>```

Body:
I tried the below code. The POSTMAN and console response is:

"undefined[object Object],[object Object],[object Object],[object
  Object],[object Object],[object Object],[object Object],[object
  Object],"

I want the correct JSON output:

    exports.getIssues = function(req, res) {
        console.log(filename + '>>get Issues>>');
        var response = {
            status: Boolean,
            message: String,
            data: String
        };
        var request = require('request');
        var username =
            const.username;
        var password =
            const.password;
        var options = {
            url: 'https://computenext.atlassian.net/rest/api/2/search?jql=status+%3D+Resolved+ORDER+BY+updated',
            auth: {
                username: username,
                password: password
            }
        };

        request(options, function(error, obj) {
            if (error) {
                response.message = appmsg.DATA_NT_FOUND;
                response.status = false;
                response.data = obj;
                res.send(response);
            } else {
                response.message = appmsg.DATA_FOUND;
                response.status = true;
                response.data = JSON.parse(obj.body);
                //res.send(response);
                var issueKey = response.data.issues;

                // var keyData = issueKey[0].key;
                // console.log(response.data.issues);
                // console.log(keyData);
                var output = [];
                for (var i = 0; i < issueKey.length; i++) {
                    var issue = issueKey[i].key;
                    //var key = [];
                    //key.push(issue);
                    console.log(issue);

                    var respon = {
                        status: Boolean,
                        message: String,
                        data: String
                    };
                    var request = require('request'),
                        username =
                        const.username,
                        password =
                        const.username,
                        url = "https://computenext.atlassian.net/rest/api/2/issue/" + issue,
                        auth = "Basic " + new Buffer(username + ":" + password).toString("base64");

                    //console.log(url);
                    request({
                        url: url,
                        headers: {
                            "Authorization": auth
                        }
                    }, function(err, object) {
                        if (object) {

                            var info = object;
                            output.push(info); // this is not working as ouput is undefined at this    point
                            //var pout = JSON.parse(output);
                            //console.log(info);
                            console.log("==============================================================================");
                            //console.log(output);
                            console.log("******************************************************************************");
                            if (issueKey.length === output.length) {
                                respon.message = appmsg.DATA_FOUND;
                                respon.status = true;
                                respon.data = output;
                                //console.log(output);
                                //res.send(respon);

                                var id = issueKey[0].id;
                                console.log(id);

                                var commitout = [];
                                for (var i = 0; i < issueKey.length; i++) {
                                    var commits = issueKey[i].id;
                                    console.log(commits);

                                    var request = require('request'),
                                        username =
                                        const.username,
                                        password =
                                        const.password,
                                        url = "https://computenext.atlassian.net/rest/dev-status/1.0/issue/detail?issueId=" + commits + "&applicationType=stash&dataType=repository",
                                        auth = "Basic " + new Buffer(username + ":" + password).toString("base64");

                                    //console.log(url);
                                    var test = [];
                                    request({
                                        url: url,
                                        headers: {
                                            "Authorization": auth
                                        }
                                    }, function(err, obj1) {
                                        if (obj1) {
                                            var info1 = obj1;
                                            commitout.push(info1);
                                            var resultdone = [];
                                            if (issueKey.length === commitout.length) {
                                                respon.message = appmsg.DATA_FOUND;
                                                respon.status = true;
                                                respon.data = commitout;
                                                // console.log(commitout);
                                                //var test = merge(output, commitout);
                                                //var text = output.body[0];

                                                resultdone.push = output + commitout;
                                                console.log(resultdone);
                                                res.send(resultdone);
                                            }
                                        }
                                    });
                                }

                            }
                        }

                    });

                }
            }

        });

    };

Body:
What are you trying to do here: resultdone.push = output + commitout;
This concatenates your arrays, hence the [object object]s. Also Why are you assigning it to resultdone.push? I think you actually want to call the method.

Try this instead:

resultdone.push(commitout.concat(output ))


问:
Return json from web api controller with Angular
I am using ASP.NET Core for my backend and Angular for my frontend.
I have an API that gives me my data as JSON from the backend.

I created a service to load the api-data, but it's just returning 'undefined'.

employee.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Http } from '@angular/http';

import { Observable } from 'rxjs/Rx';
import { of } from 'rxjs/observable/of';
import { catchError, map, tap } from 'rxjs/operators';
import 'rxjs/add/operator/map';
import 'rxjs/Rx';

import { Employee } from './employee';

//interface Employee_interface {
//    id: number;
//    name: string;
//}

@Injectable()
export class EmployeeService {

    constructor(public http: HttpClient, private _httpService: Http) {}

    //apiEmployees: JSON;
    employees: Employee[];
    stuff: Object;

    getEmployees(): Observable<Employee[]> {

        this.http.get('/api/employees').subscribe(data => { console.log(data); }); //I can see an array with my json-data from the api
        this.http.get('/api/employees').subscribe(data => this.stuff = data);
        console.log("LOG: " + this.stuff); //LOG: undefined
        console.log("LOG1 :" + this.http.get('/api/employees').pipe()); //LOG1 :[object Object]

        return this.http.get('/api/employees').pipe();
    }
}
```
<p>What do I have to return?</p>
<p>app.components.ts</p>
<pre class="lang-ts prettyprint-override"><code>import { Component, OnInit } from '@angular/core';
import { Http } from '@angular/http';
import { HttpClient } from '@angular/common/http';

import { Employee } from './employee';
import { EmployeeService } from './employee.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
    title = 'app';
    employees: Employee[];

    constructor(public http: HttpClient, private _httpService: Http, private employeeService: EmployeeService) { }

    ngOnInit() {
        this.getEmployees();
    }

    getEmployees(): void {
        this.employeeService.getEmployees()
            .subscribe(employees => this.employees = employees);
    }
}
</code>```

答:
Change this:

```<code>return this.http.get('/api/employees').pipe();
</code>```

Into this:

```<code>return this.http.get('/api/employees')
    .map(response => response.json())
    .catch((error: any) => Observable.throw(
        { message: error.json().message, details: error.json().details }));
</code>```

Here we handle the error (first thing to understand what goes wrong, if it goes wrong) and we are mapping the response parsing it into JSON.

Hope it was helpful.

Body:
I am using ASP.NET Core for my backend and Angular for my frontend.
I have an API that gives me my data as JSON from the backend.

I created a service to load the api-data, but it's just returning 'undefined'.

employee.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Http } from '@angular/http';

import { Observable } from 'rxjs/Rx';
import { of } from 'rxjs/observable/of';
import { catchError, map, tap } from 'rxjs/operators';
import 'rxjs/add/operator/map';
import 'rxjs/Rx';

import { Employee } from './employee';

//interface Employee_interface {
//    id: number;
//    name: string;
//}

@Injectable()
export class EmployeeService {

    constructor(public http: HttpClient, private _httpService: Http) {}

    //apiEmployees: JSON;
    employees: Employee[];
    stuff: Object;

    getEmployees(): Observable<Employee[]> {

        this.http.get('/api/employees').subscribe(data => { console.log(data); }); //I can see an array with my json-data from the api
        this.http.get('/api/employees').subscribe(data => this.stuff = data);
        console.log("LOG: " + this.stuff); //LOG: undefined
        console.log("LOG1 :" + this.http.get('/api/employees').pipe()); //LOG1 :[object Object]

        return this.http.get('/api/employees').pipe();
    }
}

What do I have to return?

app.components.ts

import { Component, OnInit } from '@angular/core';
import { Http } from '@angular/http';
import { HttpClient } from '@angular/common/http';

import { Employee } from './employee';
import { EmployeeService } from './employee.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
    title = 'app';
    employees: Employee[];

    constructor(public http: HttpClient, private _httpService: Http, private employeeService: EmployeeService) { }

    ngOnInit() {
        this.getEmployees();
    }

    getEmployees(): void {
        this.employeeService.getEmployees()
            .subscribe(employees => this.employees = employees);
    }
}

Body:
Change this:

return this.http.get('/api/employees').pipe();

Into this:

return this.http.get('/api/employees')
    .map(response => response.json())
    .catch((error: any) => Observable.throw(
        { message: error.json().message, details: error.json().details }));

Here we handle the error (first thing to understand what goes wrong, if it goes wrong) and we are mapping the response parsing it into JSON.

Hope it was helpful.


问:
Grails Application With SpringBoot using different yml files for different environments
I am using Grails 3.3.1 with spring boot. the build tool is gradle.
All application related properties are configured in application.yml file.

Now I want to access different .yml files for different environments [development, test etc]. For this I have created different .yml files per environment.
The command used to run server is : grails -Dgrails.env=test run-app
Now when i access any property, it gives me the values from application-test.yml file which is as expected.

But when I access server.port, it is reading this property from application.yml instead of application-test.yml.

Can anyone help me in running the application by using server.port from application-test.yml file

The application.yml is as follows:

server:
  port: 8081

  contextPath : /ssp

the application-test.yml is as follows:

server:
  port: 8443

  contextPath : /ssp

I am expecting the server to run on port 8443 as this property is in application-test.yml. But the server runs on port 8081 as mentioned in application.yml

答:
I could resolve the above issue by adding server.port per environment in the .yml files

#application.yml:

environments:

```<code>development:
    dataSource:
        dbCreate: none
        url: //url
        logSql: true
        username: //username
        password: //password
        driverClassName: "oracle.jdbc.driver.OracleDriver"
        pooled: true
        jmxExport: true
    server:
        port: 8081
        contextPath : /ssp
test:
    dataSource:
        dbCreate: none
        url: //url
        username: //username
        password: //password
        driverClassName: "oracle.jdbc.driver.OracleDriver"
        pooled: true
        jmxExport: true
        logSql: true
    server:
        port: 8082
        contextPath : /ssp
</code>```

Body:
I could resolve the above issue by adding server.port per environment in the .yml files

#application.yml:

environments:

development:
    dataSource:
        dbCreate: none
        url: //url
        logSql: true
        username: //username
        password: //password
        driverClassName: "oracle.jdbc.driver.OracleDriver"
        pooled: true
        jmxExport: true
    server:
        port: 8081
        contextPath : /ssp
test:
    dataSource:
        dbCreate: none
        url: //url
        username: //username
        password: //password
        driverClassName: "oracle.jdbc.driver.OracleDriver"
        pooled: true
        jmxExport: true
        logSql: true
    server:
        port: 8082
        contextPath : /ssp


问:
How to write a query in yii2 for with rollup
how to write a find() with rollup :

```<code> $leadsCount = Approval::find()
                ->select(['COUNT(id) AS cnt, coalesce(status, "total")'])
                ->groupBy(['status'])
                ->with(rollup)
                ->all();
</code>```

While running the query am

getting an error like this : Use of undefined constant rollup - assumed 'rollup'

答:
I guess you mean this:

```<code> $leadsCount = Approval::find()
                ->select(['COUNT(id) AS cnt, coalesce(`status`, "total")'])
                ->groupBy(new \yii\db\Expression('`status` ASC WITH ROLLUP'))
                ->all();
</code>```

The method with() is about object relations what is something completly different.

You also need to quote the column status since it is a reserved word in MySQL.

btw: you may want to use asArray() as well (->asArray()->all();) since you don't get Approval objects with this query.

Body:
how to write a find() with rollup :

 $leadsCount = Approval::find()
                ->select(['COUNT(id) AS cnt, coalesce(status, "total")'])
                ->groupBy(['status'])
                ->with(rollup)
                ->all();

While running the query am

getting an error like this : Use of undefined constant rollup - assumed 'rollup'

Body:
I guess you mean this:

 $leadsCount = Approval::find()
                ->select(['COUNT(id) AS cnt, coalesce(`status`, "total")'])
                ->groupBy(new \yii\db\Expression('`status` ASC WITH ROLLUP'))
                ->all();

The method with() is about object relations what is something completly different.

You also need to quote the column status since it is a reserved word in MySQL.

btw: you may want to use asArray() as well (->asArray()->all();) since you don't get Approval objects with this query.


问:
What is the exact behaviour of comparing Integers in Java?
as far as I understand due to Java autoboxing I can do this:

```<code>Integer i = 10;
Integer j = 10;
boolean b = i == j;
</code>```

Or this:

```<code>int ii = 10;
int jj = 10;
Integer i = ii;
Integer j = jj;
boolean b = i == j;
</code>```

In both cases b is TRUE.
Then if Integer.parseInt() function returns an int in theory I can do this:

```<code>Integer i = Integer.parseInt("10");
Integer j = Integer.parseInt("10");
boolean b = i == j;
</code>```

In this case b is also TRUE.
Then if I do this b should be true as well:

```<code>Integer i = Integer.parseInt("200");
Integer j = Integer.parseInt("200");
boolean b = i == j;
</code>```

Actually here b is FALSE. Anyone has an idea of what is going on? Thanks.

答: You should never use == between Integers.. It sometimes works only because certain values (I think below 128) are cached by Integer.valueOf() for performance reasons.</p>

Body:
as far as I understand due to Java autoboxing I can do this:

Integer i = 10;
Integer j = 10;
boolean b = i == j;

Or this:

int ii = 10;
int jj = 10;
Integer i = ii;
Integer j = jj;
boolean b = i == j;

In both cases b is TRUE.
Then if Integer.parseInt() function returns an int in theory I can do this:

Integer i = Integer.parseInt("10");
Integer j = Integer.parseInt("10");
boolean b = i == j;

In this case b is also TRUE.
Then if I do this b should be true as well:

Integer i = Integer.parseInt("200");
Integer j = Integer.parseInt("200");
boolean b = i == j;

Actually here b is FALSE. Anyone has an idea of what is going on? Thanks.


答:
Try this query</p>

```<code>DECLARE @ReportDate date='20171116'

SELECT
  curData.[date],
  curData.Item,
  curData.Location,
  curData.Qty,
  lastData.[date] LastChange,
  lastData.Qty LastQty
FROM
  (
    SELECT *
    FROM #t
    WHERE [date]=@ReportDate
  ) curData
OUTER APPLY
  (
    SELECT TOP 1 *
    FROM #t lastData
    WHERE lastData.Item=curData.Item
      AND lastData.Location=curData.Location
      AND lastData.[date]<curData.[date]
      AND lastData.Qty<>curData.Qty
    ORDER BY lastData.[date] DESC
  ) lastData
</code>```

Title: SQL Server: detect inventory changes

Body:
I have a simple inventory table:

IF OBJECT_ID('tempdb.dbo.#t') IS NOT NULL
    DROP TABLE #t
GO

CREATE TABLE #t
(
    [date] DATE,
    Item VARCHAR(1),
    [Location] INT,
    Qty INT
)

INSERT INTO #t ([date], [Item], [Location], [Qty])
VALUES ('2017-11-16', 'A', 1, 5),
       ('2017-11-16', 'B', 1, 5),
       ('2017-11-16', 'B', 2, 10),
       ('2017-11-16', 'A', 3, 1),
       ('2017-11-16', 'C', 3, 2),
       ('2017-11-16', 'A', 4, 20),
       ('2017-11-15', 'A', 1, 5),
       ('2017-11-15', 'B', 1, 5),
       ('2017-11-15', 'B', 2, 10),
       ('2017-11-15', 'A', 3, 1),
       ('2017-11-15', 'C', 3, 8),
       ('2017-11-14', 'A', 1, 10),
       ('2017-11-14', 'B', 1, 1),
       ('2017-11-14', 'B', 2, 10),
       ('2017-11-14', 'A', 3, 1),
       ('2017-11-14', 'C', 3, 8)

I would like to find out the date (in the where clause) and also the difference in quantity of a location-item-level for the past.

Thus the result should be as follows:

+------------+------+----------+-----+------------+---------+
|    Date    | Item | Location | Qty | LastChange | LastQty |
+------------+------+----------+-----+------------+---------+
| 16.11.2017 | A    |        1 |   5 | 14.11.2017 |      10 |
| 16.11.2017 | B    |        1 |   5 | 14.11.2017 |       1 |
| 16.11.2017 | B    |        2 |  10 |            |         |
| 16.11.2017 | A    |        3 |   1 |            |         |
| 16.11.2017 | C    |        3 |   2 | 15.11.2017 |       8 |
| 16.11.2017 | A    |        4 |  20 |            |         |
+------------+------+----------+-----+------------+---------+

Since the inventory table is quite big I would like to avoid windowed-functions if possible.

I have self-joined the inventory table. However, I have problems to find a clause for eliminating the irrelevant data sets.

SELECT
    a.[date],
    a.Item,
    a.Location,
    a.qty,
    b.[date] LastChange,
    b.qty LastQty
FROM
    #t a
LEFT JOIN
    #t b ON a.Item = b.Item
         AND a.location = b.location
         AND b.date < a.date
WHERE
    a.date = '2017-11-16'

Body:
Try this query

DECLARE @ReportDate date='20171116'

SELECT
  curData.[date],
  curData.Item,
  curData.Location,
  curData.Qty,
  lastData.[date] LastChange,
  lastData.Qty LastQty
FROM
  (
    SELECT *
    FROM #t
    WHERE [date]=@ReportDate
  ) curData
OUTER APPLY
  (
    SELECT TOP 1 *
    FROM #t lastData
    WHERE lastData.Item=curData.Item
      AND lastData.Location=curData.Location
      AND lastData.[date]<curData.[date]
      AND lastData.Qty<>curData.Qty
    ORDER BY lastData.[date] DESC
  ) lastData


问:
Conventions for naming class operations?
What conventions do you use for naming class operations? </p>

答:
Full word doc : Download C# Coding Standards & Best Practices

Naming Conventions and Standards

Note :
The terms Pascal Casing and Camel Casing are used throughout this document.
Pascal Casing - First character of all words are Upper Case and other characters are lower case.
Example: BackColor
Camel Casing - First character of all words, except the first word are Upper Case and other characters are lower case.
Example: backColor

Use Pascal casing for Class names

public class HelloWorld
{
 ...
}

Use Pascal casing for Method names

void SayHello(string name)
{
 ...
}

Use Camel casing for variables and method parameters

int totalCount = 0;
void SayHello(string name)
{
 string fullMessage = "Hello " + name;
 ...
}

Use the prefix “I” with Camel Casing for interfaces ( Example: IEntity )

Do not use Hungarian notation to name variables.

In earlier days most of the programmers liked it - having the data type as a prefix for the variable name and using m_ as prefix for member variables. Eg:

string m_sName;
int nAge;

However, in .NET coding standards, this is not recommended. Usage of data type and m_ to represent member variables should not be used. All variables should use camel casing.

Some programmers still prefer to use the prefix m_ to represent member variables, since there is no other easy way to identify a member variable.

Use Meaningful, descriptive words to name variables. Do not use abbreviations.

Good:

```<code>string address
int salary
</code>```

Not Good:

```<code>string nam
string addr
int sal
</code>```

Do not use single character variable names like i, n, s etc. Use names like index, temp

One exception in this case would be variables used for iterations in loops:

```<code>for ( int i = 0; i < count; i++ )
{
 ...
}
</code>```

If the variable is used only as a counter for iteration and is not used anywhere else in the loop, many people still like to use a single char variable (i) instead of inventing a different suitable name.

Do not use underscores (_) for local variable names.

All member variables must be prefixed with underscore (_) so that they can be identified from other local variables.

Do not use variable names that resemble keywords.

Prefix boolean variables, properties and methods with “is” or similar prefixes.

Ex: private bool _isFinished

Namespace names should follow the standard pattern

...

Use appropriate prefix for the UI elements so that you can identify them from the rest of the variables.

There are 2 different approaches recommended here.

a. Use a common prefix ( ui_ ) for all UI elements. This will help you group all of the UI elements together and easy to access all of them from the intellisense.

b. Use appropriate prefix for each of the ui element. A brief list is given below. Since .NET has given several controls, you may have to arrive at a complete list of standard prefixes for each of the controls (including third party controls) you are using.

```<code>Control Prefix
Label lbl
TextBox txt
DataGrid dtg
Button btn
ImageButton imb
Hyperlink hlk
DropDownList ddl
ListBox lst
DataList dtl
Repeater rep
Checkbox chk
CheckBoxList cbl
RadioButton rdo
RadioButtonList rbl
Image img
Panel pnl
PlaceHolder phd
Table tbl
Validators val
</code>```

File name should match with class name.

For example, for the class HelloWorld, the file name should be helloworld.cs (or, helloworld.vb)

Use Pascal Case for file names.

Indentation and Spacing

Use TAB for indentation. Do not use SPACES.  Define the Tab size as 4.

Comments should be in the same level as the code (use the same level of indentation).

Good:

```<code>// Format a message and display

string fullMessage = "Hello " + name;
DateTime currentTime = DateTime.Now;
string message = fullMessage + ", the time is : " + currentTime.ToShortTimeString();
MessageBox.Show ( message );
</code>```

Not Good:

```<code>// Format a message and display
string fullMessage = "Hello " + name;
DateTime currentTime = DateTime.Now;
string message = fullMessage + ", the time is : " + currentTime.ToShortTimeString();
MessageBox.Show ( message );
</code>```

Curly braces ( {} ) should be in the same level as the code outside the braces.

Use one blank line to separate logical groups of code.

Good:

```<code> bool SayHello ( string name )
 {
  string fullMessage = "Hello " + name;
  DateTime currentTime = DateTime.Now;

  string message = fullMessage + ", the time is : " + currentTime.ToShortTimeString();

  MessageBox.Show ( message );

  if ( ... )
  {
   // Do something
   // ...

   return false;
  }

  return true;
 }
</code>```

Not Good:

```<code>bool SayHello (string name)
 {
  string fullMessage = "Hello " + name;
  DateTime currentTime = DateTime.Now;
  string message = fullMessage + ", the time is : " + currentTime.ToShortTimeString();
  MessageBox.Show ( message );
  if ( ... )
  {
   // Do something
   // ...
   return false;
  }
  return true;
 }
</code>```

There should be one and only one single blank line between each method inside the class.

The curly braces should be on a separate line and not in the same line as if, for etc.

Good:

```<code>if ( ... )
  {
   // Do something
  }
</code>```

Not Good:

```<code>if ( ... ) {
   // Do something
  }
</code>```

Use a single space before and after each operator and brackets.

Good:

```<code>string nam
string addr
int sal
</code>```0

Not Good:

```<code>string nam
string addr
int sal
</code>```1

Use #region to group related pieces of code together. If you use proper grouping using #region, the page should like this when all definitions are collapsed.

Keep private member variables, properties and methods in the top of the file and public members in the bottom.

Body:
Full word doc : Download C# Coding Standards & Best Practices

Naming Conventions and Standards

Note :
The terms Pascal Casing and Camel Casing are used throughout this document.
Pascal Casing - First character of all words are Upper Case and other characters are lower case.
Example: BackColor
Camel Casing - First character of all words, except the first word are Upper Case and other characters are lower case.
Example: backColor

Use Pascal casing for Class names

public class HelloWorld
{
 ...
}

Use Pascal casing for Method names

void SayHello(string name)
{
 ...
}

Use Camel casing for variables and method parameters

int totalCount = 0;
void SayHello(string name)
{
 string fullMessage = "Hello " + name;
 ...
}

Use the prefix “I” with Camel Casing for interfaces ( Example: IEntity )

Do not use Hungarian notation to name variables.

In earlier days most of the programmers liked it - having the data type as a prefix for the variable name and using m_ as prefix for member variables. Eg:

string m_sName;
int nAge;

However, in .NET coding standards, this is not recommended. Usage of data type and m_ to represent member variables should not be used. All variables should use camel casing.

Some programmers still prefer to use the prefix m_ to represent member variables, since there is no other easy way to identify a member variable.

Use Meaningful, descriptive words to name variables. Do not use abbreviations.

Good:

string address
int salary

Not Good:

string nam
string addr
int sal

Do not use single character variable names like i, n, s etc. Use names like index, temp

One exception in this case would be variables used for iterations in loops:

for ( int i = 0; i < count; i++ )
{
 ...
}

If the variable is used only as a counter for iteration and is not used anywhere else in the loop, many people still like to use a single char variable (i) instead of inventing a different suitable name.

Do not use underscores (_) for local variable names.

All member variables must be prefixed with underscore (_) so that they can be identified from other local variables.

Do not use variable names that resemble keywords.

Prefix boolean variables, properties and methods with “is” or similar prefixes.

Ex: private bool _isFinished

Namespace names should follow the standard pattern

...

Use appropriate prefix for the UI elements so that you can identify them from the rest of the variables.

There are 2 different approaches recommended here.

a. Use a common prefix ( ui_ ) for all UI elements. This will help you group all of the UI elements together and easy to access all of them from the intellisense.

b. Use appropriate prefix for each of the ui element. A brief list is given below. Since .NET has given several controls, you may have to arrive at a complete list of standard prefixes for each of the controls (including third party controls) you are using.

Control Prefix
Label lbl
TextBox txt
DataGrid dtg
Button btn
ImageButton imb
Hyperlink hlk
DropDownList ddl
ListBox lst
DataList dtl
Repeater rep
Checkbox chk
CheckBoxList cbl
RadioButton rdo
RadioButtonList rbl
Image img
Panel pnl
PlaceHolder phd
Table tbl
Validators val

File name should match with class name.

For example, for the class HelloWorld, the file name should be helloworld.cs (or, helloworld.vb)

Use Pascal Case for file names.

Indentation and Spacing

Use TAB for indentation. Do not use SPACES.  Define the Tab size as 4.

Comments should be in the same level as the code (use the same level of indentation).

Good:

// Format a message and display

string fullMessage = "Hello " + name;
DateTime currentTime = DateTime.Now;
string message = fullMessage + ", the time is : " + currentTime.ToShortTimeString();
MessageBox.Show ( message );

Not Good:

// Format a message and display
string fullMessage = "Hello " + name;
DateTime currentTime = DateTime.Now;
string message = fullMessage + ", the time is : " + currentTime.ToShortTimeString();
MessageBox.Show ( message );

Curly braces ( {} ) should be in the same level as the code outside the braces.

Use one blank line to separate logical groups of code.

Good:

 bool SayHello ( string name )
 {
  string fullMessage = "Hello " + name;
  DateTime currentTime = DateTime.Now;

  string message = fullMessage + ", the time is : " + currentTime.ToShortTimeString();

  MessageBox.Show ( message );

  if ( ... )
  {
   // Do something
   // ...

   return false;
  }

  return true;
 }

Not Good:

bool SayHello (string name)
 {
  string fullMessage = "Hello " + name;
  DateTime currentTime = DateTime.Now;
  string message = fullMessage + ", the time is : " + currentTime.ToShortTimeString();
  MessageBox.Show ( message );
  if ( ... )
  {
   // Do something
   // ...
   return false;
  }
  return true;
 }

There should be one and only one single blank line between each method inside the class.

The curly braces should be on a separate line and not in the same line as if, for etc.

Good:

if ( ... )
  {
   // Do something
  }

Not Good:

if ( ... ) {
   // Do something
  }

Use a single space before and after each operator and brackets.

Good:

if ( showResult == true )
  {
   for ( int i = 0; i < 10; i++ )
   {
    //
   }
  }

Not Good:

if(showResult==true)
  {
   for(int    i= 0;i<10;i++)
   {
    //
   }
  }

Use #region to group related pieces of code together. If you use proper grouping using #region, the page should like this when all definitions are collapsed.

Keep private member variables, properties and methods in the top of the file and public members in the bottom.


问:
Angular 5 HTTP interceptor not working
My interceptor service is adding the authorization header to my http calls, but fails to include the actual bearer token value that I pass into the interceptor service. The bearer token value that appears in chrome dev tools is just the 'not set' value, not the bearer token value.  The bearer token value does show correctly when I console log it from the login component so I know is it being set, but I guess it is getting reset back to the 'not set' value at some point before it is used in the subsequent http call?  </p>

```<code>import { Component, OnInit }                            from '@angular/core';
import { Router }                                       from "@angular/router";
import { HttpClient }                                   from "@angular/common/http";
import { Response, Headers, RequestOptions }            from "@angular/http";
import { AuthInterceptor }                              from "../../services/authInterceptor.service";
import { MatSnackBar }                                  from '@angular/material';
import "rxjs/Rx";

@Component({
  selector: 'login',
  templateUrl: './login.component.html'
})
export class LoginComponent implements OnInit {

    memberLogin: any = {
        'emailAddress': '',
        'password': ''
    };

    public constructor(private http: HttpClient, private authInterceptor: AuthInterceptor, public snackBar: MatSnackBar, public router: Router) {
    }

    public ngOnInit() {
    }

    public login() {

        let url: string = 'http://localhost:63741/api/Account/Login';
        let body = { "Email": this.memberLogin.emailAddress, "Password": this.memberLogin.password };

        this.http.post(url, body)
            .subscribe(
                data => {
                    this.authInterceptor.authToken = data.toString();
                    console.log('token data in login component : ' + this.authInterceptor.authToken);
                    this.snackBar.open('welcome back, you are now logged in', 'ok', { duration: 2200 })
                },
                err => {

                });

        return;
    };

}

import { Injectable }                                               from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest }     from '@angular/common/http';
import { Observable }                                               from 'rxjs/Observable';

@Injectable()
export class AuthInterceptor {

    authToken: string = 'not set';

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const authReq = req.clone({ headers: req.headers.set('Authorization', 'Bearer ' + this.authToken ) });
        return next.handle(authReq);
    }
}
</code>```

答:
The AuthInterceptor that you are injecting into LoginComponent is not the same object as the one used by the HttpClient framework (i.e. the one in the useClass for HTTP_INTERCEPTORS in AppModule).

Have the AuthInterceptor use a new injectable, say AuthService, in which you store the authToken. Inject this into both the AuthInterceptor and LoginComponent:

```<code>@Injectable()
export class AuthService {
    public authToken: string = 'not set';
}
</code>```

Make sure to declare this as a provider in AppModule.

Title: Angular 5 HTTP interceptor not working

Body:
My interceptor service is adding the authorization header to my http calls, but fails to include the actual bearer token value that I pass into the interceptor service. The bearer token value that appears in chrome dev tools is just the 'not set' value, not the bearer token value.  The bearer token value does show correctly when I console log it from the login component so I know is it being set, but I guess it is getting reset back to the 'not set' value at some point before it is used in the subsequent http call?

import { Component, OnInit }                            from '@angular/core';
import { Router }                                       from "@angular/router";
import { HttpClient }                                   from "@angular/common/http";
import { Response, Headers, RequestOptions }            from "@angular/http";
import { AuthInterceptor }                              from "../../services/authInterceptor.service";
import { MatSnackBar }                                  from '@angular/material';
import "rxjs/Rx";

@Component({
  selector: 'login',
  templateUrl: './login.component.html'
})
export class LoginComponent implements OnInit {

    memberLogin: any = {
        'emailAddress': '',
        'password': ''
    };

    public constructor(private http: HttpClient, private authInterceptor: AuthInterceptor, public snackBar: MatSnackBar, public router: Router) {
    }

    public ngOnInit() {
    }

    public login() {

        let url: string = 'http://localhost:63741/api/Account/Login';
        let body = { "Email": this.memberLogin.emailAddress, "Password": this.memberLogin.password };

        this.http.post(url, body)
            .subscribe(
                data => {
                    this.authInterceptor.authToken = data.toString();
                    console.log('token data in login component : ' + this.authInterceptor.authToken);
                    this.snackBar.open('welcome back, you are now logged in', 'ok', { duration: 2200 })
                },
                err => {

                });

        return;
    };

}

import { Injectable }                                               from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest }     from '@angular/common/http';
import { Observable }                                               from 'rxjs/Observable';

@Injectable()
export class AuthInterceptor {

    authToken: string = 'not set';

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const authReq = req.clone({ headers: req.headers.set('Authorization', 'Bearer ' + this.authToken ) });
        return next.handle(authReq);
    }
}

Body:
The AuthInterceptor that you are injecting into LoginComponent is not the same object as the one used by the HttpClient framework (i.e. the one in the useClass for HTTP_INTERCEPTORS in AppModule).

Have the AuthInterceptor use a new injectable, say AuthService, in which you store the authToken. Inject this into both the AuthInterceptor and LoginComponent:

@Injectable()
export class AuthService {
    public authToken: string = 'not set';
}

Make sure to declare this as a provider in AppModule.


问:
Spring Integration - File Inbound Adapter - set id
Does anyone know how you can setup the id for an FileInboundChannelAdapterSpec?

This is how I am building the inbound adapter:

```<code>Files.inboundAdapter(new File("etc")).nioLocker().preventDuplicates();
</code>```

Thanks in advance.

答:
I've been able to setup an id for the flow, when registering it to the integrationFlowContext.

Sample:
    this.integrationFlowContext.registration(flow).id(flowId).autoStartup(false).register();

Body:
Does anyone know how you can setup the id for an FileInboundChannelAdapterSpec?

This is how I am building the inbound adapter:

Files.inboundAdapter(new File("etc")).nioLocker().preventDuplicates();

Thanks in advance.


问:
Query for custom post types not working via AJAX
I've created a custom post type called 'award'. I'm on archive-award.php and I'm displaying a list of the 'award' posts. So far so good.

Now I want to pull the next posts via AJAX, at the click of a 'Load More' button. Here's the action I pass to the AJAX script:

```<code>function load_next_award_posts() {

    $args = array(
        'paged' => 2,
        'post_type' => 'award',
        'post_status' => 'publish'
    );

    $next_posts = new WP_Query( $args );

    if( $next_posts->have_posts() ) :
        while( $next_posts->have_posts() ) : $next_posts->the_post();
            echo '<p>Hello</p>';
        endwhile;
    endif;

    wp_reset_postdata();
    die();

}
</code>```

Unfortunately, the query returns no results. If instead I change the post_type to the default post or page, it all works fine. So what's going on? Why isn't the query working with my custom post type?

答:
```<code><a id="more_posts" href="#">Load More</a>
</code>```

Your file.js

```<code>    var ajaxUrl = "<?php echo admin_url('admin-ajax.php')?>";
    var page = 1; // What page we are on.
    var ppp = 10; // Post per page

    $("#more_posts").on("click",function(){
        $("#more_posts").attr("disabled",true);
        $.post(ajaxUrl, {
            action:"more_post_ajax",
            offset: (page * ppp) + 1,
            ppp: ppp
        }).success(function(posts){
            page++;
            $(".name_of_posts_class").append(posts);
            $("#more_posts").attr("disabled",false);
        });

   });

</script>
</code>```

Functions.php

```<code>function more_post_ajax(){
    $offset = $_POST["offset"];
    $ppp = $_POST["ppp"];
    header("Content-Type: text/html");

    $args = array(
        'post_type' => 'award',
        'posts_per_page' => $ppp,
        'offset' => $offset,
    );

    $loop = new WP_Query($args);
    while ($loop->have_posts()) { $loop->the_post();
       the_content();
    }

    exit;
}

add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');
</code>```

Body:
I've created a custom post type called 'award'. I'm on archive-award.php and I'm displaying a list of the 'award' posts. So far so good.

Now I want to pull the next posts via AJAX, at the click of a 'Load More' button. Here's the action I pass to the AJAX script:

function load_next_award_posts() {

    $args = array(
        'paged' => 2,
        'post_type' => 'award',
        'post_status' => 'publish'
    );

    $next_posts = new WP_Query( $args );

    if( $next_posts->have_posts() ) :
        while( $next_posts->have_posts() ) : $next_posts->the_post();
            echo '
Hello
';
        endwhile;
    endif;

    wp_reset_postdata();
    die();

}

Unfortunately, the query returns no results. If instead I change the post_type to the default post or page, it all works fine. So what's going on? Why isn't the query working with my custom post type?

Body:
<a id="more_posts" href="#">Load More</a>

Your file.js

    var ajaxUrl = "<?php echo admin_url('admin-ajax.php')?>";
    var page = 1; // What page we are on.
    var ppp = 10; // Post per page

    $("#more_posts").on("click",function(){
        $("#more_posts").attr("disabled",true);
        $.post(ajaxUrl, {
            action:"more_post_ajax",
            offset: (page * ppp) + 1,
            ppp: ppp
        }).success(function(posts){
            page++;
            $(".name_of_posts_class").append(posts);
            $("#more_posts").attr("disabled",false);
        });

   });

</script>

Functions.php

function more_post_ajax(){
    $offset = $_POST["offset"];
    $ppp = $_POST["ppp"];
    header("Content-Type: text/html");

    $args = array(
        'post_type' => 'award',
        'posts_per_page' => $ppp,
        'offset' => $offset,
    );

    $loop = new WP_Query($args);
    while ($loop->have_posts()) { $loop->the_post();
       the_content();
    }

    exit;
}

add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');


问:
at what scene do we use this php array?
at what scene do we use this php array ?
i have seen in many places like </p>

```<code>   echo $var1[$var2[]];
</code>```

答:
One scenario could be something like this:

You have an array of books. Each book in turn has an array of pages.

So basically:

```<code>[
    book1 => [ page1, page2, page3 ],
    book2 => [ page1, page2, page3 ]
]
</code>```

Title: at what scene do we use this php array?

Body:
at what scene do we use this php array ?
i have seen in many places like

   echo $var1[$var2[]];

Body:
One scenario could be something like this:

You have an array of books. Each book in turn has an array of pages.

So basically:

[
    book1 => [ page1, page2, page3 ],
    book2 => [ page1, page2, page3 ]
]


问:
What is the meaning of the version numbers in an output of "pod outdated"?
I have executed "pod outdated" for my project. This is the output:

```<code>Analyzing dependencies
The following pod updates are available:
- Kingfisher 4.0.0 -> 4.0.0 (latest version 4.2.0)
- Lokalise 0.7.0 -> 0.7.0 (latest version 0.7.1)
- LokaliseLiveEdit 0.2.2 -> 0.2.2 (latest version 0.2.3)
- Realm 3.0.0 -> 3.0.0 (latest version 3.0.2)
- RealmSwift 3.0.0 -> 3.0.0 (latest version 3.0.2)
- SwiftLint 0.23.0 -> 0.23.0 (latest version 0.24.0)
- SwiftyJSON 3.1.4 -> 3.1.4 (latest version 4.0.0)
- Tabman 1.0.6 -> 1.0.6 (latest version 1.0.7)
</code>```

What is the meaning of the version numbers which are presented three times per line?

答:
In general, this is the scheme of a line of pod outdated's output:

```<code>- <pod name> <current version> -> <latest version (with restrictions)> (latest version <latest version (without restrictions)>)
</code>```

The first version number (before the arrow) is the current version of a Pod.

The second number (after the arrow) is the latest available version according to the restrictions in your Podfile.

The third version number (inside the brackets, after "latest version") is the latest available version without the personal restrictions.

From CocoaPods Guides:

When you run pod outdated, CocoaPods will list all pods which have newer versions than the ones listed in the Podfile.lock (the versions currently installed for each pod). This means that if you run pod update PODNAME on those pods, they will be updated — as long as the new version still matches the restrictions like pod 'MyPod', '~>x.y' set in your Podfile.

Body:
I have executed "pod outdated" for my project. This is the output:

Analyzing dependencies
The following pod updates are available:
- Kingfisher 4.0.0 -> 4.0.0 (latest version 4.2.0)
- Lokalise 0.7.0 -> 0.7.0 (latest version 0.7.1)
- LokaliseLiveEdit 0.2.2 -> 0.2.2 (latest version 0.2.3)
- Realm 3.0.0 -> 3.0.0 (latest version 3.0.2)
- RealmSwift 3.0.0 -> 3.0.0 (latest version 3.0.2)
- SwiftLint 0.23.0 -> 0.23.0 (latest version 0.24.0)
- SwiftyJSON 3.1.4 -> 3.1.4 (latest version 4.0.0)
- Tabman 1.0.6 -> 1.0.6 (latest version 1.0.7)

What is the meaning of the version numbers which are presented three times per line?

Body:
In general, this is the scheme of a line of pod outdated's output:

- <pod name> <current version> -> <latest version (with restrictions)> (latest version <latest version (without restrictions)>)

The first version number (before the arrow) is the current version of a Pod.

The second number (after the arrow) is the latest available version according to the restrictions in your Podfile.

The third version number (inside the brackets, after "latest version") is the latest available version without the personal restrictions.

From CocoaPods Guides:

When you run pod outdated, CocoaPods will list all pods which have newer versions than the ones listed in the Podfile.lock (the versions currently installed for each pod). This means that if you run pod update PODNAME on those pods, they will be updated — as long as the new version still matches the restrictions like pod 'MyPod', '~>x.y' set in your Podfile.


答:
I find it makes everyone's life easier to use the same naming conventions used by the language and framework you are working in.

For example, .Net has a convention.  Model what your language does, and the "users" of your code and libraries will be happier.  So, the answer may be, it depends on your language and / or platform...

Title: Conventions for naming class operations?

Body: What conventions do you use for naming class operations?


问:
Filter and export data in .csv
I need a few instructions to scroll a list of servers, remotely edit some registry keys for each server and save the output of each registry key update in a .csv file.
I tried my scripts and they seem to work but I'm not able to filter the results and save only (and exactly) what I need in the .csv:

Script 1:

```<code>$Invocation = (Get-Variable MyInvocation -Scope 0).Value
$LocalDir = Split-Path $Invocation.MyCommand.Path
$Computers = Get-Content $LocalDir'\HostsList.txt'
$Results = foreach ($Computer in $Computers) {
    Invoke-Command -ComputerName $Computer -FilePath $LocalDir'\autologon_editor.ps1' -ArgumentList $Computer
}
$Results | Export-Csv -NoTypeInformation -Path $LocalDir'\ResultsAutologon.csv'
</code>```

Script 2:

```<code>Param(
    [Parameter(Mandatory=$true,
    ValueFromPipeline=$true)]
    [string[]]$Computer
)
$Path = 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon'
$Property1 = 'DefaultUserName'
$Property2 = 'DefaultPassword'
$Value1 = 'NewUserName-new4'
$Value2 = 'NewPassword-new4'
if (Test-Connection -ComputerName $Computer -Count 1 -Quiet) {
    try {
        Set-ItemProperty -Path $Path -Name $Property1 -Value $Value1 -ErrorAction 'Stop'
        Set-ItemProperty -Path $Path -Name $Property2 -Value $Value2 -ErrorAction 'Stop'
        $Status = 'Username and password set ok'
    } catch {
        $Status = 'Username or password set ko'
    }
} else {
    $Status = 'Unreachable'
}
Get-ItemProperty -Path $Path
RUNDLL32.EXE USER32.DLL,UpdatePerUserSystemParameters ,1 ,True
$Properties = @{
    'Computer' = $Computer;
    'Status'   = $Status
}
$Record = New-Object -TypeName PSObject -Property $Properties
</code>```

Issue

My filter is not working: the .csv does not contain the fields "Computer" and "Status", but the following list:

"Userinit", "LegalNoticeText", "Shell", "LegalNoticeCaption", "DebugServerCommand", "ForceUnlockLogon", "ReportBootOk", "VMApplet", "AutoRestartShell", "PowerdownAfterShutdown", "ShutdownWithoutLogon", "Background", "PreloadFontFile", "PasswordExpiryWarning", "CachedLogonsCount", "WinStationsDisabled", "PreCreateKnownFolders", "DisableCAD", "scremoveoption", "ShutdownFlags", "AutoLogonSID", "LastUsedUsername", "DefaultUserName", "DefaultPassword", "PSPath", "PSParentPath", "PSChildName", "PSDrive", "PSProvider", "PSComputerName", "RunspaceId", "PSShowComputerName"

答:
Script 2 (which I assume is autologon_editor.ps1) is not currently outputting $Record. However I suspect it is instead returning the output from this command:

```<code>Get-ItemProperty -Path $Path
</code>```

Which I'm not sure is needed.

I suggest removing the above command and then modifying the end of your script to this:

```<code>RUNDLL32.EXE USER32.DLL,UpdatePerUserSystemParameters ,1 ,True
$Properties = @{
    'Computer'=$Computer;
    'Status'=$Status
}
New-Object -TypeName PSObject -Property $Properties
</code>```

This will return the result of the New-Object command (the object) to the pipeline, which will in turn make it the output of the Invoke-Command.

Title: Filter and export data in .csv

Body:
I need a few instructions to scroll a list of servers, remotely edit some registry keys for each server and save the output of each registry key update in a .csv file.
I tried my scripts and they seem to work but I'm not able to filter the results and save only (and exactly) what I need in the .csv:

Script 1:

$Invocation = (Get-Variable MyInvocation -Scope 0).Value
$LocalDir = Split-Path $Invocation.MyCommand.Path
$Computers = Get-Content $LocalDir'\HostsList.txt'
$Results = foreach ($Computer in $Computers) {
    Invoke-Command -ComputerName $Computer -FilePath $LocalDir'\autologon_editor.ps1' -ArgumentList $Computer
}
$Results | Export-Csv -NoTypeInformation -Path $LocalDir'\ResultsAutologon.csv'

Script 2:

Param(
    [Parameter(Mandatory=$true,
    ValueFromPipeline=$true)]
    [string[]]$Computer
)
$Path = 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon'
$Property1 = 'DefaultUserName'
$Property2 = 'DefaultPassword'
$Value1 = 'NewUserName-new4'
$Value2 = 'NewPassword-new4'
if (Test-Connection -ComputerName $Computer -Count 1 -Quiet) {
    try {
        Set-ItemProperty -Path $Path -Name $Property1 -Value $Value1 -ErrorAction 'Stop'
        Set-ItemProperty -Path $Path -Name $Property2 -Value $Value2 -ErrorAction 'Stop'
        $Status = 'Username and password set ok'
    } catch {
        $Status = 'Username or password set ko'
    }
} else {
    $Status = 'Unreachable'
}
Get-ItemProperty -Path $Path
RUNDLL32.EXE USER32.DLL,UpdatePerUserSystemParameters ,1 ,True
$Properties = @{
    'Computer' = $Computer;
    'Status'   = $Status
}
$Record = New-Object -TypeName PSObject -Property $Properties

Issue

My filter is not working: the .csv does not contain the fields "Computer" and "Status", but the following list:

"Userinit", "LegalNoticeText", "Shell", "LegalNoticeCaption", "DebugServerCommand", "ForceUnlockLogon", "ReportBootOk", "VMApplet", "AutoRestartShell", "PowerdownAfterShutdown", "ShutdownWithoutLogon", "Background", "PreloadFontFile", "PasswordExpiryWarning", "CachedLogonsCount", "WinStationsDisabled", "PreCreateKnownFolders", "DisableCAD", "scremoveoption", "ShutdownFlags", "AutoLogonSID", "LastUsedUsername", "DefaultUserName", "DefaultPassword", "PSPath", "PSParentPath", "PSChildName", "PSDrive", "PSProvider", "PSComputerName", "RunspaceId", "PSShowComputerName"

Body:
Script 2 (which I assume is autologon_editor.ps1) is not currently outputting $Record. However I suspect it is instead returning the output from this command:

Get-ItemProperty -Path $Path

Which I'm not sure is needed.

I suggest removing the above command and then modifying the end of your script to this:

RUNDLL32.EXE USER32.DLL,UpdatePerUserSystemParameters ,1 ,True
$Properties = @{
    'Computer'=$Computer;
    'Status'=$Status
}
New-Object -TypeName PSObject -Property $Properties

This will return the result of the New-Object command (the object) to the pipeline, which will in turn make it the output of the Invoke-Command.


问:
App installation failed when transfered code
So i started my project on Mac OS and than with USB i transfered to MacOS, using same version of Android studio, but on Mac it doesn't want to run i tried to delte gradle and idea folders build a gradle and all but no success. The error i get is Application Installation Failed:

Installation failed with message Invalid File: /Users/myuser/Code/App/E:\Android\apps\build\intermediates\split-apk\debug\slices\slice_2.apk

Do you want to uninstall this existing application?

So as it looks like its picking up my Windows things from somewhere any idea how i can fix this?

答: So i just run: ./gradlew clean and disabled instant run and its working now.</p>


问:
XMLHttpRequest Getting old values
I'm trying to read a file with XMLHttpRequest, get its content and add it to a chart from chart.js.

```<code>function loadFile() {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', 'file.txt');
  xhr.onreadystatechange = function () {
    if (xhr.readyState == 4 && xhr.status == 200) {
      val = xhr.responseText;
    }
  }
  xhr.send();
}
</code>```

file.txt :

```<code>123
</code>```

I have a button, when I click on it it adds val to an array (for my chart).It works, but val does not changes when the file is getting changed by the server. So it keeps adding '123' while the content of file.txt has changed.

答:
Answer is in comment from Paulo Diogo:

have you tried check the cache? Like: Press CTRL + F5 before fire another request. Or add xhr.setRequestHeader("Cache-Control", "max-age=0");

I added xhr.setRequestHeader("Cache-Control", "max-age=0"); in my button click.

Title: XMLHttpRequest Getting old values

Body:
I'm trying to read a file with XMLHttpRequest, get its content and add it to a chart from chart.js.

function loadFile() {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', 'file.txt');
  xhr.onreadystatechange = function () {
    if (xhr.readyState == 4 && xhr.status == 200) {
      val = xhr.responseText;
    }
  }
  xhr.send();
}

file.txt :

123

I have a button, when I click on it it adds val to an array (for my chart).It works, but val does not changes when the file is getting changed by the server. So it keeps adding '123' while the content of file.txt has changed.