问:
How to define specificity as a callable scorer for model evaluation
I am using this code to compare performance of a number of models:

```<code>from sklearn import model_selection

X = input data
Y = binary labels

models = []
models.append(('LR', LogisticRegression()))
models.append(('LDA', LinearDiscriminantAnalysis()))
models.append(('KNN', KNeighborsClassifier()))
models.append(('CART', DecisionTreeClassifier()))

results = []
names = []
scoring = 'accuracy'

for name, model in models:
    kfold = model_selection.KFold(n_splits=10, random_state=7)
    cv_results = model_selection.cross_val_score(model, X, Y, cv=kfold,scoring=scoring)
    results.append(cv_results)
    names.append(name)
    msg = "%s: %.2f (%.2f)" % (name, cv_results.mean(), cv_results.std())
    print(msg)
</code>```

I can use 'accuracy' and 'recall' as scoring and these will give accuracy and sensitivity. How can I create a scorer that gives me 'specificity'

Specificity= TN/(TN+FP)

where TN, and FP are true negative and false positive values in the confusion matrix

I have tried this

```<code>def tp(y_true, y_pred):
error= confusion_matrix(y_true, y_pred)[0,0]/(confusion_matrix(y_true,y_pred)[0,0] + confusion_matrix(y_true, y_pred)[0,1])
return error

my_scorer = make_scorer(tp, greater_is_better=True)
</code>```

and then

```<code>cv_results = model_selection.cross_val_score(model, X,Y,cv=kfold,scoring=my_scorer)
</code>```

but it will not work for n_split >=10
I get this error for calculation of my_scorer

IndexError: index 1 is out of bounds for axis 1 with size 1

答:
You cannot get specificity in scikit but what you can actually get is fpr which is:

```<code>fpr = 1 - specificity
</code>```

So for getting specificity, you just need to subtract fpr from 1.

fpr can be calculated using roc_curve.

```<code>import numpy as np
from sklearn.metrics import roc_curve
y_true = np.array([1, 1, 2, 2])
y_pred = np.array([0.1, 0.4, 0.35, 0.8])
fpr, tpr, thresholds = roc_curve(y_true, y_pred)

print(fpr)
# array([ 0. ,  0.5,  0.5,  1. ])

specificity = 1 - fpr
# array([ 1. ,  0.5,  0.5,  0. ])
</code>```

But for the above to work you need to calculate the y_pred by training the model.

If you want to use this inside the cross_val_score, you can make a custom scorer like this:

```<code>from sklearn.metrics import roc_curve
def specificity(y_true, y_pred):
    fpr, tpr, thresholds = roc_curve(y_true, y_pred)
    speci = 1 - fpr
    return speci

from sklearn.metrics import make_scorer
scorer = make_scorer(specificity)
</code>```

And then:

```<code>cv_results = model_selection.cross_val_score(model, X, Y, cv=kfold,scoring=scorer)
</code>```

NOTE: The above codes will only give correct results for binary y.

Body:
I am using this code to compare performance of a number of models:

from sklearn import model_selection

X = input data
Y = binary labels

models = []
models.append(('LR', LogisticRegression()))
models.append(('LDA', LinearDiscriminantAnalysis()))
models.append(('KNN', KNeighborsClassifier()))
models.append(('CART', DecisionTreeClassifier()))

results = []
names = []
scoring = 'accuracy'

for name, model in models:
    kfold = model_selection.KFold(n_splits=10, random_state=7)
    cv_results = model_selection.cross_val_score(model, X, Y, cv=kfold,scoring=scoring)
    results.append(cv_results)
    names.append(name)
    msg = "%s: %.2f (%.2f)" % (name, cv_results.mean(), cv_results.std())
    print(msg)

I can use 'accuracy' and 'recall' as scoring and these will give accuracy and sensitivity. How can I create a scorer that gives me 'specificity'

Specificity= TN/(TN+FP)

where TN, and FP are true negative and false positive values in the confusion matrix

I have tried this

def tp(y_true, y_pred):
error= confusion_matrix(y_true, y_pred)[0,0]/(confusion_matrix(y_true,y_pred)[0,0] + confusion_matrix(y_true, y_pred)[0,1])
return error

my_scorer = make_scorer(tp, greater_is_better=True)

and then

cv_results = model_selection.cross_val_score(model, X,Y,cv=kfold,scoring=my_scorer)

but it will not work for n_split >=10
I get this error for calculation of my_scorer

IndexError: index 1 is out of bounds for axis 1 with size 1

Body:
You cannot get specificity in scikit but what you can actually get is fpr which is:

fpr = 1 - specificity

So for getting specificity, you just need to subtract fpr from 1.

fpr can be calculated using roc_curve.

import numpy as np
from sklearn.metrics import roc_curve
y_true = np.array([1, 1, 2, 2])
y_pred = np.array([0.1, 0.4, 0.35, 0.8])
fpr, tpr, thresholds = roc_curve(y_true, y_pred)

print(fpr)
# array([ 0. ,  0.5,  0.5,  1. ])

specificity = 1 - fpr
# array([ 1. ,  0.5,  0.5,  0. ])

But for the above to work you need to calculate the y_pred by training the model.

If you want to use this inside the cross_val_score, you can make a custom scorer like this:

from sklearn.metrics import roc_curve
def specificity(y_true, y_pred):
    fpr, tpr, thresholds = roc_curve(y_true, y_pred)
    speci = 1 - fpr
    return speci

from sklearn.metrics import make_scorer
scorer = make_scorer(specificity)

And then:

cv_results = model_selection.cross_val_score(model, X, Y, cv=kfold,scoring=scorer)

NOTE: The above codes will only give correct results for binary y.


来源: stackexchange

问:
Is a SQL Constraint On Multiple Columns and Values Possible?
I'm using SQL Server and have a table ProjectAccess which I'm hoping to use as a way to "lock" access to Projects. Currently the table looks like this:

```<code>CREATE TABLE [dbo].[ProjectAccess]
(
    [ProjectAccessID] INT IDENTITY (1, 1) NOT NULL,
    [ProjectID] INT NOT NULL,
    [UserSessionID] INT NOT NULL,
    [Locked] BIT NOT NULL,

    CONSTRAINT [uq_UserSessionID]
        UNIQUE NONCLUSTERED ([UserSessionID]),
    CONSTRAINT [fk_ProjectAccessToProject]
        FOREIGN KEY ([ProjectID]) REFERENCES [dbo].[Project] ([ProjectID])
                ON DELETE CASCADE,
    CONSTRAINT [fk_ProjectAccessToUserSession]
        FOREIGN KEY ([UserSessionID]) REFERENCES [dbo].[UserSession] ([UserSessionID])
                ON DELETE CASCADE,
    CONSTRAINT [PK_ProjectAccess]
        PRIMARY KEY ([ProjectAccessID])
);
</code>```

The idea was to only allow for multiple of the same project ID's into this table, but only one could have the Locked column value as true. For example you could have two records with ProjectID 1 in the table at the same time as long as both did not have the Locked value set to true. So is there a way to do this? I see that there is a check constraint but that seems to check all values in a column satisfy a certain condition which is a little different than what I'm hoping for. Thank you in advance and let me know if anything isn't clear enough.

答:
You can use a filtered unique index:</p>

```<code>create unique index unq_projectaccess_projectid_locked
    on projectaccess(projectid)
    where locked = 1;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm using SQL Server and have a table ProjectAccess which I'm hoping to use as a way to "lock" access to Projects. Currently the table looks like this:

CREATE TABLE [dbo].[ProjectAccess]
(
    [ProjectAccessID] INT IDENTITY (1, 1) NOT NULL,
    [ProjectID] INT NOT NULL,
    [UserSessionID] INT NOT NULL,
    [Locked] BIT NOT NULL,

    CONSTRAINT [uq_UserSessionID]
        UNIQUE NONCLUSTERED ([UserSessionID]),
    CONSTRAINT [fk_ProjectAccessToProject]
        FOREIGN KEY ([ProjectID]) REFERENCES [dbo].[Project] ([ProjectID])
                ON DELETE CASCADE,
    CONSTRAINT [fk_ProjectAccessToUserSession]
        FOREIGN KEY ([UserSessionID]) REFERENCES [dbo].[UserSession] ([UserSessionID])
                ON DELETE CASCADE,
    CONSTRAINT [PK_ProjectAccess]
        PRIMARY KEY ([ProjectAccessID])
);

The idea was to only allow for multiple of the same project ID's into this table, but only one could have the Locked column value as true. For example you could have two records with ProjectID 1 in the table at the same time as long as both did not have the Locked value set to true. So is there a way to do this? I see that there is a check constraint but that seems to check all values in a column satisfy a certain condition which is a little different than what I'm hoping for. Thank you in advance and let me know if anything isn't clear enough.

Body:
You can use a filtered unique index:

create unique index unq_projectaccess_projectid_locked
    on projectaccess(projectid)
    where locked = 1;


问:
Drupal views PHP filter is showing node id instead of value
I'm trying to print the taxonomy terms (which is field_company) but it's printing node id of that article.

These are my available variables

code used in Global: PHP

```<code><?php
$term = $row->field_company;
print($term);
?>
</code>```

In my view Auto Preview, its showing like below.

article 1 Title

PHP: 2345 //these are node ids

article 2 Title

PHP: 2346 //these are node ids

article 3 Title

PHP: 2347 //these are node ids

article 4 Title

PHP: 2348 //these are node ids

What I'm expecting here is:
for example in my taxonomy list (company) I have terms like,

```<code>company taxonomy terms list
-term1
-term2
-term3
</code>```

article 1 Title

PHP: term1

article 2 Title

PHP: term2

article 3 Title

PHP: term2

article 4 Title

PHP: term3

article 5 Title

PHP: term1

答:
If the field field_company is a taxonomy reference field, then below should work.

```<code>$tid = $row->field_company;
$term = taxonomy_term_load($tid);
print($term->name);
</code>```

But you say it is outputting a node id? Which means field_company is not a taxonomy term reference field, maybe it is a node reference field?

If it is referencing a node, then this may work.

```<code>$nid = $row->field_company;
$n = node_load($nid);
print($n->title);
</code>```

Or you could use the entity api to load the term or node.

But,

you really should not be doing this with a Global:PHP field (in fact you should probably never use Global:PHP).

The output you want should be easy to achived in views (relationshiips) without using the Global:PHP field and will likely be faster and easier to change later if need be.

Body:
I'm trying to print the taxonomy terms (which is field_company) but it's printing node id of that article.

These are my available variables

code used in Global: PHP

<?php
$term = $row->field_company;
print($term);
?>

In my view Auto Preview, its showing like below.

article 1 Title

PHP: 2345 //these are node ids

article 2 Title

PHP: 2346 //these are node ids

article 3 Title

PHP: 2347 //these are node ids

article 4 Title

PHP: 2348 //these are node ids

What I'm expecting here is:
for example in my taxonomy list (company) I have terms like,

company taxonomy terms list
-term1
-term2
-term3

article 1 Title

PHP: term1

article 2 Title

PHP: term2

article 3 Title

PHP: term2

article 4 Title

PHP: term3

article 5 Title

PHP: term1

Body:
If the field field_company is a taxonomy reference field, then below should work.

$tid = $row->field_company;
$term = taxonomy_term_load($tid);
print($term->name);

But you say it is outputting a node id? Which means field_company is not a taxonomy term reference field, maybe it is a node reference field?

If it is referencing a node, then this may work.

$nid = $row->field_company;
$n = node_load($nid);
print($n->title);

Or you could use the entity api to load the term or node.

But,

you really should not be doing this with a Global:PHP field (in fact you should probably never use Global:PHP).

The output you want should be easy to achived in views (relationshiips) without using the Global:PHP field and will likely be faster and easier to change later if need be.


问:
It's better to hardcore constant values than make query to DB?
I have quite complicated form which contains a lot of values and I wonder, which option is better from performance perspective:

Load the data () from the database

Hardcode these data () right in the form

Basically these constant options (values will never change) are in the Database and have their own tables to avoid data duplication and they also have ManyToMany relationships with posts.

But wouldn't be better to hardcode these options in the selectable fields rather than making bunch of queries to the database to get these options?

Thanks in advance.

答:
Usually you'd write a form generator that would, based on whatever's in the database, generate a form. If this form is generated very frequently and changes are very infrequent that's a candidate for caching.

Hard-coding is usually a bad idea for a multitude of reasons, but the biggest concern here is that your database and your form will differ in some subtle but important way. By having the form be generated by the database there's fewer chances of mistakes. You can also have the database be generated by the form (e.g. document store) but that's less common.


问:
What does this symbol mean in C++? "~"
If we use ~ before a function like this: ~func();, what does this mean?

Thanks.

答:
If it's part of a class definition, it's a destructor for that class, provided the function name is the same as the class name (Otherwise it would be a syntax error).

```<code>class stuff {
  stuff(); // constructor for stuff
  ~stuff(); // destructor for stuff
};
</code>```

It could also be a bit-wise not operator. i.e.

```<code>int x = ~func();
</code>```

In this context, it will take the return value from func(), which is presumably returning an integral type, flip all the bits and store the result in x.

If func() returns an object which has operator~ defined in its class, then it could mean just about anything ;-)

ContentLicense: CC BY-SA 2.5

Title: What does this symbol mean in C++? "~"

Body:
If it's part of a class definition, it's a destructor for that class, provided the function name is the same as the class name (Otherwise it would be a syntax error).

class stuff {
  stuff(); // constructor for stuff
  ~stuff(); // destructor for stuff
};

It could also be a bit-wise not operator. i.e.

int x = ~func();

In this context, it will take the return value from func(), which is presumably returning an integral type, flip all the bits and store the result in x.

If func() returns an object which has operator~ defined in its class, then it could mean just about anything ;-)


问:
create submit form with jquery
i want to make a submit action, so when i click submit the page will not refresh and data i input in div1 will send to kanjiconverter.php and display it to div2 by <?php echo $newkanji ?>. i have 3 form in these page.

here my kanjiconverter.php. i save a submit code here.

```<code><?php
  if(isset($_POST['submit1'])){
        $kanji = ($_POST['convertkanji']);

        $replacements = [
        'class="rt">' => "",
        ];
        $newkanji = strtr($kanji, $replacements);
  }
