问:
Copying a row, inserting multiple new rows with the pasted info on multiple sheets Excel VBA
Data This is where all the items are with each region code

I have a "New Item" worksheet, a "Data" worksheet, and a "View" worksheet in the same workbook.
In my "New Item" worksheet, I have a section B2:H2 for inputing new items and click a button to run the macro.  I need help fixing the error.  It runs but adds a "true" to each point instead of the copied section.

I need the macro to add a line, copy the region code (in column A; there are over 30 regions but every item is added to a region by default), insert the B2:H2 in the B:H columns of the new line on the "Data" Sheet and also just add it to the end of the "View" sheet.
It keeps inputting true now.  Why does it do this? Also, why does the code not copy the B2:H2?  I am fairly new to VBA.

Also if possible, if there was a way to adjust the chart's Selected Data  on the View sheet to add a line to the viewed data, that would be great.  Ex: the chart shows 50 lines, and it adds another line to the selected data through the macro.

Thank you in advance for all suggestions.  I can clarify anything or upload the excel if needed.
Here is the code so far:

```<code>Sub AddItem()
   Sheets("Data").Select
        Dim lastRow As Long
        Dim rowPtr As Long
        lastRow = Range("A" & Rows.Count).End(xlUp).Row
    For rowPtr = lastRow To 2 Step -1
        If Not IsEmpty(Range("A" & rowPtr)) Then
          If Range("A" & rowPtr) <> Range("A" & rowPtr - 1) Then
            Range("A" & rowPtr).EntireRow.Insert
          End If
        End If
  Next
   Sheets("New Item").Select
   Application.ScreenUpdating = False
   Dim copySheet As Worksheet
   Dim pasteSheet1 As Worksheet

   Set copySheet = Worksheets("New Item")
   Set pasteSheet1 = Worksheets("Data")

   copySheet.Range("B2:H2").Copy
   pasteSheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 1).PasteSpecial xlPasteValues
   Application.CutCopyMode = False
   Application.ScreenUpdating = True
End Sub
</code>```

答:
So im not sure if this is what you want.

```<code>Sub Add()
Dim Data As Worksheet, NItem As Worksheet, View As Worksheet
Dim lRow As Long

Application.ScreenUpdating = False

Set NItem = Worksheets("New Item")
Set Data = Worksheets("Data")
Set View = Worksheets("View")

lRow = View.Cells(View.Rows.Count, 2).End(xlUp).Row

Data.Range("A2").EntireRow.Insert
NItem.Range("B2:H2").Copy
Data.Range("B2").PasteSpecial xlPasteValues
View.Cells(lRow + 1, 2).PasteSpecial xlPasteValues

Application.CutCopyMode = False
Application.ScreenUpdating = True
End Sub
</code>```

But this will add a line in Row 2 in the Datasheet, paste in the values. (Your For Loop inserts a new line after every entry, why?). It also pastes it in the viewsheet. Other than that please avoid using .Select and objectify .Range, .Cells etc. like you've done in the second part of the code.

Body:
Data This is where all the items are with each region code

I have a "New Item" worksheet, a "Data" worksheet, and a "View" worksheet in the same workbook.
In my "New Item" worksheet, I have a section B2:H2 for inputing new items and click a button to run the macro.  I need help fixing the error.  It runs but adds a "true" to each point instead of the copied section.

I need the macro to add a line, copy the region code (in column A; there are over 30 regions but every item is added to a region by default), insert the B2:H2 in the B:H columns of the new line on the "Data" Sheet and also just add it to the end of the "View" sheet.
It keeps inputting true now.  Why does it do this? Also, why does the code not copy the B2:H2?  I am fairly new to VBA.

Also if possible, if there was a way to adjust the chart's Selected Data  on the View sheet to add a line to the viewed data, that would be great.  Ex: the chart shows 50 lines, and it adds another line to the selected data through the macro.

Thank you in advance for all suggestions.  I can clarify anything or upload the excel if needed.
Here is the code so far:

Sub AddItem()
   Sheets("Data").Select
        Dim lastRow As Long
        Dim rowPtr As Long
        lastRow = Range("A" & Rows.Count).End(xlUp).Row
    For rowPtr = lastRow To 2 Step -1
        If Not IsEmpty(Range("A" & rowPtr)) Then
          If Range("A" & rowPtr) <> Range("A" & rowPtr - 1) Then
            Range("A" & rowPtr).EntireRow.Insert
          End If
        End If
  Next
   Sheets("New Item").Select
   Application.ScreenUpdating = False
   Dim copySheet As Worksheet
   Dim pasteSheet1 As Worksheet

   Set copySheet = Worksheets("New Item")
   Set pasteSheet1 = Worksheets("Data")

   copySheet.Range("B2:H2").Copy
   pasteSheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 1).PasteSpecial xlPasteValues
   Application.CutCopyMode = False
   Application.ScreenUpdating = True
End Sub

Body:
So im not sure if this is what you want.

Sub Add()
Dim Data As Worksheet, NItem As Worksheet, View As Worksheet
Dim lRow As Long

Application.ScreenUpdating = False

Set NItem = Worksheets("New Item")
Set Data = Worksheets("Data")
Set View = Worksheets("View")

lRow = View.Cells(View.Rows.Count, 2).End(xlUp).Row

Data.Range("A2").EntireRow.Insert
NItem.Range("B2:H2").Copy
Data.Range("B2").PasteSpecial xlPasteValues
View.Cells(lRow + 1, 2).PasteSpecial xlPasteValues

Application.CutCopyMode = False
Application.ScreenUpdating = True
End Sub

But this will add a line in Row 2 in the Datasheet, paste in the values. (Your For Loop inserts a new line after every entry, why?). It also pastes it in the viewsheet. Other than that please avoid using .Select and objectify .Range, .Cells etc. like you've done in the second part of the code.


来源: stackexchange

问:
Event system similar to C# (.NET?)
In C# (at least using .NET, but I think it's general), you can create events like this: Understanding events and event handlers in C#.

Is there a similar mechanism for C++?

PS: I've never liked signal/slot system, so please don't suggest it, since I'm already using it and would love to switch to something else.

答: If boost is not an option, I implemented events in c++ here. The semantics is almost the same as in .NET . It's a compact implementation but uses quite advanced C++ features: a modern C++11 compiler is required.</p>

ContentLicense: CC BY-SA 3.0

Title: Event system similar to C# (.NET?)


问:
Prolog program to exclude integer from result list
I need to split a list into one that is bigger than N and one smaller, while ignoring any non-integers. It works perfectly except that it throws an exception when i include non integers. Can anyone see what I'm doing wrong please:</p>

```<code>split([],N, [],[]).
split([HeadOrig | TailOrig], N, L1, TailOrig):-
    \+ integer(HeadOrig),
    split(TailOrig, N, L1, TailOrig).
split([HeadOrig|TailOrig],N, [HeadOrig|Tail1],L2):-
    integer(HeadOrig), HeadOrig >= N,
    !,
    split(TailOrig, N, Tail1, L2).
split([HeadOrig | TailOrig], N, L1, [HeadOrig | Tail2]) :-
    integer(HeadOrig), HeadOrig < N,
    !,
    split(TailOrig, N, L1, Tail2).
</code>```

答:
The problem is that the last term in that clause should not be TailOrig:

```<code>split([], _, [],[]).

split([HeadOrig | TailOrig], N, L1, L2):-
    \+ integer(HeadOrig),
    split(TailOrig, N, L1, L2),
    !.

split([HeadOrig|TailOrig], N, [HeadOrig|Tail1], L2):-
    integer(HeadOrig), HeadOrig >= N,
    !,
    split(TailOrig, N, Tail1, L2).

split([HeadOrig | TailOrig], N, L1, [HeadOrig | Tail2]) :-
    integer(HeadOrig), HeadOrig < N,
    !,
    split(TailOrig, N, L1, Tail2).
</code>```

Body:
I need to split a list into one that is bigger than N and one smaller, while ignoring any non-integers. It works perfectly except that it throws an exception when i include non integers. Can anyone see what I'm doing wrong please:

split([],N, [],[]).
split([HeadOrig | TailOrig], N, L1, TailOrig):-
    \+ integer(HeadOrig),
    split(TailOrig, N, L1, TailOrig).
split([HeadOrig|TailOrig],N, [HeadOrig|Tail1],L2):-
    integer(HeadOrig), HeadOrig >= N,
    !,
    split(TailOrig, N, Tail1, L2).
split([HeadOrig | TailOrig], N, L1, [HeadOrig | Tail2]) :-
    integer(HeadOrig), HeadOrig < N,
    !,
    split(TailOrig, N, L1, Tail2).

Body:
The problem is that the last term in that clause should not be TailOrig:

split([], _, [],[]).

split([HeadOrig | TailOrig], N, L1, L2):-
    \+ integer(HeadOrig),
    split(TailOrig, N, L1, L2),
    !.

split([HeadOrig|TailOrig], N, [HeadOrig|Tail1], L2):-
    integer(HeadOrig), HeadOrig >= N,
    !,
    split(TailOrig, N, Tail1, L2).

split([HeadOrig | TailOrig], N, L1, [HeadOrig | Tail2]) :-
    integer(HeadOrig), HeadOrig < N,
    !,
    split(TailOrig, N, L1, Tail2).


问:
Transpose factorplot in seaborn
Following my previous question how to draw several box plots, now I am wondering how transpose the factor plot and instead of having 1x5 pictures

I need to get it as 5x1.

How to vertically align the factorplot?

答:
For a seaborn boxplot you need to use the row argument to supply the quantity to map along the rows, instead of the col  argument.

```<code>import seaborn as sns
import matplotlib.pyplot as plt

titanic = sns.load_dataset("titanic")

g = sns.factorplot(y="age", x="embark_town",
                    hue="sex", row="class",
                    data=titanic[titanic.embark_town.notnull()],
                   orient="v", kind="box", size=3)
plt.show()
</code>```

Title: Transpose factorplot in seaborn

Body:
For a seaborn boxplot you need to use the row argument to supply the quantity to map along the rows, instead of the col  argument.

import seaborn as sns
import matplotlib.pyplot as plt

titanic = sns.load_dataset("titanic")

g = sns.factorplot(y="age", x="embark_town",
                    hue="sex", row="class",
                    data=titanic[titanic.embark_town.notnull()],
                   orient="v", kind="box", size=3)
plt.show()


问:
how can I valid where_in empty
I want to valid empty where_in in codeigniter, but when I dont have any item on my array i get an error like

Error Number: 1064

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use
  near ')' at line 3

```<code>SELECT `code`, `description`, `purchase_price`, `sale_price`, `wholesale_price`, `min_stock`, `stock`, `max_stock`, `provider_id` FROM `storelte_products` WHERE `id` IN()
</code>```

