问:
.Net Core Entity Framework Abstraction
I have an .Net Core Class Library project which has a context file that uses Entity Framework. The context file looks like this;

```<code>public partial class Qcrr : DbContext
{
    public virtual DbSet<AirWorthyNess> AirWorthyNess { get; set; }
    public virtual DbSet<AwLog> AwLog { get; set; }
    public virtual DbSet<AwserialNumbers> AwserialNumbers { get; set; }
    public virtual DbSet<EmployeeInformation> EmployeeInformation { get; set; }
    public virtual DbSet<Password256> Password256 { get; set; }
    public virtual DbSet<Persistant> Persistant { get; set; }
    public virtual DbSet<TblApplicationRights> TblApplicationRights { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseSqlServer(@"my connection string");
        }
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        /* my tables
        .
        .
        .

        */
    }
}
</code>```

Now, I also have a simple .Net Core Console Application that references the class library dll for testing purposes. I want to be able to use the EF DbSet functionality as it is, within my console app without having to reference EF again. Of course if I try to use the context file directly, I have the following error;

Its telling me to reference Entity Framework again.

So my question is, what would be the best practice approach to abstract my dbcontext which lies within my Class Library ?

Would I need to implement the DbContext functionalities (scuh as Add, AddRange, Delete, IQueryable implementations (Select, Where, First...))?

答:
Entity framework is already a good abstraction for DB.
if You add another layer, you always will be forced to add more and more functionality to your abstraction.

Good example is AsNoTracking function for EF. It is good for performance, but adding it's implementation to your abstraction without re-implementing whole EF logic is a big deal. Another example is Spatial data types, raw SQL queries and much more interesting functions that your business logic might require, but you can't use them, because of your abstractions. So don't add another layer.

In my opinion the solution is to use Repository pattern.

Title: .Net Core Entity Framework Abstraction

Body:
I have an .Net Core Class Library project which has a context file that uses Entity Framework. The context file looks like this;

public partial class Qcrr : DbContext
{
    public virtual DbSet<AirWorthyNess> AirWorthyNess { get; set; }
    public virtual DbSet<AwLog> AwLog { get; set; }
    public virtual DbSet<AwserialNumbers> AwserialNumbers { get; set; }
    public virtual DbSet<EmployeeInformation> EmployeeInformation { get; set; }
    public virtual DbSet<Password256> Password256 { get; set; }
    public virtual DbSet<Persistant> Persistant { get; set; }
    public virtual DbSet<TblApplicationRights> TblApplicationRights { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseSqlServer(@"my connection string");
        }
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        /* my tables
        .
        .
        .

        */
    }
}

Now, I also have a simple .Net Core Console Application that references the class library dll for testing purposes. I want to be able to use the EF DbSet functionality as it is, within my console app without having to reference EF again. Of course if I try to use the context file directly, I have the following error;

Its telling me to reference Entity Framework again.

So my question is, what would be the best practice approach to abstract my dbcontext which lies within my Class Library ?

Would I need to implement the DbContext functionalities (scuh as Add, AddRange, Delete, IQueryable implementations (Select, Where, First...))?


来源: stackexchange

问:
Change image Floating Action Button Android
I used this library https://github.com/futuresimple/android-floating-action-button. How can I change the image of the main button? I want to change the button image right after selecting one of the smaller buttons.</p>

答:
I faced same issue recently, I tried with following option

```<code>  fab:fab_icon="@drawable/icon"
</code>```

and

```<code> android:src="@drawable/icon" // change backgroung icon
</code>```

even tried programmatically

```<code> fab_menu_btn.setImageResource();
</code>```

Nothing worked.

Solution: In app's build.gradle file  replace

```<code>  compile 'com.getbase:floatingactionbutton:1.10.0'
</code>```

to

```<code>compile 'com.github.toanvc:floatingactionmenu:0.8.9'
</code>```

In .xml file Use:

```<code>           <toan.android.floatingactionmenu.FloatingActionsMenu
          </toan.android.floatingactionmenu.FloatingActionsMenu>
</code>```

In activity File:

```<code>      floatingActionsMenu.setIcon(getResources().getDrawable(R.mipmap.icon));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I faced same issue recently, I tried with following option

  fab:fab_icon="@drawable/icon"

and

 android:src="@drawable/icon" // change backgroung icon

even tried programmatically

 fab_menu_btn.setImageResource();

Nothing worked.

Solution: In app's build.gradle file  replace

  compile 'com.getbase:floatingactionbutton:1.10.0'

to

compile 'com.github.toanvc:floatingactionmenu:0.8.9'

In .xml file Use:

           <toan.android.floatingactionmenu.FloatingActionsMenu
          </toan.android.floatingactionmenu.FloatingActionsMenu>

In activity File:

      floatingActionsMenu.setIcon(getResources().getDrawable(R.mipmap.icon));

ContentLicense: CC BY-SA 4.0


问:
Python loop through text and set numpy array index
Given a block of text with matrix rows and columns separated by commas and semicolons, I want to parse the text and set the indices of numpy arrays. Here is the code with the variable 'matrixText' representing the base text.

I first create the matrices and then split the text by semicolons and then by commas. I loop through the split text and set each index. However with the text ...

1,2,3;4,5,6;7,8,9

I get the result

7,7,7;8,8,8;9,9,9

```<code>temp1=matrixText.split(';')
temp2=temp1[0].split(',')
rows=len(temp1)
columns=len(temp2)
rA=np.zeros((rows, columns))
arrayText=matrixText.split(';')
rowText=range(len(arrayText))
for rowIndex, rowItem in enumerate(arrayText):
    rowText[rowIndex]=arrayText[rowIndex].split(',')
    for colIndex, colItem in enumerate(rowText[rowIndex]):
        rA[[rowIndex, colIndex]]=rowText[rowIndex][colIndex]
</code>```

I thought that by setting each index, I would avoid any copy by reference issues.

To provide more info, in the first iteration, the 0,0 index is set to 1 and the output of that is then 1,1,1;0,0,0;0,0,0 which I can't figure out since setting one index in the numpy array sets three.

In the second iteration, the index 0-1 is set to 2 and the result is then 2,2,2;2,2,2;0,0,0

The third iteration sets 0-2 to 3 but the result is 3,3,3;2,2,2;3,3,3

Any suggestions?

答:
Using a nested list-comprehension:

Having defined:

```<code>s = "1,2,3;4,5,6;7,8,9"
</code>```

we can use a nice one-liner:

```<code>np.array([[int(c) for c in r.split(",")] for r in s.split(";")])
</code>```

which would give the following array:

```<code>array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])
</code>```

Body:
Given a block of text with matrix rows and columns separated by commas and semicolons, I want to parse the text and set the indices of numpy arrays. Here is the code with the variable 'matrixText' representing the base text.

I first create the matrices and then split the text by semicolons and then by commas. I loop through the split text and set each index. However with the text ...

1,2,3;4,5,6;7,8,9

I get the result

7,7,7;8,8,8;9,9,9

temp1=matrixText.split(';')
temp2=temp1[0].split(',')
rows=len(temp1)
columns=len(temp2)
rA=np.zeros((rows, columns))
arrayText=matrixText.split(';')
rowText=range(len(arrayText))
for rowIndex, rowItem in enumerate(arrayText):
    rowText[rowIndex]=arrayText[rowIndex].split(',')
    for colIndex, colItem in enumerate(rowText[rowIndex]):
        rA[[rowIndex, colIndex]]=rowText[rowIndex][colIndex]

I thought that by setting each index, I would avoid any copy by reference issues.

To provide more info, in the first iteration, the 0,0 index is set to 1 and the output of that is then 1,1,1;0,0,0;0,0,0 which I can't figure out since setting one index in the numpy array sets three.

In the second iteration, the index 0-1 is set to 2 and the result is then 2,2,2;2,2,2;0,0,0

The third iteration sets 0-2 to 3 but the result is 3,3,3;2,2,2;3,3,3

Any suggestions?

Body:
Using a nested list-comprehension:

Having defined:

s = "1,2,3;4,5,6;7,8,9"

we can use a nice one-liner:

np.array([[int(c) for c in r.split(",")] for r in s.split(";")])

which would give the following array:

array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])


问:
Masking a pandas dataframe object
I am trying to run the following code but I am getting the error message like
"TypeError: The numpy boolean negative, the - operator, is not supported, use the ~ operator or the logical_not function instead."

I am getting the error when the line np_mask = A_df_masked.notnull() is runned.

How can I fix this issue?

Thanks in advance.

```<code>A_orig = np.array([[3, 4, 5, 2],
                   [4, 4, 3, 3],
                   [5, 5, 4, 4]], dtype=np.float32).T

A_orig_df = pd.DataFrame(A_orig)

#masking some of the entries
A_df_masked = A_orig_df.copy()
A_df_masked.iloc[0,0]=np.NAN