?>
</code>```

and my form code is here. submit button was in div1 but im using input tag not button tag.

```<code><form id="convertkanji" method="post" action="kanjiconverter.php"></form>
        <form>
          <div class="form-row">

            <!-- START DIV1 HERE -->
          <div id="div1" class="form-group col-md-6">
            <label for="convertkanji">Kanji Convert</label>
            <textarea id="convertkanji1" name="convertkanji" rows="10" form="convertkanji"></textarea>
            <input type="submit" name="submit1" class="btn btn-default" form="convertkanji" value="Convert" style="width: 100%; margin-top: 6px;" />
          </div>
          <!-- Ended DIV1 HERE -->

          <!-- START DIV2 HERE -->
            <div id="div2" class="form-group col-md-6" style="display: none;">
      <label for="kanji">New Kanji</label>
      <textarea id="kanji" name="kanji" rows="12" form="tambahposting"><?php echo $newkanji ?></textarea>
    </div>
          <!-- Ended DIV2 HERE -->
    </form>
</code>```

and heres my jquery script. im place it above  tag.

```<code>    <script>
        $(function() {
  $('#div1').show();
  $('#div2').hide();

  $('input[name="submit1"]').on('click', function(e) {
    e.preventDefault();

    $('#div1').hide();
    $('#div2').show();

    $.post('kanjiconverter.php', $('form').serialize(), function(response) {
      //Your response from the server-side
    })
  });
});
      </script>
</code>```

i make div2 hide for first and div1 show. but when i click submit div1 will hide and div2 will show.

and i place  between  and  tag.

the problem is, when i click submit the data i input not showing. only hide and show who was working. i think the data is not send.

答: You have two opening form tags. Bad HTML. Please review.</p>

Title: create submit form with jquery

Body:
i want to make a submit action, so when i click submit the page will not refresh and data i input in div1 will send to kanjiconverter.php and display it to div2 by <?php echo $newkanji ?>. i have 3 form in these page.

here my kanjiconverter.php. i save a submit code here.

<?php
  if(isset($_POST['submit1'])){
        $kanji = ($_POST['convertkanji']);

        $replacements = [
        'class="rt">' => "",
        ];
        $newkanji = strtr($kanji, $replacements);
  }
?>

and my form code is here. submit button was in div1 but im using input tag not button tag.

<form id="convertkanji" method="post" action="kanjiconverter.php"></form>
        <form>

            Kanji Convert
            <textarea id="convertkanji1" name="convertkanji" rows="10" form="convertkanji"></textarea>
            <input type="submit" name="submit1" class="btn btn-default" form="convertkanji" value="Convert" style="width: 100%; margin-top: 6px;" />

      New Kanji
      <textarea id="kanji" name="kanji" rows="12" form="tambahposting"><?php echo $newkanji ?></textarea>

    </form>

and heres my jquery script. im place it above  tag.

i make div2 hide for first and div1 show. but when i click submit div1 will hide and div2 will show.

and i place  between  and  tag.

the problem is, when i click submit the data i input not showing. only hide and show who was working. i think the data is not send.


问:
How to count uppercase and lowercase letters in a string?
yo, so im trying to make a program that can take string input from the user for instance: "ONCE UPON a time" and then report back how many upper and lowercase letters the string contains: </p>

<p>output example:  the string has 8 uppercase letters
the string has 5 lowercase letters, and im supposed to use string class not arrays, any tips on how to get started on this one? thanks in advance, here is what I have done so far :D! </p>

```<code>import java.util.Scanner;
public class q36{
    public static void main(String args[]){

        Scanner keyboard = new Scanner(System.in);
        System.out.println("Give a string ");
        String input=keyboard.nextLine();

        int lengde = input.length();
        System.out.println("String: " + input + "\t " + "lengde:"+ lengde);

        for(int i=0; i<lengde;i++) {
            if(Character.isUpperCase(CharAt(i))){

            }
        }
    }
}
</code>```

答:
java 8

```<code>private static long countUpperCase(String inputString) {
        return inputString.chars().filter((s)->Character.isUpperCase(s)).count();
    }

    private static long countLowerCase(String inputString) {
        return inputString.chars().filter((s)->Character.isLowerCase(s)).count();
    }
</code>```

Body:
yo, so im trying to make a program that can take string input from the user for instance: "ONCE UPON a time" and then report back how many upper and lowercase letters the string contains:

output example:  the string has 8 uppercase letters
the string has 5 lowercase letters, and im supposed to use string class not arrays, any tips on how to get started on this one? thanks in advance, here is what I have done so far :D!

import java.util.Scanner;
public class q36{
    public static void main(String args[]){

        Scanner keyboard = new Scanner(System.in);
        System.out.println("Give a string ");
        String input=keyboard.nextLine();

        int lengde = input.length();
        System.out.println("String: " + input + "\t " + "lengde:"+ lengde);

        for(int i=0; i<lengde;i++) {
            if(Character.isUpperCase(CharAt(i))){

            }
        }
    }
}

Body:
java 8

private static long countUpperCase(String inputString) {
        return inputString.chars().filter((s)->Character.isUpperCase(s)).count();
    }

    private static long countLowerCase(String inputString) {
        return inputString.chars().filter((s)->Character.isLowerCase(s)).count();
    }


问:
How does this Bash script work?
```<code>read -r -p "Are you sure? [y/N] " response
 if [[ "$response" =~ ^([yY][eE][sS]|[yY])+$ ]]
then
 do_something
else
 do_something_else