how could I valid that error on codeigniter when it's empty?

my code looks like this

controller

```<code>$this->session->carrito = $this->sale->checar_existe_carrito();
        $array = $this->sale->get_all_cart($this->session->carrito);
        $product_id = array();
    foreach ($array as $key => $value) {
             $product_id[] = $value['id'];
        }
        print_r($this->products->get_product_id($product_id));
</code>```

model

```<code>  public function get_product_id($id) {
        $this->db->select('code,description,purchase_price,sale_price,wholesale_price,min_stock,stock,max_stock,provider_id');
        $this->db->from('storelte_products');
        $this->db->where_in('id', $id);
        $response = $this->db->get();
        return $response ? $response->row() : false;
    }
</code>```

答:
just check if it is empty before executing the query: </p>

```<code>public function get_product_id($id) {
    if(empty($id))
    {
        return false;
    }
    $this->db->select('code,description,purchase_price,sale_price,wholesale_price,min_stock,stock,max_stock,provider_id');
    $this->db->from('storelte_products');
    $this->db->where_in('id', $id);
    $response = $this->db->get();
    return $response ? $response->row() : false;
}
</code>```

Title: how can I valid where_in empty

Body:
I want to valid empty where_in in codeigniter, but when I dont have any item on my array i get an error like

Error Number: 1064

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use
  near ')' at line 3

SELECT `code`, `description`, `purchase_price`, `sale_price`, `wholesale_price`, `min_stock`, `stock`, `max_stock`, `provider_id` FROM `storelte_products` WHERE `id` IN()

how could I valid that error on codeigniter when it's empty?

my code looks like this

controller

$this->session->carrito = $this->sale->checar_existe_carrito();
        $array = $this->sale->get_all_cart($this->session->carrito);
        $product_id = array();
    foreach ($array as $key => $value) {
             $product_id[] = $value['id'];
        }
        print_r($this->products->get_product_id($product_id));

model

  public function get_product_id($id) {
        $this->db->select('code,description,purchase_price,sale_price,wholesale_price,min_stock,stock,max_stock,provider_id');
        $this->db->from('storelte_products');
        $this->db->where_in('id', $id);
        $response = $this->db->get();
        return $response ? $response->row() : false;
    }

Body:
just check if it is empty before executing the query:

public function get_product_id($id) {
    if(empty($id))
    {
        return false;
    }
    $this->db->select('code,description,purchase_price,sale_price,wholesale_price,min_stock,stock,max_stock,provider_id');
    $this->db->from('storelte_products');
    $this->db->where_in('id', $id);
    $response = $this->db->get();
    return $response ? $response->row() : false;
}


问:
Can a piece of code, if reusable and applicable to different contexts be classified a pattern?
What constitutes a pattern ? If i have a template/code that is reusable and can be applied to other similar situations, can it be called a pattern ?

The following is what i have created. It is a binary approach to handling conditional constructs. I have a field in a table that is composite i.e. it comprises of 3 or more other sub-fields each of which have a true or false value.

Now, i have the sub-fields representing true/false values as 0 and 1. These fields are presented as drop downs to the user in the web based application. These fields are combined to form a byte value comprising 8 bits with the first 3 bits have values of 0 or 1 which the user chooses as false or true. If the user chooses all fields as true the main field would have a value 7 and if he chooses all fields as false, the main field would have a value 0 and like wise.

The main field represents one of the columns in an existing table. The advantage of this code is that, as new sub-fields are required, there is no need to add new columns in the table. The user interface would have an additional drop down for each new sub-field.

This code is reusable and can be applied to different contexts. Could this be classified as a pattern ?

答:
There are langage patterns but mostly a pattern refers to a design rather than anything specific to a language.

The thing you describe I would call a component.

As an aside, storing more than one value in a column is probably against the guidelines of normalization. It might be easier for you in the long run if you used a column per value.

See the first answer to this question for an illustration of normalization.

OwnerDisplayName: Subramanian

LastEditorDisplayName: Binary Worrier

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: edg


问:
mongodb node - find documents by array of json objects
I'm using mongodb in a nodejs project, in which I have a collection of users :

```<code>{ "_id" : ObjectId("1"), "firstName": "John", "lastName" : "Doe", "age":20 }
{ "_id" : ObjectId("2"), "firstName": "Jane", "lastName" : "Doe", "age":22 }
{ "_id" : ObjectId("3"), "firstName": "Bob", "lastName" : "Smith","age": 32 }
{ "_id" : ObjectId("4"), "firstName": "John", "lastName" : "Smith","age":40}
{ "_id" : ObjectId("5"), "firstName": "John", "lastName" : "Deer","age":66}
</code>```

I'd like a query to return an array of document ids matching the array of users by their first and last name ordered by the array I've given here

This is what I'm trying to fiddle with:

```<code>var usersToFind = [
  { firstName: "John", lastName: "Smith"},
  { firstName: "John", lastName:"Doe"}
];

db.collection('users').then(users => users.aggregate([
   { $match : { /* what to put here? */ } },
   { $addFields : { '__order' : { $indexOfArray : [usersToFind, /* Missing here something */} } },
   { $sort : { '__order' : 1 } }
]).toArray(results => {
  console.log(results);
  // Should print ["ObjectId(4)", "ObjectId(1)"];
});
</code>```

I'm probably missing something fundamental about how to work with mongodb due to my limited knowledge of it.

I'd be grateful if you could help me solve the query or show me a better way to achieve it.

I could always iterate my usersToFind array and find documents one by one, but I'd like to use a single query here. Another approach is to use $or and $and

Thank you

答:
Using an $or query with a projection will get you most of the way there:

```<code>db.collection('users').find({$or: usersToFind}).project({_id: 1}).toArray((err, docs) => {
  console.log(docs);
});
</code>```

But the sorting is another matter, as MongoDB doesn't have any built-in support for custom sorting. See this post for some ways of handling that.

Body:
I'm using mongodb in a nodejs project, in which I have a collection of users :

{ "_id" : ObjectId("1"), "firstName": "John", "lastName" : "Doe", "age":20 }
{ "_id" : ObjectId("2"), "firstName": "Jane", "lastName" : "Doe", "age":22 }
{ "_id" : ObjectId("3"), "firstName": "Bob", "lastName" : "Smith","age": 32 }
{ "_id" : ObjectId("4"), "firstName": "John", "lastName" : "Smith","age":40}
{ "_id" : ObjectId("5"), "firstName": "John", "lastName" : "Deer","age":66}

I'd like a query to return an array of document ids matching the array of users by their first and last name ordered by the array I've given here

This is what I'm trying to fiddle with:

var usersToFind = [
  { firstName: "John", lastName: "Smith"},
  { firstName: "John", lastName:"Doe"}
];