np_mask = A_df_masked.notnull()
</code>```

The desired output of np_mask will be:

```<code>    0       1       2
0   False   True    True
1   True    True    True
2   True    True    True
3   True    True    True
</code>```

答: This is an incompatibility between older versions of Pandas and newer versions of NumPy (Reported in this issue) If you update pandas to a more recent version, the problem should be fixed.</p>

Title: Masking a pandas dataframe object

Body:
I am trying to run the following code but I am getting the error message like
"TypeError: The numpy boolean negative, the - operator, is not supported, use the ~ operator or the logical_not function instead."

I am getting the error when the line np_mask = A_df_masked.notnull() is runned.

How can I fix this issue?

Thanks in advance.

A_orig = np.array([[3, 4, 5, 2],
                   [4, 4, 3, 3],
                   [5, 5, 4, 4]], dtype=np.float32).T

A_orig_df = pd.DataFrame(A_orig)

#masking some of the entries
A_df_masked = A_orig_df.copy()
A_df_masked.iloc[0,0]=np.NAN

np_mask = A_df_masked.notnull()

The desired output of np_mask will be:

    0       1       2
0   False   True    True
1   True    True    True
2   True    True    True
3   True    True    True


问:
How to make a div's background color translucent?
I only want the background color of white in my div to be translucent roughly 50%.  The content should be fully opaque.  What's the proper way to do this?  I imagined when I looked up the background CSS property, I'd find an opacity setting, but didn't.  Don't care about IE6.

UPDATE: solving with the rgba solution given below in conjunction with CSS3PIE's solution for getting rgba to work in IE browsers.

答:
There is a CSS property called backdrop-filter providing real translucency (as opposed to transparency, which is already available in CSS).

Currently supported by all modern browsers.

```<code>.my-selector {
   backdrop-filter: blur(5px);
}
</code>```

More about the selector

Browser support

Body:
There is a CSS property called backdrop-filter providing real translucency (as opposed to transparency, which is already available in CSS).

Currently supported by all modern browsers.

.my-selector {
   backdrop-filter: blur(5px);
}

More about the selector

Browser support


问:
menu parent-child hover - stop animation - jquery
I have this example here: http://jsfiddle.net/QRChv/

Im trying to set it up so that when you hover over a child list item, its animation will start, but the parent doesnt invoke its .hover() function.

I dont know if this can be done, but is there a way to stop the parent from actually going through with its animation. So it wont actually do anything when its child list item is being hovered over.

I have a bunch of if statements setup for each list item, tried to keep it simple.

答:
What about adding a call to stopPropagation. Something like this:

http://jsfiddle.net/rcravens/QRChv/9/

ContentLicense: CC BY-SA 2.5


问:
Is there a way to autogenerate valid arithmetic expressions?
I'm currently trying to create a Python script that will autogenerate space-delimited arithmetic expressions which are valid. However, I get sample output that looks like this: ( 32 - 42 / 95 + 24 ( ) ( 53 ) + ) 21

While the empty parentheses are perfectly OK by me, I can't use this autogenerated expression in calculations since there's no operator between the 24 and the 53, and the + before the 21 at the end has no second argument.

What I want to know is, is there a way to account for/fix these errors using a Pythonic solution? (And before anyone points it out, I'll be the first to acknowledge that the code I posted below is probably the worst code I've pushed and conforms to...well, very few of Python's core tenets.)

```<code>import random
parentheses = ['(',')']
ops = ['+','-','*','/'] + parentheses

lines = 0

while lines < 1000:
    fname = open('test.txt','a')
    expr = []
    numExpr = lines
    if (numExpr % 2 == 0):
        numExpr += 1
    isDiv = False # Boolean var, makes sure there's no Div by 0

    # isNumber, isParentheses, isOp determine whether next element is a number, parentheses, or operator, respectively
    isNumber = random.randint(0,1) == 0 # determines whether to start sequence with number or parentheses
    isParentheses = not isNumber
    isOp = False
    # Counts parentheses to ensure parentheses are matching
    numParentheses = 0
    while (numExpr > 0 or numParentheses > 0):
        if (numExpr < 0 and numParentheses > 0):
            isDiv = False
            expr.append(')')
            numParentheses -= 1
        elif (isOp and numParentheses > 0):
            rand = random.randint(0,5)
            expr.append(ops[rand])
            isDiv = (rand == 3) # True if div op was just appended
            # Checks to see if ')' was appended
            if (rand == 5):
                isNumber = False
                isOp = True
                numParentheses -= 1
            # Checks to see if '(' was appended
            elif (rand == 4):
                isNumber = True
                isOp = False
                numParentheses += 1
            # All other operations go here
            else:
                isNumber = True
                isOp = False
        # Didn't add parentheses possibility here in case expression in parentheses somehow reaches 0
        elif (isNumber and isDiv):
            expr.append(str(random.randint(1,100)))
            isDiv = False
            isNumber = False
            isOp = True
        # If a number's up, decides whether to append parentheses or a number
        elif (isNumber):
            rand = random.randint(0,1)
            if (rand == 0):
                expr.append(str(random.randint(0,100)))
                isNumber = False
                isOp = True
            elif (rand == 1):
                if (numParentheses == 0):
                    expr.append('(')
                    numParentheses += 1
                else:
                    rand = random.randint(0,1)
                    expr.append(parentheses[rand])
                    if rand == 0:
                        numParentheses += 1
                    else:
                        numParentheses -= 1
            isDiv = False
        numExpr -= 1

    fname.write(' '.join(expr) + '\n')
    fname.close()
    lines += 1
</code>```

答: Generate an array at random in RPN with mixtures of operators and numbers (always valid). Then start from middle of the array and generate the corresponding evaluation tree.</p>

Body:
I'm currently trying to create a Python script that will autogenerate space-delimited arithmetic expressions which are valid. However, I get sample output that looks like this: ( 32 - 42 / 95 + 24 ( ) ( 53 ) + ) 21

While the empty parentheses are perfectly OK by me, I can't use this autogenerated expression in calculations since there's no operator between the 24 and the 53, and the + before the 21 at the end has no second argument.

What I want to know is, is there a way to account for/fix these errors using a Pythonic solution? (And before anyone points it out, I'll be the first to acknowledge that the code I posted below is probably the worst code I've pushed and conforms to...well, very few of Python's core tenets.)

import random
parentheses = ['(',')']
ops = ['+','-','*','/'] + parentheses

lines = 0

while lines < 1000:
    fname = open('test.txt','a')
    expr = []
    numExpr = lines
    if (numExpr % 2 == 0):
        numExpr += 1
    isDiv = False # Boolean var, makes sure there's no Div by 0

    # isNumber, isParentheses, isOp determine whether next element is a number, parentheses, or operator, respectively
    isNumber = random.randint(0,1) == 0 # determines whether to start sequence with number or parentheses
    isParentheses = not isNumber
    isOp = False
    # Counts parentheses to ensure parentheses are matching
    numParentheses = 0
    while (numExpr > 0 or numParentheses > 0):
        if (numExpr < 0 and numParentheses > 0):
            isDiv = False
            expr.append(')')
            numParentheses -= 1
        elif (isOp and numParentheses > 0):
            rand = random.randint(0,5)
            expr.append(ops[rand])
            isDiv = (rand == 3) # True if div op was just appended
            # Checks to see if ')' was appended
            if (rand == 5):
                isNumber = False
                isOp = True
                numParentheses -= 1
            # Checks to see if '(' was appended
            elif (rand == 4):
                isNumber = True
                isOp = False
                numParentheses += 1
            # All other operations go here
            else:
                isNumber = True
                isOp = False
        # Didn't add parentheses possibility here in case expression in parentheses somehow reaches 0
        elif (isNumber and isDiv):
            expr.append(str(random.randint(1,100)))
            isDiv = False
            isNumber = False
            isOp = True
        # If a number's up, decides whether to append parentheses or a number
        elif (isNumber):
            rand = random.randint(0,1)
            if (rand == 0):
                expr.append(str(random.randint(0,100)))
                isNumber = False
                isOp = True
            elif (rand == 1):
                if (numParentheses == 0):
                    expr.append('(')
                    numParentheses += 1
                else:
                    rand = random.randint(0,1)
                    expr.append(parentheses[rand])
                    if rand == 0:
                        numParentheses += 1
                    else:
                        numParentheses -= 1
            isDiv = False
        numExpr -= 1

    fname.write(' '.join(expr) + '\n')
    fname.close()
    lines += 1


问:
UWP Map Control with animated Custom Layers
I am trying to animate custom layers within my application, using the MapControl.  I am able to set each layer and view them, however, I am not able to animate them smoothly.

Previously, I used Bing Maps SDK, which I had a timer set to toggle the visibility of each layer at 500ms. This technique does not work with the MapControl, as it causes a blinking occurrence (my assumption being that the layer is discarded and needs to redownload each toggle).

答:
At the moment, this is not a well supported scenario. Better support for animated tile layers is a feature under consideration for future release.
Right now, what you're doing is the best way to go, and yes the tile layers will flash. Setting the flag to not animate the tile layer will help a bit.</p>


问:
How to use a Foreach loop in PHP/Blade for Laravel?
Here is a quick question:
Is there any way to optimise this code with a foreach loop or something like this?

```<code>@if(isset($tags[0]))
    <span class="label label-primary">{{ $tags[0] }}</span>
@endif
@if(isset($tags[1]))
    <span class="label label-primary">{{ $tags[1] }}</span>
@endif
@if(isset($tags[2]))
    <span class="label label-primary">{{ $tags[2] }}</span>
@endif
@if(isset($tags[3]))
    <span class="label label-primary">{{ $tags[3] }}</span>
@endif
@if(isset($tags[4]))
    <span class="label label-primary">{{ $tags[4] }}</span>
@endif
@if(isset($tags[5]))
    <span class="label label-primary">{{ $tags[5] }}</span>
@endif
@if(isset($tags[6]))
    <span class="label label-primary">{{ $tags[6] }}</span>
@endif
@if(isset($tags[7]))
    <span class="label label-primary">{{ $tags[7] }}</span>
@endif
@if(isset($tags[8]))
    <span class="label label-primary">{{ $tags[8] }}</span>
@endif
@if(isset($tags[9]))
    <span class="label label-primary">{{ $tags[9] }}</span>
@endif
</code>```

Thank you and have a nice day/night !

答:
You can use an @foreach loop (as suggested by other answers) or an @for loop. Use blade syntax for control structures (preceeded by an @ symbol)

```<code>@for($i = 0; $i <= 9; $i++)
@if(isset($tags[$i]))
<span class="label label-primary">{{ $tags[$i] }}</span>
@endif
@endfor
</code>```

Body:
Here is a quick question:
Is there any way to optimise this code with a foreach loop or something like this?

@if(isset($tags[0]))
    {{ $tags[0] }}
@endif
@if(isset($tags[1]))
    {{ $tags[1] }}
@endif
@if(isset($tags[2]))
    {{ $tags[2] }}
@endif
@if(isset($tags[3]))
    {{ $tags[3] }}
@endif
@if(isset($tags[4]))
    {{ $tags[4] }}
@endif
@if(isset($tags[5]))
    {{ $tags[5] }}
@endif
@if(isset($tags[6]))
    {{ $tags[6] }}
@endif
@if(isset($tags[7]))
    {{ $tags[7] }}
@endif
@if(isset($tags[8]))
    {{ $tags[8] }}
@endif
@if(isset($tags[9]))
    {{ $tags[9] }}
@endif

Thank you and have a nice day/night !

Body:
You can use an @foreach loop (as suggested by other answers) or an @for loop. Use blade syntax for control structures (preceeded by an @ symbol)

@for($i = 0; $i <= 9; $i++)
@if(isset($tags[$i]))
<span class="label label-primary">{{ $tags[$i] }}</span>
@endif
@endfor


问:
Dynamic UITableViewCell not resizing according to the content

Senario A:
If I set the label content in cellForRowAtIndexPath, the cell correctly get resized.

Senario B:
If I change the text content in custom action in cell, the cell sized does not get changed.(I do call setNeedsLayout + layoutIfNeeded)

How to fix this?

EDIT:

1) I have set,
myTableView.estimatedRowHeight = 71.0
myTableView.rowHeight = UITableViewAutomaticDimension

2) I have correctly added auto layout constraints.

答: I was running into this issue, and my problem was that I was constraining the content to self (the UITableViewCell) and not to self.contentView (the contentView OF the cell). Hope this helps someone else who has built their cells all in code!


答:
Per the documentation, you can do @for loops.

```<code>@for ($i = 0; $i < 10; $i++)
    @if(isset($tags[$i]))
         <span class="label label-primary">{{ $tags[$i] }}</span>
    @endif
