问:
Using a button to deselect cells in a collectionview
I have two collection views. Tapping unselected cells in Collection View 1 selects them, and adds the selected cell to Collection View 2. Tapping on selected cells in Collection View 1 (allHobbiesCV) will unselect them and remove them from Collection View 2 (myHobbiesCV). Essentially, all it's doing is toggling.

Cells in Collection View 2 can also be manually removed by selecting as few or many as desired, then pressing a 'Remove' button. This process works great, except the cells in Collection View 1 still remain selected, even if that particular cell was removed from Collection View 2.

How do I use the remove button to deselect cells from Collection View 1 if they were manually selected and removed from Collection View 2?

Class level -

```<code>var allHobbiesArray = [String]()
var allHobbiesArraySelected = [String]()

var myHobbiesArray = [String]()
var myHobbiesArraySelected = [String]()
</code>```

didSelectItemAt

```<code>func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    // All Hobbies
    if collectionView == allHobbiesCV {
        let item = allHobbiesArray[indexPath.item]
        let cell = allHobbiesCV.cellForItem(at: indexPath) as! AllHobbiesCell

        if let itemIndex = allHobbiesArraySelected.index(of:item) {
            // DID DESELECT
            allHobbiesArraySelected.remove(at:itemIndex)
            myHobbiesArray.remove(at: itemIndex)
            myHobbiesCV.deleteItems(at: [IndexPath(item: itemIndex, section:0)])
            cell.backgroundColor = UIColor.brown
        }
        else {
            // DID SELECT
            allHobbiesArraySelected.insert(item, at: 0)
            myHobbiesArray.insert(item, at: 0)
            myHobbiesCV.insertItems(at: [IndexPath(item: 0, section:0)])
            cell.backgroundColor = UIColor.green
        }

        allHobbiesCV.deselectItem(at: indexPath, animated: false)

        for cell in myHobbiesCV.visibleCells {
            cell.backgroundColor = UIColor.white
        }
        myHobbiesArraySelected.removeAll()
        //myHobbiesCV.reloadData() // needed?
    }

    // My Hobbies
    else {
        let item = myHobbiesArray[indexPath.item]
        let cell = myHobbiesCV.cellForItem(at: indexPath) as! MyHobbiesCell

        if let itemIndex = myHobbiesArraySelected.index(of:item) {
            // DID DESELECT
            myHobbiesArraySelected.remove(at: itemIndex)
            cell.backgroundColor = UIColor.white
        }
        else {
            // DID SELECT
            myHobbiesArraySelected.insert(item, at: 0)
            cell.backgroundColor = UIColor.red
        }
        myHobbiesCV.deselectItem(at: indexPath, animated: true)
    }
}
</code>```

cellForItem

```<code>func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    if collectionView == allHobbiesCV {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ALL", for: indexPath) as! AllHobbiesCell
        cell.allHobbiesCellLabel.text = allHobbiesArray[indexPath.item]

        let allHobbies = allHobbiesArray[indexPath.item]
        if allHobbiesArraySelected.index(of: allHobbies) != nil {
            cell.backgroundColor = UIColor.green
        }
        else {
            cell.backgroundColor = UIColor.brown
        }

        return cell
    }

    else { // myHobbiesCV
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MY", for: indexPath) as! MyHobbiesCell
        cell.myHobbiesCellLabel.text = myHobbiesArray[indexPath.item]

        let myHobbies = myHobbiesArray[indexPath.item]
        if myHobbiesArraySelected.index(of: myHobbies) != nil {
            cell.backgroundColor = UIColor.red
        }
        else {
            cell.backgroundColor = UIColor.white
        }

        return cell
    }

}
</code>```

numberOfItemsInSection

```<code>    if collectionView == allHobbiesCV {
        return allHobbiesArray.count
    }
    else {
        return myHobbiesArray.count
    }
</code>```

Delete button

```<code>@IBAction func deleteHobbyButtonPressed(_ sender: UIButton) {

    print("all Hobbies - \(allHobbiesCV.indexPathsForSelectedItems!)")

    if let selectedItemPaths = myHobbiesCV.indexPathsForSelectedItems {

        var allItemIndexPaths = [IndexPath]()
        var tempSelectedItems = Array(allHobbiesArraySelected) // Need to use a temporary copy otherwise the element indexes will change
        for itemPath in selectedItemPaths {

            let removeItem = allHobbiesArraySelected[itemPath.item]
            if let removeIndex = tempSelectedItems.index(of: removeItem) {
                print("if let removeIndex")
                tempSelectedItems.remove(at: removeIndex)
            }

            if let allItemsIndex = allHobbiesArray.index(of: removeItem) {
                print("if let allItemsIndex")
                allItemIndexPaths.append(IndexPath(item: allItemsIndex, section: 0))
            }
        }

        allHobbiesArraySelected = tempSelectedItems // Selected items array without the removed items
        myHobbiesCV.deleteItems(at:selectedItemPaths)
        myHobbiesCV.reloadData()
        allHobbiesCV.reloadItems(at: allItemIndexPaths)  // Reload to update the selected status
    }

}
</code>```

The problem now is nothing is evaluating in the remove button. That first print statement always returns an empty array. And nothing prints in the if let check. Is there a way to use myHobbiesArraySelected instead of indexPathsForSelectedItems? (Since I'm saving the selected items in an array now) Along with the original intended functionality of deselecting the cell in allHobbiesCV if it was manually deleted in myHobbiesCV.

Thanks friends.

答:
Update: IndexPath conforms Equatable (see comment from @Paulw11)
<s>you compare the objects IndexPath in contains but but even if an instance of indexPath path have the same sections and rows the object itself is different.</s>

<s>1. solution: compare values
change the contains to to compare the sections and rows</s>

solution: stick on item id
stick on an unique item id which you store in the array. then you are on the more save situation, if collection1 and collection2 has different sizes and sections

i would suggest to implement solution 2

Body:
I have two collection views. Tapping unselected cells in Collection View 1 selects them, and adds the selected cell to Collection View 2. Tapping on selected cells in Collection View 1 (allHobbiesCV) will unselect them and remove them from Collection View 2 (myHobbiesCV). Essentially, all it's doing is toggling.

Cells in Collection View 2 can also be manually removed by selecting as few or many as desired, then pressing a 'Remove' button. This process works great, except the cells in Collection View 1 still remain selected, even if that particular cell was removed from Collection View 2.

How do I use the remove button to deselect cells from Collection View 1 if they were manually selected and removed from Collection View 2?

Class level -

var allHobbiesArray = [String]()
var allHobbiesArraySelected = [String]()

var myHobbiesArray = [String]()
var myHobbiesArraySelected = [String]()

didSelectItemAt

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    // All Hobbies
    if collectionView == allHobbiesCV {
        let item = allHobbiesArray[indexPath.item]
        let cell = allHobbiesCV.cellForItem(at: indexPath) as! AllHobbiesCell

        if let itemIndex = allHobbiesArraySelected.index(of:item) {
            // DID DESELECT
            allHobbiesArraySelected.remove(at:itemIndex)
            myHobbiesArray.remove(at: itemIndex)
            myHobbiesCV.deleteItems(at: [IndexPath(item: itemIndex, section:0)])
            cell.backgroundColor = UIColor.brown
        }
        else {
            // DID SELECT
            allHobbiesArraySelected.insert(item, at: 0)
            myHobbiesArray.insert(item, at: 0)
            myHobbiesCV.insertItems(at: [IndexPath(item: 0, section:0)])
            cell.backgroundColor = UIColor.green
        }

        allHobbiesCV.deselectItem(at: indexPath, animated: false)

        for cell in myHobbiesCV.visibleCells {
            cell.backgroundColor = UIColor.white
        }
        myHobbiesArraySelected.removeAll()
        //myHobbiesCV.reloadData() // needed?
    }

    // My Hobbies
    else {
        let item = myHobbiesArray[indexPath.item]
        let cell = myHobbiesCV.cellForItem(at: indexPath) as! MyHobbiesCell

        if let itemIndex = myHobbiesArraySelected.index(of:item) {
            // DID DESELECT
            myHobbiesArraySelected.remove(at: itemIndex)
            cell.backgroundColor = UIColor.white
        }
        else {
            // DID SELECT
            myHobbiesArraySelected.insert(item, at: 0)
            cell.backgroundColor = UIColor.red
        }
        myHobbiesCV.deselectItem(at: indexPath, animated: true)
    }
}

cellForItem

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    if collectionView == allHobbiesCV {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ALL", for: indexPath) as! AllHobbiesCell
        cell.allHobbiesCellLabel.text = allHobbiesArray[indexPath.item]

        let allHobbies = allHobbiesArray[indexPath.item]
        if allHobbiesArraySelected.index(of: allHobbies) != nil {
            cell.backgroundColor = UIColor.green
        }
        else {
            cell.backgroundColor = UIColor.brown
        }

        return cell
    }

    else { // myHobbiesCV
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MY", for: indexPath) as! MyHobbiesCell
        cell.myHobbiesCellLabel.text = myHobbiesArray[indexPath.item]

        let myHobbies = myHobbiesArray[indexPath.item]
        if myHobbiesArraySelected.index(of: myHobbies) != nil {
            cell.backgroundColor = UIColor.red
        }
        else {
            cell.backgroundColor = UIColor.white
        }

        return cell
    }

}

numberOfItemsInSection

    if collectionView == allHobbiesCV {
        return allHobbiesArray.count
    }
    else {
        return myHobbiesArray.count
    }

Delete button

@IBAction func deleteHobbyButtonPressed(_ sender: UIButton) {

    print("all Hobbies - \(allHobbiesCV.indexPathsForSelectedItems!)")

    if let selectedItemPaths = myHobbiesCV.indexPathsForSelectedItems {

        var allItemIndexPaths = [IndexPath]()
        var tempSelectedItems = Array(allHobbiesArraySelected) // Need to use a temporary copy otherwise the element indexes will change
        for itemPath in selectedItemPaths {

            let removeItem = allHobbiesArraySelected[itemPath.item]
            if let removeIndex = tempSelectedItems.index(of: removeItem) {
                print("if let removeIndex")
                tempSelectedItems.remove(at: removeIndex)
            }

            if let allItemsIndex = allHobbiesArray.index(of: removeItem) {
                print("if let allItemsIndex")
                allItemIndexPaths.append(IndexPath(item: allItemsIndex, section: 0))
            }
        }

        allHobbiesArraySelected = tempSelectedItems // Selected items array without the removed items
        myHobbiesCV.deleteItems(at:selectedItemPaths)
        myHobbiesCV.reloadData()
        allHobbiesCV.reloadItems(at: allItemIndexPaths)  // Reload to update the selected status
    }

}