db.collection('users').then(users => users.aggregate([
   { $match : { /* what to put here? */ } },
   { $addFields : { '__order' : { $indexOfArray : [usersToFind, /* Missing here something */} } },
   { $sort : { '__order' : 1 } }
]).toArray(results => {
  console.log(results);
  // Should print ["ObjectId(4)", "ObjectId(1)"];
});

I'm probably missing something fundamental about how to work with mongodb due to my limited knowledge of it.

I'd be grateful if you could help me solve the query or show me a better way to achieve it.

I could always iterate my usersToFind array and find documents one by one, but I'd like to use a single query here. Another approach is to use $or and $and

Thank you

Body:
Using an $or query with a projection will get you most of the way there:

db.collection('users').find({$or: usersToFind}).project({_id: 1}).toArray((err, docs) => {
  console.log(docs);
});

But the sorting is another matter, as MongoDB doesn't have any built-in support for custom sorting. See this post for some ways of handling that.


问:
Including d3 graph in Angular 4 application
I am building an Angular application with typescript, where I would like to display the force directed network graph from Mike Boston build with d3 shown here.

I have copied and translated most of the code to type script without trouble but the line

```<code>. force("link", d3.forceLink().id(function(d) { return d.id; }))
</code>```

fails with the error {} has no property id.

Only the following lines referring to d.source.x works fine?

I have installed d3 with npm and also types/d3 but still no luck, even though the typings.d.ts has an interface defining the id.

Thank you for your help!

答:
Maybe that is something related to versioning, if you are using TypeScript 2.4.1, try to downgrade to 2.3.4 and give it a go.

As a workaround you could use any:

```<code>const forceLink: any = d3.forceLink();
. force("link", forceLink.id(function(d) { return d.id; }))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am building an Angular application with typescript, where I would like to display the force directed network graph from Mike Boston build with d3 shown here.

I have copied and translated most of the code to type script without trouble but the line

. force("link", d3.forceLink().id(function(d) { return d.id; }))

fails with the error {} has no property id.

Only the following lines referring to d.source.x works fine?

I have installed d3 with npm and also types/d3 but still no luck, even though the typings.d.ts has an interface defining the id.

Thank you for your help!

Body:
Maybe that is something related to versioning, if you are using TypeScript 2.4.1, try to downgrade to 2.3.4 and give it a go.

As a workaround you could use any:

const forceLink: any = d3.forceLink();
. force("link", forceLink.id(function(d) { return d.id; }))


问:
xcode : storyboard does not reflect changes made in code in ViewController.swift
I'm new to iOS development.

When I create anything in the ViewController.swift file (UITextField or UILable etc) it doesn't show on the main.storyboard (or the storyboard preview)

this is what the storyboard looks next to the simulation

The simulation Is exactly what I want it to look like but its totally different than the storyboard

I have created a UITextField using the AutoLayout and I have connected it via outlet in the code and edited it looks like so :

the code in ViewController.swift

I just want the storyboard to reflect the changes I've made in the code and look just like the simulator.

答:
The storyboard won't run your VC's code each time it loads, so there's no way to make your code written in a VC have an effect on the storyboard.

What you can do however, is to make a custom view.

In this case, you want your text field to look different on the storyboard, so try creating a UITextField subclass. If you then set the text field's custom class in the storyboard to your custom subclass, it will look the way you wanted.

Here's how you do this:

```<code>@IBDesignable // this is important as it tells IB that it should draw this view in the storyboard
class MyTextField: UITextField {
    override func draw(in rect: CGRect) {
        // configure how you want the text field to look here...
    }
}
</code>```

Body:
The storyboard won't run your VC's code each time it loads, so there's no way to make your code written in a VC have an effect on the storyboard.

What you can do however, is to make a custom view.

In this case, you want your text field to look different on the storyboard, so try creating a UITextField subclass. If you then set the text field's custom class in the storyboard to your custom subclass, it will look the way you wanted.

Here's how you do this:

@IBDesignable // this is important as it tells IB that it should draw this view in the storyboard
class MyTextField: UITextField {
    override func draw(in rect: CGRect) {
        // configure how you want the text field to look here...
    }
}


问:
Radio input and submit pass value
Im trying to make a radio button form where the chosen option, "123, 456" value is passed to the "data-offer-id" part of my submit button.  I think this needs to be javascript but I don't know how to do this.  Please help if you can!.  Thanks in advance</p>

```<code><form>
  <input type="radio" name="data-offer-id" value="123"> 123<br>
  <input type="radio" name="data-offer-id" value="456"> 456<br>
 </form>

<button class="btn btn-success btn-large"
                    data-dismiss="learnmodal"
                    data-cleeng-trigger
                    data-action="checkout"
                    data-locale="en_US"
                    data-display-type="overlay"
                    data-offer-id="***Need Value to dynamically populate here****"
                   data-completed-callback="cleengCallbackHandler(result)">
<span style="color: #ffffff">$9.95 / Month
</span></button>
</code>```

答:
This would be handled when the radio button is clicked so that by the time the submit button is pressed, the value is already there.

// Get reference to the submit button
var sub = document.querySelector("button.btn-success");

// Get a reference to both radio buttons as an array
var radBtns = Array.prototype.slice.call(document.querySelectorAll("input[name='data-offer-id']"));

// Loop over the buttons
radBtns.forEach(function(btn){
  // Set each button to have a click event handler
  btn.addEventListener("click", function(){
    // Set the radio button's value as the id of the submit button
    sub.setAttribute("data-offer-id", btn.value);

    // Just for testing:
    console.clear();
    console.log(sub);
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
  <input type="radio" name="data-offer-id" value="123"> 123<br>
  <input type="radio" name="data-offer-id" value="456"> 456<br>
 </form>

<button class="btn btn-success btn-large"
                    data-dismiss="learnmodal"
                    data-cleeng-trigger
                    data-action="checkout"
                    data-locale="en_US"
                    data-display-type="overlay"
                    data-offer-id=""
                   data-completed-callback="cleengCallbackHandler(result)">
<span style="color: #ffffff">$9.95 / Month
</span></button></code>```

Title: Radio input and submit pass value

Body:
Im trying to make a radio button form where the chosen option, "123, 456" value is passed to the "data-offer-id" part of my submit button.  I think this needs to be javascript but I don't know how to do this.  Please help if you can!.  Thanks in advance

<form>
  <input type="radio" name="data-offer-id" value="123"> 123

  <input type="radio" name="data-offer-id" value="456"> 456

 </form>

<button class="btn btn-success btn-large"
                    data-dismiss="learnmodal"
                    data-cleeng-trigger
                    data-action="checkout"
                    data-locale="en_US"
                    data-display-type="overlay"
                    data-offer-id="***Need Value to dynamically populate here****"
                   data-completed-callback="cleengCallbackHandler(result)">
$9.95 / Month
</button>

Body:
This would be handled when the radio button is clicked so that by the time the submit button is pressed, the value is already there.

// Get reference to the submit button
var sub = document.querySelector("button.btn-success");

// Get a reference to both radio buttons as an array
var radBtns = Array.prototype.slice.call(document.querySelectorAll("input[name='data-offer-id']"));

// Loop over the buttons
radBtns.forEach(function(btn){
  // Set each button to have a click event handler
  btn.addEventListener("click", function(){
    // Set the radio button's value as the id of the submit button
    sub.setAttribute("data-offer-id", btn.value);

    // Just for testing:
    console.clear();
    console.log(sub);
  });
});

<form>
  <input type="radio" name="data-offer-id" value="123"> 123<br>
  <input type="radio" name="data-offer-id" value="456"> 456<br>
 </form>

<button class="btn btn-success btn-large"
                    data-dismiss="learnmodal"
                    data-cleeng-trigger
                    data-action="checkout"
                    data-locale="en_US"
                    data-display-type="overlay"
                    data-offer-id=""
                   data-completed-callback="cleengCallbackHandler(result)">
<span style="color: #ffffff">$9.95 / Month
</span></button>


问:
Group duplicate column IDs in pandas dataframe
Now there are a lot of similar questions but most of them answer how to delete the duplicate columns. However, I want to know how can I make a list of tuples where each tuple contains the column names of duplicate columns. I am assuming that each column has a unique name. Just to further illustrate my question:

```<code>df = pd.DataFrame({'A': [1, 2, 3, 4, 5],'B': [2, 4, 2, 1, 9],
                   'C': [1, 2, 3, 4, 5],'D': [2, 4, 2, 1, 9],
                   'E': [3, 4, 2, 1, 2],'F': [1, 1, 1, 1, 1]},
                   index = ['a1', 'a2', 'a3', 'a4', 'a5'])
</code>```

then I want the output:

```<code>[('A', 'C'), ('B', 'D')]
</code>```

And if you are feeling great today then also extend the same question to rows. How to get a list of tuples where each tuple contains duplicate rows.

答:
Here's one NumPy approach -

```<code>def group_duplicate_cols(df):
    a = df.values
    sidx = np.lexsort(a)
    b = a[:,sidx]

    m = np.concatenate(([False], (b[:,1:] == b[:,:-1]).all(0), [False] ))
    idx = np.flatnonzero(m[1:] != m[:-1])
    C = df.columns[sidx].tolist()
    return [C[i:j] for i,j in zip(idx[::2],idx[1::2]+1)]
</code>```

Sample runs -

```<code>In [100]: df
Out[100]:
    A  B  C  D  E  F
a1  1  2  1  2  3  1
a2  2  4  2  4  4  1
a3  3  2  3  2  2  1
a4  4  1  4  1  1  1
a5  5  9  5  9  2  1

In [101]: group_duplicate_cols(df)
Out[101]: [['A', 'C'], ['B', 'D']]

# Let's add one more duplicate into group containing 'A'
In [102]: df.F = df.A

In [103]: group_duplicate_cols(df)
Out[103]: [['A', 'C', 'F'], ['B', 'D']]
</code>```

Converting to do the same, but for rows(index), we just need to switch the operations along the other axis, like so -

```<code>def group_duplicate_rows(df):
    a = df.values
    sidx = np.lexsort(a.T)
    b = a[sidx]

    m = np.concatenate(([False], (b[1:] == b[:-1]).all(1), [False] ))
    idx = np.flatnonzero(m[1:] != m[:-1])
    C = df.index[sidx].tolist()
    return [C[i:j] for i,j in zip(idx[::2],idx[1::2]+1)]
</code>```

Sample run -

```<code>In [260]: df2
Out[260]:
   a1  a2  a3  a4  a5
A   3   5   3   4   5
B   1   1   1   1   1
C   3   5   3   4   5
D   2   9   2   1   9
E   2   2   2   1   2
F   1   1   1   1   1

In [261]: group_duplicate_rows(df2)
Out[261]: [['B', 'F'], ['A', 'C']]
</code>```

Benchmarking

Approaches -

```<code># @John Galt's soln-1
from itertools import combinations
def combinations_app(df):
    return[x for x in combinations(df.columns, 2) if (df[x[0]] == df[x[-1]]).all()]

# @Abdou's soln
def pandas_groupby_app(df):
    return [tuple(d.index) for _,d in df.T.groupby(list(df.T.columns)) if len(d) > 1]

# @COLDSPEED's soln
def triu_app(df):
    c = df.columns.tolist()
    i, j = np.triu_indices(len(c), 1)
    x = [(c[_i], c[_j]) for _i, _j in zip(i, j) if (df[c[_i]] == df[c[_j]]).all()]
    return x

# @cmaher's soln
def lambda_set_app(df):
    return list(filter(lambda x: len(x) > 1, list(set([tuple([x for x in df.columns if all(df[x] == df[y])]) for y in df.columns]))))
</code>```

Note : @John Galt's soln-2 wasn't included because the inputs being of size (8000,500) would blow up with the proposed broadcasting for that one.

Timings -

```<code>In [179]: # Setup inputs with sizes as mentioned in the question
     ...: df = pd.DataFrame(np.random.randint(0,10,(8000,500)))
     ...: df.columns = ['C'+str(i) for i in range(df.shape[1])]
     ...: idx0 = np.random.choice(df.shape[1], df.shape[1]//2,replace=0)
     ...: idx1 = np.random.choice(df.shape[1], df.shape[1]//2,replace=0)
     ...: df.iloc[:,idx0] = df.iloc[:,idx1].values
     ...:

# @John Galt's soln-1
In [180]: %timeit combinations_app(df)
1 loops, best of 3: 24.6 s per loop

# @Abdou's soln
In [181]: %timeit pandas_groupby_app(df)
1 loops, best of 3: 3.81 s per loop

# @COLDSPEED's soln
In [182]: %timeit triu_app(df)
1 loops, best of 3: 25.5 s per loop

# @cmaher's soln
In [183]: %timeit lambda_set_app(df)
1 loops, best of 3: 27.1 s per loop

# Proposed in this post
In [184]: %timeit group_duplicate_cols(df)
10 loops, best of 3: 188 ms per loop
</code>```

Super boost with NumPy's view functionality

Leveraging NumPy's view functionality that lets us view each group of elements as one dtype, we could gain further noticeable performance boost, like so -

```<code>def view1D(a): # a is array
    a = np.ascontiguousarray(a)
    void_dt = np.dtype((np.void, a.dtype.itemsize * a.shape[1]))
    return a.view(void_dt).ravel()

def group_duplicate_cols_v2(df):
    a = df.values
    sidx = view1D(a.T).argsort()
    b = a[:,sidx]

    m = np.concatenate(([False], (b[:,1:] == b[:,:-1]).all(0), [False] ))
    idx = np.flatnonzero(m[1:] != m[:-1])
    C = df.columns[sidx].tolist()
    return [C[i:j] for i,j in zip(idx[::2],idx[1::2]+1)]
</code>```

Timings -

```<code>In [322]: %timeit group_duplicate_cols(df)
10 loops, best of 3: 185 ms per loop

In [323]: %timeit group_duplicate_cols_v2(df)
10 loops, best of 3: 69.3 ms per loop
</code>```

Just crazy speedups!

Body:
Now there are a lot of similar questions but most of them answer how to delete the duplicate columns. However, I want to know how can I make a list of tuples where each tuple contains the column names of duplicate columns. I am assuming that each column has a unique name. Just to further illustrate my question:

df = pd.DataFrame({'A': [1, 2, 3, 4, 5],'B': [2, 4, 2, 1, 9],
                   'C': [1, 2, 3, 4, 5],'D': [2, 4, 2, 1, 9],
                   'E': [3, 4, 2, 1, 2],'F': [1, 1, 1, 1, 1]},
                   index = ['a1', 'a2', 'a3', 'a4', 'a5'])

then I want the output:

[('A', 'C'), ('B', 'D')]

And if you are feeling great today then also extend the same question to rows. How to get a list of tuples where each tuple contains duplicate rows.

Body:
Here's one NumPy approach -

def group_duplicate_cols(df):
    a = df.values
    sidx = np.lexsort(a)
    b = a[:,sidx]

    m = np.concatenate(([False], (b[:,1:] == b[:,:-1]).all(0), [False] ))
    idx = np.flatnonzero(m[1:] != m[:-1])
    C = df.columns[sidx].tolist()
    return [C[i:j] for i,j in zip(idx[::2],idx[1::2]+1)]

Sample runs -

In [100]: df
Out[100]:
    A  B  C  D  E  F
a1  1  2  1  2  3  1
a2  2  4  2  4  4  1
a3  3  2  3  2  2  1
a4  4  1  4  1  1  1
a5  5  9  5  9  2  1

In [101]: group_duplicate_cols(df)
Out[101]: [['A', 'C'], ['B', 'D']]

# Let's add one more duplicate into group containing 'A'
In [102]: df.F = df.A

In [103]: group_duplicate_cols(df)
Out[103]: [['A', 'C', 'F'], ['B', 'D']]

Converting to do the same, but for rows(index), we just need to switch the operations along the other axis, like so -

def group_duplicate_rows(df):
    a = df.values
    sidx = np.lexsort(a.T)
    b = a[sidx]

    m = np.concatenate(([False], (b[1:] == b[:-1]).all(1), [False] ))
    idx = np.flatnonzero(m[1:] != m[:-1])
    C = df.index[sidx].tolist()
    return [C[i:j] for i,j in zip(idx[::2],idx[1::2]+1)]

Sample run -

In [260]: df2
Out[260]:
   a1  a2  a3  a4  a5
A   3   5   3   4   5
B   1   1   1   1   1
C   3   5   3   4   5
D   2   9   2   1   9
E   2   2   2   1   2
F   1   1   1   1   1

In [261]: group_duplicate_rows(df2)
Out[261]: [['B', 'F'], ['A', 'C']]

Benchmarking

Approaches -

# @John Galt's soln-1
from itertools import combinations
def combinations_app(df):
    return[x for x in combinations(df.columns, 2) if (df[x[0]] == df[x[-1]]).all()]

# @Abdou's soln
def pandas_groupby_app(df):
    return [tuple(d.index) for _,d in df.T.groupby(list(df.T.columns)) if len(d) > 1]

# @COLDSPEED's soln
def triu_app(df):
    c = df.columns.tolist()
    i, j = np.triu_indices(len(c), 1)
    x = [(c[_i], c[_j]) for _i, _j in zip(i, j) if (df[c[_i]] == df[c[_j]]).all()]
    return x

# @cmaher's soln
def lambda_set_app(df):
    return list(filter(lambda x: len(x) > 1, list(set([tuple([x for x in df.columns if all(df[x] == df[y])]) for y in df.columns]))))

Note : @John Galt's soln-2 wasn't included because the inputs being of size (8000,500) would blow up with the proposed broadcasting for that one.

Timings -

In [179]: # Setup inputs with sizes as mentioned in the question
     ...: df = pd.DataFrame(np.random.randint(0,10,(8000,500)))
     ...: df.columns = ['C'+str(i) for i in range(df.shape[1])]
     ...: idx0 = np.random.choice(df.shape[1], df.shape[1]//2,replace=0)
     ...: idx1 = np.random.choice(df.shape[1], df.shape[1]//2,replace=0)
     ...: df.iloc[:,idx0] = df.iloc[:,idx1].values
     ...:

# @John Galt's soln-1
In [180]: %timeit combinations_app(df)
1 loops, best of 3: 24.6 s per loop

# @Abdou's soln
In [181]: %timeit pandas_groupby_app(df)
1 loops, best of 3: 3.81 s per loop

# @COLDSPEED's soln
In [182]: %timeit triu_app(df)
1 loops, best of 3: 25.5 s per loop

# @cmaher's soln
In [183]: %timeit lambda_set_app(df)
1 loops, best of 3: 27.1 s per loop

# Proposed in this post
In [184]: %timeit group_duplicate_cols(df)
10 loops, best of 3: 188 ms per loop

Super boost with NumPy's view functionality

Leveraging NumPy's view functionality that lets us view each group of elements as one dtype, we could gain further noticeable performance boost, like so -

def view1D(a): # a is array
    a = np.ascontiguousarray(a)
    void_dt = np.dtype((np.void, a.dtype.itemsize * a.shape[1]))
    return a.view(void_dt).ravel()

def group_duplicate_cols_v2(df):
    a = df.values
    sidx = view1D(a.T).argsort()
    b = a[:,sidx]

    m = np.concatenate(([False], (b[:,1:] == b[:,:-1]).all(0), [False] ))
    idx = np.flatnonzero(m[1:] != m[:-1])
    C = df.columns[sidx].tolist()
    return [C[i:j] for i,j in zip(idx[::2],idx[1::2]+1)]

Timings -

In [322]: %timeit group_duplicate_cols(df)
10 loops, best of 3: 185 ms per loop

In [323]: %timeit group_duplicate_cols_v2(df)
10 loops, best of 3: 69.3 ms per loop

Just crazy speedups!


问:
Restart Delphi Application Programmatically
It should not be possible to run multiple instances of my application. Therefore the project source contains:

```<code>CreateMutex (nil, False, PChar (ID));
if (GetLastError = ERROR_ALREADY_EXISTS) then
  Halt;
</code>```

Now I want to restart my application programmatically. The usual way would be:

```<code>AppName := PChar(Application.ExeName) ;
ShellExecute(Handle,'open', AppName, nil, nil, SW_SHOWNORMAL) ;
Application.Terminate;
</code>```

But this won't work in my case because of the mutex. Even if I release the mutex before starting the second instace it won't work because shutdown takes some time and two instance cannot run in parallel (because of common resources and other effects).

Is there a way to restart an application with such characteristics? (If possible without an additional executable)

Thanks in advance.

答: Perhaps you should think outside the box. Instead of futzing with the mutex / instance logic, you could simply create another executable that waits for your app to close then starts it again. As an added bonus, you can later use this mechanism to, for example, update some of your main app's binaries. It's also much easier to run it elevated instead of maintaining different integrity levels inside the same app, etc.

Body:
It should not be possible to run multiple instances of my application. Therefore the project source contains:

CreateMutex (nil, False, PChar (ID));
if (GetLastError = ERROR_ALREADY_EXISTS) then
  Halt;

Now I want to restart my application programmatically. The usual way would be:

AppName := PChar(Application.ExeName) ;
ShellExecute(Handle,'open', AppName, nil, nil, SW_SHOWNORMAL) ;
Application.Terminate;

But this won't work in my case because of the mutex. Even if I release the mutex before starting the second instace it won't work because shutdown takes some time and two instance cannot run in parallel (because of common resources and other effects).

Is there a way to restart an application with such characteristics? (If possible without an additional executable)

Thanks in advance.


问:
Google Chrome extension to display url of current tab by click of button
I would simply like to display the URL of the current tab that I am in by clicking a button from my chrome extension. I tried using alert() in popup.js but it is not working. I am new to javascript and chrome extensions so please have mercy :)

The popup.html code is:

```<code><!doctype html>
<html>

<head>
    <title>Save URL</title>
    <script src="popup.js"></script>
</head>

<body>
    <h2> FYDP: Save Current Tab URL </h2>
    <button id="Get URL"> Get the URL of this page! </button>
</body>

</html>
</code>```

The popup.js code is:

```<code>    function getCurrentTabUrl(callback) {

    var queryInfo = {
        active: true,
        currentWindow: true
    };

    chrome.tabs.query(queryInfo, function(tabs) {

        var tab = tabs[0];

        var url = tab.url;
        document.getElementById("Get URL").onclick = alert(url);

        console.assert(typeof url == 'string', 'tab.url should be a string');

        callback(url);
    });
}
</code>```

The manifest.json code is:

```<code>{
    "manifest_version": 2,

    "name": "Save URL",
    "description": "This extension saves the URL of the current tab in a
    variable ",
    "version": "1.0",

    "browser_action": {
        "default_icon": "icon.png",
        "default_popup": "popup.html",
        "default_title": "Click here!"
    },
    "permissions": [
        "activeTab"
    ]
}
</code>```

答:
You actually can't display alerts from javascript events in chrome extension popups (see this other stack overflow post for more info). But in case you were curious what it would look like if you could, here's what it'd be (I changed a couple things in your code):

ids can't have spaces in them, so I changed the button's id to get-url

You have to register the event listener on the button, you were registering it in a function that was never called so the listener was never added

I moved the script to the end of the  because you're using querySelector, and script tags are executed in-line, which means that only elements that are before the script tag are rendered yet. That is to say, you have to have the script tag after the button tag

I added the tabs permission to the manifest-- you need it to query all tabs

popup.js:

```<code>function getCurrentTabUrl() {
  var queryInfo = {
    active: true,
    currentWindow: true,
  }

  chrome.tabs.query(queryInfo, function(tabs) {
    var tab = tabs[0]
    alert(tab.url)
  })
}

document.querySelector('#get-url').addEventListener('click', getCurrentTabUrl)
</code>```

popup.html:

```<code><html>
  <head>
    <title>Save URL</title>
  </head>

  <body>
    <h2> FYDP: Save Current Tab URL </h2>
    <button id="get-url"> Get the URL of this page!</button>
    <script src="popup.js"></script>
  </body>
</html>
</code>```

manifest.json:

```<code>{
  "manifest_version": 2,

  "name": "Save URL",
  "description": "This extension saves the URL of the current tab in a variable",
  "version": "1.0",

  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html",
    "default_title": "Click here!"
  },

  "permissions": [
    "activeTab",
    "tabs"
  ]
}
</code>```

Body:
I would simply like to display the URL of the current tab that I am in by clicking a button from my chrome extension. I tried using alert() in popup.js but it is not working. I am new to javascript and chrome extensions so please have mercy :)

The popup.html code is:

<!doctype html>

    <title>Save URL</title>

 FYDP: Save Current Tab URL

    <button id="Get URL"> Get the URL of this page! </button>

The popup.js code is:

    function getCurrentTabUrl(callback) {

    var queryInfo = {
        active: true,
        currentWindow: true
    };

    chrome.tabs.query(queryInfo, function(tabs) {

        var tab = tabs[0];

        var url = tab.url;
        document.getElementById("Get URL").onclick = alert(url);

        console.assert(typeof url == 'string', 'tab.url should be a string');

        callback(url);
    });
}

The manifest.json code is:

{
    "manifest_version": 2,

    "name": "Save URL",
    "description": "This extension saves the URL of the current tab in a
    variable ",
    "version": "1.0",

    "browser_action": {
        "default_icon": "icon.png",
        "default_popup": "popup.html",
        "default_title": "Click here!"
    },
    "permissions": [
        "activeTab"
    ]
}

Body:
You actually can't display alerts from javascript events in chrome extension popups (see this other stack overflow post for more info). But in case you were curious what it would look like if you could, here's what it'd be (I changed a couple things in your code):

ids can't have spaces in them, so I changed the button's id to get-url

You have to register the event listener on the button, you were registering it in a function that was never called so the listener was never added

I moved the script to the end of the <body> because you're using querySelector, and script tags are executed in-line, which means that only elements that are before the script tag are rendered yet. That is to say, you have to have the script tag after the button tag

I added the tabs permission to the manifest-- you need it to query all tabs

popup.js:

function getCurrentTabUrl() {
  var queryInfo = {
    active: true,
    currentWindow: true,
  }

  chrome.tabs.query(queryInfo, function(tabs) {
    var tab = tabs[0]
    alert(tab.url)
  })
}

document.querySelector('#get-url').addEventListener('click', getCurrentTabUrl)

popup.html:

<html>
  <head>
    <title>Save URL</title>
  </head>

  <body>
    <h2> FYDP: Save Current Tab URL </h2>
    <button id="get-url"> Get the URL of this page!</button>
    <script src="popup.js"></script>
  </body>
</html>

manifest.json:

{
  "manifest_version": 2,

  "name": "Save URL",
  "description": "This extension saves the URL of the current tab in a variable",
  "version": "1.0",

  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html",
    "default_title": "Click here!"
  },

  "permissions": [
    "activeTab",
    "tabs"
  ]
}


问:
How to combine two boost::filesystem::path's?
I need to combine an absolute path A with path B, given that B may be relative as well as absolute, preferably using boost::filesystem.

In other words, I want to have:

/usr/home/ + abc = /usr/home/abc

/usr/home/ + ../abc = /usr/home/../abc (or, even better /usr/abc - this is not my question)

/usr/home/ + /abc = /abc

The first two are easy with the / operator but I can't get the third one to work.

I tried:

```<code>std::cout << boost::filesystem::path("/usr/home/") / "/abc";
</code>```

Prints /usr/home//abc.

```<code>std::cout << boost::filesystem::path("/usr/home/") + "/abc";
</code>```

Still prints /usr/home//abc.

Of course I can "see" when path B is absolute by looking at it and just use that, but I don't want to hardcode the check for the leading / because on Windows it can be different (e.g. C:\\ or \\).

答:
If you are looking to make a relative path absolute with respect to some  directory (often the current working directory), there is a function to do this:

http://www.boost.org/doc/libs/1_64_0/libs/filesystem/doc/reference.html#absolute

see also canonical

Body:
I need to combine an absolute path A with path B, given that B may be relative as well as absolute, preferably using boost::filesystem.

In other words, I want to have:

/usr/home/ + abc = /usr/home/abc

/usr/home/ + ../abc = /usr/home/../abc (or, even better /usr/abc - this is not my question)

/usr/home/ + /abc = /abc

The first two are easy with the / operator but I can't get the third one to work.

I tried:

std::cout << boost::filesystem::path("/usr/home/") / "/abc";

Prints /usr/home//abc.

std::cout << boost::filesystem::path("/usr/home/") + "/abc";

Still prints /usr/home//abc.

Of course I can "see" when path B is absolute by looking at it and just use that, but I don't want to hardcode the check for the leading / because on Windows it can be different (e.g. C:\\ or \\).


问:
Android create object of one of the similar classes
I have two classes that do the same things but by the different ways. I need to create an object of one of these classes depending on config settings. Here is a brief example of what do I want to do.

```<code>public class A {
    public string getLetter() {
        return "A";
    }
}
public class B {
    public string getLetter() {
        return "B";
    }
}

public class MainActivity {
    private myObject; // How to declare it in my case?
    private int config = 0;

    public void onCreate(Bundle savedInstanceState) {
        if (config == 0) {
            myObject = new A();
        } else {
            myObject = new B();
        }
        String letter = myObject.getLetter();
    }
}
</code>```

Actually everything is much more complex. Each of classes A and B asynchronously listens to the different sources of data, converts it to the format that can be used in further processing and passes it to MainActivity. Depending on configuration only one source of data must be selected. How can I do this? Variant with

```<code>letter = A.getLetter();
</code>```

will not work.

答:
This should work:</p>

```<code>public class A {
    public String getLetter() {
        return "A";
    }
}
public class B {
    public String getLetter() {
        return "B";
    }
}

public class MainActivity {

    private int config = 0;

    public void onCreate(Bundle savedInstanceState) {

        String letter="";
        if (config == 0) {
            A myObject = new A();
            letter = myObject.getLetter();
        } else {
           B myObject = new B();
             letter = myObject.getLetter();
        }

    }
}
</code>```

Body:
I have two classes that do the same things but by the different ways. I need to create an object of one of these classes depending on config settings. Here is a brief example of what do I want to do.

public class A {
    public string getLetter() {
        return "A";
    }
}
public class B {
    public string getLetter() {
        return "B";
    }
}

public class MainActivity {
    private myObject; // How to declare it in my case?
    private int config = 0;

    public void onCreate(Bundle savedInstanceState) {
        if (config == 0) {
            myObject = new A();
        } else {
            myObject = new B();
        }
        String letter = myObject.getLetter();
    }
}

Actually everything is much more complex. Each of classes A and B asynchronously listens to the different sources of data, converts it to the format that can be used in further processing and passes it to MainActivity. Depending on configuration only one source of data must be selected. How can I do this? Variant with

letter = A.getLetter();

will not work.

Body:
This should work:

public class A {
    public String getLetter() {
        return "A";
    }
}
public class B {
    public String getLetter() {
        return "B";
    }
}

public class MainActivity {

    private int config = 0;

    public void onCreate(Bundle savedInstanceState) {

        String letter="";
        if (config == 0) {
            A myObject = new A();
            letter = myObject.getLetter();
        } else {
           B myObject = new B();
             letter = myObject.getLetter();
        }

    }
}


问:
Python: Inconsistent importing behavior for "import package1.module1"?
I was assuming that statements of the form

import package1.module1

were only for packages and modules, but not for an object in a module, so for instance if module1 contains variable1, I am not able to do

import package1.module1.variable1

Here's the perceived inconsistency: assume that module1 and variable1 have the same name, for instance let's say both are called module1. And, in the __init__.py of package1 I have

from .module1 import module1

then doing

import package1.module1

will import the object module1, not the module module1.
This only works if module1 is the same name for both the object and the module.

答:
The official explanation can be found in the docs:

The import statement first tests whether the item is defined in the package; if not, it assumes it is a module and attempts to load it. If it fails to find it, an ImportError exception is raised.

It seems that import appears to think the object module1 from the module module1 is a module, which is why the import package1.module1 works but yields the object instead.

As far as a workaround goes, if you try the from _ import _ as x, that will rename the attribute and get around the name shadowing. It should yield the result you're looking for - a path import of the module module1 (since Python will see type <module>) and not an object import of the variable module1.

Here is some code output to help illustrate things more clearly:

```<code>>>> import package1.module1
>>> print(package1.module1)
<module 'package1.module1' from 'package1/module1.pyc'>
>>> from package1.module1 import module1
>>> print(module1)
1
>>> from package1 import m
>>> print(m)
1
</code>```

Here I did from module1 import module1 as m in the __init__.py of package1 and I set the module1 variable to 1 in module1.py.

Body:
The official explanation can be found in the docs:

The import statement first tests whether the item is defined in the package; if not, it assumes it is a module and attempts to load it. If it fails to find it, an ImportError exception is raised.

It seems that import appears to think the object module1 from the module module1 is a module, which is why the import package1.module1 works but yields the object instead.

As far as a workaround goes, if you try the from _ import _ as x, that will rename the attribute and get around the name shadowing. It should yield the result you're looking for - a path import of the module module1 (since Python will see type <module>) and not an object import of the variable module1.

Here is some code output to help illustrate things more clearly:

>>> import package1.module1
>>> print(package1.module1)
<module 'package1.module1' from 'package1/module1.pyc'>
>>> from package1.module1 import module1
>>> print(module1)
1
>>> from package1 import m
>>> print(m)
1

Here I did from module1 import module1 as m in the __init__.py of package1 and I set the module1 variable to 1 in module1.py.


问:
IOS/Objective-C:Add another variable to a mutableArray
I have a simple array of strings such as the following:

```<code>myArray *NSArray = [NSArray arrayWithObjects: @"chevy", @"ford", @"toyota", nil];
</code>```

I want to add another dimension to the array such as @"1",@"2",@"3" in order to keep track of the order.

Is there a simple way to do this?

Edit

I found answer here.  Create 2nd array and employ loop:

```<code>//For your 2D array
NSMutableArray *secondArray = [[NSMutableArray alloc] initWithCapacity:[homePlayersArray count]];

//populate as required
for(int i=0;i<[homePlayersArray count];i++){
    NSArray *tempArray = [[NSArray alloc] initWithObjects:[homePlayersArray objectAtIndex:i],[NSNumber numberWithInt:0], nil];
    [secondArray addObject:tempArray];
}
</code>```

答:
The most straightforward way to fix this is to create a second array and then loop through the records as suggested in this answer.  For a more complicated way that has some advantages, see CRD's answer.  The other answers do not address the question.  </p>

```<code>//For your 2D array
NSMutableArray *secondArray = [[NSMutableArray alloc] initWithCapacity:[homePlayersArray count]];

//populate as required
for(int i=0;i<[homePlayersArray count];i++){
    NSArray *tempArray = [[NSArray alloc] initWithObjects:[homePlayersArray objectAtIndex:i],[NSNumber numberWithInt:0], nil];
    [secondArray addObject:tempArray];
}
</code>```

Body:
I have a simple array of strings such as the following:

myArray *NSArray = [NSArray arrayWithObjects: @"chevy", @"ford", @"toyota", nil];

I want to add another dimension to the array such as @"1",@"2",@"3" in order to keep track of the order.

Is there a simple way to do this?

Edit

I found answer here.  Create 2nd array and employ loop:

//For your 2D array
NSMutableArray *secondArray = [[NSMutableArray alloc] initWithCapacity:[homePlayersArray count]];

//populate as required
for(int i=0;i<[homePlayersArray count];i++){
    NSArray *tempArray = [[NSArray alloc] initWithObjects:[homePlayersArray objectAtIndex:i],[NSNumber numberWithInt:0], nil];
    [secondArray addObject:tempArray];
}

Body:
The most straightforward way to fix this is to create a second array and then loop through the records as suggested in this answer.  For a more complicated way that has some advantages, see CRD's answer.  The other answers do not address the question.

//For your 2D array
NSMutableArray *secondArray = [[NSMutableArray alloc] initWithCapacity:[homePlayersArray count]];

//populate as required
for(int i=0;i<[homePlayersArray count];i++){
    NSArray *tempArray = [[NSArray alloc] initWithObjects:[homePlayersArray objectAtIndex:i],[NSNumber numberWithInt:0], nil];
    [secondArray addObject:tempArray];
}


问:
Custom animation for tableView.moveRow(at: to:)
I have a UITableView with three sections set up which works as expected.

When a button is tapped, multiple cells at a time will move either between section 0 and 1, or 1 and 2. This all works fine, however the default animation is too fast for my needs. Is it possible to define a custom animation or remove the default animation entirely for...

```<code>tableView.moveRow(at: IndexPath(row: 0, section: 0), to: IndexPath(row: 0, section: 1))
</code>```

I have tried using tableView.insertRows and tableView.deleteRows with their animations set to .none as an alternative, but even then there is still a default animation happening where the rows collapse on top of each other and vanish.

Thanks in advance!

答:
Implement Custom Methods with Custom Animation

The default animations in iOS are triggered using a combination of a delegate method and enumeration values.  The animation is baked into the UITableView component.  To implement your own custom animation, you would need to define your own methods to handle CRUD operations and override the drawRect method to carefully implement your animation, according to your timing needs.  You would also need to handle your own deletion and data source sync, of course.

Consider the Following

On a philosophical note, by deviating from the standard timing, you will be walking away from the standardized iOS experience for this action.  By doing so, your user may gain the sense that your application is less performant.

Body:
I have a UITableView with three sections set up which works as expected.

When a button is tapped, multiple cells at a time will move either between section 0 and 1, or 1 and 2. This all works fine, however the default animation is too fast for my needs. Is it possible to define a custom animation or remove the default animation entirely for...

tableView.moveRow(at: IndexPath(row: 0, section: 0), to: IndexPath(row: 0, section: 1))

I have tried using tableView.insertRows and tableView.deleteRows with their animations set to .none as an alternative, but even then there is still a default animation happening where the rows collapse on top of each other and vanish.

Thanks in advance!


问:
php Add to array that comes from function
I am breaking my head on this all day.
I am work with a Webservice and once I can get the array back one way or I get it back a different  way.
So I have a function that strips and pulls the data fro me.

this is the function.

```<code>function Detail($a){
            $age= array();
            $countArray = arrayCount($a);

        if ($countArray == 1){

                    array_push ($age,
                        array(
                        "Name"=>$a['Name'],
                         "ProductReference"=>$a['ProductReference'],
                          "AdicRange"=>$a['AdicRange'],
                          "Pages"=>$s['Pages']
                          );

            }elseif($countArray >= 2){

         foreach ($a as $key => $d) {

            array_push ($age,
                array(
                "Name"=>$d['Name'],
                 "ProductReference"=>$d['ProductReference'],
                  "AdicRange"=>$d['AdicRange'],
                  "Pages"=>$d['Pages']
                 ) );

             }

            }else{

            }

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

I am trying t add to the array but I get the array back not correct.
This is the array I get back.

```<code>Array
(
    [0] => Array
        (

        )

    [1] => Array
        (
            [0] => Array
                (
                    [Name] => 21X29 booklet Ver
                    [ProductReference] => DF0754(A4)
                    [AdicRange] => 4
                    [Pages] => 24
                )

            [1] => Array
                (
                    [Name] => pro book 35X35
                    [ProductReference] => FM8774
                    [AdicRange] => 2
                    [Pages] => 20
                )

            [2] => Array
                (
                    [Name] => pro book 26X10
                    [ProductReference] => FM1032
                    [AdicRange] => 2
                    [Pages] => 20
                )

            [3] => Array
                (
                    [Name] => 21X29 booklet Hor
                    [ProductReference] => DF0750
                    [AdicRange] => 4
                    [Pages] => 24
                )

            [4] => Array
                (
                    [Name] => pro book 35X35
                    [ProductReference] => FM8755
                    [AdicRange] => 2
                    [Pages] => 20
                )

            [5] => Array
                (
                    [Name] => pro book 38X76
                    [ProductReference] => FM0099
                    [AdicRange] => 2
                    [Pages] => 50
                )

            [6] => Array
                (
                    [Name] => pro book 40X80
                    [ProductReference] => FM7291
                    [AdicRange] => 2
                    [Pages] => 20
                )

            [7] => Array
                (
                    [Name] => pro book 30X80
                    [ProductReference] => FM0058
                    [AdicRange] => 2
                    [Pages] => 20
                )

            [8] => Array
                (
                    [Name] => pro book 20X60
                    [ProductReference] => FM1065
                    [AdicRange] => 2
                    [Pages] => 20
                )

        )
)
</code>```

Can some one please Help me.

I am trying to get the array back like this.

```<code>Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [Name] => pro book 40X80
                    [ProductReference] => FM7291
                    [AdicRange] => 2
                    [Pages] =>
                )

        )

    [1] => Array
        (
            [0] => Array
                (
                    [Name] => 21X29 booklet Ver
                    [ProductReference] => DF0754(A4)
                    [AdicRange] => 4
                    [Pages] => 24
                )

            [1] => Array
                (
                    [Name] => pro book 35X35
                    [ProductReference] => FM8774
                    [AdicRange] => 2
                    [Pages] => 20
                )

            [2] => Array
                (
                    [Name] => pro book 26X10
                    [ProductReference] => FM1032
                    [AdicRange] => 2
                    [Pages] => 20
                )

            [3] => Array
                (
                    [Name] => 21X29 booklet Hor
                    [ProductReference] => DF0750
                    [AdicRange] => 4
                    [Pages] => 24
                )

            [4] => Array
                (
                    [Name] => pro book 35X35
                    [ProductReference] => FM8755
                    [AdicRange] => 2
                    [Pages] => 20
                )

            [5] => Array
                (
                    [Name] => pro book 38X76
                    [ProductReference] => FM0099
                    [AdicRange] => 2
                    [Pages] => 50
                )

            [6] => Array
                (
                    [Name] => pro book 40X80
                    [ProductReference] => FM7291
                    [AdicRange] => 2
                    [Pages] => 20
                )

            [7] => Array
                (
                    [Name] => pro book 30X80
                    [ProductReference] => FM0058
                    [AdicRange] => 2
                    [Pages] => 20
                )

            [8] => Array
                (
                    [Name] => pro book 20X60
                    [ProductReference] => FM1065
                    [AdicRange] => 2
                    [Pages] => 20
                )
         [9] => Array
                (
                    [Name] => pro book 40X80
                    [ProductReference] => FM7291
                    [AdicRange] => 2
                    [Pages] =>
                )
        )
)
</code>```

答:
You were missing a closing parenthesis within your first if clause.    </p>

```<code>function Detail($a) {
$age = array();
$countArray = arrayCount($a);

if ($countArray == 0) {

    array_push ($age,
    array(
    "Name" => $a['Name'],
    "ProductReference" => $a['ProductReference'],
    "AdicRange" => $a['AdicRange'],
    "Pages" => $s['Pages']
    ));
} elseif ($countArray >= 1) {

    foreach ($a as $key => $d) {

        array_push($age, array(
            "Name" => $d['Name'],
            "ProductReference" => $d['ProductReference'],
            "AdicRange" => $d['AdicRange'],
            "Pages" => $d['Pages']
        ));
    }
} else {

}

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

Body:
I am breaking my head on this all day.
I am work with a Webservice and once I can get the array back one way or I get it back a different  way.
So I have a function that strips and pulls the data fro me.

this is the function.

function Detail($a){
            $age= array();
            $countArray = arrayCount($a);

        if ($countArray == 1){

                    array_push ($age,
                        array(
                        "Name"=>$a['Name'],
                         "ProductReference"=>$a['ProductReference'],
                          "AdicRange"=>$a['AdicRange'],
                          "Pages"=>$s['Pages']
                          );

            }elseif($countArray >= 2){

         foreach ($a as $key => $d) {

            array_push ($age,
                array(
                "Name"=>$d['Name'],
                 "ProductReference"=>$d['ProductReference'],
                  "AdicRange"=>$d['AdicRange'],
                  "Pages"=>$d['Pages']
                 ) );

             }

            }else{

            }

        return $age;
        }

I am trying t add to the array but I get the array back not correct.
This is the array I get back.

Array
(
    [0] => Array
        (

        )

    [1] => Array
        (
            [0] => Array
                (
                    [Name] => 21X29 booklet Ver
                    [ProductReference] => DF0754(A4)
                    [AdicRange] => 4
                    [Pages] => 24
                )

            [1] => Array
                (
                    [Name] => pro book 35X35
                    [ProductReference] => FM8774
                    [AdicRange] => 2
                    [Pages] => 20
                )

            [2] => Array
                (
                    [Name] => pro book 26X10
                    [ProductReference] => FM1032
                    [AdicRange] => 2
                    [Pages] => 20
                )

            [3] => Array
                (
                    [Name] => 21X29 booklet Hor
                    [ProductReference] => DF0750
                    [AdicRange] => 4
                    [Pages] => 24
                )

            [4] => Array
                (
                    [Name] => pro book 35X35
                    [ProductReference] => FM8755
                    [AdicRange] => 2
                    [Pages] => 20
                )

            [5] => Array
                (
                    [Name] => pro book 38X76
                    [ProductReference] => FM0099
                    [AdicRange] => 2
                    [Pages] => 50
                )

            [6] => Array
                (
                    [Name] => pro book 40X80
                    [ProductReference] => FM7291
                    [AdicRange] => 2
                    [Pages] => 20
                )

            [7] => Array
                (
                    [Name] => pro book 30X80
                    [ProductReference] => FM0058
                    [AdicRange] => 2
                    [Pages] => 20
                )

            [8] => Array
                (
                    [Name] => pro book 20X60
                    [ProductReference] => FM1065
                    [AdicRange] => 2
                    [Pages] => 20
                )

        )
)

Can some one please Help me.

I am trying to get the array back like this.

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [Name] => pro book 40X80
                    [ProductReference] => FM7291
                    [AdicRange] => 2
                    [Pages] =>
                )

        )

    [1] => Array
        (
            [0] => Array
                (
                    [Name] => 21X29 booklet Ver
                    [ProductReference] => DF0754(A4)
                    [AdicRange] => 4
                    [Pages] => 24
                )

            [1] => Array
                (
                    [Name] => pro book 35X35
                    [ProductReference] => FM8774
                    [AdicRange] => 2
                    [Pages] => 20
                )

            [2] => Array
                (
                    [Name] => pro book 26X10
                    [ProductReference] => FM1032
                    [AdicRange] => 2
                    [Pages] => 20
                )

            [3] => Array
                (
                    [Name] => 21X29 booklet Hor
                    [ProductReference] => DF0750
                    [AdicRange] => 4
                    [Pages] => 24
                )

            [4] => Array
                (
                    [Name] => pro book 35X35
                    [ProductReference] => FM8755
                    [AdicRange] => 2
                    [Pages] => 20
                )

            [5] => Array
                (
                    [Name] => pro book 38X76
                    [ProductReference] => FM0099
                    [AdicRange] => 2
                    [Pages] => 50
                )

            [6] => Array
                (
                    [Name] => pro book 40X80
                    [ProductReference] => FM7291
                    [AdicRange] => 2
                    [Pages] => 20
                )

            [7] => Array
                (
                    [Name] => pro book 30X80
                    [ProductReference] => FM0058
                    [AdicRange] => 2
                    [Pages] => 20
                )

            [8] => Array
                (
                    [Name] => pro book 20X60
                    [ProductReference] => FM1065
                    [AdicRange] => 2
                    [Pages] => 20
                )
         [9] => Array
                (
                    [Name] => pro book 40X80
                    [ProductReference] => FM7291
                    [AdicRange] => 2
                    [Pages] =>
                )
        )
)