@endfor
</code>```

Title: How to use a Foreach loop in PHP/Blade for Laravel?

Body:
Per the documentation, you can do @for loops.

@for ($i = 0; $i < 10; $i++)
    @if(isset($tags[$i]))
         <span class="label label-primary">{{ $tags[$i] }}</span>
    @endif
@endfor


问:
Yii2 register mix of JS Files and Inline JS in order
I'm trying to register the following from the Google Analytics docs:

```<code><!-- Google Analytics -->
<script>
  window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
  ga('create', 'UA-XXXXX-Y', 'auto');
  ga('send', 'pageview');
</script>
<script async src='https://www.google-analytics.com/analytics.js'></script>
<!-- End Google Analytics -->
</code>```

So I did the following in my widget:

```<code>$this->view->registerJs('
    window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
    ga(\'create\', \'UA-XXXXX-Y\', \'auto\');
    ga(\'send\', \'pageview\');
', View::POS_HEAD);

$this->view->registerJsFile(
    'https://www.google-analytics.com/analytics.js',
    [
       'async'=>'async',
       'position' => View::POS_HEAD,
    ]
);
</code>```

But the registered JS File came out BEFORE the Inline JS. Is there a way to get the scripts to respect the order?

I thought about using an AssetBundle and the 'depends' protocol, but there's nothing in the Yii2 Docs about Inline JS in an AssetBundle.

You can give the Inline JS a key, but sadly the 'depends' protocol requires a class name.

答:
You can move the first code block to a js file and use it in an asset bundle. Then for the second js url use that asset as dependancy

google_analytics.js

```<code>window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
 ga('create', 'UA-XXXXX-Y', 'auto');
 ga('send', 'pageview');
</code>```

GoogleAnalyticsAsset.php

```<code><?php

namespace app\assets;

use yii\web\AssetBundle;

class GoogleAnalyticsAsset extends AssetBundle
{
   public $basePath = '@webroot/web';
   public $baseUrl = '@web/web';

   public $jsOptions = ['position' => \yii\web\View::POS_HEAD];
   public $css = [
   ];
   public $js = [
       'js/google_analytics.js',
   ];
   public $depends = [
   ];
}
</code>```

Inside your widget

```<code>use app\assets\GoogleAnalyticsAsset;
public function init() {
    GoogleAnalyticsAsset::register( $this->getView() );
    parent::init();
}

public function run()
{
   $this->registerJsFile('https://www.google.com/jsapi',['position' => \yii\web\View::POS_HEAD,'depends' => 'app\assets\GoogleAnalyticsAsset']);
}
</code>```

Body:
I'm trying to register the following from the Google Analytics docs:

So I did the following in my widget:

$this->view->registerJs('
    window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
    ga(\'create\', \'UA-XXXXX-Y\', \'auto\');
    ga(\'send\', \'pageview\');
', View::POS_HEAD);

$this->view->registerJsFile(
    'https://www.google-analytics.com/analytics.js',
    [
       'async'=>'async',
       'position' => View::POS_HEAD,
    ]
);

But the registered JS File came out BEFORE the Inline JS. Is there a way to get the scripts to respect the order?

I thought about using an AssetBundle and the 'depends' protocol, but there's nothing in the Yii2 Docs about Inline JS in an AssetBundle.

You can give the Inline JS a key, but sadly the 'depends' protocol requires a class name.

Body:
You can move the first code block to a js file and use it in an asset bundle. Then for the second js url use that asset as dependancy

google_analytics.js

window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
 ga('create', 'UA-XXXXX-Y', 'auto');
 ga('send', 'pageview');

GoogleAnalyticsAsset.php

<?php

namespace app\assets;

use yii\web\AssetBundle;

class GoogleAnalyticsAsset extends AssetBundle
{
   public $basePath = '@webroot/web';
   public $baseUrl = '@web/web';

   public $jsOptions = ['position' => \yii\web\View::POS_HEAD];
   public $css = [
   ];
   public $js = [
       'js/google_analytics.js',
   ];
   public $depends = [
   ];
}

Inside your widget

use app\assets\GoogleAnalyticsAsset;
public function init() {
    GoogleAnalyticsAsset::register( $this->getView() );
    parent::init();
}

public function run()
{
   $this->registerJsFile('https://www.google.com/jsapi',['position' => \yii\web\View::POS_HEAD,'depends' => 'app\assets\GoogleAnalyticsAsset']);
}


问:
Adding values to new Pandas dataframe column based on partial string contents of existing column
I have data stored as a dataframe using Python Pandas. Among the columns, I have a "Product" column which contains the brand name and model (e.g. Nike Air Jordan, Adidas Gazelle). I want to create a new column that just contains the brand (e.g. Nike, Adidas), which I will later use in groupby to summarize the data.
From my research, I believe contains and regex can be used to do this. However, the implementation has not worked. I've also seen different approaches, some using "for i in range" while others do it as a replace in a single line of code.

```<code>import pandas as pd
import numpy as np

shoes_df = pd.DataFrame({'Product':['Nike vaporfly', 'Nike Jordans', 'Adidas supernova', 'Asics Kayano', 'Asics GT2010', 'Adidas gazelle', 'Nike air max',
                                  'Nike Lebron'], 'Unit sales':[1500, 1600,
2341, 1345, 4523, 2345, 1634, 3129]})

shoes_df['Brand'] = np.where(shoes_df['Product'].str.contains('Nike.*|Adidas.*').any(), 'Nike|Adidas', np.nan)

print(shoes_df)
</code>```

Here was my attempt at doing the "for i in range" approach, which did not work either. Here, I got the error "TypeError: 'Series' objects are mutable, thus they cannot be hashed"

```<code>shoes_df = pd.DataFrame({'Product':['Nike vaporfly', 'Nike Jordans', 'Adidas supernova', 'Asics Kayano', 'Asics GT2010', 'Adidas gazelle', 'Nike air max',
                                  'Nike Lebron'], 'Unit sales':[1500, 1600, 2341, 1345, 4523,
                                   2345, 1634, 3129]})

for i in shoes_df.iterrows():
    if shoes_df['Product'].str.contains('Nike').any():
        shoes_df.set_value(i, 'Brand', 'Nike')
    elif shoes_df['Product'].str.contains('Adidas').any():
        shoes_df.set_value(i, 'Brand', 'Adidas')
    elif shoes_df['Product'].str.contains('Asics').any():
        shoes_df.set_value(i, 'Brand', 'Asics')
    else:
        shoes_df.set_value(i, 'Brand', np.nan)
</code>```

答:
Option 1  (the hard way)

str.extract

```<code>brands = ['Nike', 'Adidas', 'Asics']
df['Brand'] = df.Product.str.extract('({})'.format('|'.join(brands)), expand=True)

df

            Product  Unit sales   Brand
0     Nike vaporfly        1500    Nike
1      Nike Jordans        1600    Nike
2  Adidas supernova        2341  Adidas
3      Asics Kayano        1345   Asics
4      Asics GT2010        4523   Asics
5    Adidas gazelle        2345  Adidas
6      Nike air max        1634    Nike
7       Nike Lebron        3129    Nike
</code>```

Option 2 (somewhat simpler)

str.split

```<code>df['Brand'] = df.Product.str.split().str[0]
df

            Product  Unit sales   Brand
0     Nike vaporfly        1500    Nike
1      Nike Jordans        1600    Nike
2  Adidas supernova        2341  Adidas
3      Asics Kayano        1345   Asics
4      Asics GT2010        4523   Asics
5    Adidas gazelle        2345  Adidas
6      Nike air max        1634    Nike
7       Nike Lebron        3129    Nike
</code>```

You can extend this a bit to replace anything that isn't in brands with NaN:

```<code>df['Brand'] = np.where(df.Brand.isin(brands), df.Brand, np.nan)
</code>```

Body:
I have data stored as a dataframe using Python Pandas. Among the columns, I have a "Product" column which contains the brand name and model (e.g. Nike Air Jordan, Adidas Gazelle). I want to create a new column that just contains the brand (e.g. Nike, Adidas), which I will later use in groupby to summarize the data.
From my research, I believe contains and regex can be used to do this. However, the implementation has not worked. I've also seen different approaches, some using "for i in range" while others do it as a replace in a single line of code.

import pandas as pd
import numpy as np

shoes_df = pd.DataFrame({'Product':['Nike vaporfly', 'Nike Jordans', 'Adidas supernova', 'Asics Kayano', 'Asics GT2010', 'Adidas gazelle', 'Nike air max',
                                  'Nike Lebron'], 'Unit sales':[1500, 1600,
2341, 1345, 4523, 2345, 1634, 3129]})

shoes_df['Brand'] = np.where(shoes_df['Product'].str.contains('Nike.*|Adidas.*').any(), 'Nike|Adidas', np.nan)

print(shoes_df)

Here was my attempt at doing the "for i in range" approach, which did not work either. Here, I got the error "TypeError: 'Series' objects are mutable, thus they cannot be hashed"

shoes_df = pd.DataFrame({'Product':['Nike vaporfly', 'Nike Jordans', 'Adidas supernova', 'Asics Kayano', 'Asics GT2010', 'Adidas gazelle', 'Nike air max',
                                  'Nike Lebron'], 'Unit sales':[1500, 1600, 2341, 1345, 4523,
                                   2345, 1634, 3129]})

for i in shoes_df.iterrows():
    if shoes_df['Product'].str.contains('Nike').any():
        shoes_df.set_value(i, 'Brand', 'Nike')
    elif shoes_df['Product'].str.contains('Adidas').any():
        shoes_df.set_value(i, 'Brand', 'Adidas')
    elif shoes_df['Product'].str.contains('Asics').any():
        shoes_df.set_value(i, 'Brand', 'Asics')
    else:
        shoes_df.set_value(i, 'Brand', np.nan)

Body:
Option 1  (the hard way)

str.extract

brands = ['Nike', 'Adidas', 'Asics']
df['Brand'] = df.Product.str.extract('({})'.format('|'.join(brands)), expand=True)

df

            Product  Unit sales   Brand
0     Nike vaporfly        1500    Nike
1      Nike Jordans        1600    Nike
2  Adidas supernova        2341  Adidas
3      Asics Kayano        1345   Asics
4      Asics GT2010        4523   Asics
5    Adidas gazelle        2345  Adidas
6      Nike air max        1634    Nike
7       Nike Lebron        3129    Nike

Option 2 (somewhat simpler)

str.split

df['Brand'] = df.Product.str.split().str[0]
df

            Product  Unit sales   Brand
0     Nike vaporfly        1500    Nike
1      Nike Jordans        1600    Nike
2  Adidas supernova        2341  Adidas
3      Asics Kayano        1345   Asics
4      Asics GT2010        4523   Asics
5    Adidas gazelle        2345  Adidas
6      Nike air max        1634    Nike
7       Nike Lebron        3129    Nike

You can extend this a bit to replace anything that isn't in brands with NaN:

df['Brand'] = np.where(df.Brand.isin(brands), df.Brand, np.nan)


答:
You can do it simply like this :</p>

```<code>@foreach ($tags as $tag)
    <span class="label label-primary">{{ $tag }}</span>
@endforeach
</code>```

Body:
You can do it simply like this :

@foreach ($tags as $tag)
    <span class="label label-primary">{{ $tag }}</span>
@endforeach


问:
Python elegant assignment based on True/False values
I have a variable I want to set depending on the values in three booleans. The most straight-forward way is an if statement followed by a series of elifs:

```<code>if a and b and c:
    name = 'first'
elif a and b and not c:
    name = 'second'
elif a and not b and c:
    name = 'third'
elif a and not b and not c:
    name = 'fourth'
elif not a and b and c:
    name = 'fifth'
elif not a and b and not c:
    name = 'sixth'
elif not a and not b and c:
    name = 'seventh'
elif not a and not b and not c:
    name = 'eighth'
</code>```

This is a bit awkward, and I'm wondering if there's a more Pythonic way to handle this problem. A couple of ideas come to mind.

Dictionary hack:

```<code>name = {a and b and c: 'first',
        a and b and not c: 'second',
        a and not b and c: 'third',
        a and not b and not c: 'fourth',
        not a and b and c: 'fifth',
        not a and b and not c: 'sixth',
        not a and not b and c: 'seventh',
        not a and not b and not c: 'eighth'}[True]
</code>```

I call it a hack because I'm not too wild about seven of the keys being False and overriding each other.

And/or magic

```<code>name = (a and b and c and 'first' or
        a and b and not c and 'second' or
        a and not b and c and 'third' or
        a and not b and not c and 'fourth' or
        not a and b and c and 'fifth' or
        not a and b and not c and 'sixth' or
        not a and not b and c and 'seventh' or
        not a and not b and not c and 'eighth')
</code>```

This works because Python ands and ors return the last value to be evaluated, but you have to know that in order to understand this otherwise bizarre code.

None of these three options is very satisfying. What do you recommend?

答:
To measure speeds:

```<code>from time import clock
a,b,c = True,False,False

A,B,C,D,E,F,G,H = [],[],[],[],[],[],[],[]

for j in xrange(30):

    te = clock()
    for i in xrange(10000):
        name = (a and b and c and 'first' or
                a and b and not c and 'second' or
                a and not b and c and 'third' or
                a and not b and not c and 'fourth' or
                not a and b and c and 'fifth' or
                not a and b and not c and 'sixth' or
                not a and not b and c and 'seventh' or
                not a and not b and not c and 'eighth')
    A.append(clock()-te)

    te = clock()
    for i in xrange(10000):
        if a and b and c:
            name = 'first'
        elif a and b and not c:
            name = 'second'
        elif a and not b and c:
            name = 'third'
        elif a and not b and not c:
            name = 'fourth'
        elif not a and b and c:
            name = 'fifth'
        elif not a and b and not c:
            name = 'sixth'
        elif not a and not b and c:
            name = 'seventh'
        elif not a and not b and not c:
            name = 'eighth'
    B.append(clock()-te)

    #=====================================================================================

    li = ['eighth', 'seventh', 'sixth', 'fifth', 'fourth', 'third', 'second', 'first']
    te = clock()
    for i in xrange(10000):
        name = li[a*4 + b*2 + c]
    C.append(clock()-te)

    #=====================================================================================

    nth = ['eighth', 'seventh', 'sixth', 'fifth', 'fourth', 'third', 'second', 'first']
    te = clock()
    for i in xrange(10000):
        name = nth[(a and 4 or 0) | (b and 2 or 0) | (c and 1 or 0)]
    D.append(clock()-te)

    nth = ['eighth', 'seventh', 'sixth', 'fifth', 'fourth', 'third', 'second', 'first']
    te = clock()
    for i in xrange(10000):
        name = nth[(a and 4 or 0) + (b and 2 or 0) + (c and 1 or 0)]
    E.append(clock()-te)

    #=====================================================================================

    values = ['eighth', 'seventh', 'sixth', 'fifth', 'fourth', 'third', 'second', 'first']
    te = clock()
    for i in xrange(10000):
        name = values[( 4 if a else 0 )| ( 2 if b else 0 ) | ( 1 if c else 0 )]
    F.append(clock()-te)

    values = ['eighth', 'seventh', 'sixth', 'fifth', 'fourth', 'third', 'second', 'first']
    te = clock()
    for i in xrange(10000):
        name = values[( 4 if a else 0 ) + ( 2 if b else 0 ) + ( 1 if c else 0 )]
    G.append(clock()-te)

    #=====================================================================================

    dic = {(True, True, True): "first",
           (True, True, False): "second",
           (True, False, True): "third",
           (True, False, False): "fourth",
           (False, True, True): "fifth",
           (False, True, False): "sixth",
           (False, False, True): "seventh",
           (False, False, False): "eighth"}
    te = clock()
    for i in xrange(10000):
        name = dic[a,b,c]
    H.append(clock()-te)

print min(A),'\n', min(B),'\n\n', min(C),'\n\n', min(D),'\n',min(E),'\n\n',min(F),'\n', min(G),'\n\n', min(H)
</code>```

Result

```<code>0.0480533140385
0.0450973517584

0.0309056039245

0.0295291720037
0.0286550385594

0.0280122194301
0.0266760160858

0.0249769174574
</code>```

Body:
I have a variable I want to set depending on the values in three booleans. The most straight-forward way is an if statement followed by a series of elifs:

if a and b and c:
    name = 'first'
elif a and b and not c:
    name = 'second'
elif a and not b and c:
    name = 'third'
elif a and not b and not c:
    name = 'fourth'
elif not a and b and c:
    name = 'fifth'
elif not a and b and not c:
    name = 'sixth'
elif not a and not b and c:
    name = 'seventh'
elif not a and not b and not c:
    name = 'eighth'

This is a bit awkward, and I'm wondering if there's a more Pythonic way to handle this problem. A couple of ideas come to mind.

Dictionary hack:

name = {a and b and c: 'first',
        a and b and not c: 'second',
        a and not b and c: 'third',
        a and not b and not c: 'fourth',
        not a and b and c: 'fifth',
        not a and b and not c: 'sixth',
        not a and not b and c: 'seventh',
        not a and not b and not c: 'eighth'}[True]

I call it a hack because I'm not too wild about seven of the keys being False and overriding each other.

And/or magic

name = (a and b and c and 'first' or
        a and b and not c and 'second' or
        a and not b and c and 'third' or
        a and not b and not c and 'fourth' or
        not a and b and c and 'fifth' or
        not a and b and not c and 'sixth' or
        not a and not b and c and 'seventh' or
        not a and not b and not c and 'eighth')

This works because Python ands and ors return the last value to be evaluated, but you have to know that in order to understand this otherwise bizarre code.

None of these three options is very satisfying. What do you recommend?

Body:
To measure speeds:

from time import clock
a,b,c = True,False,False

A,B,C,D,E,F,G,H = [],[],[],[],[],[],[],[]

for j in xrange(30):

    te = clock()
    for i in xrange(10000):
        name = (a and b and c and 'first' or
                a and b and not c and 'second' or
                a and not b and c and 'third' or
                a and not b and not c and 'fourth' or
                not a and b and c and 'fifth' or
                not a and b and not c and 'sixth' or
                not a and not b and c and 'seventh' or
                not a and not b and not c and 'eighth')
    A.append(clock()-te)

    te = clock()
    for i in xrange(10000):
        if a and b and c:
            name = 'first'
        elif a and b and not c:
            name = 'second'
        elif a and not b and c:
            name = 'third'
        elif a and not b and not c:
            name = 'fourth'
        elif not a and b and c:
            name = 'fifth'
        elif not a and b and not c:
            name = 'sixth'
        elif not a and not b and c:
            name = 'seventh'
        elif not a and not b and not c:
            name = 'eighth'
    B.append(clock()-te)

    #=====================================================================================

    li = ['eighth', 'seventh', 'sixth', 'fifth', 'fourth', 'third', 'second', 'first']
    te = clock()
    for i in xrange(10000):
        name = li[a*4 + b*2 + c]
    C.append(clock()-te)

    #=====================================================================================

    nth = ['eighth', 'seventh', 'sixth', 'fifth', 'fourth', 'third', 'second', 'first']
    te = clock()
    for i in xrange(10000):
        name = nth[(a and 4 or 0) | (b and 2 or 0) | (c and 1 or 0)]
    D.append(clock()-te)

    nth = ['eighth', 'seventh', 'sixth', 'fifth', 'fourth', 'third', 'second', 'first']
    te = clock()
    for i in xrange(10000):
        name = nth[(a and 4 or 0) + (b and 2 or 0) + (c and 1 or 0)]
    E.append(clock()-te)

    #=====================================================================================

    values = ['eighth', 'seventh', 'sixth', 'fifth', 'fourth', 'third', 'second', 'first']
    te = clock()
    for i in xrange(10000):
        name = values[( 4 if a else 0 )| ( 2 if b else 0 ) | ( 1 if c else 0 )]
    F.append(clock()-te)

    values = ['eighth', 'seventh', 'sixth', 'fifth', 'fourth', 'third', 'second', 'first']
    te = clock()
    for i in xrange(10000):
        name = values[( 4 if a else 0 ) + ( 2 if b else 0 ) + ( 1 if c else 0 )]
    G.append(clock()-te)

    #=====================================================================================

    dic = {(True, True, True): "first",
           (True, True, False): "second",
           (True, False, True): "third",
           (True, False, False): "fourth",
           (False, True, True): "fifth",
           (False, True, False): "sixth",
           (False, False, True): "seventh",
           (False, False, False): "eighth"}
    te = clock()
    for i in xrange(10000):
        name = dic[a,b,c]
    H.append(clock()-te)

print min(A),'\n', min(B),'\n\n', min(C),'\n\n', min(D),'\n',min(E),'\n\n',min(F),'\n', min(G),'\n\n', min(H)

Result

0.0480533140385
0.0450973517584

0.0309056039245

0.0295291720037
0.0286550385594

0.0280122194301
0.0266760160858

0.0249769174574


问:
Custom Splash Screen size - Tabris-JS
I've searched around questions but I didn't find anything.

I'm new to Tabris-JS framework, is very powerful and simple but I have some issue with the Splash Screen.

As mentioned in this commit, in Tabris-JS 2.x there are two theme options: one light theme, and the other dark theme.
But they both have margin around the image.

The result is this (behind the image there is the 'dark gray' background):

I try to search for the correct Activity that is responsable for the Launcher, but I'm not good in Java.

PS: Splash Screen images are all correctly generated, with online tools for all screen sizes.

答:
Per the Tabris.js issue tracker, the solution is to theme the android app with a color background on splash, and assume that the splash screen image will be centered.

Since iOS has a more finite number of resolutions this shouldn't be an issue and the regular Cordova splash screen configuration applies.

Title: Custom Splash Screen size - Tabris-JS


问:
Extracting centroids using k-means clustering in python?
I have some data in a 1D array with shape [1000,] with 1000 elements in it. I applied k-means clustering on this data with 10 as number of clusters. After applying the k-means, I got cluster labels (id's) with shape [1000,] and centroids of shape [10,] for each cluster. The labels array allots value between 0 and 9 to each of the 1000 elements. However,  I want each element to show its centroid rather than its cluster id's. How can I achieve this?

```<code>from sklearn.cluster import KMeans
kmeans = KMeans(n_clusters=10)
kmeans.fit(data)   #data is of shape [1000,]
#learn the labels and the means
labels = kmeans.predict(data)  #labels of shape [1000,] with values 0<= i <= 9
centroids  = kmeans.cluster_centers_  #means of shape [10,]
</code>```

In the code above, I want respective centroids for each element in the [1000,] array instead of its cluster id's.

答:
Just use the centroids array as lookup table:

```<code>samplesCentroids = centroids[labels]
</code>```

Body:
I have some data in a 1D array with shape [1000,] with 1000 elements in it. I applied k-means clustering on this data with 10 as number of clusters. After applying the k-means, I got cluster labels (id's) with shape [1000,] and centroids of shape [10,] for each cluster. The labels array allots value between 0 and 9 to each of the 1000 elements. However,  I want each element to show its centroid rather than its cluster id's. How can I achieve this?

from sklearn.cluster import KMeans
kmeans = KMeans(n_clusters=10)
kmeans.fit(data)   #data is of shape [1000,]
#learn the labels and the means
labels = kmeans.predict(data)  #labels of shape [1000,] with values 0<= i <= 9
centroids  = kmeans.cluster_centers_  #means of shape [10,]

In the code above, I want respective centroids for each element in the [1000,] array instead of its cluster id's.

Body:
Just use the centroids array as lookup table:

samplesCentroids = centroids[labels]


问:
Property 'address' does not exist on type {} while going into production mode Angular 4
I was working on a site that used Angular 4. It worked fine until when i go to production mode. During production mode ng build seems to work fine but when i execute ng build --prod the it throws error. like this

my view is something like this

```<code><ul class="personal-info list-inline clearfix mb-5">
  <li><strong>Full Name :</strong>{{details.name}}</li>
  <li><strong>Birthday :</strong>{{details.birth_day}}</li>
  <li><strong>Address :</strong>{{details.address}}</li>
  <li><strong>Phone :</strong>{{details.phone}}</li>
  <li><strong>Email :</strong> <a href="">{{details.email}}</a></li>
  <li><strong>Job :</strong>{{details.job}}</li>
  <li><strong>Skype :</strong> {{details.skype}}</li>
</ul>
</code>```

and my component is something like this

```<code>export class AppComponent implements OnInit {

  title = 'app';
  slider = {};
  specialities = {};
  works = {};
  details = {};
  image;
  html;
  image1;
  private url = "http://localhost/portfolio/api/home/data"

  constructor(private http: Http) {
  }
  ngOnInit() {
    this.getData();
  }

  getData() {
    return this.http.get(this.url)
      .map((res: Response) => res.json()).subscribe(res => {
        this.slider = res.slider;
        this.specialities = res.specialities;
        this.works = res.works
        this.details = res.details;
        console.log(res);
      });
  }

}
</code>```

i searched for the error but i cant find the solution. What could be done to solve this problem. Any help would be appreciated. Thank You

答:
You should create a class  Details  and declare details as follow in the component,

```<code>export class Detail {
  name : string;
  .............
  etc
}
</code>```

and inside the component,

```<code>details:Detail ;
</code>```

Body:
I was working on a site that used Angular 4. It worked fine until when i go to production mode. During production mode ng build seems to work fine but when i execute ng build --prod the it throws error. like this

my view is something like this

Full Name :{{details.name}}

Birthday :{{details.birth_day}}

Address :{{details.address}}

Phone :{{details.phone}}

Email : {{details.email}}

Job :{{details.job}}

Skype : {{details.skype}}

and my component is something like this

export class AppComponent implements OnInit {

  title = 'app';
  slider = {};
  specialities = {};
  works = {};
  details = {};
  image;
  html;
  image1;
  private url = "http://localhost/portfolio/api/home/data"

  constructor(private http: Http) {
  }
  ngOnInit() {
    this.getData();
  }

  getData() {
    return this.http.get(this.url)
      .map((res: Response) => res.json()).subscribe(res => {
        this.slider = res.slider;
        this.specialities = res.specialities;
        this.works = res.works
        this.details = res.details;
        console.log(res);
      });
  }

}

i searched for the error but i cant find the solution. What could be done to solve this problem. Any help would be appreciated. Thank You

Body:
You should create a class  Details  and declare details as follow in the component,

export class Detail {
  name : string;
  .............
  etc
}

and inside the component,

details:Detail ;


问:
JQuery Pop up and JSON parsing not working
I have built a dog naming tool through jquery. It was requested that a json file with all the names be added into the tool. For some reason now that I have converted to use the JSON file, it's no longer working. Here is the code for HTML and jquery:

```<code> <div class="dnt-container-mobile seasonal-bg-dark">
<h1 class="mobile-heading">Dog Name Finder</h1>
<h1 class="wide-heading"><!-- <span class="logo teal icon-akc-logo dnt-logo"></span> -->Dog Name Finder</h1>
<form class="dnt-tool" id="dnt" name="dnt">
    <div class="dnt-overlay">
        <input id="male" name="gender" type="radio" value="Male" />
            <label for="male">Male</label>
        <input data-id="594" id="female" name="gender" type="radio" value="Female" />
            <label for="female">Female</label>
        <input checked="checked" data-id="0" id="all" name="gender" type="radio" value="All" />
            <label for="all">All</label>
        <select>
            <option data-id="0" value="/dog-name-finder/">Select a Category</option>
            <option data-id="0" value="/dog-name-finder/">All</option>
            <option value="/dog-name-finder/baby/">Baby</option>
            <option data-id="602" value="/dog-name-finder/celebrity/">Celebrity</option>
            <option data-id="603" value="/dog-name-finder/cute/">Cute</option>
            <option data-id="598" value="/dog-name-finder/disney/">Disney</option>
            <option data-id="600" value="/dog-name-finder/fancy/">Fancy</option>
            <option data-id="605" value="/dog-name-finder/most-popular/">Most Popular</option>
            <option data-id="599" value="/dog-name-finder/presidential/">Presidential</option>
            <option data-id="597" value="/dog-name-finder/techy/">Techy</option>
            <option data-id="596" value="/dog-name-finder/television/">Television</option>
            <option data-id="606" value="/dog-name-finder/trendy/">Trendy</option>
            <option data-id="595" value="/dog-name-finder/unisex/">Unisex</option>
            <option data-id="604" value="/dog-name-finder/video-game/">Video Game</option>
        </select>
    </div><!-- end of dnt-overlay -->
    <div class="dnt-btn">
        <button id="submit" type="submit">Show Names</button>
    </div><!-- end of dnt btn -->
    </form><!-- end of dnt-tool -->
  </div><!-- end of dnt-container-mobile -->

   <div class="white-popup mfp-hide" id="dnt-popup">
    <div class="popup-logo">
   <a class="logo teal icon-logo"></a>
</div><!-- end of logo -->
<h1>Most Popular Dog Names</h1>
<img src="gender-all.png" id="dnt-all-img" alt=
all puppies">
<img src="female-puppy.png" id="dnt-female-img" alt="Female puppy">
<img src="male-puppy.png" id="dnt-male-img" alt="Male puppy">
<div class="results-list">
    <ul>
    </ul>
</div><!-- end of results list -->
<div class="more-btn">
    <div class="short-btn"><a href="/dog-name/">Tap to See More Names</a></div>
    <div class="long-btn"><a href="/dog-name/">Get More Names on Dog Name Finder</a></div>
</div><!-- end of dnt btn -->
</code>```

Here is the JQuery portion:

```<code>   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

   <script src="https://cdnjs.cloudflare.com/ajax/libs/magnific-popup.js/0.9.9/jquery.magnific-popup.min.js"></script>
 <script>
    $(document).ready(function() {
         $('#dnt').submit(function(e){
               var cat_id = $('.dnt-overlay > select > option:selected').data('id') || 0;
           var cat_title = $('.dnt-overlay > select > option:selected').text() || 'All';
           if (cat_id === 0)
           {
              cat_title = 'All';
           }
           var dnt_url = $('.dnt-overlay > select > option:selected').val();
           var gender = $('.dnt-overlay > [name=gender]:checked').data('id') || 0;
           var gender_title = $('.dnt-overlay > [name=gender]:checked').val() || 'All';
           var title = cat_title;
           var html = '';

          var params = '';

          if(window.innerWidth <= 320)
          {
           params = '?limit=18';
          }
          else
          {
          params = '?limit=21';
          }

         if (cat_id > 0)
         {
         params += '&' + 'cat_id=' + cat_id;
         }

         if (gender > 0 && cat_title != 'Gender Agnostic' && cat_title != 'Unisex' && cat_title != 'Male' && cat_title != 'Female')
    {
        title += ' ' + gender_title;
        //params += '&' + 'gender=' + gender;
        if(cat_title == 'All')
        {
            dnt_url += gender_title.toLowerCase() + '/';
        }
        else
        {
            dnt_url += '?gender=' + gender_title.charAt(0).toLowerCase();
        }
    }

    title += ' Dog Names';

    $('#dnt-popup > h1').text(title);
    $('#dnt-popup > .more-btn').find('a').attr('href',dnt_url);

    e.preventDefault(); // We don't need to send the form, because it's all local
    if($('#male').is(':checked')) { // Check if male is checked
        $('#dnt-popup').removeClass('dnt-all').removeClass('dnt-female').addClass('dnt-male');
    } else if($('#female').is(':checked')) { // Check if female is checked
        $('#dnt-popup').removeClass('dnt-all').removeClass('dnt-male').addClass('dnt-female');
    } else if($('#all').is(':checked')) { // Check if all is checked
        $('#dnt-popup').removeClass('dnt-female').removeClass('dnt-male').addClass('dnt-all');
    }
    $.ajax({
      dataType: "json",
      url: "dnt.json"
    })
      .done(function( data ) {

        $.each(data, function( index, value ) {
          html +='<li>' + value.title + '</li>';
        });

        $('#dnt-popup > .results-list > ul').html(html);

        $.magnificPopup.open({ // open pop up for male
                items: {
                src: '#dnt-popup',
                type: 'inline'

                },//item
                mainClass: 'animated slideInRight'
        });///popup open

      });

});///submit function

$('#dnt-popup > .more-btn > .long-btn > a, #dnt-popup > .more-btn > .short-btn > a').on("click",function(){

    var cat_id = $('.dnt-overlay > select > option:selected').data('id') || 0;
    var cat_title = $('.dnt-overlay > select > option:selected').text() || 'All';
    if (cat_id === 0)
    {
        cat_title = 'All';
    }

    var gender_title = $('.dnt-overlay > [name=gender]:checked').val() || 'All';

    }); //event for click to DNT landing page

  });///submit function
  });//JQuery
 </script>
</code>```

sample data from the dnt.json file:

```<code>    [
      {
        "Name": "Aaliyah",
        "Female": 594,
        "Baby": 601
      },
     {
        "Name": "Abby",
        "Female": 594
     },
    {
        "Name": "Abe",
        "Male": 593,
        "Video Games": 604
    },
   {
         "Name": "Abigail",
         "Female": 594,
         "Baby": 601
    },
   {
         "Name": "Abu",
         "Male": 593,
         "Disney": 598
   },
  {
         "Name": "Ace",
         "Male": 593,
         "Fancy": 600,
         "Cool": 611
   },
  {
      "Name": "Ace",
      "Male": 593,
      "Fancy": 600,
      "Cool": 611
   },
   {
      "Name": "Action",
      "Male": 593,
      "Female": 594,
      "Agnostic": 595
   },
   {
       "Name": "Ada",
       "Female": 594,
       "German": 610
    },
    {
      "Name": "Adalyn",
      "Female": 594,
      "Baby": 601
    },
  ]
</code>```

Is there something I'm overlooking? Any Help would be greatly appreciated.

答:
When I run this code (after cleaning up some syntax errors) I hit this error:

SyntaxError: JSON.parse: unexpected character at line 54 column 3 of
  the JSON data

This is because of the comma here

```<code>    {
      "Name": "Adalyn",
      "Female": 594,
      "Baby": 601
    }, // <-- this comma
  ]