The problem now is nothing is evaluating in the remove button. That first print statement always returns an empty array. And nothing prints in the if let check. Is there a way to use myHobbiesArraySelected instead of indexPathsForSelectedItems? (Since I'm saving the selected items in an array now) Along with the original intended functionality of deselecting the cell in allHobbiesCV if it was manually deleted in myHobbiesCV.

Thanks friends.


来源: stackexchange

问:
Android loop problem
I am new to android but not to programming. And the code below makes the icon.png that is available by default in android, go across the screen or at least it is supposed to. This doesn't work. Can anyone help?</p>

```<code>> package com.android.test; import
> android.app.Activity; import
> android.content.Context; import
> android.graphics.Bitmap; import
> android.graphics.BitmapFactory; import
> android.graphics.Canvas; import
> android.graphics.Color; import
> android.os.Bundle;
>
>
> import android.view.View; import
> android.view.Window;
>
> public class Android extends Activity
> { int x,y=10;
>
> @Override public void onCreate(Bundle
> savedInstanceState) {
> super.onCreate(savedInstanceState);
> requestWindowFeature(Window.FEATURE_NO_TITLE);
> setContentView(new Panel(this)); }
>
> class Panel extends View { public
> Panel(Context context) {
> super(context); }
>
> @Override public void onDraw(Canvas
> canvas) { Bitmap _scratch =
> BitmapFactory.decodeResource(getResources(),
> R.drawable.icon);
> canvas.drawColor(Color.BLACK); int
> n=1;  while (n==1){ try {
> Thread.sleep(30);  } catch
> (InterruptedException e) { }
> canvas.drawBitmap(_scratch, x, y,
> null);  x+=2; y+=2;
>
> canvas.drawBitmap(_scratch, x, y,
> null);  } } } }
</code>```

答:
Your onDraw() method never returns. It needs to. Does your app Force Close after a few seconds? You're going to have to post a message to the UI thread to redraw after 30 milliseconds instead of looping within onDraw(). Off the top of my head, try this instead:

```<code>class Panel extends View {
  public Panel(Context context) {
    super(context);
  }

  int x = 0;
  int y = 0;
  Bitmap _scratch = BitmapFactory.decodeResource(getResources(), R.drawable.icon);

  @Override public void onDraw(Canvas canvas) {
    canvas.drawColor(Color.BLACK);
    canvas.drawBitmap(_scratch, x, y, null);
    x+=2; y+=2;
    this.postInvalidateDelayed(30);
  }
}
</code>```

Of course you need to add some code to stop looping once the icon has gone off the edge.

ContentLicense: CC BY-SA 2.5

Title: Android loop problem

Body:
I am new to android but not to programming. And the code below makes the icon.png that is available by default in android, go across the screen or at least it is supposed to. This doesn't work. Can anyone help?

> package com.android.test; import
> android.app.Activity; import
> android.content.Context; import
> android.graphics.Bitmap; import
> android.graphics.BitmapFactory; import
> android.graphics.Canvas; import
> android.graphics.Color; import
> android.os.Bundle;
>
>
> import android.view.View; import
> android.view.Window;
>
> public class Android extends Activity
> { int x,y=10;
>
> @Override public void onCreate(Bundle
> savedInstanceState) {
> super.onCreate(savedInstanceState);
> requestWindowFeature(Window.FEATURE_NO_TITLE);
> setContentView(new Panel(this)); }
>
> class Panel extends View { public
> Panel(Context context) {
> super(context); }
>
> @Override public void onDraw(Canvas
> canvas) { Bitmap _scratch =
> BitmapFactory.decodeResource(getResources(),
> R.drawable.icon);
> canvas.drawColor(Color.BLACK); int
> n=1;  while (n==1){ try {
> Thread.sleep(30);  } catch
> (InterruptedException e) { }
> canvas.drawBitmap(_scratch, x, y,
> null);  x+=2; y+=2;
>
> canvas.drawBitmap(_scratch, x, y,
> null);  } } } }

Body:
Your onDraw() method never returns. It needs to. Does your app Force Close after a few seconds? You're going to have to post a message to the UI thread to redraw after 30 milliseconds instead of looping within onDraw(). Off the top of my head, try this instead:

class Panel extends View {
  public Panel(Context context) {
    super(context);
  }

  int x = 0;
  int y = 0;
  Bitmap _scratch = BitmapFactory.decodeResource(getResources(), R.drawable.icon);

  @Override public void onDraw(Canvas canvas) {
    canvas.drawColor(Color.BLACK);
    canvas.drawBitmap(_scratch, x, y, null);
    x+=2; y+=2;
    this.postInvalidateDelayed(30);
  }
}

Of course you need to add some code to stop looping once the icon has gone off the edge.


问:
spring mvc crud example without database
Is it possible to create a CRUD system without database in spring mvc framework?
If possible then which way?
I made an application where i can save and update a single value but i need to save and update a list of value.</p>

答:
HSQLDB offers in memory DB, you can use it to do crud operations for your unit tests. You can maintain spring configuration for the Unit tests and another spring configuration for deployed code. The db configuration can be different for both, so, you run the data updates on the in-memory databse when running tests and actual database when deployed to server. Spring takes care of this seamlessly.

http://hsqldb.org/ spring boot has this inbuild

Other ways to test out your code is to using mockito where you test your code on mock data/objects.

Update: there is something called DBUnit, just found out, it can also help you test against fake db

ContentLicense: CC BY-SA 3.0


问:
Linker "Duplicate Symbol" error due to circular reference
I have two header of a class and it's extension(generated by Xcode for NSManaged object). But I'm getting a linker error and I figured out it was due to a circular reference.

Conversation+CoreDataClass.h

```<code>NS_ASSUME_NONNULL_BEGIN

@interface Conversation : NSManagedObject

@end

NS_ASSUME_NONNULL_END

#import "Conversation+CoreDataProperties.h"
</code>```

Conversation+CoreDataProperties.h

```<code>#import "Conversation+CoreDataClass.h"

NS_ASSUME_NONNULL_BEGIN

@interface Conversation (CoreDataProperties)

+ (NSFetchRequest<Conversation *> *)fetchRequest;

@end

NS_ASSUME_NONNULL_END
</code>```

You can clearly see the circular reference here. I found this question where the problem was to add a @class declaration and remove the header. So I commented out the import statement in the Conversation+CoreDataProperties.h and added @class Conversation;. Now two errors pop up saying it's an undefined class. Have attached the screenshot of the error below. I don't quite understand why this is happening and what I need to do to fix it. Any help is much appreciated. Thanks!

Linker error

duplicate symbol _OBJC_CLASS_$_Conversation in:
      /Users/xxx/Library/Developer/Xcode/DerivedData/xxx-gbhivuwptwzhkldfbmjghkokozgn/Build/Intermediates/xxx.build/Debug-iphoneos/xxx.build/Objects-normal/arm64/Conversation+CoreDataClass.o
  duplicate symbol _OBJC_METACLASS_$_Conversation in:
      /Users/xxx/Library/Developer/Xcode/DerivedData/xxx-gbhivuwptwzhkldfbmjghkokozgn/Build/Intermediates/xxx.build/Debug-iphoneos/xxx.build/Objects-normal/arm64/Conversation+CoreDataClass.o
  duplicate symbol _OBJC_CLASS_$_ConversationDate in:
      /Users/xxx/Library/Developer/Xcode/DerivedData/xxx-gbhivuwptwzhkldfbmjghkokozgn/Build/Intermediates/xxx.build/Debug-iphoneos/xxx.build/Objects-normal/arm64/ConversationDate+CoreDataClass.o
  duplicate symbol _OBJC_METACLASS_$_ConversationDate in:
      /Users/xxx/Library/Developer/Xcode/DerivedData/xxx-gbhivuwptwzhkldfbmjghkokozgn/Build/Intermediates/xxx.build/Debug-iphoneos/xxx.build/Objects-normal/arm64/ConversationDate+CoreDataClass.o
  ld: 4 duplicate symbols for architecture arm64 clang: error: linker
  command failed with exit code 1 (use -v to see invocation)

答:
So I commented out the import statement in the Conversation+CoreDataProperties.h and added @class Conversation;.

You may only do this if you're aren't using any of the Convention class's interface (for instance declaring a property of type Convention. You can't do this if you're extending Convention via a category or class extension.

You have a legit circular reference here you must resolve.  You can either:

Move the class and the category into the same source file (if there's no special reason this needs to be in a category you could just move the declaration of fetchRequest into the class itself).

Stop importing +CoreDataProperties.h in the class header, and import it instead wherever callers need to be calling fetchRequest.

ContentLicense: CC BY-SA 4.0

Body:
I have two header of a class and it's extension(generated by Xcode for NSManaged object). But I'm getting a linker error and I figured out it was due to a circular reference.

Conversation+CoreDataClass.h

NS_ASSUME_NONNULL_BEGIN

@interface Conversation : NSManagedObject

@end

NS_ASSUME_NONNULL_END

#import "Conversation+CoreDataProperties.h"

Conversation+CoreDataProperties.h

#import "Conversation+CoreDataClass.h"

NS_ASSUME_NONNULL_BEGIN

@interface Conversation (CoreDataProperties)

+ (NSFetchRequest<Conversation *> *)fetchRequest;

@end

NS_ASSUME_NONNULL_END

You can clearly see the circular reference here. I found this question where the problem was to add a @class declaration and remove the header. So I commented out the import statement in the Conversation+CoreDataProperties.h and added @class Conversation;. Now two errors pop up saying it's an undefined class. Have attached the screenshot of the error below. I don't quite understand why this is happening and what I need to do to fix it. Any help is much appreciated. Thanks!

Linker error

duplicate symbol _OBJC_CLASS_$_Conversation in:
      /Users/xxx/Library/Developer/Xcode/DerivedData/xxx-gbhivuwptwzhkldfbmjghkokozgn/Build/Intermediates/xxx.build/Debug-iphoneos/xxx.build/Objects-normal/arm64/Conversation+CoreDataClass.o
  duplicate symbol _OBJC_METACLASS_$_Conversation in:
      /Users/xxx/Library/Developer/Xcode/DerivedData/xxx-gbhivuwptwzhkldfbmjghkokozgn/Build/Intermediates/xxx.build/Debug-iphoneos/xxx.build/Objects-normal/arm64/Conversation+CoreDataClass.o
  duplicate symbol _OBJC_CLASS_$_ConversationDate in:
      /Users/xxx/Library/Developer/Xcode/DerivedData/xxx-gbhivuwptwzhkldfbmjghkokozgn/Build/Intermediates/xxx.build/Debug-iphoneos/xxx.build/Objects-normal/arm64/ConversationDate+CoreDataClass.o
  duplicate symbol _OBJC_METACLASS_$_ConversationDate in:
      /Users/xxx/Library/Developer/Xcode/DerivedData/xxx-gbhivuwptwzhkldfbmjghkokozgn/Build/Intermediates/xxx.build/Debug-iphoneos/xxx.build/Objects-normal/arm64/ConversationDate+CoreDataClass.o
  ld: 4 duplicate symbols for architecture arm64 clang: error: linker
  command failed with exit code 1 (use -v to see invocation)


问:
Difference between "//" and "/" in XPath?
I was trying my hands on XPath for python-selenium.

I used this link for trying some XPaths' from tutorials:

So I tried these two variants of XPaths'.

This expression

```<code>//webengagedata//preceding-sibling::*
</code>```

returned 14 results

And this expression

```<code>//webengagedata/preceding-sibling::*
</code>```

returned 9 results

What does the "//" do to match 5 more results?

答:
For your example

```<code>//webengagedata/preceding-sibling::* ---> returned 9 results
</code>```

Because there are only 9 tags which are exact sibling of webengagedatatags thats why it is showing 9 records

```<code>//webengagedata//preceding-sibling::* ---> returned 14 results
</code>```

Here it is considering child tags as well as biziclop said x/descendant-or-self::node()/y

Body:
I was trying my hands on XPath for python-selenium.

I used this link for trying some XPaths' from tutorials:

So I tried these two variants of XPaths'.

This expression

//webengagedata//preceding-sibling::*

returned 14 results

And this expression

//webengagedata/preceding-sibling::*

returned 9 results

What does the "//" do to match 5 more results?

Body:
For your example

//webengagedata/preceding-sibling::* ---> returned 9 results

Because there are only 9 tags which are exact sibling of webengagedatatags thats why it is showing 9 records

//webengagedata//preceding-sibling::* ---> returned 14 results

Here it is considering child tags as well as biziclop said x/descendant-or-self::node()/y


问:
Error 1064 - using the IN statement
List customer names who ordered Apple Laptop (Choose your own join type). I have gour tables customer, orderline, ordertable, and product. I keep getting this error

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use
  near ''product' where product_name = 'Apple Laptop'))) LIMIT 0, 25' at
  line 4

```<code>select customer.cust_name
from customer
where customer.cust_id in (
        select cust_id
        from ordertable
        where order_id in (
                select order_id
                from orderline
                where product in (
                        select product_id
                        from 'product'
                        where product_name = 'Apple Laptop'
                        )
                )
        )
</code>```

答: Remove the quotes from 'product' in the last select statement. It's the name of a table, so it does not need to be quoted. </p>

Title: Error 1064 - using the IN statement

Body:
List customer names who ordered Apple Laptop (Choose your own join type). I have gour tables customer, orderline, ordertable, and product. I keep getting this error

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use
  near ''product' where product_name = 'Apple Laptop'))) LIMIT 0, 25' at
  line 4

select customer.cust_name
from customer
where customer.cust_id in (
        select cust_id
        from ordertable
        where order_id in (
                select order_id
                from orderline
                where product in (
                        select product_id
                        from 'product'
                        where product_name = 'Apple Laptop'
                        )
                )
        )


问:
ReSharper Refactor > Move doesn't work
I have a function I want to move to a different object.  In the code, I select the function that I want to move.  I use ReSharper > Refactor > Move but nothing happens.

答: I was having this problem too, while trying to move a file via the ReSharper Refactor menu. Checking the box "To enable Undo, open all files with changes for editing" in the Move dialog fixed the issue.</p>

Title: ReSharper Refactor > Move doesn't work


问:
Performing Google Search In Spreadsheet And Scraping The SERP Data
I hope that you guys are fine. I want to build a simple spreadsheet and I thought I could be able to make one but blank sheet looks horrible to me. I am sure that you guys are kind enough to help me out.

I want to perform multiple Google search queries in Google spreadsheet and want to parse results of each search (top 10 results of each search)

Something like this: https://www.youtube.com/watch?v=tBwEbuMRFlI

But when I tried his given formula in description to play test, Google returned #Error to me, I don't know why.

Can you guys please help me out in making a simple spreadsheet compatible for multiple queries at once? Like one column for keywords (where I could paste my list of keywords) and then 10 columns of search results. All results for one keyword should come in one row

Something like this:

My 1st Example Query = 1st search result, 2nd search result, 3rd result and so on.
My 2nd Example Query = 1st search result, 2nd search result, 3rd result and so on.

It must be easy to code but yeah, it might be time-consuming and I would be very grateful if anyone of you could help me about it.

Looking forward to your help guys.

答:
The problem is that you want to scrape out of Spreadsheets, that's a bad approach and is almost certainly not going to work. Even if you manage to write a scraper inside that limited environment it will easily be spotted by Google.

As you said time is not a problem, I would suggest another route.

Use a backend tool/script that scrapes the data

Use a backend tool/script that creates/modifies the Google spreadsheet

You can run such a script(s) manually on your PC or from a server full automated using a scheduler/cron job.

To create/modify spreadsheets look here: How do I access the Google Spreadsheets API in PHP?

To scrape Google look here: Is it ok to scrape data from Google results?

So this is PHP as language of choice but you can do the exactly same in Java or Python or C#


问:
dplyr mutate returning NA wheras sapply isn't with strsplit
I am working with the kaggle titanic dataset where the column Cabin is class character. I used the function shown below to get the first element of each Cabin.

```<code>sapply(df$Cabin,function(x) strsplit(x,NULL)[[1]][1])

Cabin    deck
 NA      NA
 C85     C
 NA      NA
 C123    C
 NA      NA
 E46     E
</code>```

However when I use dplyr's mutate to achieve the same task I just get a column of NAs for deck. These are the functions I tried with mutate and both returned just NAs.

```<code>df %>% mutate(deck = ifelse(is.na(Cabin),Cabin, strsplit(Cabin,NULL)[[1]][1]))
</code>```

and

```<code>df %>% mutate(deck = strsplit(Cabin,NULL)[[1]][1])
</code>```

Is there something wrong with mutate or am I just doing something wrong?

答:
I believe the answer has to do with what object strsplit is acting on when you call it the two different ways.

From strsplit's documentation, it returns

A list of the same length as x, the i-th element of which contains the
  vector of splits of x[i].

When you call sapply(df$Cabin,function(x) strsplit(x,NULL)[[1]][1]), strsplit acts separately on each element of the vector df$Cabin, so it's as if you're calling:

```<code>strsplit(df$Cabin[1], NULL)[[1]][1]
# [1] NA
strsplit(df$Cabin[2], NULL)[[1]][1]
# [1] C
...
</code>```

In contrast, mutate is calling strsplit on the entire vector, so it's as if you're calling strsplit(df$Cabin, NULL)

```<code>strsplit(df$Cabin, NULL)
# [[1]]
# [1] NA
#
# [[2]]
# [1] "C" "8" "5"
#
# [[3]]
# [1] NA
#
# [[4]]
# [1] "C" "1" "2" "3"
#
# [[5]]
# [1] NA
#
# [[6]]
# [1] "E" "4" "6"
</code>```

As we can see from the output, strsplit(df$Cabin, NULL)[[1]][1] is NA, so that gets populated everywhere.

To get the desired output, you could use substring since the info you want is always in the same position.

```<code>df %>%
  mutate(deck = substring(Cabin, 1, 1))
 # Cabin deck
 #  <NA> <NA>
 #   C85    C
 #  <NA> <NA>
 #  C123    C
 #  <NA> <NA>
 #   E46    E
</code>```

Body:
I am working with the kaggle titanic dataset where the column Cabin is class character. I used the function shown below to get the first element of each Cabin.

sapply(df$Cabin,function(x) strsplit(x,NULL)[[1]][1])

Cabin    deck
 NA      NA
 C85     C
 NA      NA
 C123    C
 NA      NA
 E46     E

However when I use dplyr's mutate to achieve the same task I just get a column of NAs for deck. These are the functions I tried with mutate and both returned just NAs.

df %>% mutate(deck = ifelse(is.na(Cabin),Cabin, strsplit(Cabin,NULL)[[1]][1]))

and

df %>% mutate(deck = strsplit(Cabin,NULL)[[1]][1])

Is there something wrong with mutate or am I just doing something wrong?

Body:
I believe the answer has to do with what object strsplit is acting on when you call it the two different ways.

From strsplit's documentation, it returns

A list of the same length as x, the i-th element of which contains the
  vector of splits of x[i].

When you call sapply(df$Cabin,function(x) strsplit(x,NULL)[[1]][1]), strsplit acts separately on each element of the vector df$Cabin, so it's as if you're calling:

strsplit(df$Cabin[1], NULL)[[1]][1]
# [1] NA
strsplit(df$Cabin[2], NULL)[[1]][1]
# [1] C
...

In contrast, mutate is calling strsplit on the entire vector, so it's as if you're calling strsplit(df$Cabin, NULL)

strsplit(df$Cabin, NULL)
# [[1]]
# [1] NA
#
# [[2]]
# [1] "C" "8" "5"
#
# [[3]]
# [1] NA
#
# [[4]]
# [1] "C" "1" "2" "3"
#
# [[5]]
# [1] NA
#
# [[6]]
# [1] "E" "4" "6"

As we can see from the output, strsplit(df$Cabin, NULL)[[1]][1] is NA, so that gets populated everywhere.

To get the desired output, you could use substring since the info you want is always in the same position.

df %>%
  mutate(deck = substring(Cabin, 1, 1))
 # Cabin deck
 #  <NA> <NA>
 #   C85    C
 #  <NA> <NA>
 #  C123    C
 #  <NA> <NA>
 #   E46    E


问:
TypeError: Error #1009: Cannot access a property or method of a null object reference. For My PAP
This is for my game of obstacles that I am creating and what is giving error is at the time of the player colliding with the end that appears the following error:

TypeError: Error #1009: Cannot access a property or method of a null
  object reference.     at
  obstaculo_fla::MainTimeline/handleCollision()[obstaculo_fla.MainTimeline::frame9:55]

TypeError: Error #1009: Cannot access a property or method of a null
  object reference.     at
  obstaculo_fla::MainTimeline/handleCollision_final()[obstaculo_fla.MainTimeline::frame367:18]

This is the code:

```<code>player.addEventListener( Event.ENTER_FRAME, handleCollision_final)

function handleCollision_final( e:Event ):void
{
if(player.hitTestObject(nextum))
   {
       gotoAndPlay(368);
   }
   else
   {
       trace("MISS");
   }
}

player.addEventListener( Event.ENTER_FRAME, handleCollision)

function handleCollision( e:Event ):void
{
if(player.hitTestObject(wall))
   {
       player.y-=20;
       gotoAndPlay(6);
   }
   else
   {
       trace("MISS");
   }
}
</code>```

Thank You

答:
I tried modifying your code with a Drag event (in a single scene), everything seem to be working OK. I've run in to a similar problem in the past, and found that I had to get rid of the event listeners. I've also found that I need a separate function to do that. Give this a shot:

```<code>player.addEventListener(Event.ENTER_FRAME, handleCollision_final)

function handleCollision_final(e: Event): void {
    if (player.hitTestObject(nextum)) {
        removeELs(); //<<<<<<<<<<<<<<<<<<<<<<<<< ELs (EventListeners)
        gotoAndPlay(368);
    } else {
        trace("nextum: MISS");
    }
}

player.addEventListener(Event.ENTER_FRAME, handleCollision)

function handleCollision(e: Event): void {
    if (player.hitTestObject(wall)) {
        player.y -= 20;
        removeELs(); //<<<<<<<<<<<<<<<<<<<<<<<<< ELs (EventListeners)
        gotoAndPlay(6);
    } else {
        trace("wall: MISS");
    }
}

// This probably won't work if you try 'removeEventListener'
// from within the collision functions.
function removeELs() {
    player.removeEventListener(Event.ENTER_FRAME, handleCollision)
    player.removeEventListener(Event.ENTER_FRAME, handleCollision_final)
}
</code>```

As you can see, I added the 'removeELs()' function at the bottom of your code.

Good luck

Body:
This is for my game of obstacles that I am creating and what is giving error is at the time of the player colliding with the end that appears the following error:

TypeError: Error #1009: Cannot access a property or method of a null
  object reference.     at
  obstaculo_fla::MainTimeline/handleCollision()[obstaculo_fla.MainTimeline::frame9:55]

TypeError: Error #1009: Cannot access a property or method of a null
  object reference.     at
  obstaculo_fla::MainTimeline/handleCollision_final()[obstaculo_fla.MainTimeline::frame367:18]

This is the code:

player.addEventListener( Event.ENTER_FRAME, handleCollision_final)

function handleCollision_final( e:Event ):void
{
if(player.hitTestObject(nextum))
   {
       gotoAndPlay(368);
   }
   else
   {
       trace("MISS");
   }
}

player.addEventListener( Event.ENTER_FRAME, handleCollision)

function handleCollision( e:Event ):void
{
if(player.hitTestObject(wall))
   {
       player.y-=20;
       gotoAndPlay(6);
   }
   else
   {
       trace("MISS");
   }
}

Thank You

Body:
I tried modifying your code with a Drag event (in a single scene), everything seem to be working OK. I've run in to a similar problem in the past, and found that I had to get rid of the event listeners. I've also found that I need a separate function to do that. Give this a shot:

player.addEventListener(Event.ENTER_FRAME, handleCollision_final)

function handleCollision_final(e: Event): void {
    if (player.hitTestObject(nextum)) {
        removeELs(); //<<<<<<<<<<<<<<<<<<<<<<<<< ELs (EventListeners)
        gotoAndPlay(368);
    } else {
        trace("nextum: MISS");
    }
}

player.addEventListener(Event.ENTER_FRAME, handleCollision)

function handleCollision(e: Event): void {
    if (player.hitTestObject(wall)) {
        player.y -= 20;
        removeELs(); //<<<<<<<<<<<<<<<<<<<<<<<<< ELs (EventListeners)
        gotoAndPlay(6);
    } else {
        trace("wall: MISS");
    }
}

// This probably won't work if you try 'removeEventListener'
// from within the collision functions.
function removeELs() {
    player.removeEventListener(Event.ENTER_FRAME, handleCollision)
    player.removeEventListener(Event.ENTER_FRAME, handleCollision_final)
}

As you can see, I added the 'removeELs()' function at the bottom of your code.

Good luck


问:
How to take data from URL
I am developing API for my company. Normally, we use POST & GET method to send form data to other website or another page. But what I want, If we want to send data in URL like
      http://www.example.com/data1/data2/data3

like that.
In that case, Data1, Data2, Data3 is our data and I want this data in PHP.
I am searching on that but I can't find what I want.

答:
What you are looking for is called URL Rewriting which is supported by all major Web Servers like Apache and NGINX.

To read more about URL rewriting in apache go thorugh:
https://code.tutsplus.com/tutorials/using-htaccess-files-for-pretty-urls--net-6049

To read more about neat urls in NGINX go through https://serverfault.com/questions/653177/clean-url-with-several-params-in-nginx

In apache servers clean URLS can be achieved by enabling a module called mod_rewrite and a simple way to do it is using the .htaccess file.

In nginx you can use web.config file.

After having clean URL's you can use any method from GET,PUT, POST, PATCH, DELETE etc. but remember if the user enters your URL in your browser then it is always a GET request by default.

Title: How to take data from URL


问:
reduceByKey not working as expected when keys are of type bitarray
Following is the code that I am trying out in pyspark shell.

```<code>from bitarray import bitarray
a = bitarray('0') * 5
b = bitarray('1') * 5
c = [a.copy() for x in range(3)]
d = [b.copy() for x in range(5)]
e = c + d
rdd = sc.parallelize(e).map(lambda x : (x, 1)).reduceByKey(lambda x, y : x + y).collect()
print(rdd)
</code>```

Expected:

```<code>[(bitarray('11111'), 5), (bitarray('00000'), 3)
</code>```

Actual output:

```<code>[(bitarray('11111'), 1), (bitarray('00000'), 1), (bitarray('11111'), 1), (bitarray('11111'), 1), (bitarray('00000'), 1), (bitarray('11111'), 1), (bitarray('00000'), 1), (bitarray('11111'), 1)]
</code>```

Why isn't spark engine able to differentiate between the different bitarray values?

答:
One way of circumventing the issue would convert all the bitarray into bytes using the tobytes. Also, cause of the problem is discussed in the link provided by @mtoto which is bitarray does not maintain the hash invariant.

```<code>from bitarray import bitarray

def back2Bit(U):
        res = bitarray()
        res.frombytes(U)
        return res

a = bitarray('0') * 5
b = bitarray('1') * 5
c = [a.copy() for x in range(3)]
d = [b.copy() for x in range(5)]
e = c + d
rdd = sc.parallelize([x.tobytes() for x in e]).map(lambda x : (x, 1)).reduceByKey(lambda x, y : x + y).collect()
rdd = [(back2Bit(x[0]), x[1]) for x in rdd]
</code>```

Body:
Following is the code that I am trying out in pyspark shell.

from bitarray import bitarray
a = bitarray('0') * 5
b = bitarray('1') * 5
c = [a.copy() for x in range(3)]
d = [b.copy() for x in range(5)]
e = c + d
rdd = sc.parallelize(e).map(lambda x : (x, 1)).reduceByKey(lambda x, y : x + y).collect()
print(rdd)

Expected:

[(bitarray('11111'), 5), (bitarray('00000'), 3)

Actual output:

[(bitarray('11111'), 1), (bitarray('00000'), 1), (bitarray('11111'), 1), (bitarray('11111'), 1), (bitarray('00000'), 1), (bitarray('11111'), 1), (bitarray('00000'), 1), (bitarray('11111'), 1)]

Why isn't spark engine able to differentiate between the different bitarray values?

Body:
One way of circumventing the issue would convert all the bitarray into bytes using the tobytes. Also, cause of the problem is discussed in the link provided by @mtoto which is bitarray does not maintain the hash invariant.

from bitarray import bitarray

def back2Bit(U):
        res = bitarray()
        res.frombytes(U)
        return res

a = bitarray('0') * 5
b = bitarray('1') * 5
c = [a.copy() for x in range(3)]
d = [b.copy() for x in range(5)]
e = c + d
rdd = sc.parallelize([x.tobytes() for x in e]).map(lambda x : (x, 1)).reduceByKey(lambda x, y : x + y).collect()
rdd = [(back2Bit(x[0]), x[1]) for x in rdd]


问:
SQL Server database - get last record
How do I we get last row in SQL Server if we don't have primary id and numeric column? For example we only have a name and a few other columns in the table</p>

答:
With no definition of 'last row'... :</p>

```<code>select top 1 *
from t
order by Name desc
</code>```

Title: SQL Server database - get last record

Body:
With no definition of 'last row'... :

select top 1 *
from t
order by Name desc


问:
How can I retrieve the content of a specific stashed file after have pull the new version of my project form GIT?
I am not so into GIT and I have the following problem.

I have some uncommitted file in my project that I have stashed by this statment:

```<code>git stash
</code>```

Then I have pull the repository taking the work of a coolegue, that seems have correctly overwrite the changes of my stashed file.

Now I want to retrieve the content of a specific stashed file without lose the modification of my collegue.

I don't want to override the pulled version but only access to the code of the stashed version of a specific file.

Performing git stash list I obtain:

```<code>$ git stash list
stash@{0}: WIP on master: fd2a59b First version of iterate/aggregate for data received from dataservice
stash@{1}: WIP on master: 4910263 DSS project added
</code>```

How can I do it from the shell?

答:
There are several parts to this answer, because using git stash can be surprisingly difficult.  The way you used it in this case is correct for your use-case but there are many traps here for the unwary and the new-to / not-so-into Git folks.

Stash makes several commits

The main thing to know, from which everything else flows, is this: git stash makes commits.  In fact, it makes at least two commits; if you tell it to (with -u or -a) it makes a third commit.  All of these commits are on no branch, but they are still commits, and hence behave like commits.  The format of these commits is that they look, to other Git commands, like a bizarre kind of merge commit, which means in general that you want to keep other Git commands from looking too closely at them, and mostly use git stash to deal with them.

The index and work-tree, and git checkout

What git stash commits are the index and the work-tree.  The work-tree is the easiest to explain, by far: Git stores files in an internal, Git-only format, so to work with the files, you need a place where they are stored in the normal computer format.  That's the work-tree.  You can put, in this work-tree, files that are not going to be stored in Git as well, and this is where the index first comes in.

Git's index has several uses, but this is the main one: it is "where you build the next commit".  That is, you start out, in any Git repository, with a current commit that you ran git checkout to get.  (On the first git clone, Git runs git checkout master for you.  Well, it's usually master anyway, but it's definitely something checked out.)  This picks a branch name, uses it to find the tip commit of the branch, and makes that branch and that commit your current branch and commit.  Then it fills the index—which was completely empty, the very first time—from that particular commit, so now the index has in it all the files that are in the current (or HEAD) commit.  When adding these files to the index, Git also copies them into the work-tree, and so now you have the HEAD commit equal to the index which is equal to the work-tree.

If you now git checkout some other branch/commit, Git changes HEAD to account for the new branch and tip commit, removes the old files (for the previous HEAD) from the index and work-tree, adds the new files to the index and work-tree, and once again you have the HEAD commit equal to the index which is equal to the work-tree.

Note that in all of this shuffling-about, any file that is in the work-tree that is not in the index, goes untouched.  These are your untracked files, and that's what it means for a file to be untracked: A file is tracked if and only if it is in the index.  (This only has a little to do with git stash itself, but it's crucial to using Git and .gitignore, because .gitignore has no effect on a tracked file.)

To make a new commit yourself, you first modify a file in the work-tree, then use git add to copy the new version into the index.  This makes the new file ready to be committed, with the data it has right at the time you run git add.  This leaves all the existing index files the way they are, so the new commit will still have all the other files unchanged.  To add a file that isn't already in the index, you create it in the work-tree and again run git add.  The copies the file into the index, just as before, but this time it's not overwriting an existing copy.  To delete a file, you run git rm, which removes it from both the index and the work-tree.

This process of adding (overwriting existing or adding new) files to the index, and removing files from both index-and-work-tree, is what we mean when we say staging files for commit.  This is why the index is also called "the staging area": it's where we copy the updated work-tree files into, to get them staged.  Note that unless you git rm everything, the index itself is never actually empty: it's just that once you git commit the index, the index and the new commit you made, now match.  (This makes the --allow-empty flag to git commit a bit misleading.)

Back to git stash, specifically the "save new stash" sub-command

Again, git stash save makes (at least) two commits: first, it commits the index itself—which is really easy since that's how Git always makes commits—and then it makes a second commit that consists, in effect, of git adding all the tracked work-tree files, i.e., copying them into the index, and then committing again.  For internal reasons, though, it makes this second commit as a merge commit, merging HEAD and the index commit it just made.  We don't have to care as long as we use git stash to deal with this weird merge.  It's only if and when we step outside git stash that we suddenly have to care about it.

After git stash makes those commits, it mostly does the equivalent of git reset --hard HEAD, although here again there are flag options to change this.  (For much—perhaps too much—more about this process, see How to recover from "git stash save --all"?)  What git reset --hard HEAD does is to re-set (hence git reset) three things:

It moves (i.e., re-sets) the current branch from its current commit to the specified new commit.  Because the specified new commit is HEAD, which is the current commit, this is like trying to drive from your kitchen to your kitchen: you may scurry around for a while, but you just end up exactly where you started.

It re-sets the index.  That is, it makes the index match the HEAD commit.  This un-stages all your staged changes, un-removing git rm-ed files, un-adding any totally-new-files, and recovering from the HEAD commit any files you modified and then staged.

It re-sets the work-tree.  That is, it makes all tracked files in the work-tree match their versions in the HEAD commit and (now) the index.

As a kind of mental short cut, though, you can think of this as "ream out the index and work-tree".  The stash code just saved them both, as commits, so it's now safe to clean them out.  Now the index and work-tree both look like they would if you had just freshly run git checkout on the current commit.  This is why you are now ready to use git merge or git rebase (whether or not you run it from git pull—remember, git pull is just git fetch followed by merge or rebase, in all of these cases).

Applying the stash

The process of applying (or "popping") a stash can be more complicated than the process of saving it, but in practice, it tends to be simple.  Well, except when it goes wrong, anyway.  You just get to a (usually clean) commit-and-index-and-work-tree state as before, and run:

```<code>git stash apply
</code>```

What this does is run a couple of git diff commands, to find out:

What's the difference between the saved index, and the commit that was current when git stash save saved that index?

What's the difference between the saved work-tree, and the commit that was current when git stash save saved that work-tree?

Usually, for each file, there's at most one difference (either via the saved index, or via the saved work-tree): you either staged the file, so the difference shows up in the saved index, or you didn't, so any changes you made show up in the saved work-tree (if there are no changes there's no difference at all).  Git then kind of smashes these all together, for each file, and puts all the changes into your current work-tree.  Your current index goes un-affected, by default, although there are fancier ways to git stash apply.

Once you are satisfied that the stash has applied correctly, you can run git stash drop.  This discards the two saved commits (and if git stash save "pushed" an earlier stash into stash@{1}, effectively "pops" the rest back down so that the earlier stash is now stash@{0}, or just stash).

If you're sure you want to toss the stash after applying it, without first checking for correctness, you can use git stash pop.  This literally just turns into git stash apply && git stash drop internally.  (Of course, it passes the specific stash through, if you're using git stash pop stash@{n}.)

Some hard cases, like XML files

The process of applying each change—each git diff from commit-that-was-HEAD-at-the-time, to saved index or saved work-tree—uses Git's full merge powers.  This is a simple(ish) mechanical process, but it works surprisingly well for most files.  XML files, unfortunately, tend to defeat Git's not-exactly-super powers.

In this case, you may want to do exactly what you did here.

Because git stash save simply makes two commits (that are not on a branch), you can use all the usual Git tools to deal with these two commits.  But once you do so, you must be careful, because the work-tree commit looks like a merge commit.  (Well, in fact, it is a merge commit.)  Fortunately, git show <commit>:<path> doesn't care if the commit is a merge: it just extracts the saved version of the file.

Each stash name or reflog name points to the saved work-tree commit.  Hence:

```<code>git show stash:path/to/file.xml
</code>```

prints the saved work-tree contents of that file.  Redirecting that to a new file in your work-tree gives you a chance to examine the saved contents.  So this is a fine thing to do.

Watch out, though, for git show stash.  For those of us with dyslexia,1 it's really easy to use this instead of git stash show.  But git show <commit> does care if the <commit> is a merge commit.  While git stash show knows to treat the work-tree commit as a separate, non-merge-y commit, git show—which sees stash as a commit ID, which then works but gets you the work-tree commit—tries to treat it as a merge commit.  It tries to show a combined diff, which often just ends up showing nothing at all.  (The most confusing case occurs when it does show something, but not all of what you stashed, which happens when you first staged a file, then modified it again in the work-tree.)

TL;DR summary (if it's not too late): git show stash:path/to/file is OK, but git show stash is always a mistake.  Mostly you want git stash apply, but for odd cases, git show stash:path/to/file will get you the saved work-tree version.  And, for really complicated cases, see my other longer answer and consider using git stash branch.

1Dyslexics of the world untie!

Body:
I am not so into GIT and I have the following problem.

I have some uncommitted file in my project that I have stashed by this statment:

git stash

Then I have pull the repository taking the work of a coolegue, that seems have correctly overwrite the changes of my stashed file.

Now I want to retrieve the content of a specific stashed file without lose the modification of my collegue.

I don't want to override the pulled version but only access to the code of the stashed version of a specific file.

Performing git stash list I obtain:

$ git stash list
stash@{0}: WIP on master: fd2a59b First version of iterate/aggregate for data received from dataservice
stash@{1}: WIP on master: 4910263 DSS project added

How can I do it from the shell?

Body:
There are several parts to this answer, because using git stash can be surprisingly difficult.  The way you used it in this case is correct for your use-case but there are many traps here for the unwary and the new-to / not-so-into Git folks.

Stash makes several commits

The main thing to know, from which everything else flows, is this: git stash makes commits.  In fact, it makes at least two commits; if you tell it to (with -u or -a) it makes a third commit.  All of these commits are on no branch, but they are still commits, and hence behave like commits.  The format of these commits is that they look, to other Git commands, like a bizarre kind of merge commit, which means in general that you want to keep other Git commands from looking too closely at them, and mostly use git stash to deal with them.

The index and work-tree, and git checkout

What git stash commits are the index and the work-tree.  The work-tree is the easiest to explain, by far: Git stores files in an internal, Git-only format, so to work with the files, you need a place where they are stored in the normal computer format.  That's the work-tree.  You can put, in this work-tree, files that are not going to be stored in Git as well, and this is where the index first comes in.

Git's index has several uses, but this is the main one: it is "where you build the next commit".  That is, you start out, in any Git repository, with a current commit that you ran git checkout to get.  (On the first git clone, Git runs git checkout master for you.  Well, it's usually master anyway, but it's definitely something checked out.)  This picks a branch name, uses it to find the tip commit of the branch, and makes that branch and that commit your current branch and commit.  Then it fills the index—which was completely empty, the very first time—from that particular commit, so now the index has in it all the files that are in the current (or HEAD) commit.  When adding these files to the index, Git also copies them into the work-tree, and so now you have the HEAD commit equal to the index which is equal to the work-tree.

If you now git checkout some other branch/commit, Git changes HEAD to account for the new branch and tip commit, removes the old files (for the previous HEAD) from the index and work-tree, adds the new files to the index and work-tree, and once again you have the HEAD commit equal to the index which is equal to the work-tree.

Note that in all of this shuffling-about, any file that is in the work-tree that is not in the index, goes untouched.  These are your untracked files, and that's what it means for a file to be untracked: A file is tracked if and only if it is in the index.  (This only has a little to do with git stash itself, but it's crucial to using Git and .gitignore, because .gitignore has no effect on a tracked file.)

To make a new commit yourself, you first modify a file in the work-tree, then use git add to copy the new version into the index.  This makes the new file ready to be committed, with the data it has right at the time you run git add.  This leaves all the existing index files the way they are, so the new commit will still have all the other files unchanged.  To add a file that isn't already in the index, you create it in the work-tree and again run git add.  The copies the file into the index, just as before, but this time it's not overwriting an existing copy.  To delete a file, you run git rm, which removes it from both the index and the work-tree.

This process of adding (overwriting existing or adding new) files to the index, and removing files from both index-and-work-tree, is what we mean when we say staging files for commit.  This is why the index is also called "the staging area": it's where we copy the updated work-tree files into, to get them staged.  Note that unless you git rm everything, the index itself is never actually empty: it's just that once you git commit the index, the index and the new commit you made, now match.  (This makes the --allow-empty flag to git commit a bit misleading.)

Back to git stash, specifically the "save new stash" sub-command

Again, git stash save makes (at least) two commits: first, it commits the index itself—which is really easy since that's how Git always makes commits—and then it makes a second commit that consists, in effect, of git adding all the tracked work-tree files, i.e., copying them into the index, and then committing again.  For internal reasons, though, it makes this second commit as a merge commit, merging HEAD and the index commit it just made.  We don't have to care as long as we use git stash to deal with this weird merge.  It's only if and when we step outside git stash that we suddenly have to care about it.

After git stash makes those commits, it mostly does the equivalent of git reset --hard HEAD, although here again there are flag options to change this.  (For much—perhaps too much—more about this process, see How to recover from "git stash save --all"?)  What git reset --hard HEAD does is to re-set (hence git reset) three things:

It moves (i.e., re-sets) the current branch from its current commit to the specified new commit.  Because the specified new commit is HEAD, which is the current commit, this is like trying to drive from your kitchen to your kitchen: you may scurry around for a while, but you just end up exactly where you started.

It re-sets the index.  That is, it makes the index match the HEAD commit.  This un-stages all your staged changes, un-removing git rm-ed files, un-adding any totally-new-files, and recovering from the HEAD commit any files you modified and then staged.

It re-sets the work-tree.  That is, it makes all tracked files in the work-tree match their versions in the HEAD commit and (now) the index.

As a kind of mental short cut, though, you can think of this as "ream out the index and work-tree".  The stash code just saved them both, as commits, so it's now safe to clean them out.  Now the index and work-tree both look like they would if you had just freshly run git checkout on the current commit.  This is why you are now ready to use git merge or git rebase (whether or not you run it from git pull—remember, git pull is just git fetch followed by merge or rebase, in all of these cases).

Applying the stash

The process of applying (or "popping") a stash can be more complicated than the process of saving it, but in practice, it tends to be simple.  Well, except when it goes wrong, anyway.  You just get to a (usually clean) commit-and-index-and-work-tree state as before, and run:

git stash apply

What this does is run a couple of git diff commands, to find out:

What's the difference between the saved index, and the commit that was current when git stash save saved that index?

What's the difference between the saved work-tree, and the commit that was current when git stash save saved that work-tree?

Usually, for each file, there's at most one difference (either via the saved index, or via the saved work-tree): you either staged the file, so the difference shows up in the saved index, or you didn't, so any changes you made show up in the saved work-tree (if there are no changes there's no difference at all).  Git then kind of smashes these all together, for each file, and puts all the changes into your current work-tree.  Your current index goes un-affected, by default, although there are fancier ways to git stash apply.

Once you are satisfied that the stash has applied correctly, you can run git stash drop.  This discards the two saved commits (and if git stash save "pushed" an earlier stash into stash@{1}, effectively "pops" the rest back down so that the earlier stash is now stash@{0}, or just stash).

If you're sure you want to toss the stash after applying it, without first checking for correctness, you can use git stash pop.  This literally just turns into git stash apply && git stash drop internally.  (Of course, it passes the specific stash through, if you're using git stash pop stash@{n}.)

Some hard cases, like XML files

The process of applying each change—each git diff from commit-that-was-HEAD-at-the-time, to saved index or saved work-tree—uses Git's full merge powers.  This is a simple(ish) mechanical process, but it works surprisingly well for most files.  XML files, unfortunately, tend to defeat Git's not-exactly-super powers.

In this case, you may want to do exactly what you did here.

Because git stash save simply makes two commits (that are not on a branch), you can use all the usual Git tools to deal with these two commits.  But once you do so, you must be careful, because the work-tree commit looks like a merge commit.  (Well, in fact, it is a merge commit.)  Fortunately, git show <commit>:<path> doesn't care if the commit is a merge: it just extracts the saved version of the file.

Each stash name or reflog name points to the saved work-tree commit.  Hence:

git show stash:path/to/file.xml

prints the saved work-tree contents of that file.  Redirecting that to a new file in your work-tree gives you a chance to examine the saved contents.  So this is a fine thing to do.

Watch out, though, for git show stash.  For those of us with dyslexia,1 it's really easy to use this instead of git stash show.  But git show <commit> does care if the <commit> is a merge commit.  While git stash show knows to treat the work-tree commit as a separate, non-merge-y commit, git show—which sees stash as a commit ID, which then works but gets you the work-tree commit—tries to treat it as a merge commit.  It tries to show a combined diff, which often just ends up showing nothing at all.  (The most confusing case occurs when it does show something, but not all of what you stashed, which happens when you first staged a file, then modified it again in the work-tree.)

TL;DR summary (if it's not too late): git show stash:path/to/file is OK, but git show stash is always a mistake.  Mostly you want git stash apply, but for odd cases, git show stash:path/to/file will get you the saved work-tree version.  And, for really complicated cases, see my other longer answer and consider using git stash branch.

1Dyslexics of the world untie!


问:
Returning ints versus void

Possible Duplicate:

  What is the proper declaration of main?

A little while ago I took a course on c++ algorithms. We used visual studio in the classroom and sometimes when writing the main function we would declare it void main() { as opposed to int main(){return 0;} . This worked fine although I knew it normally you should use int. Just recently I tried compiling the same code from the class in netbeans in linux. This time, it would not accept the main function to be declared void. Why is it that the g++ compiler requires the main function to be declared an int? Sorry if this is a silly question.

答:
I remember that every program has a return value, although I don't remember whether or not it just returns a certain number by default. In assembly, you can just say return, if I recall correctly, and not have to give a value.

Or it could just be that it's just not the standard for C++ compilers, like EboMike said.

Title: Returning ints versus void


问:
pip install error python3 linux
I'm using linux mint and can not install the pip from the downloaded script file due to zlib error.

1 ) Tried to reinstall zlib with following command and it is success.

$ sudo apt-get install --reinstall zlibc zlib1g zlib1g-dev

2) python3 is installed correctly.

$ which python3

```<code>/usr/local/bin/python3
</code>```

3) Whenever I try to run get-pip.py file following errors are displayed.

$ python3 get-pip.py

```<code>Traceback (most recent call last):
  File "get-pip.py", line 20061, in <module>
    main()
  File "get-pip.py", line 194, in main
    bootstrap(tmpdir=tmpdir)
  File "get-pip.py", line 82, in bootstrap
    import pip
zipimport.ZipImportError: can't decompress data; zlib not available
</code>```

How can I run the script? It has no problem when installing zlib using apt-get.

答:
Maybe you need to install zlib
apt-cache search zlib
apt-get install zlib</p>

Title: pip install error python3 linux

Body:
I'm using linux mint and can not install the pip from the downloaded script file due to zlib error.

1 ) Tried to reinstall zlib with following command and it is success.