fi
</code>```

I saw this script on a stack overflow website I used the following script because I couldn't write one myself because it threw errors. I know this script will wait for user input such as y/n but I would like detailed explanation about how this script works like what does =~ do and what does ^([yY][eE][sS]|[yY])+$ ]] do.

答:
```<code>if [[ "$response" =~ ^([yY][eE][sS]|[yY])+$ ]]
</code>```

The [[ ]] is a bashism testing statement, similar to [ ] but with a few differences. More detail is available in man bash.

The =~ does RegEx matching, and

```<code>^([yY][eE][sS]|[yY])+$
</code>```

is a regular expression, standing for One or more combinations of y and yes, case-insensitive.

It actually tests if the user's input is y, Yes, yES, YyyY or YyyYYesyesyes (or anything else that matches the given RegEx).

From man 1 bash:

An additional binary operator, =~, is available, with the same precedence as == and !=.  When it is used, the string to the right of the operator is considered an extended regular expression and matched accordingly (as in regex(3)).

[[ expression ]]

Return a status of 0 or 1 depending on the evaluation of the conditional expression expression.

Title: How does this Bash script work?

Body:
read -r -p "Are you sure? [y/N] " response
 if [[ "$response" =~ ^([yY][eE][sS]|[yY])+$ ]]
then
 do_something
else
 do_something_else
fi

I saw this script on a stack overflow website I used the following script because I couldn't write one myself because it threw errors. I know this script will wait for user input such as y/n but I would like detailed explanation about how this script works like what does =~ do and what does ^([yY][eE][sS]|[yY])+$ ]] do.

Body:
if [[ "$response" =~ ^([yY][eE][sS]|[yY])+$ ]]

The [[ ]] is a bashism testing statement, similar to [ ] but with a few differences. More detail is available in man bash.

The =~ does RegEx matching, and

^([yY][eE][sS]|[yY])+$

is a regular expression, standing for One or more combinations of y and yes, case-insensitive.

It actually tests if the user's input is y, Yes, yES, YyyY or YyyYYesyesyes (or anything else that matches the given RegEx).

From man 1 bash:

An additional binary operator, =~, is available, with the same precedence as == and !=.  When it is used, the string to the right of the operator is considered an extended regular expression and matched accordingly (as in regex(3)).

[[ expression ]]

Return a status of 0 or 1 depending on the evaluation of the conditional expression expression.


问:
Verbatim search in azure/cognitive/bing web search (API, not website)
I cannot find any option to achieve a verbatim azure/cognitive/bing Web search.

In my case the difference is trying to sift through tens of millions of irrelevant search results to find the 10 results that actually match my query literally.

Even though I am a paying customer, there is no support available. And the API documentation did not help either.

I would think it should be super easy to provide a verbatim search option. Is there one that I did not see?

答: I checked further and it seems for the Bing Search APIs - +"phrase" works and returns documents containing this phrase at the top. Just add + in front of what you have been trying. Support link is here: https://azure.microsoft.com/en-us/support/plans/.


问:
Uncaught syntaxerror: unexpected identifier in chrome console SCRIPT1003: expected ':' in IE
I am unable to show data provided from database in the google chart. I am constantly getting the same error in chrome console.

Uncaught syntaxerror: unexpected identifier in chrome console SCRIPT1003: expected ':' in IE

@model IEnumerable

```<code>google.charts.load('current', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(drawDualY);

function drawDualY() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topic');
data.addColumn('string', 'Test');
data.addColumn('string', 'Retest');

@foreach (var item in Model)
{
@: data.addRows[{@item.TTopic},@item.TScoreTest,@item.TScoreRetest],
}

var options = {
chart: {
title: 'Employee Score Card',

},
series: {
0: {axis: ''},
1: {axis: ''}
},
axes: {
y: {
MotivationLevel: {label: 'Test Score'},
EnergyLevel: {label: 'Restest Score'}
}
},
hAxis: {
title: 'Test Topic',
format: '',
viewWindow: {
min: [9, 30, 0],
max: [17, 30, 0]
}
},
vAxis: {
title: 'Employee Score'
}
};

var materialChart = new google.charts.Bar(document.getElementById('chart_div'));
materialChart.draw(data, options);
}
</code>```

答:
var options = {
chart: {
title: 'Employee Score Card',

You have an extra comma after 'Employee Score Card',

Body:
I am unable to show data provided from database in the google chart. I am constantly getting the same error in chrome console.

Uncaught syntaxerror: unexpected identifier in chrome console SCRIPT1003: expected ':' in IE

@model IEnumerable

google.charts.load('current', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(drawDualY);

function drawDualY() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topic');
data.addColumn('string', 'Test');
data.addColumn('string', 'Retest');

@foreach (var item in Model)
{
@: data.addRows[{@item.TTopic},@item.TScoreTest,@item.TScoreRetest],
}

var options = {
chart: {
title: 'Employee Score Card',

},
series: {
0: {axis: ''},
1: {axis: ''}
},
axes: {
y: {
MotivationLevel: {label: 'Test Score'},
EnergyLevel: {label: 'Restest Score'}
}
},
hAxis: {
title: 'Test Topic',
format: '',
viewWindow: {
min: [9, 30, 0],
max: [17, 30, 0]
}
},
vAxis: {
title: 'Employee Score'
}
};

var materialChart = new google.charts.Bar(document.getElementById('chart_div'));
materialChart.draw(data, options);
}


问:
How to go from Try to Catch in specific condition in Try
I have a specific condition in try want it to be in catch if happened

```<code>string x;
try {
    if(x==null)
        //send to catch
}
catch {
    //Show messagebox
}
</code>```

I tried throw new Exception but found most of answers here recommend not to use and i have more than 1 condition i want to send each separated to handle in different catch
so is this possible or I should just spam if else ?

what I realy trying to do is that

I have 2 TextBox want to make sure they not empty and 2 DateTime Picker want to make sure 1always before the other (start date and end date)

答:
Point to be noted, throwing exceptions in your code slows down the performance of your application. So always avoid throwing non-fatal exceptions. Throw exceptions only when you cannot handle the consequences.

For everything else that you should handle using either if or switch (if you need to test multiple cases).

Example:

```<code>string x;
if(x == null) { /* show message */ }
if(x == "") { /* show another message */ }
if(x == "1") { /* show yet another message */ }
</code>```

Using switch:

```<code>string x = null;
switch (x)
{
    case null:
    Console.WriteLine("string is null");
    break;
    case "":
    Console.WriteLine("string is empty");
    break;
    case "1":
    Console.WriteLine("string is 1");
    break;
}
</code>```

By the way for string is null or empty, use string.IsNullOrEmpty or string.IsNullOrWhiteSpace

Body:
I have a specific condition in try want it to be in catch if happened

string x;
try {
    if(x==null)
        //send to catch
}
catch {
    //Show messagebox
}

I tried throw new Exception but found most of answers here recommend not to use and i have more than 1 condition i want to send each separated to handle in different catch
so is this possible or I should just spam if else ?

what I realy trying to do is that

I have 2 TextBox want to make sure they not empty and 2 DateTime Picker want to make sure 1always before the other (start date and end date)

Body:
Point to be noted, throwing exceptions in your code slows down the performance of your application. So always avoid throwing non-fatal exceptions. Throw exceptions only when you cannot handle the consequences.

For everything else that you should handle using either if or switch (if you need to test multiple cases).

Example:

string x;
if(x == null) { /* show message */ }
if(x == "") { /* show another message */ }
if(x == "1") { /* show yet another message */ }

Using switch:

string x = null;
switch (x)
{
    case null:
    Console.WriteLine("string is null");
    break;
    case "":
    Console.WriteLine("string is empty");
    break;
    case "1":
    Console.WriteLine("string is 1");
    break;
}

By the way for string is null or empty, use string.IsNullOrEmpty or string.IsNullOrWhiteSpace


问:
Replace values of multiple columns from one dataframe using another dataframe with conditions
Hi I have two data frames as followed:

```<code>df1:
ID   x    y     z
1    a    b     c
2    a    b     c
3    a    b     c
4    a    b     c
</code>```

and df2:

```<code>ID   x    y
 2   d    NA
 3   NA   e
</code>```

and I am after a result like this:

df1:

```<code>    ID   x    y     z
    1    a    b     c
    2    d    b     c
    3    a    e     c
    4    a    b     c
</code>```

I have been trying to use the match function as suggested by some other posts but I keep getting the issue where my df1 dataframe being replaced with NA values from df2.
This is the code I have been using without luck

```<code>for (i in names(df2)[2:length(names(df2))]) {
  df1[i] <- df2[match(df1$ID, df2$ID)]
}
</code>```

Thanks

答:
Your code didn't work for me so I change it a little but it works. If you are reading data from an external file use the stringAsFactor = FALSE when you read it so you don't run into problems.

```<code>df1 = data.frame("ID" = 1:4,"x" = rep("a",4), "y" =rep("b",4),"z" = rep("c",4),
                 stringsAsFactors=FALSE)
df2 = data.frame("ID" = 2:3,"x" = c("d",NA), "y" = c(NA,"e"),stringsAsFactors=FALSE)

for(i in 1:nrow(df2)){
  new_data = df2[i,-which(apply(df2[i,],2,is.na))]
  pos = as.numeric(new_data[1])
  col_replace = intersect(colnames(new_data),colnames(df1))
  df1[pos,col_replace] = new_data
}
</code>```

Body:
Hi I have two data frames as followed:

df1:
ID   x    y     z
1    a    b     c
2    a    b     c
3    a    b     c
4    a    b     c

and df2:

ID   x    y
 2   d    NA
 3   NA   e

and I am after a result like this:

df1:

    ID   x    y     z
    1    a    b     c
    2    d    b     c
    3    a    e     c
    4    a    b     c

I have been trying to use the match function as suggested by some other posts but I keep getting the issue where my df1 dataframe being replaced with NA values from df2.
This is the code I have been using without luck

for (i in names(df2)[2:length(names(df2))]) {
  df1[i] <- df2[match(df1$ID, df2$ID)]
}

Thanks

Body:
Your code didn't work for me so I change it a little but it works. If you are reading data from an external file use the stringAsFactor = FALSE when you read it so you don't run into problems.

df1 = data.frame("ID" = 1:4,"x" = rep("a",4), "y" =rep("b",4),"z" = rep("c",4),
                 stringsAsFactors=FALSE)
df2 = data.frame("ID" = 2:3,"x" = c("d",NA), "y" = c(NA,"e"),stringsAsFactors=FALSE)

for(i in 1:nrow(df2)){
  new_data = df2[i,-which(apply(df2[i,],2,is.na))]
  pos = as.numeric(new_data[1])
  col_replace = intersect(colnames(new_data),colnames(df1))
  df1[pos,col_replace] = new_data
}


问:
TVOS requires 2 Menu Button Presses to exit to Dashboard from Root Controller
I have been charged with updating an existing TVOS project.  I have run into a bit of a snag.

If I am on the root controller(ie: the controller that presents on app launch.)

Pressing the Menu button takes me to an empty gray/white screen. A second press of menu returns me to the Dashboard.

I have tried to use the hierarchy viewer to see what exactly that gray/white screen is, but it has not helped. The gray/white screen consists of a UIWindow with a UILayoutContainerView, that contains a single UINavigationTransitionView in it.  I can find no other identifiable characteristics about it to help me identify what exactly is going on.

When launched the app loads a UINavigationController that presents a UIViewController. Neither the Nav controller nor the presented ViewController override pressesBegin, pressesEnd or assign any gestureRecongnizers to intercept or otherwise override the Menu button functionality.

Near as I can tell the app should exhibit the default Menu button pressed behavior of navigate back to the root, then exit to the Dashboard once at the root.  That said, the Menu button does navigate backwards as it should. It just does not terminate the app once at the root.  When it does go to the gray/white screen none of the functions: applicationWill... are executed until after the second press of the Menu button on the remote.  The app will also resume to this gray/white screen instead.

My question is thus, what is going on here. Baring that how can I
  debug this behavior more effectively.

I have tried to be thorough with this explanation. I recognize that without code things get hard. Thing is, I have no idea what code would be relevant so any guidance or requests for specific code that may be useful will be posted.

Thanks.

答:
Let's call your navigation controller A and the presented view controller B.

It sounds like what's happening is that A doesn't actually have any children, or it has a blank view controller as it's only child. I'm assuming that you never call pushViewController(_, animated:) on A? What are you passing to A when you create it with init(rootViewController:)?

When you press the Menu button the first time, UIKit is automatically dismissing the presented view controller B, and revealing the empty navigation controller A. The gray screen you see is actually the tvOS wallpaper, which is rendered outside the app's view hierarchy.

Then pressing the Menu button the second time actually causes the app to resign, since the navigation controller A doesn't have any more children to pop.

So it sounds like you should either:

Add the view controller B as a child of A, instead of presenting it.

Or, set B as the root view controller and forget about A.


问:
Combine columns of dataframe into new dataframe
I am new to pandas and working with DataFrames. I'm looking at the documentation for Merge,Join,Concatenate, and it's probably staring me right in the face, but I'm still having trouble transposing the data the way I need it.

I have data that looks like this ( R rows x 4302 columns ):

```<code>| w:350 |       r:350 | w:351 |   r:351 |  ...  | w:2499 |      r:2499 | w:2500 |  r:2500 |
-------------------------------------------------------------------------------------------
|   350 | -3.0998e-04 |   351 |  0.0001 |  ...  |   2499 | -3.6000e-05 |   2500 |  0.0004 |
|   350 | -1.8316e-03 |   351 | -0.0008 |  ...  |   2499 | -3.1124e-04 |   2500 | -0.0004 |
|   350 | -1.0520e-03 |   351 | -0.0014 |  ...  |   2499 |  4.0166e-04 |   2500 |  0.0012 |
|   350 | -3.4060e-04 |   351 |  0.0006 |  ...  |   2499 |  1.2782e-03 |   2500 |  0.0012 |
</code>```

That I want to look like this ( X rows x 2 columns ):

```<code>|     x |           y |
-----------------------
|   350 | -3.0998e-04 |
|   350 | -1.8316e-03 |
|   350 | -1.0520e-03 |
|   350 | -3.4060e-04 |
|   351 |      0.0001 |
|   351 |     -0.0008 |
|   351 |     -0.0014 |
|   351 |      0.0006 |
...
|  2499 | -3.6000e-05 |
|  2499 | -3.1124e-04 |
|  2499 |  4.0166e-04 |
|  2499 |  1.2782e-03 |
|  2500 |      0.0004 |
|  2500 |     -0.0004 |
|  2500 |      0.0012 |
|  2500 |      0.0012 |
</code>```

I guess you can think of it as a DataFrame of rows of multiple sets of x,y data, that I want combined into a DataFrame of rows of a single set of x,y data. Or in other words, each row is currently a graph of x,y data. And I need a single collection of x,y data of all the graphs.

I've tried this, but it's not working (probably because the column names not named the same). It's also probably not the most efficient way to do what I'm trying to do. Here output is my original data, and outputxy is the transposed data that I want.

```<code>outputxy = pandas.DataFrame()
for i in range(0, len(output.columns), 2):
    outputxy = pandas.concat([output.iloc[:, i:i+2], outputxy])