</code>```

When I remove that comma, the code still doesn't exactly work, but it does something when I click 'Show names'.

For reference, the way I debugged it was to add this code to the $.ajax call:

```<code>.fail(function(a,b,c) {
    console.log(a);
    console.log(b);
    console.log(c);
})
</code>```

This showed me that the done segment was never running, because the json was not formatted correctly.

Body:
I have built a dog naming tool through jquery. It was requested that a json file with all the names be added into the tool. For some reason now that I have converted to use the JSON file, it's no longer working. Here is the code for HTML and jquery:

Dog Name Finder

Dog Name Finder

<form class="dnt-tool" id="dnt" name="dnt">

        <input id="male" name="gender" type="radio" value="Male" />
            Male
        <input data-id="594" id="female" name="gender" type="radio" value="Female" />
            Female
        <input checked="checked" data-id="0" id="all" name="gender" type="radio" value="All" />
            All
        <select>
            <option data-id="0" value="/dog-name-finder/">Select a Category</option>
            <option data-id="0" value="/dog-name-finder/">All</option>
            <option value="/dog-name-finder/baby/">Baby</option>
            <option data-id="602" value="/dog-name-finder/celebrity/">Celebrity</option>
            <option data-id="603" value="/dog-name-finder/cute/">Cute</option>
            <option data-id="598" value="/dog-name-finder/disney/">Disney</option>
            <option data-id="600" value="/dog-name-finder/fancy/">Fancy</option>
            <option data-id="605" value="/dog-name-finder/most-popular/">Most Popular</option>
            <option data-id="599" value="/dog-name-finder/presidential/">Presidential</option>
            <option data-id="597" value="/dog-name-finder/techy/">Techy</option>
            <option data-id="596" value="/dog-name-finder/television/">Television</option>
            <option data-id="606" value="/dog-name-finder/trendy/">Trendy</option>
            <option data-id="595" value="/dog-name-finder/unisex/">Unisex</option>
            <option data-id="604" value="/dog-name-finder/video-game/">Video Game</option>
        </select>

        <button id="submit" type="submit">Show Names</button>

    </form>

Most Popular Dog Names

Tap to See More Names

Get More Names on Dog Name Finder

Here is the JQuery portion:

sample data from the dnt.json file:

    [
      {
        "Name": "Aaliyah",
        "Female": 594,
        "Baby": 601
      },
     {
        "Name": "Abby",
        "Female": 594
     },
    {
        "Name": "Abe",
        "Male": 593,
        "Video Games": 604
    },
   {
         "Name": "Abigail",
         "Female": 594,
         "Baby": 601
    },
   {
         "Name": "Abu",
         "Male": 593,
         "Disney": 598
   },
  {
         "Name": "Ace",
         "Male": 593,
         "Fancy": 600,
         "Cool": 611
   },
  {
      "Name": "Ace",
      "Male": 593,
      "Fancy": 600,
      "Cool": 611
   },
   {
      "Name": "Action",
      "Male": 593,
      "Female": 594,
      "Agnostic": 595
   },
   {
       "Name": "Ada",
       "Female": 594,
       "German": 610
    },
    {
      "Name": "Adalyn",
      "Female": 594,
      "Baby": 601
    },
  ]

Is there something I'm overlooking? Any Help would be greatly appreciated.

Body:
When I run this code (after cleaning up some syntax errors) I hit this error:

SyntaxError: JSON.parse: unexpected character at line 54 column 3 of
  the JSON data

This is because of the comma here

    {
      "Name": "Adalyn",
      "Female": 594,
      "Baby": 601
    }, // <-- this comma
  ]

When I remove that comma, the code still doesn't exactly work, but it does something when I click 'Show names'.

For reference, the way I debugged it was to add this code to the $.ajax call:

.fail(function(a,b,c) {
    console.log(a);
    console.log(b);
    console.log(c);
})

This showed me that the done segment was never running, because the json was not formatted correctly.


答:
Typescript is looking for name, birth_day, etc. properties on the Object class, but they don't exist on the Object class. You need to declare the type of your objects as any and then Typescript won't complain about your property names. Like this:

slider: any = {};
specialities: any = {};
works: any = {};
details: any = {};```