$ sudo apt-get install --reinstall zlibc zlib1g zlib1g-dev

2) python3 is installed correctly.

$ which python3

/usr/local/bin/python3

3) Whenever I try to run get-pip.py file following errors are displayed.

$ python3 get-pip.py

Traceback (most recent call last):
  File "get-pip.py", line 20061, in <module>
    main()
  File "get-pip.py", line 194, in main
    bootstrap(tmpdir=tmpdir)
  File "get-pip.py", line 82, in bootstrap
    import pip
zipimport.ZipImportError: can't decompress data; zlib not available

How can I run the script? It has no problem when installing zlib using apt-get.


问:
Google Analytics Reporting API v4 missing required authentication credential
I'm new to using this API, and I am struggling with retrieving my data using Google Analytics Reporting API v4. I am only attempting to retrieve the analytics for a website so I can build a dashboard.  I am following the example here: Hello Analytics Reporting API v4; JavaScript quick start for web applications

I am able to make a request, however, I keep getting a 400 error that is might be this: 400: Invalid Credentials

```<code>`Invalid JSON payload received. Unknown name "express" at 'report_requests[0].metrics[0]': Cannot find field.
handleError @ Test.js:64
h.o0 @ cb=gapi.loaded_0:53
xs @ cb=gapi.loaded_0:56
Wq @ cb=gapi.loaded_0:56
_.C.uea @ cb=gapi.loaded_0:55
Ap @ cb=gapi.loaded_0:49`
</code>```