Body:
You were missing a closing parenthesis within your first if clause.

function Detail($a) {
$age = array();
$countArray = arrayCount($a);

if ($countArray == 0) {

    array_push ($age,
    array(
    "Name" => $a['Name'],
    "ProductReference" => $a['ProductReference'],
    "AdicRange" => $a['AdicRange'],
    "Pages" => $s['Pages']
    ));
} elseif ($countArray >= 1) {

    foreach ($a as $key => $d) {

        array_push($age, array(
            "Name" => $d['Name'],
            "ProductReference" => $d['ProductReference'],
            "AdicRange" => $d['AdicRange'],
            "Pages" => $d['Pages']
        ));
    }
} else {

}

return $age;
}


问:
How to play the iPod Library file in the AVPlayer
How can I get an ipod library music file into AVAudioPlayer? </p>

答:
```<code>- (void)mediaPicker:(MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection {
    NSURL *url = [[mediaItemCollection.items objectAtIndex:0] valueForProperty:MPMediaItemPropertyAssetURL];

    NSError *error;
    self.player = [[AVAudioPlayer alloc] url error:&error];

    if (!error) {
        [self.player prepareToPlay];
        [self.player play];
    }

    [mediaPicker dismissModalViewControllerAnimated:YES];
}
</code>```