Title: Property 'address' does not exist on type {} while going into production mode Angular 4


问:
If functions are objects in JavaScript, then why can't they have name-value pair syntax for their properties?
If functions are objects in javascript, then why can't they have name-value pair syntax for their properties? For example, why is the following not possible/allowed?

```<code>function xx() {
    name: 'jhg'
}
alert(xx.name);
</code>```

and vice versa:

```<code>var person = {
    this.age = 32;
};
alert(person.age);
</code>```

答:
You could assign the properties, you want, but not Function.name, which is a read only property with the name of the function.

function xx() { }

xx.name = 'jhg'; // is read only, because it's the function's name
xx.foo = 'bar';

console.log(xx.name);
console.log(xx.foo);```

Body:
If functions are objects in javascript, then why can't they have name-value pair syntax for their properties? For example, why is the following not possible/allowed?

function xx() {
    name: 'jhg'
}
alert(xx.name);

and vice versa:

var person = {
    this.age = 32;
};
alert(person.age);


问:
how to start c++ mfc application
i work last 3 years on c#. now for some reason i have to make some MFC cpp application.
so what u people suggest for me. is it harder then c#? how can i begin? in c# i started just making some puzzle game do i follow the same for it? what is the best way to learn MFC c++? where i can find the resource? </p>

答:
MFC and C++ are harder than C#. It's very powerful but has a learning curve.

I would suggest you read the documentation on "Model/View Architecture" then use the wizard in visual studio to create an example application to use as a model.

Title: how to start c++ mfc application


问:
How can I add a dynamic value to the Contact Form 7 Plugin?
How can I add a dynamic value to Contact Form 7 without using an extra plugin. I need to display the Post title in the emails sent.

I am using the example in the Contact Form 7 docs here, but the clock tag only shows in the form page and not in the emails sent.

I don't know if there is something missing, or if I should add anything else to make this work?

```<code>add_action( 'wpcf7_init', 'custom_add_form_tag_clock' );