I have no idea what I am doing wrong, and I am hoping someone can point me in the right direction.

This is a react application. I am making the request after the component mounts.

```<code>import React, { Component } from 'react';
import GoogleLogin from 'react-google-login';
import $ from 'jquery';

const VIEW_ID = '17414592';
const CLIENT_ID = "936270024581-stgn130l17v21s6vjch9p751hiqbovac.apps.googleusercontent.com";
const DISC_DOCS = 'https://analyticsreporting.googleapis.com/$discovery/rest?version=v4';

export default class Test extends Component {
  constructor(props) {
    super(props)

    this.printResults = this.printResults.bind(this);
    this.handleRequest = this.handleRequest.bind(this);
    this.handleError = this.handleError.bind(this);
  }

  //when component mounts, create a google sign in button.
  componentDidMount() {
    //load gapi
    $.getScript("https://apis.google.com/js/client:platform.js")
    .done(() => {
      window.gapi.signin2.render('my-signin2', {
        'scope': 'profile email',
        'width': 240,
        'height': 50,
        'longtitle': true,
        'theme': 'dark',
        'onsuccess': this.handleRequest,
        'onfailure': this.handleError
      });
    })
  }

  //on success, make a request to get google analytics data
  handleRequest() {
    window.gapi.client.request({
      path: '/v4/reports:batchGet',
      root: 'https://analyticsreporting.googleapis.com',
      method: 'POST',
      body: {
        reportRequests: [
          {
            viewId: VIEW_ID,
            dateRanges: [{
              startDate: '7daysAgo',
              endDate: 'today'
            }],
            metrics: [{ express: 'ga:sessions' }]
          }
        ]
      }
    }).then(this.printResults, this.handleError)
  }

  //log the data
  printResults(response) {
    console.log(response)
  }

  //or the error if there is one
  handleError(reason) {
    console.error(reason)
    console.error(reason.result.error.message);
  }

  //render it all
  render() {
    return (
      <div>
      <div id="my-signin2"></div>
      </div>
    )
  }
}
</code>```