问:
TypeScript: can't disable type definitions for one special library

TypeScript Version:  2.4.1

For example I want to consume a library from npm called awesome-lib. This library already ships with a TypeScript type definition but this one is outdated and buggy. The author of the library doesn't update this one.

I've tried to disable that type definition completely in my own declarations.d.ts file in my project:

```<code>declare module 'awesome-lib';
</code>```

Unfortunately TypeScript reads first the type definition in the library and throws some errors. So it is not possible for me to disable / hide this library for my project.

Does anyone know how to disable type checking for one special library?

答:
Maybe you could try to use require instead of import:

```<code>/* tslint:disable:no-var-requires */
const awesomeLib: any = require("awesome-lib");
/* tslint:enable:no-var-requires */
</code>```

the downside is you have no type checking nor intellisense.

Body:
TypeScript Version:  2.4.1

For example I want to consume a library from npm called awesome-lib. This library already ships with a TypeScript type definition but this one is outdated and buggy. The author of the library doesn't update this one.

I've tried to disable that type definition completely in my own declarations.d.ts file in my project:

declare module 'awesome-lib';

Unfortunately TypeScript reads first the type definition in the library and throws some errors. So it is not possible for me to disable / hide this library for my project.

Does anyone know how to disable type checking for one special library?

Body:
Maybe you could try to use require instead of import:

/* tslint:disable:no-var-requires */
const awesomeLib: any = require("awesome-lib");
/* tslint:enable:no-var-requires */

the downside is you have no type checking nor intellisense.


问:
Does upstream branch have be a remote branch?
I ran below 2 commands successfully. So it leads me to think an upstream branch is not necessarily a remote branch. So what good is a local upstream branch?

```<code>$ git branch local_branch5 --set-upstream origin/branch5
Branch local_branch5 set up to track remote branch branch5 from origin.

$ git branch local_branch6 --set-upstream local_branch3
Branch local_branch6 set up to track local branch local_branch3.
</code>```

My branchs look like this:

```<code>$ git branch -vv
  local_branch3          a758e52 Initial commit
* local_branch4          db11990 Update README.md
  local_branch5          ce0762c [origin/branch5] change on local_branch2
  local_branch6          a758e52 [local_branch3] Initial commit
  master                 064aa08 [origin/master: ahead 1] change on local master
</code>```

ADD 1

As I tested, it seems the so-called upstream just create a relation between 2 branches/named commits. These branches can be both local or one local one remote. Only need to note that when push to a local upstream, the repo needs to be ..

答:
You are correct, local branches can have other local branches as their upstream setting.  I'd reword your "ADD 1" section to say that it's the remote part of the setting that must be . for the upstream to be another ordinary, i.e., local, branch.