function custom_add_form_tag_clock() {
   wpcf7_add_form_tag( 'clock', 'custom_clock_form_tag_handler' ); // "clock" is the type of the form-tag
}

function custom_clock_form_tag_handler( $tag ) {
   return date_i18n( get_option( 'time_format' ) );
}
</code>```

答: There is a plugin build exactly for that. https://wordpress.org/plugins/contact-form-7-dynamic-text-extension/  Please check to see if it fits your needs!</p>

Body:
How can I add a dynamic value to Contact Form 7 without using an extra plugin. I need to display the Post title in the emails sent.

I am using the example in the Contact Form 7 docs here, but the clock tag only shows in the form page and not in the emails sent.

I don't know if there is something missing, or if I should add anything else to make this work?

add_action( 'wpcf7_init', 'custom_add_form_tag_clock' );

function custom_add_form_tag_clock() {
   wpcf7_add_form_tag( 'clock', 'custom_clock_form_tag_handler' ); // "clock" is the type of the form-tag
}

function custom_clock_form_tag_handler( $tag ) {
   return date_i18n( get_option( 'time_format' ) );
}


问:
WiX: DB Restore does not restore tables and records
i am attempting to restore a backup database file using WiX, and the database is created but none of the tables and data are restored.  it seems as though it is only creating the database and doing nothing else.  not sure if this is WiX related or has something to do with MSSQL usage.  here is the WiX XML:

```<code>      <Component Id="sql_backup_restore" Guid="8C95F258-7AB7-4A3A-A0CD-438FC61D45CC">
        <CreateFolder Directory="javaaaanew_dir"/>
        <sql:SqlDatabase Id="aaanew3_db" Server="[MSSQLSERVER]" Database="master" ConfirmOverwrite="yes" ContinueOnError="yes" DropOnReinstall="no" DropOnInstall="no" DropOnUninstall="no" CreateOnInstall="yes" CreateOnReinstall="no" CreateOnUninstall="no">
          <!-- restore blankaaa database -->
          <sql:SqlString Id="attach_db" ExecuteOnInstall ="yes" ExecuteOnReinstall="no" ExecuteOnUninstall="no" ContinueOnError="yes" Sequence="1" SQL="RESTORE DATABASE blankaaa FROM DISK = '[blankaaaBAK]' WITH RECOVERY;" />
          <!-- rename blankaaa to aaanew3 -->
          <sql:SqlString Id="alter_db_name" ExecuteOnInstall ="yes" ExecuteOnReinstall="no" ExecuteOnUninstall="no" ContinueOnError="yes" Sequence="2" SQL="USE master;GO;ALTER DATABASE blankaaa Modify Name = 'aaanew3' GO;" /> <!-- should fail here if preexisting database? -->
          <!-- change aaanew3 dbowner to 'sa' -->
          <sql:SqlString Id="alter_db_owner" ExecuteOnInstall ="yes" ExecuteOnReinstall="no" ExecuteOnUninstall="no" ContinueOnError="yes" Sequence="3" SQL="ALTER AUTHORIZATION ON DATABASE::aaanew3 TO sa;" />
          <!-- add user 'sa' to database security? -->
          <sql:SqlString Id="alter_db_sa" ExecuteOnInstall ="yes" ExecuteOnReinstall="no" ExecuteOnUninstall="no" ContinueOnError="yes" Sequence="4" SQL="USE [aaanew3];GO;CREATE USER [sa] FOR LOGIN [sa];GO;" />
          <!-- add user mapping for 'sa' on aaanew3 with schema 'dbo' -->
          <sql:SqlString Id="alter_db_schema" ExecuteOnInstall ="yes" ExecuteOnReinstall="no" ExecuteOnUninstall="no" ContinueOnError="yes" Sequence="5" SQL="USE [aaanew3];GO;ALTER USER [sa] WITH DEFAULT_SCHEMA=[dbo];GO;" />
        </sql:SqlDatabase>
      </Component>