What am I doing wrong? How can I properly do a batchRequest to retrieve all data from 7 days using Google Analytics Reporting APIv4? I feel as though I am using all required fields, however, I do not know what I am missing. Can you point me in the right direction?

答:
I'm answering my own question in case anyone else needs help using google analytics reporting api v4 with react. This is what I needed to do in order to construct a gapi button that would then make a basic request. The error I was creating was from a typo. Instead of metrics:[{expression: 'ga:sessions'}] I was using metrics:[{express: 'ga:sessions'}].

Here is a component that will create a simple request. Please note you have to change the VIEW_ID to your value.

```<code>import React, { Component } from 'react';
import $ from 'jquery';

const VIEW_ID = '17414592';

export default class Test extends Component {
  constructor(props) {
    super(props)

    this.printResults = this.printResults.bind(this);
    this.handleRequest = this.handleRequest.bind(this);
    this.handleError = this.handleError.bind(this);
  }

  //when component mounts, create a google sign in button.
  componentDidMount() {
    //load gapi
    $.getScript("https://apis.google.com/js/client:platform.js")
    .done(() => {
      window.gapi.signin2.render('my-signin2', {
        'scope': 'profile email',
        'width': 240,
        'height': 50,
        'longtitle': true,
        'theme': 'dark',
        'onsuccess': this.handleRequest,
        'onfailure': this.handleError
      });
    })
  }

  //on success, make a request to get google analytics data
  handleRequest() {
    window.gapi.client.request({
      path: '/v4/reports:batchGet',
      root: 'https://analyticsreporting.googleapis.com',
      method: 'POST',
      body: {
        reportRequests: [
          {
            viewId: VIEW_ID,
            dateRanges: [{
              startDate: '7daysAgo',
              endDate: 'today'
            }],
            metrics: [{ expression: 'ga:sessions' }]
          }
        ]
      }
    }).then(this.printResults, this.handleError)
  }

  //log the data
  printResults(response) {
    console.log(response)
  }

  //or the error if there is one
  handleError(reason) {
    console.error(reason)
    console.error(reason.result.error.message);
  }

  //render it all
  render() {
    return (
      <div>
      <div id="my-signin2"></div>
      </div>
    )
  }
}
</code>```