</code>```

Thank you in advance for any help!

答:
You could name the columns equivocally with:

```<code>['X': [ output.iloc[:, i:i+1]],'Y': [ [ output.iloc[:, i+1:i+2]]
</code>```

You could also place an index with the number of rows.

Body:
I am new to pandas and working with DataFrames. I'm looking at the documentation for Merge,Join,Concatenate, and it's probably staring me right in the face, but I'm still having trouble transposing the data the way I need it.

I have data that looks like this ( R rows x 4302 columns ):

| w:350 |       r:350 | w:351 |   r:351 |  ...  | w:2499 |      r:2499 | w:2500 |  r:2500 |
-------------------------------------------------------------------------------------------
|   350 | -3.0998e-04 |   351 |  0.0001 |  ...  |   2499 | -3.6000e-05 |   2500 |  0.0004 |
|   350 | -1.8316e-03 |   351 | -0.0008 |  ...  |   2499 | -3.1124e-04 |   2500 | -0.0004 |
|   350 | -1.0520e-03 |   351 | -0.0014 |  ...  |   2499 |  4.0166e-04 |   2500 |  0.0012 |
|   350 | -3.4060e-04 |   351 |  0.0006 |  ...  |   2499 |  1.2782e-03 |   2500 |  0.0012 |

That I want to look like this ( X rows x 2 columns ):

|     x |           y |
-----------------------
|   350 | -3.0998e-04 |
|   350 | -1.8316e-03 |
|   350 | -1.0520e-03 |
|   350 | -3.4060e-04 |
|   351 |      0.0001 |
|   351 |     -0.0008 |
|   351 |     -0.0014 |
|   351 |      0.0006 |
...
|  2499 | -3.6000e-05 |
|  2499 | -3.1124e-04 |
|  2499 |  4.0166e-04 |
|  2499 |  1.2782e-03 |
|  2500 |      0.0004 |
|  2500 |     -0.0004 |
|  2500 |      0.0012 |
|  2500 |      0.0012 |

I guess you can think of it as a DataFrame of rows of multiple sets of x,y data, that I want combined into a DataFrame of rows of a single set of x,y data. Or in other words, each row is currently a graph of x,y data. And I need a single collection of x,y data of all the graphs.

I've tried this, but it's not working (probably because the column names not named the same). It's also probably not the most efficient way to do what I'm trying to do. Here output is my original data, and outputxy is the transposed data that I want.

outputxy = pandas.DataFrame()
for i in range(0, len(output.columns), 2):
    outputxy = pandas.concat([output.iloc[:, i:i+2], outputxy])

Thank you in advance for any help!

Body:
You could name the columns equivocally with:

['X': [ output.iloc[:, i:i+1]],'Y': [ [ output.iloc[:, i+1:i+2]]

You could also place an index with the number of rows.


问:
install ROS Kinetic to Mac following ROS tutorial
I am trying to install ROS Kinetic to Mac(macOS Sierra) and ran into two questions:

Q1. Do I install the ROS into a workspace?

According to the tutorial:http://wiki.ros.org/kinetic/Installation/OSX/Homebrew/Source, the installation of the ROS will be done inside a catkin workspace. Did I misunderstood? :
Create a catkin Workspace

In order to build the core packages, you will need a catkin workspace. Create one now:

$ mkdir ~/ros_catkin_ws
$ cd ~/ros_catkin_ws
Next we will want to fetch the core packages so we can build them. We will use wstool for this. Select the wstool command for the particular variant you want to install:

Desktop-Full Install: ROS, rqt, rviz, robot-generic libraries, 2D/3D simulators, navigation and 2D/3D perception

$ rosinstall_generator desktop_full --rosdistro kinetic --deps --wet-only --tar > kinetic-desktop-full-wet.rosinstall
$ wstool init -j8 src kinetic-desktop-full-wet.rosinstall

So I did follow this but then for the later step, it warned me of the lack of some tools which are installed outside of the workspace from the tutorial perviously.

Q2. I didn't follow the installation of the ROS desktop version to set inside a catkin workspace but under the root directory, everything was going fine until the command:

$ rosdep install --from-paths src --ignore-src --rosdistro kinetic -y

I got this error:

ERROR: the following packages/stacks could not have their rosdep keys resolved to system dependencies:

actionlib: No definition of [python-wxtools] for OS [osx]

Anyone can help? Thanks in advance!

答:
Just managed to get rosdep install to run by adding the --skip-keys argument so the command becomes:

rosdep install --from-paths src --ignore-src --skip-keys python-wxtools --rosdistro kinetic -y

Note: If it turns out at some point that you do not have the wx package, install it with:

sudo -H python2 -m pip install wxPython


答: it specifies the destructor of a class or struct</p>

Title: What does this symbol mean in C++? "~"

Body:
If we use ~ before a function like this: ~func();, what does this mean?

Thanks.


问:
Passing URL Parameters in href Link
I’m a bit new to this JS stuff and have been surfing and surfing and reading up as much as I can, but I got stumped on this one issue.

I have a website that may contain parameters in the URL. A parameter named “who” to be exact.

If a user comes to the site and their url is http://example.com/?who=123, I want them to be able to click a href link and their parameter get carried on. So if the link goes to http://anotherexample.com, I’d want the link to contain the user’s parameter as well. http://anotherexample.com/?who=123.

What’s the best way to accomplish this? It only needs to be on one of the links, so no concerns about getting the whole site to pass on the parameter.

Thanks!

答:
Would this suffice for you?

Source: https://css-tricks.com/snippets/javascript/get-url-variables/

```<code>var svalue=location.search.match(new RegExp("[\?\&]" + "who" + "=([^\&]*)(\&?)","i"));
yourelement.href=yourelement.href+(svalue?svalue[0]:"");
</code>```

Title: Passing URL Parameters in href Link

Body:
Would this suffice for you?

Source: https://css-tricks.com/snippets/javascript/get-url-variables/

var svalue=location.search.match(new RegExp("[\?\&]" + "who" + "=([^\&]*)(\&?)","i"));
yourelement.href=yourelement.href+(svalue?svalue[0]:"");


问:
Intel PEBS sample context
I am using Linux perf tool to monitor system-wide  (exclude_kernel == 0) PEBS samples. I was wondering whether PEBS sample can occur at interrupt context (i.e., during an interrupt is being served by the interrupt handler). If it is possible, is there any way to determine the context (e.g, process context, interrupt context) of the PEBS sample (i.e., register bits)? </p>

答:
PEBS sampling never occurs when an interrupt is being serviced.

PEBS uses the above buffering mechanism to store its records. You can clearly see all the PEBS relevant fields like PEBS buffer base and PEBS interrupt threshold etc. PEBS interrupts occur when the PEBS buffer index matches the PEBS interrupt threshold specified.

The PEBS interrupt handler will reset the PEBS Buffer Index back to the start of the PEBS buffer base. If PEBS sampling were to continue, then PEBS would also try to access the DS buffer to increment the PEBS Buffer Index. So both the PEBS Interrupt and PEBS itself will try to write to the same DS save area. This obviously points to a race condition between the PEBS interrupt handler and PEBS module.

To avoid this race condition, it is required to disable PEBS sampling (by disabling flags in the IA32_PEBS_ENABLE msr register). Also all the event counters must be disabled as well by the interrupt handler. This is the proof in the kernel.

However, if the PEBS interrupts cause too much throttling on the CPU, you can have a PERF_RECORD_THROTTLE event, but this is of course, not a PEBS_SAMPLE event but rather a PERF_RECORD event.

Title: Intel PEBS sample context


问:
Is mobile browser geolocation as good as native?
When you open a webpage on a phone/tablet, and use

```<code>navigator.geolocation.getCurrentPosition()
</code>```

Do we get the same results that when we use Google Play services location API?

And do we get the same results that when we use iOS native location API?

Thank you!

答:
It is really depends to what level of information is available in both OS.

For example, if both GPS chip is working in both Android and iOS and locked to the right numbers of satellite, then you should get the same results.

However, when GPS is not available, each API uses their own way such as wifi, cell tower ID or IP address to estimate the location, then you will find some discrepancy.

Reference: http://www.geolocation.com

Body:
When you open a webpage on a phone/tablet, and use

navigator.geolocation.getCurrentPosition()

Do we get the same results that when we use Google Play services location API?

And do we get the same results that when we use iOS native location API?

Thank you!


问:
After adding new UDIDs to provisioning profile, do I need to rebuild the IPA?
I have an app (adhoc dist.) and uploaded it to Diawi.
Now, I should add new UDIDs. After add them, do I need to recreate or rebuild the IPA and re-upload to Diawi?

Thanks in advance

答:
The answer to your query may be in two types of accounts

1) If you have an Enterprise Apple Account: No need to add tester UUDI to the account as the app can be released using Universal distribution binary which any device can install using OTA installation method.

2) If you have the developer account: your existing app will have no impact but yes for the new devices to install you have to regenerate the profile as the existing as on store account portal will get Invalid and needs to be updated for New IPA compilation. The old one will not work.

I would always recommend having an Enterprise account for a testing/building app company as Appstore Developer account is better for Distribution on Appstore or small scale company who rarely adds device ID for debugging and testing unless its standalone developer like scenario.


答:
Here is one way you can do it in javascript
first when the document loads write a function in your js to get the parameters from the url

```<code>function getparms(variable)
{
       let item = window.location.search.substring(1);
       let vars = item.split("&");
       for (let i=0;i< vars.length;i++) {
               let pair = vars[i].split("=");
               if(pair[0] == variable){return pair[1];}
       }
       return(false);
}
</code>```

This function would return the following from a url

http://www.somesite.com/index.html?who=100&location=2

Calling getparams('who') would return "100"

So you would call it as:

```<code>let myParam = getparams('id');
</code>```

You can build the url in a new function and navigate to it as:

```<code>function goToUrl(urlParam){
let hostAddress= 'yourwebsiteaddress';
let url = "http://" + hostAddress "/?=who" + urlParam;

//go to address
window.location.href = url;
}
</code>```

which would be called as goToUrl(myParam);

*Disclaimer: I wrote this on the fly so it may not be 100% syntactically correct but it should be accurate enough as pseudo code to help you accomplish what you want.

Title: Passing URL Parameters in href Link

Body:
I’m a bit new to this JS stuff and have been surfing and surfing and reading up as much as I can, but I got stumped on this one issue.

I have a website that may contain parameters in the URL. A parameter named “who” to be exact.

If a user comes to the site and their url is http://example.com/?who=123, I want them to be able to click a href link and their parameter get carried on. So if the link goes to http://anotherexample.com, I’d want the link to contain the user’s parameter as well. http://anotherexample.com/?who=123.

What’s the best way to accomplish this? It only needs to be on one of the links, so no concerns about getting the whole site to pass on the parameter.

Thanks!

Body:
Here is one way you can do it in javascript
first when the document loads write a function in your js to get the parameters from the url

function getparms(variable)
{
       let item = window.location.search.substring(1);
       let vars = item.split("&");
       for (let i=0;i< vars.length;i++) {
               let pair = vars[i].split("=");
               if(pair[0] == variable){return pair[1];}
       }
       return(false);
}

This function would return the following from a url

http://www.somesite.com/index.html?who=100&location=2

Calling getparams('who') would return "100"

So you would call it as:

let myParam = getparams('id');

You can build the url in a new function and navigate to it as:

function goToUrl(urlParam){
let hostAddress= 'yourwebsiteaddress';
let url = "http://" + hostAddress "/?=who" + urlParam;

//go to address
window.location.href = url;
}

which would be called as goToUrl(myParam);

*Disclaimer: I wrote this on the fly so it may not be 100% syntactically correct but it should be accurate enough as pseudo code to help you accomplish what you want.


问:
Delete line containing pattern found anywhere in another file
I'd like to compare two files and delete lines in file1 if they contain a pattern found anywhere in file2. I did some searching and the closest answers I've been able to find were how to delete lines that appear in another file.

I'd like a simple grep, awk, sed, etc one-liner if possible. I'm matching on IP addresses, as shown below.

file1

```<code>10.10.50.1 00:00:10:23 0000.0012.3456 Vlan1
10.10.50.2 00:00:12:34 1234.56AB.CDEF Vlan2
10.10.50.3 00:00:23:10 ABCD.EF12.345 Vlan3billion
</code>```

file2

```<code>these-are some_words 10.10.50.2 andmaybe some-other words
theseare somewords 10.10.50.99 and-maybe some_other words
</code>```

Expected output:

```<code>10.10.50.1 00:00:10:23 0000.0012.3456 Vlan1
10.10.50.3 00:00:23:10 ABCD.EF12.345 Vlan3billion
</code>```

Body:
I'd like to compare two files and delete lines in file1 if they contain a pattern found anywhere in file2. I did some searching and the closest answers I've been able to find were how to delete lines that appear in another file.

I'd like a simple grep, awk, sed, etc one-liner if possible. I'm matching on IP addresses, as shown below.

file1

10.10.50.1 00:00:10:23 0000.0012.3456 Vlan1
10.10.50.2 00:00:12:34 1234.56AB.CDEF Vlan2
10.10.50.3 00:00:23:10 ABCD.EF12.345 Vlan3billion

file2

these-are some_words 10.10.50.2 andmaybe some-other words
theseare somewords 10.10.50.99 and-maybe some_other words

Expected output:

10.10.50.1 00:00:10:23 0000.0012.3456 Vlan1
10.10.50.3 00:00:23:10 ABCD.EF12.345 Vlan3billion

Body:
More awk ... at the core snaffled from karafka ..

$ awk 'NR==FNR{a[gensub(/^.* (([0-9]{1,3}\.){3}[0-9]{1,3}) .*$/,"\\1",1,$0)];next} !($1 in a)' file2 file1
10.10.50.1 00:00:10:23 0000.0012.3456 Vlan1
10.10.50.3 00:00:23:10 ABCD.EF12.345 Vlan3billion


问:
Spark get the actual cluster centeroids with StandardScaler

I have a fitted a KMeans with scaled features using StandardScaler. The issue is the cluster centeroids are also scaled. Is it possible to get the original centeroids programmatically ?
</p>

```<code>import pandas as pd
import numpy as np
from pyspark.ml.feature import VectorAssembler
from pyspark.ml.feature import StandardScaler, StandardScalerModel
from pyspark.ml.clustering import KMeans

from sklearn.datasets import load_iris

# iris data set
iris = load_iris()
iris_data = pd.DataFrame(iris['data'], columns=iris['feature_names'])

iris_df = sqlContext.createDataFrame(iris_data)

assembler = VectorAssembler(
    inputCols=[x for x in iris_df.columns],outputCol='features')

data = assembler.transform(iris_df)

scaler = StandardScaler(inputCol="features", outputCol="scaledFeatures", withStd=True, withMean=False)
scalerModel = scaler.fit(data)
scaledData = scalerModel.transform(data).drop('features').withColumnRenamed('scaledFeatures', 'features')

kmeans = KMeans().setFeaturesCol("features").setPredictionCol("prediction").setK(3)
model = kmeans.fit(scaledData)
centers = model.clusterCenters()

print("Cluster Centers: ")
for center in centers:
    print(center)
</code>```

<p>
Here I want to get the centeroids in original scale.

The centeroids are scaled. </p>

```<code>[ 7.04524479  6.17347978  2.50588155  1.88127377]
[ 6.0454109   7.88294475  0.82973422  0.31972295]
[ 8.22013841  7.19671468  3.13005178  2.59685552]
</code>```

答:
You StandardScaler with withStd=True and withMean=False. To move back to initial space you have to multiply be std vector:

```<code>[cluster * scalerModel.std  for cluster in model.clusterCenters()]
</code>```

If withMean was True you'd use:

```<code>[cluster * scalerModel.std + scalerModel.mean
    for cluster in model.clusterCenters()]
</code>```

Body:
I have a fitted a KMeans with scaled features using StandardScaler. The issue is the cluster centeroids are also scaled. Is it possible to get the original centeroids programmatically ?

import pandas as pd
import numpy as np
from pyspark.ml.feature import VectorAssembler
from pyspark.ml.feature import StandardScaler, StandardScalerModel
from pyspark.ml.clustering import KMeans

from sklearn.datasets import load_iris

# iris data set
iris = load_iris()
iris_data = pd.DataFrame(iris['data'], columns=iris['feature_names'])

iris_df = sqlContext.createDataFrame(iris_data)

assembler = VectorAssembler(
    inputCols=[x for x in iris_df.columns],outputCol='features')

data = assembler.transform(iris_df)

scaler = StandardScaler(inputCol="features", outputCol="scaledFeatures", withStd=True, withMean=False)
scalerModel = scaler.fit(data)
scaledData = scalerModel.transform(data).drop('features').withColumnRenamed('scaledFeatures', 'features')

kmeans = KMeans().setFeaturesCol("features").setPredictionCol("prediction").setK(3)
model = kmeans.fit(scaledData)
centers = model.clusterCenters()

print("Cluster Centers: ")
for center in centers:
    print(center)

Here I want to get the centeroids in original scale.

The centeroids are scaled.

[ 7.04524479  6.17347978  2.50588155  1.88127377]
[ 6.0454109   7.88294475  0.82973422  0.31972295]
[ 8.22013841  7.19671468  3.13005178  2.59685552]

Body:
You StandardScaler with withStd=True and withMean=False. To move back to initial space you have to multiply be std vector:

[cluster * scalerModel.std  for cluster in model.clusterCenters()]

If withMean was True you'd use:

[cluster * scalerModel.std + scalerModel.mean
    for cluster in model.clusterCenters()]


问:
Network adapter Disabled on windows azure virtual machine (how to reactivate)
I have a problem with my azure virtual machine (name : Davzen, resource group : Rs1). I made a bad manipulation accidentally : I desactivated the network adapter of the virtual machine , it has ejected me of the Remote Desktop and I didn’t manage to reconnect me since this moment. I tried : restart , réinitialise connection, change virtual machine plan ( 3,5go ram-> 7 go ram). But this setting persist and I didn’t manage to reactivite the network adapter and to connect me with Remote Desktop.
Can everybody help me ?

But it doesn’t work any at all

答:
After you disable your NIC, you will not connect to your VM, we can follow those steps to enable it:

1.Go to the Azure portal.

2.Select the affected Virtual Machine.

3.Select Network Interfaces.

4.Select the Network Interface associated with your machine

5.Select IP configurations.

6.Select the IP.

7.If the Private IP assignment is not Static, change it to Static.

8.Change the IP address to another IP address that is available in the Subnet, for example, change 10.0.0.4 to 10.0.0.5.

9.The virtual machine will restart to initialize the new NIC to the system.

10.Try to RDP to your machine. If successful, you can change the Private IP address back to the original if you would like. Otherwise, you can keep it.

After you can remote desktop to the machine, you must delete the old NICs to avoid the potential problem:

1.Open Device Manager.

2.Select View > Show hidden devices.

3.Select Network Adapters.

4.Check for the adapters named as "Microsoft Hyper-V Network Adapter".

5.You might see an unavailable adapter that is grayed out. Right-click the adapter and then select Uninstall.

6.Now all unavailable adapter should be cleared out from your system.

More information about re-enable NIC from Azure VM, please refer to this article.


问:
addEventListener + setTimeout
It's the first time I encounter such an issue with the addEventListener() method.
When I try to use it with a setTimeout, the function is automatically called, even though the addEventListener has a "click" property.

<button id="test">Test</button>

```<code>document.getElementById("test").addEventListener("click", setTimeout(myFunc, 2000));

function myFunc() {
  console.log("Hello");
}
</code>```

答:
This would be what you want.

document.getElementById("test").addEventListener("click", function(){setTimeout(myFunc, 2000)});

function myFunc() {
  console.log("Hello");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="test">Test</button></code>```

Title: addEventListener + setTimeout

Body:
It's the first time I encounter such an issue with the addEventListener() method.
When I try to use it with a setTimeout, the function is automatically called, even though the addEventListener has a "click" property.

<button id="test">Test</button>

document.getElementById("test").addEventListener("click", setTimeout(myFunc, 2000));

function myFunc() {
  console.log("Hello");
}

Body:
This would be what you want.

document.getElementById("test").addEventListener("click", function(){setTimeout(myFunc, 2000)});

function myFunc() {
  console.log("Hello");
}

<button id="test">Test</button>


问:
Qt Designer button image change while keeping windows style?
I can change the image or any other style of a QPushButton in the designer by changing the stylesheet, but any change in the style sheet changes all the other properties.

For instance, when I change the border image everything else is changed and it does not inherit the rest of the properties from the parent (or windows style).

How can I keep the windows style while changing only the image?

答:
Did you try set style to the single push button: </p>

```<code>your_push_button_pointer->setStyleSheet(
    "QPushButton{background-image: url(:/images/call_up.bmp);}"
    "QPushButton:hover{background-image: url(:/images/call_hov.bmp);}"
    "QPushButton:pressed{background-image: url(:/images/call_down.bmp);}");
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Did you try set style to the single push button:

your_push_button_pointer->setStyleSheet(
    "QPushButton{background-image: url(:/images/call_up.bmp);}"
    "QPushButton:hover{background-image: url(:/images/call_hov.bmp);}"
    "QPushButton:pressed{background-image: url(:/images/call_down.bmp);}");


问:
How to create seconds object with new operator

Im trying to create 2 class objects with operator new, but when im trying to create a new one it says that the second one was not declared and if I change interface to something else it also gives an error.

```<code>void Game::start(){
    // clear the screen
    scene->clear();

    //player1 = new Player("Player 1");
    //player2 = new Player("Player 2");
    player = new Player("Player1");

    interface = new Interface();
    interface2 = new Interface();
    //Interface interface;
    interface->placeCombatColumn();
    //interface.placeCombatColumn();
    drawGUI();
    interface->placeCombat();

}
</code>```

Errors:

player was not declared in this scope

interface2 was not declared in this scope

答:
You should have a (possibly) private member

```<code>Player * player;
</code>```

in your class, like this:

```<code>class Game {

public:
  void start();

private:
  Player * player;

};
</code>```

This way, you can refer to the variable player from inside your Game class methods (all of them, including start()). Same apply to other variables, like interface.

If you need a variable to be local to a method, instead (i.e. you don't need it outside the method scope) you have to declare it, at least when assigning a value to it, inside the method:

```<code>void Game::start() {

    // clear the screen
    scene->clear();

    Player * player = new Player("Player1");

...
</code>```

Body:
Im trying to create 2 class objects with operator new, but when im trying to create a new one it says that the second one was not declared and if I change interface to something else it also gives an error.

void Game::start(){
    // clear the screen
    scene->clear();

    //player1 = new Player("Player 1");
    //player2 = new Player("Player 2");
    player = new Player("Player1");

    interface = new Interface();
    interface2 = new Interface();
    //Interface interface;
    interface->placeCombatColumn();
    //interface.placeCombatColumn();
    drawGUI();
    interface->placeCombat();

}

Errors:

player was not declared in this scope

interface2 was not declared in this scope

Body:
You should have a (possibly) private member

Player * player;

in your class, like this:

class Game {

public:
  void start();

private:
  Player * player;

};

This way, you can refer to the variable player from inside your Game class methods (all of them, including start()). Same apply to other variables, like interface.

If you need a variable to be local to a method, instead (i.e. you don't need it outside the method scope) you have to declare it, at least when assigning a value to it, inside the method:

void Game::start() {

    // clear the screen
    scene->clear();

    Player * player = new Player("Player1");

...


答:
You can use setTimeout inside the function that you call.
Jsfiddle

```<code>document.getElementById("test").addEventListener("click", myFunc);

function myFunc() {
    setTimeout(function(){
      console.log("Hello");
    }, 6000);
}
</code>```

Title: addEventListener + setTimeout

Body:
You can use setTimeout inside the function that you call.
Jsfiddle

document.getElementById("test").addEventListener("click", myFunc);

function myFunc() {
    setTimeout(function(){
      console.log("Hello");
    }, 6000);
}


问:
java.lang.IllegalStateException: Unable to return a default Coder in dataflow 2.X
I have a simple pipeline in dataflow 2.1 sdk. Which reads data from pubsub then applies a DoFn to it.

```<code>PCollection<MyClass> e = streamData.apply("ToE", ParDo.of(new MyDoFNClass()));
</code>```

Getting below error on this pipeline:

java.lang.IllegalStateException: Unable to return a default Coder for ToEvents/ParMultiDo(MyDoFNClass).out0 [PCollection]. Correct one of the following root causes:
    No Coder has been manually specified;  you may do so using .setCoder().
    Inferring a Coder from the CoderRegistry failed: Unable to provide a Coder for com.X.X.model.MyClass.

MyDoFn class is below:

```<code>@DefaultCoder(AvroCoder.class)

public class MyClass{

    public long id;
    public HashMap<String,HashSet<String>> a;

    @SerializedName("a")
    public Integer Id;
    @SerializedName("ae")
    public String ae;
}
</code>```

答:
Found the solution just neeeded to add implements Serializable to MyClass

```<code>@DefaultCoder(AvroCoder.class)

public class MyClass implements Serializable {

public long id;
public HashMap<String,HashSet<String>> a;

@SerializedName("a")
public Integer Id;
@SerializedName("ae")
public String ae;
}
</code>```

Body:
I have a simple pipeline in dataflow 2.1 sdk. Which reads data from pubsub then applies a DoFn to it.

PCollection<MyClass> e = streamData.apply("ToE", ParDo.of(new MyDoFNClass()));

Getting below error on this pipeline:

java.lang.IllegalStateException: Unable to return a default Coder for ToEvents/ParMultiDo(MyDoFNClass).out0 [PCollection]. Correct one of the following root causes:
    No Coder has been manually specified;  you may do so using .setCoder().
    Inferring a Coder from the CoderRegistry failed: Unable to provide a Coder for com.X.X.model.MyClass.

MyDoFn class is below:

@DefaultCoder(AvroCoder.class)

public class MyClass{

    public long id;
    public HashMap<String,HashSet<String>> a;

    @SerializedName("a")
    public Integer Id;
    @SerializedName("ae")
    public String ae;
}

Body:
Found the solution just neeeded to add implements Serializable to MyClass

@DefaultCoder(AvroCoder.class)

public class MyClass implements Serializable {

public long id;
public HashMap<String,HashSet<String>> a;

@SerializedName("a")
public Integer Id;
@SerializedName("ae")
public String ae;
}


问:
Problem accessing remote CSV using dojo
I am trying to create a website where I host my data on google spreadsheets, and show data to the user in his browser using dojo.

However, I am getting the error

```<code>Access to restricted URI denied" code: "1012
</code>```

when the browser encounters:

```<code>var stateStore = new dojox.data.CsvStore(
{url: "http://spreadsheets.google.com/pub?key=p0jvMlPF5YqcUllrbwZzQBg&output=csv&gid=0",
label: "name"});
</code>```

while replacing it with a locally stored copy of the same CSV works fine.

From what my google searches told me, this is due to security restrictions in modern browsers which try to protect you from cross-site scripting attack. Of course, I would like some way to be able to "whitelist" this domain for the purpose of my page.

Any suggestions?

The Full HTML Code is

```<code><html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <style type="text/css">
        @import "dojo-release-1.2.3/dijit/themes/tundra/tundra.css";
        @import "dojo-release-1.2.3/dojo/resources/dojo.css"
    </style>
    <script type="text/javascript" src="dojo-release-1.2.3/dojo/dojo.js"
         djConfig="parseOnLoad:true, isDebug: true"></script>
    <script>
        dojo.require("dojox.data.CsvStore");
        dojo.require("dijit.Tree");
        dojo.require("dojo.parser");
    </script>
    <script type="text/javascript">
        var stateStore = new dojox.data.CsvStore({url: "http://spreadsheets.google.com/pub?key=p0jvMlPF5YqcUllrbwZzQBg&output=csv&gid=0", label: "name"});
//      var stateStore = new dojox.data.CsvStore({url: "states.csv", label: "name"});
    </script>

</head>
<body class="tundra">
<!--    <div dojoType="dojox.data.CsvStore" url="http://spreadsheets.google.com/pub?key=p0jvMlPF5YqcUllrbwZzQBg&output=csv&gid=0" jsid="stateStore" /> -->
    <div dojoType="dijit.Tree" store="stateStore" labelAttr="name" label="States"></div>
</body>
</html>
</code>```

Thanks in advance,
Animesh

答:
Same origin policy.

The domain used to access the page must match the domain requested. So, you can't access spreadsheets.google.com from somewhere else using JavaScript solely.

The workaround that I hear about most is a cross-domain proxy -- a server-side script that GETs (or POSTs) to another domain and echoes the results back to JavaScript.

OwnerDisplayName: Animesh

Title: Problem accessing remote CSV using dojo

Body:
I am trying to create a website where I host my data on google spreadsheets, and show data to the user in his browser using dojo.

However, I am getting the error

Access to restricted URI denied" code: "1012

when the browser encounters:

var stateStore = new dojox.data.CsvStore(
{url: "http://spreadsheets.google.com/pub?key=p0jvMlPF5YqcUllrbwZzQBg&output=csv&gid=0",
label: "name"});

while replacing it with a locally stored copy of the same CSV works fine.

From what my google searches told me, this is due to security restrictions in modern browsers which try to protect you from cross-site scripting attack. Of course, I would like some way to be able to "whitelist" this domain for the purpose of my page.

Any suggestions?

The Full HTML Code is

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

Thanks in advance,
Animesh

OwnerDisplayName: Jonathan Lonowski


问:
Windows Azure local development environment speed
I've started porting an existing ASP.NET web app to Windows Azure and have noticed that the development process is really slow. Each time I make a change to my code and want to view it, I have to effectively redeploy it to the local dev cloud (using Start debugging (F5) or Start without debugging (Ctrl-F5). The process itself takes over a minute, during which time Visual Studio is completely unresponsive.

Am I doing something wrong or is that simply how things are developing for Azure?

My specs:

Visual Studio 2008 9.0.30729.1 SP

5 projects running on .NET 3.5 SP1

Azure SDK 1.1 (February 2010)

Single instance of a single web role

Dual-core AMD 64 machine with 8GB RAM, 64-bit Windows 7, fully patched

The main project itself is quite large (3k files, ~200k lines) but compiles normally in 10-15 seconds

答: In my case when I changed the port from 80 to something else (under end points) the speed returned to normal.</p>


问:
Get HTML code from dynamic page
I am trying to get the HTML code of the following website.
http://fortune.com/fortune500/list/

But the problem is when we visit this website in browser, it only shows the first 20 companies and when we go to the bottom part of website it loads the next 50 companies.

How do i get the first 700 companies in HTML code from this website?
I tried the code from this website https://www.mkyong.com/java/how-to-get-url-content-in-java/ to get the HTML content but as expected it gives only the top 20 companies

Any help is much appreciated
Thanks

答:
CURL: http://fortune.com/api/v2/list/2013055/expand/item/ranking/asc/{{start_from}}/{{num_limit}}

Example: http://fortune.com/api/v2/list/2013055/expand/item/ranking/asc/1/100

The site "fortune.com" return max 100 elements form CURL.

The CURL return a JSON.

Title: Get HTML code from dynamic page


问:
automapper working with attributes c#
I have two objects, I want to map them using AutoMapper Attributes, these are my target objects:

```<code>public class ClaseB
{
    public string UBLVersionID_nuevo { get; set; }

    public ClaseB_inside objetoB_inside { get; set; }
}

public class ClaseB_inside
{
    public string texto_inside { get; set; }
}
</code>```

and this is my source class:

```<code>[MapsTo(typeof(ClaseB))]
public class ClaseA
{
    [MapsToProperty(typeof(ClaseB), "objetoB_inside.texto_inside")]
    public string texto { get; set; } = "texto prueba";

    [MapsToProperty(typeof(ClaseB), "UBLVersionID_nuevo")]
    public string texto2 { get; set; } = "texto 2 de prueba";
}
</code>```

when I try to map I get the following error:

Error mapping types

and with this change:

```<code>[MapsTo(typeof(ClaseB))]
public class ClaseA
{
    [MapsToProperty(typeof(ClaseB_inside), "objetoB_inside.texto_inside")]
    public string texto { get; set; } = "texto prueba";

    [MapsToProperty(typeof(ClaseB), "UBLVersionID_nuevo")]
    public string texto2 { get; set; } = "texto 2 de prueba";
}
</code>```

I get null in ClaseB.objetoB_inside  but ClaseB.UBLVersionID_nuevo it works.

What am I doing wrong?

答:
I think the issue is with the way you are defining the mapping.  Consider the following if you weren't using Automapper attributes and was initializing through the static API:

```<code>        Mapper.Initialize(expression =>
        {
            expression.CreateMap<ClaseA, ClaseB>()
                .ForMember(
                    from => from.objetoB_inside.texto_inside,
                    to => to.MapFrom(a => a.texto2));
        });
</code>```

This mapping would result in the following exception:
Expression 'from => from.objetoB_inside.texto_inside' must resolve to top-level member and not any child object's properties. Use a custom resolver on the child type or the AfterMap option instead.

And I think that's the same issue with the Attributes definition.

So I would suggest implementing the following:

```<code>public class MapsToClaseB : MapsToAttribute
{
    public MapsToClaseB() : base(typeof(ClaseB)) { }

    public void ConfigureMapping(IMappingExpression<ClaseA, ClaseB> mappingExpression)
    {
        mappingExpression.AfterMap(
            (a, b) => b.objetoB_inside = new ClaseB_inside{texto_inside = a.texto});
    }
}
</code>```

You just then need to decorate your class with this:

[MapsToClaseB]

Title: automapper working with attributes c#

Body:
I have two objects, I want to map them using AutoMapper Attributes, these are my target objects:

public class ClaseB
{
    public string UBLVersionID_nuevo { get; set; }

    public ClaseB_inside objetoB_inside { get; set; }
}

public class ClaseB_inside
{
    public string texto_inside { get; set; }
}

and this is my source class:

[MapsTo(typeof(ClaseB))]
public class ClaseA
{
    [MapsToProperty(typeof(ClaseB), "objetoB_inside.texto_inside")]
    public string texto { get; set; } = "texto prueba";

    [MapsToProperty(typeof(ClaseB), "UBLVersionID_nuevo")]
    public string texto2 { get; set; } = "texto 2 de prueba";
}

when I try to map I get the following error:

Error mapping types

and with this change:

[MapsTo(typeof(ClaseB))]
public class ClaseA
{
    [MapsToProperty(typeof(ClaseB_inside), "objetoB_inside.texto_inside")]
    public string texto { get; set; } = "texto prueba";

    [MapsToProperty(typeof(ClaseB), "UBLVersionID_nuevo")]
    public string texto2 { get; set; } = "texto 2 de prueba";
}

I get null in ClaseB.objetoB_inside  but ClaseB.UBLVersionID_nuevo it works.

What am I doing wrong?

Body:
I think the issue is with the way you are defining the mapping.  Consider the following if you weren't using Automapper attributes and was initializing through the static API:

        Mapper.Initialize(expression =>
        {
            expression.CreateMap<ClaseA, ClaseB>()
                .ForMember(
                    from => from.objetoB_inside.texto_inside,
                    to => to.MapFrom(a => a.texto2));
        });

This mapping would result in the following exception:
Expression 'from => from.objetoB_inside.texto_inside' must resolve to top-level member and not any child object's properties. Use a custom resolver on the child type or the AfterMap option instead.

And I think that's the same issue with the Attributes definition.

So I would suggest implementing the following:

public class MapsToClaseB : MapsToAttribute
{
    public MapsToClaseB() : base(typeof(ClaseB)) { }

    public void ConfigureMapping(IMappingExpression<ClaseA, ClaseB> mappingExpression)
    {
        mappingExpression.AfterMap(
            (a, b) => b.objetoB_inside = new ClaseB_inside{texto_inside = a.texto});
    }
}

You just then need to decorate your class with this:

[MapsToClaseB]


答:
You talked about href, so I assume all links are set with  tag.

There are many options to do that, I'll show you the easiest and cleanest one.

So, assuming the current URL is http://www.example.com/?who=123.

```<code>var who = window.location.href.split('?')[1]; // Get `?who=123` from current url
var a = document.getElementsByTagName('a');   // Get all `<a>`
var href;

// Loop through all `<a>`
for (var i = 0; i < a.length; i++){
    // Add `?who=123` to all hrefs found.
    a[i].href += who;
}
</code>```

You can freely change document.getElementsByTagName('a') to document.getElementById() to suit your needs.

Title: Passing URL Parameters in href Link

Body:
I’m a bit new to this JS stuff and have been surfing and surfing and reading up as much as I can, but I got stumped on this one issue.

I have a website that may contain parameters in the URL. A parameter named “who” to be exact.

If a user comes to the site and their url is http://example.com/?who=123, I want them to be able to click a href link and their parameter get carried on. So if the link goes to http://anotherexample.com, I’d want the link to contain the user’s parameter as well. http://anotherexample.com/?who=123.

What’s the best way to accomplish this? It only needs to be on one of the links, so no concerns about getting the whole site to pass on the parameter.

Thanks!

Body:
You talked about href, so I assume all links are set with <a> tag.

There are many options to do that, I'll show you the easiest and cleanest one.

So, assuming the current URL is http://www.example.com/?who=123.

var who = window.location.href.split('?')[1]; // Get `?who=123` from current url
var a = document.getElementsByTagName('a');   // Get all `<a>`
var href;

// Loop through all `<a>`
for (var i = 0; i < a.length; i++){
    // Add `?who=123` to all hrefs found.
    a[i].href += who;
}

You can freely change document.getElementsByTagName('a') to document.getElementById() to suit your needs.


问:
How can I use an 'update' function to 'open' and update if the object is not yet open?
My example is a progress bar

In its simplest form a progress bar is

```<code>bar = ProgressBar.Open()
for item in list:
    bar.Update(count, len(list))
</code>```

I would instead like my calling code to be

```<code>for item in list:
    bar.Update(count, len(list))
</code>```

I want my Update() function to Open() a bar for the caller if one is not open.  The caller doesn't need any other access to the bar than to update it so there's no value in having the meter` handle.

How can I retain state to tell if the Update had been previously called?

I could create a global variable and keep track that way, but I have a gut sense there's a Pythonista way of doing it.

Trying again, but in a way that has no application to stumble on.

The base question is:
I have a function that will be called multiple times.
I want to do something different the first time it is called.
How can a function in Python do that?

In C, that of course would be a...
static variable

I'm just now kinda figuring it out as I type, sorry.

========================

I'm sure all these edits are not how stackoverflow is supposed to work. I'm sorry for not getting it right yet, but am very appreciative of the replies.

Despite it sounding like I'm breaking all the rules of good practices, it's when looked at from the CALLER'S point of view that I had hoped to make an impact.

What if the only thing you needed to do to add a progress meter, even for debugging, to your program was make a call to a progress meter update in the location you want to show progress?

That's the underlying motivation.  Slide in 1-line, get something cool for the trouble.

This progress meter was added to my otherwise boring file de-duplicator by adding just the single call:

```<code>msg = f'Deduplicating {idx} of {total_files} files\n' f'{dup_count} Dupes found\n' f'{small_count} Too small'
not_cancelled = sGUI.ProgressBar('De-dupe', msg, idx, total_files)
</code>```

答:
OK, I found a solution using 'globals'. I thought that a nested function was the way to do it... then I mixed the two.

By 'globals' I meant variables declared outside the scope of a function.  I want to be able to import my module without the import creating anything.

Here's the code that shows how to do this with globals

```<code>def my_update(amount):
    global flag
    if 'flag' in globals():
        print('I have been here')
    else:
        print('I have not been here')
    flag = True

    return

for i in range(10):
    print(f'Calling number {i}')
    result = my_update(1)
</code>```

It does the job for the goals I had set out, but I'm SURE there are better, safer ways that are more elegant as well.

Body:
My example is a progress bar

In its simplest form a progress bar is

bar = ProgressBar.Open()
for item in list:
    bar.Update(count, len(list))

I would instead like my calling code to be

for item in list:
    bar.Update(count, len(list))

I want my Update() function to Open() a bar for the caller if one is not open.  The caller doesn't need any other access to the bar than to update it so there's no value in having the meter` handle.

How can I retain state to tell if the Update had been previously called?

I could create a global variable and keep track that way, but I have a gut sense there's a Pythonista way of doing it.

Trying again, but in a way that has no application to stumble on.

The base question is:
I have a function that will be called multiple times.
I want to do something different the first time it is called.
How can a function in Python do that?

In C, that of course would be a...
static variable

I'm just now kinda figuring it out as I type, sorry.

========================

I'm sure all these edits are not how stackoverflow is supposed to work. I'm sorry for not getting it right yet, but am very appreciative of the replies.

Despite it sounding like I'm breaking all the rules of good practices, it's when looked at from the CALLER'S point of view that I had hoped to make an impact.

What if the only thing you needed to do to add a progress meter, even for debugging, to your program was make a call to a progress meter update in the location you want to show progress?

That's the underlying motivation.  Slide in 1-line, get something cool for the trouble.

This progress meter was added to my otherwise boring file de-duplicator by adding just the single call:

msg = f'Deduplicating {idx} of {total_files} files\n' f'{dup_count} Dupes found\n' f'{small_count} Too small'
not_cancelled = sGUI.ProgressBar('De-dupe', msg, idx, total_files)

Body:
OK, I found a solution using 'globals'. I thought that a nested function was the way to do it... then I mixed the two.

By 'globals' I meant variables declared outside the scope of a function.  I want to be able to import my module without the import creating anything.

Here's the code that shows how to do this with globals

def my_update(amount):
    global flag
    if 'flag' in globals():
        print('I have been here')
    else:
        print('I have not been here')
    flag = True

    return

for i in range(10):
    print(f'Calling number {i}')
    result = my_update(1)

It does the job for the goals I had set out, but I'm SURE there are better, safer ways that are more elegant as well.


问:
Message: Array to string conversion only in PHP7 Codeigniter

I have added PHP7 to my local server and I got this error:

Message: Array to string conversion Filename:
  libraries/Data_views_array.php Line Number: 59

```<code>data = $this->CI->$this_data[0]->$method($pass_var);
</code>```

I found this post: PHP Notice: Array to string conversion only on PHP 7 and I changed my code to:

```<code>data = $this->CI->$this_data[0]->{$method($pass_var)};
</code>```

but I got a different error:

Message: Call to undefined function get_page_id()

Everything works in PHP 5.6 and I don't know how to make it work in PHP 7.

Please help.

```<code>class Data_views_array {

    var $CI;

            public function __construct() {

                    $this->CI =& get_instance();

            }

            public function action_per_module($array_modules) {

               $array_to_display = array();
               $array_view_data = array();

                if (!$array_modules) {
                    return false;
                }
                else {
                    while (list($key, $this_data) = each($array_modules)) {

                        /*
                        *  $this_data[0] -  is the controller name
                        * loading this model
                        */

                       $this->CI->load->library($this_data[0]);

                          if ($this_data[2] == 'NULL') {
                               /*
                               * if there are no arguments (method and passing variable)
                               * the model is called
                               */
                               $data = $this->CI->$this_data[0];

                          }
                            else {
                              /*
                              * getting method and passing variable from arguments
                              */
                    //echo $this_data[2]. " - json<br>";
                              $obj = json_decode($this_data[2]);
                              $method = key(get_object_vars($obj));
                    //echo $method. " - method<br>";

                              $pass_var = $obj->$method;

                             /*
                              * getting data for view
                              */
                              $data = $this->CI->$this_data[0]->$method($pass_var);

                            }

                        /*
                        * name of the View
                        */
                        $view = $this_data[1];

                        /*
                        * adding the pair of View to the $array_view_data
                        */
                        array_push($array_view_data, $view);
                        array_push($array_view_data, $data);
                        /*
                        * passing View Array to Display array
                        */
                        array_push($array_to_display, $array_view_data);
                        /*
                        * clear the array of the pair of View and passing variable
                        */
                        unset($array_view_data);
                        $array_view_data = array();

                    }
                }

                return $array_to_display;
            }

}
</code>```

The first Class that is called - $this_data[0]== page_title_display  from library has method:  get_page_id($page_id). This class gets the Title of the page.
Why the same script works in PHP 5.6 and it does not work in PHP 7?
Why the get_page_id function is found in PHP 5.6 but not in PHP 7?

```<code>class Page_title_display {

    var $CI;

    public function __construct(){

            $this->CI =& get_instance();

   }

    public function get_page_id($page_id) {
        $this->CI->load->model('pageTitle_model');
        $title = $this->CI->pageTitle_model->getPagetitle($page_id);

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

答:
I solved this issue. For some reason PHP 7 does not like when $this_data[0] is used as a part of array.:
data = $this->CI->$this_data[0]->$method($pass_var);

First solution: I assigned this value to a variable:

$libControl = $this_data[0];
data = $this->CI->$libControl->$method($pass_var);

Second solution: only $this_data[0] in brackets:

data = $this->CI->{$this_data[0]}->$method($pass_var);

Body:
I have added PHP7 to my local server and I got this error:

Message: Array to string conversion Filename:
  libraries/Data_views_array.php Line Number: 59

data = $this->CI->$this_data[0]->$method($pass_var);

I found this post: PHP Notice: Array to string conversion only on PHP 7 and I changed my code to:

data = $this->CI->$this_data[0]->{$method($pass_var)};

but I got a different error:

Message: Call to undefined function get_page_id()

Everything works in PHP 5.6 and I don't know how to make it work in PHP 7.

Please help.

class Data_views_array {

    var $CI;

            public function __construct() {

                    $this->CI =& get_instance();

            }

            public function action_per_module($array_modules) {

               $array_to_display = array();
               $array_view_data = array();

                if (!$array_modules) {
                    return false;
                }
                else {
                    while (list($key, $this_data) = each($array_modules)) {

                        /*
                        *  $this_data[0] -  is the controller name
                        * loading this model
                        */

                       $this->CI->load->library($this_data[0]);

                          if ($this_data[2] == 'NULL') {
                               /*
                               * if there are no arguments (method and passing variable)
                               * the model is called
                               */
                               $data = $this->CI->$this_data[0];

                          }
                            else {
                              /*
                              * getting method and passing variable from arguments
                              */
                    //echo $this_data[2]. " - json
";
                              $obj = json_decode($this_data[2]);
                              $method = key(get_object_vars($obj));
                    //echo $method. " - method
";

                              $pass_var = $obj->$method;

                             /*
                              * getting data for view
                              */
                              $data = $this->CI->$this_data[0]->$method($pass_var);

                            }

                        /*
                        * name of the View
                        */
                        $view = $this_data[1];

                        /*
                        * adding the pair of View to the $array_view_data
                        */
                        array_push($array_view_data, $view);
                        array_push($array_view_data, $data);
                        /*
                        * passing View Array to Display array
                        */
                        array_push($array_to_display, $array_view_data);
                        /*
                        * clear the array of the pair of View and passing variable
                        */
                        unset($array_view_data);
                        $array_view_data = array();

                    }
                }

                return $array_to_display;
            }

}

The first Class that is called - $this_data[0]== page_title_display  from library has method:  get_page_id($page_id). This class gets the Title of the page.
Why the same script works in PHP 5.6 and it does not work in PHP 7?
Why the get_page_id function is found in PHP 5.6 but not in PHP 7?

class Page_title_display {

    var $CI;

    public function __construct(){

            $this->CI =& get_instance();

   }

    public function get_page_id($page_id) {
        $this->CI->load->model('pageTitle_model');
        $title = $this->CI->pageTitle_model->getPagetitle($page_id);

        return $title;
    }
}


问:
Can't connect to "Jenkins-On-Azure"
I created a Jenkins linux vm on Azure on a new resource group.

I followed the steps described here:
Create a Jenkins server on an Azure Linux VM from the Azure portal.

So I ran the command ssh -L 127.0.0.1:8080:localhost:8080 jenkinsadmin@jenkins2517454.eastus.cloudapp.azure.com
 (changed the username and dns name to my own) on my linux vm and it seems fine (no errors).

Now whenever I try to connect from my own computer (not on azure) on port 8080 I get on the linux vm the following message: channel 2: open failed: administratively prohibited: open failed and It doesn't let me log in into Jenkins.

How can it be solved?

Thank you

答:
This is not a NSG issue. You don't need add port 8080 on Azure NSG rules.

If you want to connect from your computer with http://localhost:8080/, you should need create a SSH tunnel on your local computer. You could do it with putty.

Configure the Tunnel

Also, you could install Linux on Windows. Please refer to the following steps:

1.Install Linux on Windows.

2.Open Power shell on execute bash

3.Execute sudo -i and ssh -L 127.0.0.1:8080:localhost:8080 jenkinsadmin@jenkins2517454.eastus.cloudapp.azure.com

Now, I could access http://localhost:8080/ on my local computer.(The default user name is admin).

Title: Can't connect to "Jenkins-On-Azure"


问:
Gtk3 keys bindings in css files
Where can I find an exhaustive list of available keybindings that a user can define in a CSS file for GTK+ 3?

I have already checked those resources:

https://developer.gnome.org/gtk3/stable/GtkCssProvider.html

https://developer.gnome.org/gtk3/stable/gtk3-Bindings.html

/usr/share/themes/Default/gtk-3.0/gtk-keys.css (which is empty)

/usr/share/themes/Emacs/gtk-3.0/gtk-keys.css

For example, how can a user make <Control>Space move the cursor to the end of the text in a GtkTextView?

答:
I've also been looking for proper documentation of possible key bindings for quite a while now and just stumbled over these docs of the single-line text widget GtkEntry. In this particular case, one can scroll all the way down to the end of the menu to find all other "keybinding signals" the widget offers, like insert_at_cursor, paste_clipboard etc. including the parameters these signals accept (such as the DeleteType in case of delete_from_cursor). It now shouldn't be too hard to find the signals for other GTK widgets.

Update: If the Vala docs provide a detailed description of the keybinding signals, one might assume that the regular Gtk3 docs do, too. Indeed. It's always easier to find what you're looking for if you know what you're looking for. :)

Title: Gtk3 keys bindings in css files


问:
excel multiple column vlookup
My table

```<code>Id  index Col1  col2  col3
a    1    smith
a    2           John
b    1    mark
b    2           kay
b    3                 Van
c    1    Par
c    2           Cap
</code>```

In the Vlookup Table

```<code>ID  Col1   Col2  Col3
a   Smith  John
b   Mark   kay   Van
c   Par    Cap
</code>```

How do I achieve by doing vlookup by id

答:
I believe this will solve your issue:

This is the formula in cell I2:

```<code>=INDEX($C:$C,MATCH($H2,$A:$A,0))
</code>```

This is the formula in cell J2:

=IF(INDEX($D:$D,MATCH($H2,$A:$A,0))=0,OFFSET(INDEX($D:$D,MATCH($H2,$A:$A,0)),1,0))

This is the formula in cell K2:

=IF(INDEX($E:$E,MATCH($H2,$A:$A,0))=0,OFFSET(INDEX($E:$E,MATCH($H2,$A:$A,0)),2,0))

Hope this helps!

Thanks.

Title: excel multiple column vlookup

Body:
My table

Id  index Col1  col2  col3
a    1    smith
a    2           John
b    1    mark
b    2           kay
b    3                 Van
c    1    Par
c    2           Cap

In the Vlookup Table

ID  Col1   Col2  Col3
a   Smith  John
b   Mark   kay   Van
c   Par    Cap

How do I achieve by doing vlookup by id

Body:
I believe this will solve your issue:

This is the formula in cell I2:

=INDEX($C:$C,MATCH($H2,$A:$A,0))

This is the formula in cell J2:

=IF(INDEX($D:$D,MATCH($H2,$A:$A,0))=0,OFFSET(INDEX($D:$D,MATCH($H2,$A:$A,0)),1,0))

This is the formula in cell K2:

=IF(INDEX($E:$E,MATCH($H2,$A:$A,0))=0,OFFSET(INDEX($E:$E,MATCH($H2,$A:$A,0)),2,0))

Hope this helps!

Thanks.


问:
Load YAML nested with Jinja2 in Python
I have a YAML file (all.yaml) that looks like:

```<code>...
var1: val1
var2: val2
var3: {{var1}}-{{var2}}.txt
...
</code>```

If I load it in Python like this:

```<code>import yaml

f = open('all.yaml')
dataMap = yaml.safe_load(f)
f.close()
print(dataMap["var3"])
</code>```

the output is {{var1}}-{{var2}}.txt and not val1-val2.txt.

Is it possible to replace the nested vars with the value?

I tried to load it with:

```<code>import jinja2
templateLoader = jinja2.FileSystemLoader( searchpath="/path/to/dir" )
templateEnv = jinja2.Environment( loader=templateLoader )
TEMPLATE_FILE = "all.yaml"
template = templateEnv.get_template( TEMPLATE_FILE )
</code>```

The exception is no longer thrown, now I am stuck and have to research how to proceed.

答:
First define an Undefined class and load yaml to get known values. Then load it again and render with known values.

```<code>#!/usr/bin/env python

import yaml
from jinja2 import Template, Undefined

str1 = '''var1: val1
var2: val2
var3: {{var1}}-{{var2}}.txt
'''

class NullUndefined(Undefined):
  def __getattr__(self, key):
    return ''

t = Template(str1, undefined=NullUndefined)
c = yaml.safe_load(t.render())

print t.render(c)
</code>```

Run it:

```<code>$ ./test.py
var1: val1
var2: val2
var3: val1-val2.txt
</code>```

Title: Load YAML nested with Jinja2 in Python

Body:
I have a YAML file (all.yaml) that looks like:

...
var1: val1
var2: val2
var3: {{var1}}-{{var2}}.txt
...

If I load it in Python like this:

import yaml

f = open('all.yaml')
dataMap = yaml.safe_load(f)
f.close()
print(dataMap["var3"])

the output is {{var1}}-{{var2}}.txt and not val1-val2.txt.

Is it possible to replace the nested vars with the value?

I tried to load it with:

import jinja2
templateLoader = jinja2.FileSystemLoader( searchpath="/path/to/dir" )
templateEnv = jinja2.Environment( loader=templateLoader )
TEMPLATE_FILE = "all.yaml"
template = templateEnv.get_template( TEMPLATE_FILE )

The exception is no longer thrown, now I am stuck and have to research how to proceed.

Body:
First define an Undefined class and load yaml to get known values. Then load it again and render with known values.

#!/usr/bin/env python

import yaml
from jinja2 import Template, Undefined

str1 = '''var1: val1
var2: val2
var3: {{var1}}-{{var2}}.txt
'''

class NullUndefined(Undefined):
  def __getattr__(self, key):
    return ''

t = Template(str1, undefined=NullUndefined)
c = yaml.safe_load(t.render())

print t.render(c)

Run it:

$ ./test.py
var1: val1
var2: val2
var3: val1-val2.txt