</code>```

i have also tried "WITH RECOVERY" and using escape sequence around the square brackets:

```<code><sql:SqlString Id="attach_db" ExecuteOnInstall ="yes" ExecuteOnReinstall="no" ExecuteOnUninstall="no" ContinueOnError="yes" Sequence="1" SQL="RESTORE DATABASE blankaaa FROM DISK = '[\[]blankaaaBAK[\]]' WITH RECOVERY;" />
</code>```

the proper way to do this seems wretchedly unclear in the documentation.

答:
rather than trying to refer to the wix name of the database file, i used the following:</p>

```<code> SQL="RESTORE DATABASE blankaaa FROM DISK = '[INSTALLFOLDER]javaaaanew\blankaaa.bak' WITH RECOVERY"
</code>```

Body:
i am attempting to restore a backup database file using WiX, and the database is created but none of the tables and data are restored.  it seems as though it is only creating the database and doing nothing else.  not sure if this is WiX related or has something to do with MSSQL usage.  here is the WiX XML:

      <Component Id="sql_backup_restore" Guid="8C95F258-7AB7-4A3A-A0CD-438FC61D45CC">
        <CreateFolder Directory="javaaaanew_dir"/>
        <sql:SqlDatabase Id="aaanew3_db" Server="[MSSQLSERVER]" Database="master" ConfirmOverwrite="yes" ContinueOnError="yes" DropOnReinstall="no" DropOnInstall="no" DropOnUninstall="no" CreateOnInstall="yes" CreateOnReinstall="no" CreateOnUninstall="no">

          <sql:SqlString Id="attach_db" ExecuteOnInstall ="yes" ExecuteOnReinstall="no" ExecuteOnUninstall="no" ContinueOnError="yes" Sequence="1" SQL="RESTORE DATABASE blankaaa FROM DISK = '[blankaaaBAK]' WITH RECOVERY;" />

          <sql:SqlString Id="alter_db_name" ExecuteOnInstall ="yes" ExecuteOnReinstall="no" ExecuteOnUninstall="no" ContinueOnError="yes" Sequence="2" SQL="USE master;GO;ALTER DATABASE blankaaa Modify Name = 'aaanew3' GO;" />

          <sql:SqlString Id="alter_db_owner" ExecuteOnInstall ="yes" ExecuteOnReinstall="no" ExecuteOnUninstall="no" ContinueOnError="yes" Sequence="3" SQL="ALTER AUTHORIZATION ON DATABASE::aaanew3 TO sa;" />

          <sql:SqlString Id="alter_db_sa" ExecuteOnInstall ="yes" ExecuteOnReinstall="no" ExecuteOnUninstall="no" ContinueOnError="yes" Sequence="4" SQL="USE [aaanew3];GO;CREATE USER [sa] FOR LOGIN [sa];GO;" />

          <sql:SqlString Id="alter_db_schema" ExecuteOnInstall ="yes" ExecuteOnReinstall="no" ExecuteOnUninstall="no" ContinueOnError="yes" Sequence="5" SQL="USE [aaanew3];GO;ALTER USER [sa] WITH DEFAULT_SCHEMA=[dbo];GO;" />
        </sql:SqlDatabase>
      </Component>

i have also tried "WITH RECOVERY" and using escape sequence around the square brackets:

<sql:SqlString Id="attach_db" ExecuteOnInstall ="yes" ExecuteOnReinstall="no" ExecuteOnUninstall="no" ContinueOnError="yes" Sequence="1" SQL="RESTORE DATABASE blankaaa FROM DISK = '[\[]blankaaaBAK[\]]' WITH RECOVERY;" />

the proper way to do this seems wretchedly unclear in the documentation.

Body:
rather than trying to refer to the wix name of the database file, i used the following:

 SQL="RESTORE DATABASE blankaaa FROM DISK = '[INSTALLFOLDER]javaaaanew\blankaaa.bak' WITH RECOVERY"


问:
Hadoop 2: why are there two linux processes for each map or reduce task?
We are trying to migrate our jobs to Hadoop 2 (Hadoop 2.8.1, single node cluster, to be precise) from Hadoop 1.0.3. We are using YARN to manage our map-reduce jobs. One of the differences that we have noticed is the presence of two Linux processes for each map or reduce task that is planned for execution. For example, for any of our reduce tasks, we find these two executing processes:

hadoop   124692 124690  0 12:33 ?        00:00:00 /bin/bash -c /opt/java/bin/java -Djava.net.preferIPv4Stack=true -Dhadoop.metrics.log.level=WARN  -Xmx5800M -XX:-UsePerfData -Djava.io.tmpdir=/tmp/hadoop-hadoop/nm-local-dir/usercache/hadoop/appcache/application_1510651062679_0001/container_1510651062679_0001_01_000278/tmp -Dlog4j.configuration=container-log4j.properties -Dyarn.app.container.log.dir=/opt/hadoop/hadoop-2.8.1/logs/userlogs/application_1510651062679_0001/container_1510651062679_0001_01_000278 -Dyarn.app.container.log.filesize=0 -Dhadoop.root.logger=INFO,CLA -Dhadoop.root.logfile=syslog -Dyarn.app.mapreduce.shuffle.logger=INFO,shuffleCLA -Dyarn.app.mapreduce.shuffle.logfile=syslog.shuffle -Dyarn.app.mapreduce.shuffle.log.filesize=0 -Dyarn.app.mapreduce.shuffle.log.backups=0 org.apache.hadoop.mapred.YarnChild 192.168.101.29 33929 attempt_1510651062679_0001_r_000135_0 278 1>/opt/hadoop/hadoop-2.8.1/logs/userlogs/application_1510651062679_0001/container_1510651062679_0001_01_000278/stdout 2>/opt/hadoop/hadoop-2.8.1/logs/userlogs/application_1510651062679_0001/container_1510651062679_0001_01_000278/stderr

hadoop   124696 124692 74 12:33 ?        00:10:30 /opt/java/bin/java -Djava.net.preferIPv4Stack=true -Dhadoop.metrics.log.level=WARN -Xmx5800M -XX:-UsePerfData -Djava.io.tmpdir=/tmp/hadoop-hadoop/nm-local-dir/usercache/hadoop/appcache/application_1510651062679_0001/container_1510651062679_0001_01_000278/tmp -Dlog4j.configuration=container-log4j.properties -Dyarn.app.container.log.dir=/opt/hadoop/hadoop-2.8.1/logs/userlogs/application_1510651062679_0001/container_1510651062679_0001_01_000278 -Dyarn.app.container.log.filesize=0 -Dhadoop.root.logger=INFO,CLA -Dhadoop.root.logfile=syslog -Dyarn.app.mapreduce.shuffle.logger=INFO,shuffleCLA -Dyarn.app.mapreduce.shuffle.logfile=syslog.shuffle -Dyarn.app.mapreduce.shuffle.log.filesize=0 -Dyarn.app.mapreduce.shuffle.log.backups=0

The second process is a child of the first one. All in all, we see that the overall number of processes during our job execution is much higher than it was with Hadoop 1.0.3, where only one process was executing for each map or reduce task.

a) Could this be a reason for the job executing quite slower than it does with Hadoop 1.0.3 ?

b) Are those two processes the intended way it all works ?

Thank you in advance for your advice.

答:
On a close check you will find

```<code>Pid  124692 is /bin/bash
Pid  124696 is /opt/java/bin/java
</code>```

/bin/bash is the container process which spawns Java process within the enclosed environment (CPU , RAM restricted to a container)

You can think of this as A Virtual Machine inside which you can run your own process. Both virtual machine and the process running inside it will have a parent child relationship.

Please read about Linux container in details to know more about it .

Body:
On a close check you will find

Pid  124692 is /bin/bash
Pid  124696 is /opt/java/bin/java

/bin/bash is the container process which spawns Java process within the enclosed environment (CPU , RAM restricted to a container)

You can think of this as A Virtual Machine inside which you can run your own process. Both virtual machine and the process running inside it will have a parent child relationship.

Please read about Linux container in details to know more about it .


问:
Git run shell command for each commit
I would like to walk through a range of commits and perform a shell command on each.  If the command fails, I would like the walk to stop, otherwise keep going.  I have looked at filter-branch, but I don't want to re-write the commits, just check them out.  for-each-ref does not seem to allow you to specify a range to act on.

My specific problem is that I created a bunch of commits and I would like to ensure that each commit is buildable.  I would like to do something like:

```<code>git foreach origin/master..master 'git submodule update && make clean && make'
</code>```

I could of course write a shell script to do this, but it seems like the sort of thing that git might have a nice way to do.

答:
Here's a cool one-liner using xargs.

```<code>git rev-list @{upstream}..HEAD | xargs -n1 -I{} sh -c 'git checkout {} && git submodule update && make clean && make'
</code>```

You may also want to pass the --reverse option to rev-list so that the last checkout is HEAD.

Title: Git run shell command for each commit

Body:
I would like to walk through a range of commits and perform a shell command on each.  If the command fails, I would like the walk to stop, otherwise keep going.  I have looked at filter-branch, but I don't want to re-write the commits, just check them out.  for-each-ref does not seem to allow you to specify a range to act on.

My specific problem is that I created a bunch of commits and I would like to ensure that each commit is buildable.  I would like to do something like:

git foreach origin/master..master 'git submodule update && make clean && make'

I could of course write a shell script to do this, but it seems like the sort of thing that git might have a nice way to do.

Body:
Here's a cool one-liner using xargs.

git rev-list @{upstream}..HEAD | xargs -n1 -I{} sh -c 'git checkout {} && git submodule update && make clean && make'

You may also want to pass the --reverse option to rev-list so that the last checkout is HEAD.


问:
Why isn't my variable available inside the scope of an AngularJS promise?
I write promises to take from back-end some data. But function end() don't see my variable witch contains this data. What I'm doing wrong, and how to return overlappingProjects variable?

Console.log(1 and 2) shows massive with data but console.log(4) already have empty object.

```<code>this.checkSingleInvitation = function(invitation) {
    console.log('Оверлап сингл');
    var dtoArray = [];
    var overlappingProjects = {};

    InvitationService.acceptedProjects.models.forEach(function(accepted) {
        if(!(dateHelper.parseDate(accepted.dt_from) > dateHelper.parseDate(invitation.dt_to) || dateHelper.parseDate(accepted.dt_to) < dateHelper.parseDate(invitation.dt_from))) {
            var dto = {
                target: invitation.project_has_musicians_id,
                goal: accepted.project_id
            };
            dtoArray.push(dto);
        }
    });

    var promises = [];
    angular.forEach(dtoArray, (function(dto) {
        var deferred = $q.defer();
        var overlappingProjects = {};
        //async fun
        InvitationService.checkOverlapping(dto)
            .before(function() {
                progressBars.progressbar.requestsInProgress++;
            })
            .success(function(data) {
                // TODO: overlappingProjects - ???
                if(Object.keys(data).length) {
                    console.log('1');
                    console.log(data);
                    overlappingProjects = data;
                    console.log(overlappingProjects);
                }
                console.log('2');
                console.log(data);
                deferred.resolve(data);
            })
            .error(function(error) {
                deferred.reject(error);
            })
            .finally(function() {
                progressBars.progressbar.requestsInProgress--;
            });
        promises.push(deferred.promise);
    }));
    $q.all(promises).then(console.log(promises)).then(
        end()
    );

    function end() {
        console.log('4');
        console.log(overlappingProjects);
        return overlappingProjects;
    }
}
</code>```

答:
In addition to twice variable(overlappingProjects) declaration, you call end function immediately instead of pass it as callback:

```<code>$q.all(promises).then(console.log(promises)).then(
    end()
);
</code>```

Should be:

```<code>$q.all(promises)
  .then(() => console.log(promises)) // may be .then(results => console.log(results)) ?
  .then(end);