Body:
I'm new to using this API, and I am struggling with retrieving my data using Google Analytics Reporting API v4. I am only attempting to retrieve the analytics for a website so I can build a dashboard.  I am following the example here: Hello Analytics Reporting API v4; JavaScript quick start for web applications

I am able to make a request, however, I keep getting a 400 error that is might be this: 400: Invalid Credentials

`Invalid JSON payload received. Unknown name "express" at 'report_requests[0].metrics[0]': Cannot find field.
handleError @ Test.js:64
h.o0 @ cb=gapi.loaded_0:53
xs @ cb=gapi.loaded_0:56
Wq @ cb=gapi.loaded_0:56
_.C.uea @ cb=gapi.loaded_0:55
Ap @ cb=gapi.loaded_0:49`

I have no idea what I am doing wrong, and I am hoping someone can point me in the right direction.

This is a react application. I am making the request after the component mounts.

import React, { Component } from 'react';
import GoogleLogin from 'react-google-login';
import $ from 'jquery';

const VIEW_ID = '17414592';
const CLIENT_ID = "936270024581-stgn130l17v21s6vjch9p751hiqbovac.apps.googleusercontent.com";
const DISC_DOCS = 'https://analyticsreporting.googleapis.com/$discovery/rest?version=v4';

export default class Test extends Component {
  constructor(props) {
    super(props)

    this.printResults = this.printResults.bind(this);
    this.handleRequest = this.handleRequest.bind(this);
    this.handleError = this.handleError.bind(this);
  }

  //when component mounts, create a google sign in button.
  componentDidMount() {
    //load gapi
    $.getScript("https://apis.google.com/js/client:platform.js")
    .done(() => {
      window.gapi.signin2.render('my-signin2', {
        'scope': 'profile email',
        'width': 240,
        'height': 50,
        'longtitle': true,
        'theme': 'dark',
        'onsuccess': this.handleRequest,
        'onfailure': this.handleError
      });
    })
  }

  //on success, make a request to get google analytics data
  handleRequest() {
    window.gapi.client.request({
      path: '/v4/reports:batchGet',
      root: 'https://analyticsreporting.googleapis.com',
      method: 'POST',
      body: {
        reportRequests: [
          {
            viewId: VIEW_ID,
            dateRanges: [{
              startDate: '7daysAgo',
              endDate: 'today'
            }],
            metrics: [{ express: 'ga:sessions' }]
          }
        ]
      }
    }).then(this.printResults, this.handleError)
  }

  //log the data
  printResults(response) {
    console.log(response)
  }

  //or the error if there is one
  handleError(reason) {
    console.error(reason)
    console.error(reason.result.error.message);
  }

  //render it all
  render() {
    return (

    )
  }
}

What am I doing wrong? How can I properly do a batchRequest to retrieve all data from 7 days using Google Analytics Reporting APIv4? I feel as though I am using all required fields, however, I do not know what I am missing. Can you point me in the right direction?

Body:
I'm answering my own question in case anyone else needs help using google analytics reporting api v4 with react. This is what I needed to do in order to construct a gapi button that would then make a basic request. The error I was creating was from a typo. Instead of metrics:[{expression: 'ga:sessions'}] I was using metrics:[{express: 'ga:sessions'}].

Here is a component that will create a simple request. Please note you have to change the VIEW_ID to your value.

import React, { Component } from 'react';
import $ from 'jquery';

const VIEW_ID = '17414592';

export default class Test extends Component {
  constructor(props) {
    super(props)

    this.printResults = this.printResults.bind(this);
    this.handleRequest = this.handleRequest.bind(this);
    this.handleError = this.handleError.bind(this);
  }