See how do I get git to show me which branches are tracking what? for a related question and various answers.

You can ignore all of the below.  It's not really part of the answer, it just explains how we got here, and why some of the quirks are they way they are.

Deeper history / Git magic

It's also worth noting that only local branches have an upstream, and that this upstream setting is configured, at a very low level, in two parts.  One of these two, though, uses a third part, even though in normal setups this third part is pretty much invisible.  The reason for this is historic, going back to Git versions that were in use before 2007 or so.

If you look at your per-repository configuration—the file .git/config, or the output from git config --list --local—you will see  text like this:

```<code>$ git config --list --local
[snip]
remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*
[snip]
branch.master.remote=origin
branch.master.merge=refs/heads/master
</code>```

This means that (local) branch master has origin/master as its upstream.  The two parts are branch.master.remote, which tell Git which remote to use, and branch.master.merge, which appears to refer back to your own local master again.  What's up with that?

Before remote-tracking branches existed

The answer lies in the fact that Git's remote-tracking branches themselves did not exist in very early—prehistoric, as it were—Git.  Back in the bad old days, your Git did not remember for you the state of some other Git's repository.

When you connected to some other (upstream) Git and pulled commits from them, you would, in effect, go fetch commits from their master branch.  That is, in fact, still what happens today.  Your Git would drop this information into a file, .git/FETCH_HEAD, saying: "when I looked at <url>, I found a branch named master with commit b06d364...".  Your Git still does this today, too.  But then your Git would just stop: the FETCH_HEAD stuff was all you got.

So, at this point you had two master-s: yours, and theirs.  Both are just named master.  Your Git would then have to rebase or merge your commits right away, before your FETCH_HEAD contents were overwritten by any other different upstream's results.  This meant your Git needed to know that when you wanted to rebase or merge with your upstream, it should go get their master, and then rebase or merge your master using the information in .git/FETCH_HEAD under the name master.

Thus, the branch.master.* settings come in two parts: remote = origin—this used to be just a raw URL—and then merge = master.  The assumption back then was, and still is today, that the action should be to merge, even though rebase is arguably a better default.  The pull script would fetch from the URL, then use the contents of .git/FETCH_HEAD to get a commit hash for merging:

```<code>$ head -3 .git/FETCH_HEAD | sed 's,git://.*,<url>,'
b06d3643105c8758ed019125a4399cb7efdcce2c                branch 'master' of <url>
95d67879735cfecfdd85f89e59d993c5b4de8835        not-for-merge   branch 'maint' of <url>
4ebf3021692df4cb51da8d806fbb8b909ee7e111        not-for-merge   branch 'next' of <url>
</code>```

Note how some of these—in fact, all but one—have the string not-for-merge in them.  That's a hint to the original git pull script: only the master line is meant for use in merging.

Enter remotes

It was soon obvious to early Git users that it was nice to use a shorter name than a full URL, especially if you had several different other Git repositories from which you would frequently pull good work.  Instead of typing in protocol://some.university.ac.uk/long/path/to/brians/repo, you could just say brian.

The exact mechanism for this was apparently somewhat of a contest, or was invented independently multiple times in different ways.  I was not in on this particular bit of history myself, but traces linger even today in the git fetch documentation, under the section named remotes:

The name of one of the following can be used instead of a URL as <repository> argument:

a remote in the Git configuration file: $GIT_DIR/config,

a file in the $GIT_DIR/remotes directory, or

a file in the $GIT_DIR/branches directory.

Remote-tracking branches