</code>```

Body:
I write promises to take from back-end some data. But function end() don't see my variable witch contains this data. What I'm doing wrong, and how to return overlappingProjects variable?

Console.log(1 and 2) shows massive with data but console.log(4) already have empty object.

this.checkSingleInvitation = function(invitation) {
    console.log('Оверлап сингл');
    var dtoArray = [];
    var overlappingProjects = {};

    InvitationService.acceptedProjects.models.forEach(function(accepted) {
        if(!(dateHelper.parseDate(accepted.dt_from) > dateHelper.parseDate(invitation.dt_to) || dateHelper.parseDate(accepted.dt_to) < dateHelper.parseDate(invitation.dt_from))) {
            var dto = {
                target: invitation.project_has_musicians_id,
                goal: accepted.project_id
            };
            dtoArray.push(dto);
        }
    });

    var promises = [];
    angular.forEach(dtoArray, (function(dto) {
        var deferred = $q.defer();
        var overlappingProjects = {};
        //async fun
        InvitationService.checkOverlapping(dto)
            .before(function() {
                progressBars.progressbar.requestsInProgress++;
            })
            .success(function(data) {
                // TODO: overlappingProjects - ???
                if(Object.keys(data).length) {
                    console.log('1');
                    console.log(data);
                    overlappingProjects = data;
                    console.log(overlappingProjects);
                }
                console.log('2');
                console.log(data);
                deferred.resolve(data);
            })
            .error(function(error) {
                deferred.reject(error);
            })
            .finally(function() {
                progressBars.progressbar.requestsInProgress--;
            });
        promises.push(deferred.promise);
    }));
    $q.all(promises).then(console.log(promises)).then(
        end()
    );

    function end() {
        console.log('4');
        console.log(overlappingProjects);
        return overlappingProjects;
    }
}

Body:
In addition to twice variable(overlappingProjects) declaration, you call end function immediately instead of pass it as callback:

$q.all(promises).then(console.log(promises)).then(
    end()
);

Should be:

$q.all(promises)
  .then(() => console.log(promises)) // may be .then(results => console.log(results)) ?
  .then(end);


答:
IIUC:

```<code>shoes_df['brand'] = shoes_df.Product.str.extract(pat='(Nike|Adidas|Asics)',expand=False)
</code>```

Output:

```<code>            Product  Unit sales   brand
0     Nike vaporfly        1500    Nike
1      Nike Jordans        1600    Nike
2  Adidas supernova        2341  Adidas
3      Asics Kayano        1345   Asics
4      Asics GT2010        4523   Asics
5    Adidas gazelle        2345  Adidas
6      Nike air max        1634    Nike
7       Nike Lebron        3129    Nike
</code>```

Title: Adding values to new Pandas dataframe column based on partial string contents of existing column

Body:
I have data stored as a dataframe using Python Pandas. Among the columns, I have a "Product" column which contains the brand name and model (e.g. Nike Air Jordan, Adidas Gazelle). I want to create a new column that just contains the brand (e.g. Nike, Adidas), which I will later use in groupby to summarize the data.
From my research, I believe contains and regex can be used to do this. However, the implementation has not worked. I've also seen different approaches, some using "for i in range" while others do it as a replace in a single line of code.

import pandas as pd
import numpy as np

shoes_df = pd.DataFrame({'Product':['Nike vaporfly', 'Nike Jordans', 'Adidas supernova', 'Asics Kayano', 'Asics GT2010', 'Adidas gazelle', 'Nike air max',
                                  'Nike Lebron'], 'Unit sales':[1500, 1600,
2341, 1345, 4523, 2345, 1634, 3129]})

shoes_df['Brand'] = np.where(shoes_df['Product'].str.contains('Nike.*|Adidas.*').any(), 'Nike|Adidas', np.nan)

print(shoes_df)

Here was my attempt at doing the "for i in range" approach, which did not work either. Here, I got the error "TypeError: 'Series' objects are mutable, thus they cannot be hashed"

shoes_df = pd.DataFrame({'Product':['Nike vaporfly', 'Nike Jordans', 'Adidas supernova', 'Asics Kayano', 'Asics GT2010', 'Adidas gazelle', 'Nike air max',
                                  'Nike Lebron'], 'Unit sales':[1500, 1600, 2341, 1345, 4523,
                                   2345, 1634, 3129]})

for i in shoes_df.iterrows():
    if shoes_df['Product'].str.contains('Nike').any():
        shoes_df.set_value(i, 'Brand', 'Nike')
    elif shoes_df['Product'].str.contains('Adidas').any():
        shoes_df.set_value(i, 'Brand', 'Adidas')
    elif shoes_df['Product'].str.contains('Asics').any():
        shoes_df.set_value(i, 'Brand', 'Asics')
    else:
        shoes_df.set_value(i, 'Brand', np.nan)

Body:
IIUC:

shoes_df['brand'] = shoes_df.Product.str.extract(pat='(Nike|Adidas|Asics)',expand=False)

Output:

            Product  Unit sales   brand
0     Nike vaporfly        1500    Nike
1      Nike Jordans        1600    Nike
2  Adidas supernova        2341  Adidas
3      Asics Kayano        1345   Asics
4      Asics GT2010        4523   Asics
5    Adidas gazelle        2345  Adidas
6      Nike air max        1634    Nike
7       Nike Lebron        3129    Nike