  //when component mounts, create a google sign in button.
  componentDidMount() {
    //load gapi
    $.getScript("https://apis.google.com/js/client:platform.js")
    .done(() => {
      window.gapi.signin2.render('my-signin2', {
        'scope': 'profile email',
        'width': 240,
        'height': 50,
        'longtitle': true,
        'theme': 'dark',
        'onsuccess': this.handleRequest,
        'onfailure': this.handleError
      });
    })
  }

  //on success, make a request to get google analytics data
  handleRequest() {
    window.gapi.client.request({
      path: '/v4/reports:batchGet',
      root: 'https://analyticsreporting.googleapis.com',
      method: 'POST',
      body: {
        reportRequests: [
          {
            viewId: VIEW_ID,
            dateRanges: [{
              startDate: '7daysAgo',
              endDate: 'today'
            }],
            metrics: [{ expression: 'ga:sessions' }]
          }
        ]
      }
    }).then(this.printResults, this.handleError)
  }

  //log the data
  printResults(response) {
    console.log(response)
  }

  //or the error if there is one
  handleError(reason) {
    console.error(reason)
    console.error(reason.result.error.message);
  }

  //render it all
  render() {
    return (
      <div>
      <div id="my-signin2"></div>
      </div>
    )
  }
}


问:
can I use constraint and index in a single query to load csv to neo4j?
I was trying to import csv to neo4j and it worked but slow.
So I am trying to use 'CONSTRAINT' to speed it up.

My following works

```<code>     'USING PERIODIC COMMIT \
      LOAD CSV WITH HEADERS FROM {filepath} AS row WITH \
      row limit 1000 \
      MERGE (spot:Spot{id:row.id}) \
      .....there are more line actually ... \
     '
</code>```

but it does not work when I add 'constraint' to the query, say syntax error.

```<code>     'CREATE CONSTRAINT ON (s:Spot) ASSERT s.id is UNIQUE;\
      USING PERIODIC COMMIT \
      LOAD CSV WITH HEADERS FROM {filepath} AS row WITH \
      row limit 1000 \
      MERGE (spot:Spot{id:row.id}) \
      .....there are more line actually ... \
     '
</code>```

I tried to run constraints first, then load csv right after. but the following says some error.

```<code>         var unique_str = ' CREATE CONSTRAINT ON (s:Spot) ASSERT s.id is UNIQUE \
                       CREATE CONSTRAINT ON (c:City) ASSERT c.id is UNIQUE \
                       CREATE CONSTRAINT ON (t:Tag) ASSERT t.id is UNIQUE; '
</code>```

what is wrong with it?

Keep having problems, could someone point out my mistakes please.
What should I do?
Thanks in advance!

答:
Schema operations, such as creating a constraint, and creating an index must be done in their own transactions, where that operation is the only statement in the transaction.

What client are you using? Using the official Javascript driver it would look something like this:

```<code>var neo4j = require('neo4j-driver').v1;
var driver = neo4j.driver("bolt://localhost", neo4j.auth.basic("neo4j", "neo4j"));
var session = driver.session();
session.run("CREATE CONSTRAINT ON (s:Spot) ASSERT s.id is UNIQUE;");
session.run("CREATE CONSTRAINT ON (c:City) ASSERT c.id is UNIQUE;");
session.run("CREATE CONSTRAINT ON (t:Tag) ASSERT t.id is UNIQUE;");
session.run("USING PERIODIC COMMIT...");
</code>```

session.run will create an implicit transaction for each statement.

Body:
I was trying to import csv to neo4j and it worked but slow.
So I am trying to use 'CONSTRAINT' to speed it up.

My following works

     'USING PERIODIC COMMIT \
      LOAD CSV WITH HEADERS FROM {filepath} AS row WITH \
      row limit 1000 \
      MERGE (spot:Spot{id:row.id}) \
      .....there are more line actually ... \
     '

but it does not work when I add 'constraint' to the query, say syntax error.

     'CREATE CONSTRAINT ON (s:Spot) ASSERT s.id is UNIQUE;\
      USING PERIODIC COMMIT \
      LOAD CSV WITH HEADERS FROM {filepath} AS row WITH \
      row limit 1000 \
      MERGE (spot:Spot{id:row.id}) \
      .....there are more line actually ... \
     '

I tried to run constraints first, then load csv right after. but the following says some error.

         var unique_str = ' CREATE CONSTRAINT ON (s:Spot) ASSERT s.id is UNIQUE \
                       CREATE CONSTRAINT ON (c:City) ASSERT c.id is UNIQUE \
                       CREATE CONSTRAINT ON (t:Tag) ASSERT t.id is UNIQUE; '

what is wrong with it?

Keep having problems, could someone point out my mistakes please.
What should I do?
Thanks in advance!

Body:
Schema operations, such as creating a constraint, and creating an index must be done in their own transactions, where that operation is the only statement in the transaction.

What client are you using? Using the official Javascript driver it would look something like this:

var neo4j = require('neo4j-driver').v1;
var driver = neo4j.driver("bolt://localhost", neo4j.auth.basic("neo4j", "neo4j"));
var session = driver.session();
session.run("CREATE CONSTRAINT ON (s:Spot) ASSERT s.id is UNIQUE;");
session.run("CREATE CONSTRAINT ON (c:City) ASSERT c.id is UNIQUE;");
session.run("CREATE CONSTRAINT ON (t:Tag) ASSERT t.id is UNIQUE;");
session.run("USING PERIODIC COMMIT...");

session.run will create an implicit transaction for each statement.


问:
influxdb query: specify or filter tag by regex
According to the docs, we can...

Use a regular expression to specify a tag with a value in the WHERE clause.

When I query my influxdb like this, I get the desired results.

> SELECT "field" FROM "measurement" WHERE tag = 19

When replacing the where filtering by a regex, however, I get no results.

> SELECT "field" FROM "measurement" WHERE tag =~ /19/

Can someone tell me why that is?

答:
Found the mistake myself...

I had both a field and a tag with the same key. So I was doing

> SELECT "filed_key" from "measurement" WHERE field_key =~ /val/

Now I have changed my schema so that keys across fields and tags are unique, and everything works as expected.

There's also a discussion about this phenomenon on github.


问:
Reclaim string memory quickly (device with limited RAM)
I am writing a C# app for a device with limited ram. (Mono on iPhone/iPad)

When I assign a large string:

```<code>string xml = "10 meg xml string from REST service";
</code>```

then clear it

```<code>xml = null;
</code>```

Is with the GC free up that memory asap? Is there a way to make sure it's cleaned up. GC has a collect feature, but is this executed right away?

The problem is that I am downloading many large xml files in a loop and even though I am setting the string to null, memory use is growing.

答:
In general GC does not happen immediately because garbage collection is relatively expensive.  The runtime generally tries to do it while it's not busy doing other things, but this clearly isn't always possible.  I ran into a non-deterministic out of memory error at one point because it was putting off GC too long (sometimes) while I was running a tight memory intensive loop.  Lesson: Generally the collector knows what it is doing and you don't need to tweak it.  But not always.

To force a collection to happen, you need two lines:

```<code>GC.Collect();
GC.WaitForPendingFinalizers();
</code>```

EDIT: Wrote this before I saw your note on what you were running on.  This is written based on the desktop .NET machine.  It may (or may not) be different on mono / iPad.

Body:
I am writing a C# app for a device with limited ram. (Mono on iPhone/iPad)

When I assign a large string:

string xml = "10 meg xml string from REST service";

then clear it

xml = null;

Is with the GC free up that memory asap? Is there a way to make sure it's cleaned up. GC has a collect feature, but is this executed right away?

The problem is that I am downloading many large xml files in a loop and even though I am setting the string to null, memory use is growing.

Body:
In general GC does not happen immediately because garbage collection is relatively expensive.  The runtime generally tries to do it while it's not busy doing other things, but this clearly isn't always possible.  I ran into a non-deterministic out of memory error at one point because it was putting off GC too long (sometimes) while I was running a tight memory intensive loop.  Lesson: Generally the collector knows what it is doing and you don't need to tweak it.  But not always.

To force a collection to happen, you need two lines:

GC.Collect();
GC.WaitForPendingFinalizers();

EDIT: Wrote this before I saw your note on what you were running on.  This is written based on the desktop .NET machine.  It may (or may not) be different on mono / iPad.


问:
Mapping of user level and kernel level thread
While going through OPERATING SYSTEM PRINCIPLES, 7TH ED

(By Abraham Silberschatz, Peter Baer Galvin, Greg Gagne), i encountered a

statement in Thread Scheduling Section.It is given as -:

To run on a CPU, user-level threads must ultimately be mapped
  to an associated kernel-level thread, although this mapping may
  be indirect and may use a lightweight process (LWP).

The first half of the statement i.e

To run on a CPU, user-level threads must ultimately be mapped  to an associated kernel-level

is trying to say that When a user level thread is executed ,it will need support from kernel thread like system calls.

But i am completely stuck in other half i.e

although this mapping may
  be indirect and may use a lightweight process (LWP)

What does it really mean ???

Please help me out !

答:
You're reading a book that is notoriously crapola. Threads are implemented in two ways.

In the olde days (and still persists on some operating systems) there were just processes. A process consisted of an execution stream and an address space.

When languages that needed thread support (e.g., Ada—"tasks") there was a need to create libraries to implement threads. The libraries used timers to switch among the various threads within the process. This is poor man's threading. The major drawback here is that, even when you have multiple processors, all the threads of a process run on the same processor. The threads are just interleaved execution within a single process that executes on one processors.

These are sometimes called "user level threads." Some books call this the "many-to-one model."

To say

To run on a CPU, user-level threads must ultimately be mapped to an associated kernel-level thread

is highly misleading. There [usually] ARE no kernel threads in this model; just processes. Multiple threads run interleaved in a process. To call this a mapping "to an associated kernel-level thread" is misleading and overly theoretical.

This is mumbo jumbo.

although this mapping may be indirect and may use a lightweight process (LWP)

The next stage in operating system evolution here was for the operating system to support threads directly. Instead of a process being an execution stream + address-space, a process became one-or-more-threads + address-space. Instead of scheduling processes for execution, the OS schedules threads for execution.

Those are kernel threads.

Your book is making the simple complex.


问:
How to use address function in Excel VBA?
I am trying to use VBA to dynamically add a formula to a few cells using the address function. When I run the following scripts I get a file explorer window that opens. I am not sure why that happens. What am I doing wrong?

Here is one of the solutions I tried:

```<code>Sub AddFormulas()

Set countBase = Sheet7.Range("CU2")
colCount = Sheet7.Range(countBase, countBase.End(xlToRight)).Columns.Count

Dim startCount As Integer
startCount = 98

    For i = 1 To colCount

        If IsNumeric(Sheet7.Cells(2, startCount + i)) Then
            Set bSum = Sheet7.Cells(3, colCount + startCount)
            Set bSpr = Sheet6.Cells(3, startCount + i)

            Sheet7.Cells(3, i).Formula = "=Sheet6!" & bSpr.Address() & "*" & "Sheet7!" & bSpr.Address()

         Else
            'Do some stuff
        End If
    Next i
End Sub
</code>```

I also tried this:

```<code>Sub AddFormulas()

Set countBase = Sheet7.Range("CU2")
colCount = Sheet7.Range(countBase, countBase.End(xlToRight)).Columns.Count

Dim startCount As Integer
startCount = 98

    For i = 1 To colCount

        If IsNumeric(Sheet7.Cells(2, startCount + i)) Then

            Sheet7.Cells(3, i).Formula = "=Sheet6!" & Cells(3, startCount + i).Address() & "*" & "Sheet7!" & Cells(3, colCount + startCount).Address()

         Else
            'Do some stuff
        End If
    Next i
End Sub
</code>```

答:
Did you rename your worksheets? You cannot use a codename in a worksheet formula but you can retrieve the name from the codename.

```<code>Sheet7.Cells(3, i).Formula = _
   "='" & Sheet6.Name & "'!" & bSpr.Address() & "*'" & Sheet7.Name & "'!" & bSpr.Address()
</code>```

I've added wrapping single quotes to the worksheet names in case they contain spaces; there is no detriment if they do not.

Body:
I am trying to use VBA to dynamically add a formula to a few cells using the address function. When I run the following scripts I get a file explorer window that opens. I am not sure why that happens. What am I doing wrong?

Here is one of the solutions I tried:

Sub AddFormulas()

Set countBase = Sheet7.Range("CU2")
colCount = Sheet7.Range(countBase, countBase.End(xlToRight)).Columns.Count

Dim startCount As Integer
startCount = 98

    For i = 1 To colCount

        If IsNumeric(Sheet7.Cells(2, startCount + i)) Then
            Set bSum = Sheet7.Cells(3, colCount + startCount)
            Set bSpr = Sheet6.Cells(3, startCount + i)

            Sheet7.Cells(3, i).Formula = "=Sheet6!" & bSpr.Address() & "*" & "Sheet7!" & bSpr.Address()

         Else
            'Do some stuff
        End If
    Next i
End Sub

I also tried this:

Sub AddFormulas()

Set countBase = Sheet7.Range("CU2")
colCount = Sheet7.Range(countBase, countBase.End(xlToRight)).Columns.Count

Dim startCount As Integer
startCount = 98

    For i = 1 To colCount

        If IsNumeric(Sheet7.Cells(2, startCount + i)) Then

            Sheet7.Cells(3, i).Formula = "=Sheet6!" & Cells(3, startCount + i).Address() & "*" & "Sheet7!" & Cells(3, colCount + startCount).Address()

         Else
            'Do some stuff
        End If
    Next i
End Sub

Body:
Did you rename your worksheets? You cannot use a codename in a worksheet formula but you can retrieve the name from the codename.

Sheet7.Cells(3, i).Formula = _
   "='" & Sheet6.Name & "'!" & bSpr.Address() & "*'" & Sheet7.Name & "'!" & bSpr.Address()

I've added wrapping single quotes to the worksheet names in case they contain spaces; there is no detriment if they do not.


问:
Select max date in one column based on unique dates in another
I have a data set that is loaded into the database every time the forecast for that particular date is changed.  I need to be able to select the last load_dt for each fore_dt.  An example data set is below:

```<code>load_dt, fore_dt, data,
1/1/2017, 1/14/2017, 5,
1/5/2017, 1/14/2017, 8,
1/5/2017, 1/15/2017, 9,
1/15/2017, 1/15/2017, 10,
1/17/2017, 1/16/2017, 5
</code>```

Results should look like:

```<code>load_dt, fore_dt, data,
1/5/2017, 1/14/2017, 8,
1/15/2017, 1/15/2017, 10,
1/17/2017, 1/16/2017, 5
</code>```

The actual data set is much more complex and has a lot of rows.  In the query, I need to be able to select where fore_dt between date and date.

答:
You can use window function row_number to assign sequence number to row within each fore_dt in the order of decreasing load_dt and then select the first row using a simple where clause:

```<code>select *
from (
    select t.*,
        row_number() over (
            partition by fore_dt order by load_dt desc nulls last
            ) as seqnum
    from your_table t
    ) t
where seqnum = 1;
</code>```

Body:
I have a data set that is loaded into the database every time the forecast for that particular date is changed.  I need to be able to select the last load_dt for each fore_dt.  An example data set is below:

load_dt, fore_dt, data,
1/1/2017, 1/14/2017, 5,
1/5/2017, 1/14/2017, 8,
1/5/2017, 1/15/2017, 9,
1/15/2017, 1/15/2017, 10,
1/17/2017, 1/16/2017, 5

Results should look like:

load_dt, fore_dt, data,
1/5/2017, 1/14/2017, 8,
1/15/2017, 1/15/2017, 10,
1/17/2017, 1/16/2017, 5

The actual data set is much more complex and has a lot of rows.  In the query, I need to be able to select where fore_dt between date and date.

Body:
You can use window function row_number to assign sequence number to row within each fore_dt in the order of decreasing load_dt and then select the first row using a simple where clause:

select *
from (
    select t.*,
        row_number() over (
            partition by fore_dt order by load_dt desc nulls last
            ) as seqnum
    from your_table t
    ) t
where seqnum = 1;


问:
Blocking read from file in PHP
Here is what I want expressed in bash:

```<code>while true; do
  while read $line; do
    echo "Heard: $line"
  done < fifo
done
</code>```

Here, fifo is the path to a named pipe. This will read from the fifo, but if the fifo is empty, it will block until there is something in it.

Trying a similar thing in PHP results in a busy-loop since fgets returns when there is nothing in the pipe.

答: I believe fread is blocking.</p>

Title: Blocking read from file in PHP

Body:
Here is what I want expressed in bash:

while true; do
  while read $line; do
    echo "Heard: $line"
  done < fifo
done

Here, fifo is the path to a named pipe. This will read from the fifo, but if the fifo is empty, it will block until there is something in it.

Trying a similar thing in PHP results in a busy-loop since fgets returns when there is nothing in the pipe.

Body: I believe fread is blocking.


问:
read and write scsi devices file from linux , like sdb,sdc
I want to write my own tag on the device file (scsi file sdb, sdc...) on Linux.

I use linux C open(), read(), write() functions on /dev/sdb file, write my key  in this file. But when usb disk device Unplug from computer and plug again, in /dev/sdb's key, sometimes it's gone, or is unstable.

I don't know why.

```<code>char readBuf[512] = { 0 };
char key[12] = "h%27dcd*()jd";
int fd = open("/dev/sdb",O_RDWR);
lseek(fd,1024,SEEK_SET);
read(fd,readBuf,512);
for(int i=0; i<sizeof key; ++i)
{
    readBuf[i] = ~key[i];
}
lseek(fd,1024,SEEK_SET);
write(fd,readBuf,512);
//In order to mark the Usb disk bear fruit...
</code>```

答:
for setting a fixed mount point:

you can assign a static mount point (like /dev/sdb) for USB devices using udev rules and a symlink. you can identify the device in the udev rule by i.e. vendor id and product id,...

ACTION=="add", ATTRS{idVendor}=="0403", ATTRS{idProduct}=="6001", SYMLINK+="my_device"

https://unix.stackexchange.com/questions/66901/how-to-bind-usb-device-under-a-static-name

for writing bit-wise to specific memory location on the stick:

to write data bytewise to arbitrary blocks on a block device use tools like dd ( https://en.wikipedia.org/wiki/Dd_(Unix) ). file io tools like read(), write() can not be used for writing bytewise WITHOUT using a file...

Body:
I want to write my own tag on the device file (scsi file sdb, sdc...) on Linux.

I use linux C open(), read(), write() functions on /dev/sdb file, write my key  in this file. But when usb disk device Unplug from computer and plug again, in /dev/sdb's key, sometimes it's gone, or is unstable.

I don't know why.

char readBuf[512] = { 0 };
char key[12] = "h%27dcd*()jd";
int fd = open("/dev/sdb",O_RDWR);
lseek(fd,1024,SEEK_SET);
read(fd,readBuf,512);
for(int i=0; i<sizeof key; ++i)
{
    readBuf[i] = ~key[i];
}
lseek(fd,1024,SEEK_SET);
write(fd,readBuf,512);
//In order to mark the Usb disk bear fruit...


问:
awk split column into multiple columns in staggered manner
I have a text file containing a single column of data as below :

```<code>1
2
3
4
5
6
</code>```

I want to split this into multiple columns using awk or sed command as follows:

```<code>1 2 3
4 5 6
</code>```

How can I do this? Thanks in advance

答:
here is another approach

```<code>paste -d' ' - - - < file
</code>```

with awk

```<code>awk 'ORS=NR%3?FS:RS' file
</code>```

also

```<code>pr -3ats' ' file
</code>```

Body:
I have a text file containing a single column of data as below :

1
2
3
4
5
6

I want to split this into multiple columns using awk or sed command as follows:

1 2 3
4 5 6

How can I do this? Thanks in advance

Body:
here is another approach

paste -d' ' - - - < file

with awk

awk 'ORS=NR%3?FS:RS' file

also

pr -3ats' ' file


问:
How to get a keyboard code for an Android project?
i'm trying to check a condition which says:

```<code>  keyCode = event.getKeyCode();
  Log.e("key",keyCode+"");
    if (keyCode == KeyEvent.KEYCODE_DEL && event.getAction() == KeyEvent.ACTION_DOWN)
    //logic
</code>```

On the log window, the 'keyCode' arent getting any keyboard code, except the value from KEYCODE_DEL which is 67 but doing this ONLY if the EditText is empty!

```<code>    editTextPrincipal.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            keyCode = event.getKeyCode();
            Log.e("key",keyCode+"");
            if (keyCode == KeyEvent.KEYCODE_DEL && event.getAction() == KeyEvent.ACTION_DOWN){
                usuarioDeletouCaracter = true;
                return usuarioDeletouCaracter;
            }
            return usuarioDeletouCaracter;

        }
    });

    editTextPrincipal.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!usuarioDeletouCaracter){
                editTextPrincipal.addTextChangedListener(textWatcher);
            }else{
                Toast.makeText(getApplicationContext(), "O usuario apagou", Toast.LENGTH_SHORT).show();
            }
        }
    });
</code>```

wherever a key is pressed on the keybaord, the keycode on the log window, should returns her value but this is not happen =\

答: Soft keyboards almost never generate keycodes.  Either use a TextWatcher, or you're going to have to override the InputConnection object.</p>

Body:
i'm trying to check a condition which says:

  keyCode = event.getKeyCode();
  Log.e("key",keyCode+"");
    if (keyCode == KeyEvent.KEYCODE_DEL && event.getAction() == KeyEvent.ACTION_DOWN)
    //logic

On the log window, the 'keyCode' arent getting any keyboard code, except the value from KEYCODE_DEL which is 67 but doing this ONLY if the EditText is empty!

    editTextPrincipal.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            keyCode = event.getKeyCode();
            Log.e("key",keyCode+"");
            if (keyCode == KeyEvent.KEYCODE_DEL && event.getAction() == KeyEvent.ACTION_DOWN){
                usuarioDeletouCaracter = true;
                return usuarioDeletouCaracter;
            }
            return usuarioDeletouCaracter;

        }
    });

    editTextPrincipal.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!usuarioDeletouCaracter){
                editTextPrincipal.addTextChangedListener(textWatcher);
            }else{
                Toast.makeText(getApplicationContext(), "O usuario apagou", Toast.LENGTH_SHORT).show();
            }
        }
    });

wherever a key is pressed on the keybaord, the keycode on the log window, should returns her value but this is not happen =\