The first option "won" and is what people actually use today.  (The other two are still supported.  I don't know why—they seem like they could have been deprecated and then dropped some time ago.)

Because the first option won, though, we can move on to the configured remote-tracking branches section of this same documentation:

You often interact with the same remote repository by regularly and repeatedly fetching from it. In order to keep track of the progress of such a remote repository, git fetch allows you to configure remote.<repository>.fetch configuration variables.

Typically such a variable may look like this:

```<code>[remote "origin"]
    fetch = +refs/heads/*:refs/remotes/origin/*
</code>```

This (and the rest of this section) defines how remote-tracking branch names work.  The heart of the idea is that, hey, there's another Git over there somewhere: we run git fetch brian to get Brian's stuff.  Can't we then remember: This is the stuff Brian's Git said he had, the last time we called up his Git?

Of course, we can: we'll do that by changing Brian's master to our brian/master.  The mapping, from Brian's branch names to our remote-tracking names we store in our own Git, comes from this fetch = ... line, which we control.  Each fetch line—there can be more than one—has the form +src:dst, where the leading plus sign—which means the same as --force, more or less—is optional but almost always present, and the left and right sides of the colon give "their names" and "our names" for each of their references that we intend to copy.

It's almost always the case that for remote R, the src part is just refs/heads/* and the dst part begins with refs/remotes/ and then lists the remote-name R itself.  Hence, when we have a remote named brian, the fetch setting is +refs/heads/*:refs/remotes/brian/*.

The two asterisks get matched up: any branch that Brian has (refs/heads/*) get force-copied (+) to our own repository, but renamed into our remote-tracking branch name space (refs/remotes/).  We add another word to make sure that Brian's branches, under our refs/remotes/brian/, don't conflict with Nadia's branches, under our refs/remotes/nadia/.  And then we just copy Brian's (or Nadia's, or origin's) branch name, and that becomes our remote-tracking branch name for this branch.

How this ties in with a local branch's branch@{upstream}

Most local branches have a remote-tracking branch as their upstream setting.  (As this SO question notes, that's not actually required, it's just the usual case.)  But, when local branch B "tracks"—i.e., has as its upstream—remote-tracking branch refs/remotes/origin/B, the configuration entries just say that branch.B.remote is origin and branch.B.merge is B.  There's no explicit refs/remotes/origin/B in there at all!

This is all because of the twisty history (twistory?) above.  Before there were any remote-tracking branches at all, Git's configuration listed the name of the branch as found on the remote.  Branch B "merges with" the origin version of branch B.  Since it was spelled that way back in 2005 or so, Git requires that it still be spelled that way today.  Git then takes the old spelling and maps it through the fetch = line to figure out the correct remote-tracking branch.

Suppose, for instance, that you have branch test with upstream origin/master.  That is, git config --list --local will include:

```<code>remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*
</code>```

(the usual and normal pattern) and:

```<code>branch.test.remote=origin
branch.test.merge=refs/heads/master
</code>```

One could be forgiven for thinking that all Git does is string together the remote name, origin, with the master part of the branch.test.merge=refs/heads/master, to get origin/master.  But in fact, that's not quite what happens.  Let's make another remote, but then change its fetch line:

```<code>git remote add weird <url>
git config remote.weird.fetch '+refs/heads/*:refs/remotes/twisty/*'
</code>```

Now we'll run git fetch weird:

```<code>$ git fetch weird
From <url>
 * [new branch]          maint      -> twisty/maint
 * [new branch]          master     -> twisty/master
 * [new branch]          next       -> twisty/next
 * [new branch]          pu         -> twisty/pu
 * [new branch]          todo       -> twisty/todo
</code>```

Note that they did not go to weird/* but to twisty/*.  We can now make a branch that tracks (has as its upstream) twisty/master:

```<code>$ git checkout -b test --track twisty/master
Branch test set up to track remote branch master from weird.
Switched to a new branch 'test'
$ git rev-parse --symbolic-full-name test@{upstream}
refs/remotes/twisty/master
$ git config --list --local
[snip]
branch.test.remote=weird
branch.test.merge=refs/heads/master
</code>```

The remote is weird and the merge never mentions twisty, yet the upstream really is twisty/master.

Cleaning up

Since I do not really want the test branch and the weird twisty setup, let's clean them up:

```<code>$ git checkout master
...
$ git branch -D test
Deleted branch test (was 8b2efe2a0).
$ git remote remove weird
</code>```

That's all we need to do here: git remote remove weird deletes all the twisty/* remote-tracking branches, because it too obeys the fetch = configuration lines.

Body:
I ran below 2 commands successfully. So it leads me to think an upstream branch is not necessarily a remote branch. So what good is a local upstream branch?

$ git branch local_branch5 --set-upstream origin/branch5
Branch local_branch5 set up to track remote branch branch5 from origin.

$ git branch local_branch6 --set-upstream local_branch3
Branch local_branch6 set up to track local branch local_branch3.

My branchs look like this:

$ git branch -vv
  local_branch3          a758e52 Initial commit
* local_branch4          db11990 Update README.md
  local_branch5          ce0762c [origin/branch5] change on local_branch2
  local_branch6          a758e52 [local_branch3] Initial commit
  master                 064aa08 [origin/master: ahead 1] change on local master

ADD 1

As I tested, it seems the so-called upstream just create a relation between 2 branches/named commits. These branches can be both local or one local one remote. Only need to note that when push to a local upstream, the repo needs to be ..

Body:
You are correct, local branches can have other local branches as their upstream setting.  I'd reword your "ADD 1" section to say that it's the remote part of the setting that must be . for the upstream to be another ordinary, i.e., local, branch.

See how do I get git to show me which branches are tracking what? for a related question and various answers.

You can ignore all of the below.  It's not really part of the answer, it just explains how we got here, and why some of the quirks are they way they are.

Deeper history / Git magic

It's also worth noting that only local branches have an upstream, and that this upstream setting is configured, at a very low level, in two parts.  One of these two, though, uses a third part, even though in normal setups this third part is pretty much invisible.  The reason for this is historic, going back to Git versions that were in use before 2007 or so.

If you look at your per-repository configuration—the file .git/config, or the output from git config --list --local—you will see  text like this:

$ git config --list --local
[snip]
remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*
[snip]
branch.master.remote=origin
branch.master.merge=refs/heads/master

This means that (local) branch master has origin/master as its upstream.  The two parts are branch.master.remote, which tell Git which remote to use, and branch.master.merge, which appears to refer back to your own local master again.  What's up with that?

Before remote-tracking branches existed

The answer lies in the fact that Git's remote-tracking branches themselves did not exist in very early—prehistoric, as it were—Git.  Back in the bad old days, your Git did not remember for you the state of some other Git's repository.

When you connected to some other (upstream) Git and pulled commits from them, you would, in effect, go fetch commits from their master branch.  That is, in fact, still what happens today.  Your Git would drop this information into a file, .git/FETCH_HEAD, saying: "when I looked at <url>, I found a branch named master with commit b06d364...".  Your Git still does this today, too.  But then your Git would just stop: the FETCH_HEAD stuff was all you got.

So, at this point you had two master-s: yours, and theirs.  Both are just named master.  Your Git would then have to rebase or merge your commits right away, before your FETCH_HEAD contents were overwritten by any other different upstream's results.  This meant your Git needed to know that when you wanted to rebase or merge with your upstream, it should go get their master, and then rebase or merge your master using the information in .git/FETCH_HEAD under the name master.

Thus, the branch.master.* settings come in two parts: remote = origin—this used to be just a raw URL—and then merge = master.  The assumption back then was, and still is today, that the action should be to merge, even though rebase is arguably a better default.  The pull script would fetch from the URL, then use the contents of .git/FETCH_HEAD to get a commit hash for merging:

$ head -3 .git/FETCH_HEAD | sed 's,git://.*,<url>,'
b06d3643105c8758ed019125a4399cb7efdcce2c                branch 'master' of <url>
95d67879735cfecfdd85f89e59d993c5b4de8835        not-for-merge   branch 'maint' of <url>
4ebf3021692df4cb51da8d806fbb8b909ee7e111        not-for-merge   branch 'next' of <url>

Note how some of these—in fact, all but one—have the string not-for-merge in them.  That's a hint to the original git pull script: only the master line is meant for use in merging.

Enter remotes

It was soon obvious to early Git users that it was nice to use a shorter name than a full URL, especially if you had several different other Git repositories from which you would frequently pull good work.  Instead of typing in protocol://some.university.ac.uk/long/path/to/brians/repo, you could just say brian.

The exact mechanism for this was apparently somewhat of a contest, or was invented independently multiple times in different ways.  I was not in on this particular bit of history myself, but traces linger even today in the git fetch documentation, under the section named remotes:

The name of one of the following can be used instead of a URL as <repository> argument:

a remote in the Git configuration file: $GIT_DIR/config,

a file in the $GIT_DIR/remotes directory, or

a file in the $GIT_DIR/branches directory.

Remote-tracking branches

The first option "won" and is what people actually use today.  (The other two are still supported.  I don't know why—they seem like they could have been deprecated and then dropped some time ago.)

Because the first option won, though, we can move on to the configured remote-tracking branches section of this same documentation:

You often interact with the same remote repository by regularly and repeatedly fetching from it. In order to keep track of the progress of such a remote repository, git fetch allows you to configure remote.<repository>.fetch configuration variables.

Typically such a variable may look like this:

[remote "origin"]
    fetch = +refs/heads/*:refs/remotes/origin/*

This (and the rest of this section) defines how remote-tracking branch names work.  The heart of the idea is that, hey, there's another Git over there somewhere: we run git fetch brian to get Brian's stuff.  Can't we then remember: This is the stuff Brian's Git said he had, the last time we called up his Git?

Of course, we can: we'll do that by changing Brian's master to our brian/master.  The mapping, from Brian's branch names to our remote-tracking names we store in our own Git, comes from this fetch = ... line, which we control.  Each fetch line—there can be more than one—has the form +src:dst, where the leading plus sign—which means the same as --force, more or less—is optional but almost always present, and the left and right sides of the colon give "their names" and "our names" for each of their references that we intend to copy.

It's almost always the case that for remote R, the src part is just refs/heads/* and the dst part begins with refs/remotes/ and then lists the remote-name R itself.  Hence, when we have a remote named brian, the fetch setting is +refs/heads/*:refs/remotes/brian/*.

The two asterisks get matched up: any branch that Brian has (refs/heads/*) get force-copied (+) to our own repository, but renamed into our remote-tracking branch name space (refs/remotes/).  We add another word to make sure that Brian's branches, under our refs/remotes/brian/, don't conflict with Nadia's branches, under our refs/remotes/nadia/.  And then we just copy Brian's (or Nadia's, or origin's) branch name, and that becomes our remote-tracking branch name for this branch.

How this ties in with a local branch's branch@{upstream}

Most local branches have a remote-tracking branch as their upstream setting.  (As this SO question notes, that's not actually required, it's just the usual case.)  But, when local branch B "tracks"—i.e., has as its upstream—remote-tracking branch refs/remotes/origin/B, the configuration entries just say that branch.B.remote is origin and branch.B.merge is B.  There's no explicit refs/remotes/origin/B in there at all!

This is all because of the twisty history (twistory?) above.  Before there were any remote-tracking branches at all, Git's configuration listed the name of the branch as found on the remote.  Branch B "merges with" the origin version of branch B.  Since it was spelled that way back in 2005 or so, Git requires that it still be spelled that way today.  Git then takes the old spelling and maps it through the fetch = line to figure out the correct remote-tracking branch.

Suppose, for instance, that you have branch test with upstream origin/master.  That is, git config --list --local will include:

remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*

(the usual and normal pattern) and:

branch.test.remote=origin
branch.test.merge=refs/heads/master

One could be forgiven for thinking that all Git does is string together the remote name, origin, with the master part of the branch.test.merge=refs/heads/master, to get origin/master.  But in fact, that's not quite what happens.  Let's make another remote, but then change its fetch line:

git remote add weird <url>
git config remote.weird.fetch '+refs/heads/*:refs/remotes/twisty/*'

Now we'll run git fetch weird:

$ git fetch weird
From <url>
 * [new branch]          maint      -> twisty/maint
 * [new branch]          master     -> twisty/master
 * [new branch]          next       -> twisty/next
 * [new branch]          pu         -> twisty/pu
 * [new branch]          todo       -> twisty/todo

Note that they did not go to weird/* but to twisty/*.  We can now make a branch that tracks (has as its upstream) twisty/master:

$ git checkout -b test --track twisty/master
Branch test set up to track remote branch master from weird.
Switched to a new branch 'test'
$ git rev-parse --symbolic-full-name test@{upstream}
refs/remotes/twisty/master
$ git config --list --local
[snip]
branch.test.remote=weird
branch.test.merge=refs/heads/master

The remote is weird and the merge never mentions twisty, yet the upstream really is twisty/master.

Cleaning up

Since I do not really want the test branch and the weird twisty setup, let's clean them up:

$ git checkout master
...
$ git branch -D test
Deleted branch test (was 8b2efe2a0).
$ git remote remove weird

That's all we need to do here: git remote remove weird deletes all the twisty/* remote-tracking branches, because it too obeys the fetch = configuration lines.