问:
Code Inspection for method signatures
i want to create a custom Code Inspection Rule for IntelliJ IDEA. The rule should check, if a special annotated argument type of a method call is equivalent to the parameter type of the method signature.

Example:

```<code>public void method(@MyAnnotation String input){
}

public void method2(){
    String invalid = "";
    method(invalid); // error

    @MyAnnotation String valid = (@MyAnnotation String) "";
    method(valid); // no error
}
</code>```

What I tried:

```<code>[...]
protected static class visitor extends JavaElementVisitor {
    @Override
    public void visitMethodCallExpression(PsiMethodCallExpression expression) {
      PsiMethod method = expression.resolveMethod();

      //returns no annotations
      PsiAnnotation[] annotations = method.getModifierList().getAnnotations();

      //returns also no annotations
      MethodSignatureBackedByPsiMethod methodSignature = MethodSignatureBackedByPsiMethod.create(method, PsiSubstitutor.EMPTY);
      PsiType[] types = methodSignature.getParameterTypes();
      for (PsiType psiType : types){
        TypeAnnotationProvider provider = psiType.getAnnotationProvider();
        PsiAnnotation[] annotations = provider.getAnnotations();
      }
      super.visitMethodCallExpression(expression);
    }
[...]
}
</code>```

How can I compare the annotation of the argument type with the annotation of the parameter type of the method?

Thanks!

答:
method.getModifierList() returns the modifier list of the method, but the method is not annotated. You want the annotation of the parameter. So you will need to do something like this:

```<code>method.getParameterList().getParameters()[indexOfParameter].getModifierList()
</code>```

To get the annotations of an argument of a method call, do something like this:

```<code>PsiExpression argument = expression.getArgumentList().getExpressions()[indexOfArgument];
argument = PsiUtil.skipParenthesizedExprDown(argument);
if (argument instanceof PsiReferenceExpression) {
  PsiElement target = ((PsiReferenceExpression)argument).resolve();
  if (target instanceof PsiVariable) {
    ((PsiVariable)target).getModifierList();
    // get annotations
  }
}
</code>```

Title: Code Inspection for method signatures

Body:
i want to create a custom Code Inspection Rule for IntelliJ IDEA. The rule should check, if a special annotated argument type of a method call is equivalent to the parameter type of the method signature.

Example:

public void method(@MyAnnotation String input){
}

public void method2(){
    String invalid = "";
    method(invalid); // error

    @MyAnnotation String valid = (@MyAnnotation String) "";
    method(valid); // no error
}

What I tried:

[...]
protected static class visitor extends JavaElementVisitor {
    @Override
    public void visitMethodCallExpression(PsiMethodCallExpression expression) {
      PsiMethod method = expression.resolveMethod();

      //returns no annotations
      PsiAnnotation[] annotations = method.getModifierList().getAnnotations();

      //returns also no annotations
      MethodSignatureBackedByPsiMethod methodSignature = MethodSignatureBackedByPsiMethod.create(method, PsiSubstitutor.EMPTY);
      PsiType[] types = methodSignature.getParameterTypes();
      for (PsiType psiType : types){
        TypeAnnotationProvider provider = psiType.getAnnotationProvider();
        PsiAnnotation[] annotations = provider.getAnnotations();
      }
      super.visitMethodCallExpression(expression);
    }
[...]
}

How can I compare the annotation of the argument type with the annotation of the parameter type of the method?

Thanks!

Body:
method.getModifierList() returns the modifier list of the method, but the method is not annotated. You want the annotation of the parameter. So you will need to do something like this:

method.getParameterList().getParameters()[indexOfParameter].getModifierList()

To get the annotations of an argument of a method call, do something like this:

PsiExpression argument = expression.getArgumentList().getExpressions()[indexOfArgument];
argument = PsiUtil.skipParenthesizedExprDown(argument);
if (argument instanceof PsiReferenceExpression) {
  PsiElement target = ((PsiReferenceExpression)argument).resolve();
  if (target instanceof PsiVariable) {
    ((PsiVariable)target).getModifierList();
    // get annotations
  }
}


来源: stackexchange

问:
asp.net WebForm or MVC browser game
I would like to know is this platfoerm (MVC or WebForms) good technology of creating webBrowser based games and if so maybe You have got some tutorials, books, any resources which may be helpfull in beggining with such things.

thanks for help, bye

答:
I wouldn't disagree with these answers, but I'd like to offer an alternative viewpoint, based on the type of game you're making. If you are looking at creating something very simple with little or no graphics, ASP.NET is certainly a viable solution. Some extremely nice games have been done with seemingly "non-gaming" languages ... look at Kingdom of Loathing (written in PHP).

As far as webforms vs. MVC, I would answer that question the same I always think it should it be answered: what will MVC provide that your app needs (or may need in the future) that makes the additional learning curve worth it? If you're already familiar with webforms and don't think (really, REALLY don't think) that you'll need MVC, I say save the development time and use it.

ContentLicense: CC BY-SA 2.5

Title: asp.net WebForm or MVC browser game


问:
Why do I get SQLCODE -206 when I run a query to calculate median value of a column?
I am trying to find median of the field "bal" based on "key" in DB2. I get this error when I execute this code "Error: DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=KEY, DRIVER=3.66.46, SQLState:  42703).

Appreciate your comments !!

```<code>        SELECT
           key,
           AVG(bal)
        FROM
        (
           SELECT
              key,
              bal,
              ROW_NUMBER() OVER (
                 PARTITION BY key
                 ORDER BY bal ASC) AS RowAsc,
              ROW_NUMBER() OVER (
                 PARTITION BY key
                 ORDER BY bal DESC) AS RowDesc
           FROM tab1
        ) x
        WHERE
           RowAsc IN (RowDesc, RowDesc - 1, RowDesc + 1)
        GROUP BY key
        ORDER BY key;
</code>```

答:
Ensure that every reference to key becomes "key"

```<code>SELECT
      "key"
    , AVG(bal)
FROM (
      SELECT
            "key"
          , bal
          , ROW_NUMBER() OVER (PARTITION BY "key"
                               ORDER BY bal ASC)  AS rowasc
          , ROW_NUMBER() OVER (PARTITION BY "key"
                               ORDER BY bal DESC) AS rowdesc
      FROM tab1
) x
WHERE RowAsc IN (RowDesc, RowDesc - 1, RowDesc + 1)
GROUP BY
      "key"
ORDER BY
      "key"
;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to find median of the field "bal" based on "key" in DB2. I get this error when I execute this code "Error: DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=KEY, DRIVER=3.66.46, SQLState:  42703).

Appreciate your comments !!

        SELECT
           key,
           AVG(bal)
        FROM
        (
           SELECT
              key,
              bal,
              ROW_NUMBER() OVER (
                 PARTITION BY key
                 ORDER BY bal ASC) AS RowAsc,
              ROW_NUMBER() OVER (
                 PARTITION BY key
                 ORDER BY bal DESC) AS RowDesc
           FROM tab1
        ) x
        WHERE
           RowAsc IN (RowDesc, RowDesc - 1, RowDesc + 1)
        GROUP BY key
        ORDER BY key;

Body:
Ensure that every reference to key becomes "key"

SELECT
      "key"
    , AVG(bal)
FROM (
      SELECT
            "key"
          , bal
          , ROW_NUMBER() OVER (PARTITION BY "key"
                               ORDER BY bal ASC)  AS rowasc
          , ROW_NUMBER() OVER (PARTITION BY "key"
                               ORDER BY bal DESC) AS rowdesc
      FROM tab1
) x
WHERE RowAsc IN (RowDesc, RowDesc - 1, RowDesc + 1)
GROUP BY
      "key"
ORDER BY
      "key"
;


问:
Copy non empty struct values in Golang for updating Datastore
I'm writing a PATCH API and it is not necessary to send all the fields in request. I'd like to update only the new fields.
I'm using Datastore, and I think, I need to send entire struct that contains the final value I intend to save, as it replaces all the values.
I retrieve existing values from DB in one struct and I have the request in another struct.

```<code>type product struct {
    TITLE    string `json:"title"`
    SUMMARY  string `json:"summary"`
    IMAGEURL string `json:"imageUrl"`
    CATEGORY string `json:"category"`
    TYPE     int    `json:"type"`
}

var dbVal product // Holds the existing DB values
var formVal product // Holds the values received from web form (api request)
</code>```

formVal need not have all the values. It is empty if the field is not sent in the request.

I want the dbVal struct to be updated with the values in formVal ONLY if formVal field is not empty (!= "" for string or != 0 for int).

PS: I searched for more than a day and tried different examples and tried to use reflect from some of the other answers, but not able to find out how to assign values to another struct. If this is already answered, I'm sorry for reposting this - please share the link.

答:
Consider writing a utility method on the product type that checks if it is empty and use that to determine whether to update the database values, e.g.:</p>

```<code>func (p product) isEmpty() bool {
  return (p.TITLE == "") && (p.SUMMARY == "") && (p.IMAGEURL == "") && (p.CATEGORY == "") && (p.TYPE == 0)
}
// ...

if !formVal.isEmpty() {
  // Update database values...
}
</code>```

Body:
I'm writing a PATCH API and it is not necessary to send all the fields in request. I'd like to update only the new fields.
I'm using Datastore, and I think, I need to send entire struct that contains the final value I intend to save, as it replaces all the values.
I retrieve existing values from DB in one struct and I have the request in another struct.

type product struct {
    TITLE    string `json:"title"`
    SUMMARY  string `json:"summary"`
    IMAGEURL string `json:"imageUrl"`
    CATEGORY string `json:"category"`
    TYPE     int    `json:"type"`
}

var dbVal product // Holds the existing DB values
var formVal product // Holds the values received from web form (api request)

formVal need not have all the values. It is empty if the field is not sent in the request.

I want the dbVal struct to be updated with the values in formVal ONLY if formVal field is not empty (!= "" for string or != 0 for int).

PS: I searched for more than a day and tried different examples and tried to use reflect from some of the other answers, but not able to find out how to assign values to another struct. If this is already answered, I'm sorry for reposting this - please share the link.

Body:
Consider writing a utility method on the product type that checks if it is empty and use that to determine whether to update the database values, e.g.:

func (p product) isEmpty() bool {
  return (p.TITLE == "") && (p.SUMMARY == "") && (p.IMAGEURL == "") && (p.CATEGORY == "") && (p.TYPE == 0)
}
// ...

if !formVal.isEmpty() {
  // Update database values...
}


问:
Getting a class property value from a textbox
I am wondering how to return the value of a class property with the input of a textbox? i.e. the input in the nameTextBox would go to the Name property of a Pet class, the breedTextBox would be the Breed property, etc.

Using C# windows form.

答:
This logic can be accomplished by handling the TextChanged event of your TextBox instances. Given the current Pet instance m_Pet (allocated within your class as a member, for example):

```<code>private Pet m_Pet = new Pet();
</code>```

and the events subscription in the InitializeComponent method of the form:

```<code>m_TextBoxName = new TextBox();
m_TextBoxName.TextChanged += TextBoxName_TextChanged;
</code>```

here is how you can accomplish this:

```<code>private void TextBoxName_TextChanged(Object sender, EventArgs e)
{
    m_Pet.Name = m_TextBoxName.Text;
}
</code>```

And the same can be performed for as many properties as you want:

```<code>private void TextBoxBreed_TextChanged(Object sender, EventArgs e)
{
    m_Pet.Breed = m_TextBoxBreed.Text;
}

private void TextBoxType_TextChanged(Object sender, EventArgs e)
{
    m_Pet.Type = m_TextBoxType.Text;
}
</code>```

Body:
This logic can be accomplished by handling the TextChanged event of your TextBox instances. Given the current Pet instance m_Pet (allocated within your class as a member, for example):

private Pet m_Pet = new Pet();

and the events subscription in the InitializeComponent method of the form:

m_TextBoxName = new TextBox();
m_TextBoxName.TextChanged += TextBoxName_TextChanged;

here is how you can accomplish this:

private void TextBoxName_TextChanged(Object sender, EventArgs e)
{
    m_Pet.Name = m_TextBoxName.Text;
}

And the same can be performed for as many properties as you want:

private void TextBoxBreed_TextChanged(Object sender, EventArgs e)
{
    m_Pet.Breed = m_TextBoxBreed.Text;
}

private void TextBoxType_TextChanged(Object sender, EventArgs e)
{
    m_Pet.Type = m_TextBoxType.Text;
}


问:
Spell check for latex file in Atom

I am trying to add .tex file in the Setting->Grammar of atom/spell-check so that it will check spellings in my document because .tex file is going to be a PDF document, but its not working.

答:
Found out that I was using wrong syntax. Correct scope is text.tex.latex. It was already mentioned in the README file on how to get it. Follow below procedure in Atom Editor.

To enable Spell Check for your current file type: put your cursor in
  the file, open the Command Palette (cmd-shift-p), and run the
  Editor: Log Cursor Scope command. This will trigger a notification
  which will contain a list of scopes. The first scope that's listed is
  the one you should add to the list of scopes in the settings for the
  Spell Check package. Here are some examples: source.coffee,text.plain, text.html.basic.

It should pop up as below

Title: Spell check for latex file in Atom


问:
API - Isolating returned JSON keys and values within indexed objects
Building a web app using a flight data API and, welp, the struggle is real.

My returned array and it's objects look something like this:

```<code>results:

0:{destination: "YTO",
departure_date: "2018-01-24",
return_date: "2018-01-25"
airline: "TS"}

1:{destination: "BOS",
departure_date: "2018-01-08",
return_date: "2018-01-11",
airline: "AC"}

2:{destination: "SJU",
departure_date: "2018-01-31",
return_date: "2018-02-01",
airline: "AA"}
</code>```

Before I can dump the results into the DOM to display them to the visitor of the site, I need to run certain returned values through an additional API (long story) so I obviously need to isolate them somehow.

For this example, I'm using destination so my initial thought process is start by to logging out:

```<code>console.log(response.results[0].destination);
</code>```

Which we know will print the FIRST destination in the FIRST object, since [0] is the index of that object (so in this case in this case we get back YTO).

Since every returned object has an index number, I think I need to loop through them (for each?) to pull the values I need but I'm trying variations of that with no luck.....or for all I know it's something else entirely.

(your two cents goes here)

答:
You can turn an Object's keys into an array with the Object.keys() method, this will allow you to use the Array.forEach() method to loop through an Object's enumerable properties, like so...

```<code>Object.keys(dataObj).forEach(function(k) {
    var dest = dataObj[k].destination;
    /* ... etc ... */
});
</code>```

Hope that helps.

More on Object.keys() @MDN

Body:
Building a web app using a flight data API and, welp, the struggle is real.

My returned array and it's objects look something like this:

results:

0:{destination: "YTO",
departure_date: "2018-01-24",
return_date: "2018-01-25"
airline: "TS"}

1:{destination: "BOS",
departure_date: "2018-01-08",
return_date: "2018-01-11",
airline: "AC"}

2:{destination: "SJU",
departure_date: "2018-01-31",
return_date: "2018-02-01",
airline: "AA"}

Before I can dump the results into the DOM to display them to the visitor of the site, I need to run certain returned values through an additional API (long story) so I obviously need to isolate them somehow.

For this example, I'm using destination so my initial thought process is start by to logging out:

console.log(response.results[0].destination);

Which we know will print the FIRST destination in the FIRST object, since [0] is the index of that object (so in this case in this case we get back YTO).

Since every returned object has an index number, I think I need to loop through them (for each?) to pull the values I need but I'm trying variations of that with no luck.....or for all I know it's something else entirely.

(your two cents goes here)

Body:
You can turn an Object's keys into an array with the Object.keys() method, this will allow you to use the Array.forEach() method to loop through an Object's enumerable properties, like so...

Object.keys(dataObj).forEach(function(k) {
    var dest = dataObj[k].destination;
    /* ... etc ... */
});

Hope that helps.

More on Object.keys() @MDN


问:
How to stop wasting time updating dependencies with composer?
I am building a small app with some dependencies and my back-end is in PHP with composer and I use many dependencies.

I used to keep the project up-to-date but sometimes, composer update is just to long!

Anyone have some good tips to help me updating my dependencies? any automated service that can run them for me without breaking my code?

答:
I built Dependabot to do exactly this. Every morning it will check with packagist whether there are any new versions, and if there are it will create a pull request to update you to the latest and greatest.

The core of the app is open source here and it's relatively popular with Ruby and JavaScript programmers. The PHP beta is fully functional, and I'm looking for more people to give it a try!


问:
Visual Studio Resources
I've got a relatively small program that runs on a proxy socket class I fount from the mentalis website. For some reason this program has quickly become a 100% cpu resource hog when running. I've done all I can think to find the problem in the code is there a function in visual studio that helps to identify what sections of the code are the most resource intensive? Any ideas on why a socket class would be such a cpu hog?</p>

答: Visual Studio 2010 Premium and Enterprise editions have a profiler built in -- I believe the feature is called 'Performance Explorer.' If that's not available, just do a debug build and do some manual profiling by stopping the code periodically to see which code is executed most frequently (edit: as mentioned by Doc Brown).</p>

Title: Visual Studio Resources


问:
HTML position = center-10px
I am making an HTML website. I have an map as an background picture and I need a button to be on the map. Like this:

But when I start scaling my site, this happens:
I know what is the problem: the position of the pictures is center-X px and center-Y px, not margin: 40% 0px 0px 20%. But how to do that? position: absolute; left: 50%-30px; top: 50%-83px doesn´t work.

答:
A bunch of people have mentioned using absolute margins (which would work), however there is another approach with the implementation of transform: translate.

In the example below, the inner img is always centered in its containing div which I believe would also meet your needs. I also added some random animation to the box so that you can see how effectively this positions itself.

setInterval(randomAnimation, 500);

function randomAnimation() {
  var random = Math.floor(Math.random() * (4 - 0));
  if (random == 0)
    $(".box").animate({
      top: "+=50"
    });
  else if (random == 1)
    $(".box").animate({
      left: "+=50"
    });
  else if (random == 2)
    $(".box").animate({
      top: "-=50"
    });
  else
  $(".box").animate({
      height: "+=50"
    });
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.box {
  position: relative;
  width: 150px;
  height: 100px;
  background-image: url(http://via.placeholder.com/150x100/ff0000/ffffff)
}

img {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}</code>```

```

Title: HTML position = center-10px

Body:
A bunch of people have mentioned using absolute margins (which would work), however there is another approach with the implementation of transform: translate.

In the example below, the inner img is always centered in its containing div which I believe would also meet your needs. I also added some random animation to the box so that you can see how effectively this positions itself.

setInterval(randomAnimation, 500);

function randomAnimation() {
  var random = Math.floor(Math.random() * (4 - 0));
  if (random == 0)
    $(".box").animate({
      top: "+=50"
    });
  else if (random == 1)
    $(".box").animate({
      left: "+=50"
    });
  else if (random == 2)
    $(".box").animate({
      top: "-=50"
    });
  else
  $(".box").animate({
      height: "+=50"
    });
}

.box {
  position: relative;
  width: 150px;
  height: 100px;
  background-image: url(http://via.placeholder.com/150x100/ff0000/ffffff)
}

img {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

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

<div class="box">
  <img src="http://via.placeholder.com/50x50" />
</div>


问:
Kelogger/pasowrd asterrix replace
I would like to make a keylogger and I want the password to look like its asterisk like in the log on:

```<code>@echo off
mode con: cols=10000 lines=300
color a
title Login
cls
echo LOGIN ERROR
ver
echo (c) 2017 Microsoft Corporation. All rights reserved.
echo.
cd “C:Logs”
set /p user=Username:
set /p pass=Password:
echo Username=”%user%” Password=”%pass%” >> Log.txt
start open2.bat
exit
</code>```

I expect it to look real I have tried searching but all I found is for the log on screen I want it for the desktop

just text no asterisks

答:
I know this is a duplicate question here on StackOverFlow but I can't find it.  I may have found this code on DosTips.com as well.  When I find the original links I will update the question.

Essentially this is the code you are looking for to mask password input with asterisks.

```<code>@echo off &setlocal

:username
cls
SET "username="
SET /P "username=Enter your username:"
IF NOT DEFINED username GOTO username

:password
cls
<nul set /p "=Enter your password: "
call :HInput password
IF NOT DEFINED password GOTO password

setlocal EnableDelayedExpansion
echo user:%username% pass:!password!
pause
goto :eof

:HInput [ByRef_VarName]
:: inspired by Carlos
:: improved by pieh-ejdsch
if "%__HI__%" neq "__HI__" (
  setlocal DisableDelayedExpansion
  set "S=" &set "N=0" &set "__HI__=__HI__"
  for /f %%i in ('"prompt;$h&for %%i in (1) do rem"') do set "BS=%%i"
)
set "C="
for /f "eol=1 delims=" %%i in ('xcopy /lwq "%~f0" :\') do set "C=%%i"
set "C=%C:~-1%"
setlocal EnableDelayedExpansion
if not defined C (
  echo(
  if "%~1"=="" (
    echo(!S!
    endlocal &endlocal &exit /b %N%
  ) else (
    if defined S (
      for /f delims^=^ eol^= %%i in ("!S!") do endlocal &endlocal &set "%~1=%%i" &exit /b %N%
    ) else endlocal &endlocal &set "%~1=" &exit /b 0
  )
)
if "!BS!"=="!C!" (
  set "C="
  if defined S set /a "N -= 1" &set "S=!S:~,-1!" &<nul set /p "=%BS% %BS%"
) else set /a "N += 1" &<nul set /p "=*"
if not defined S (
  endlocal &set "N=%N%" &set "S=%C%"
) else for /f delims^=^ eol^= %%i in ("!S!") do endlocal &set "N=%N%" &set "S=%%i%C%"
goto HInput
</code>```

Title: Kelogger/pasowrd asterrix replace

Body:
I would like to make a keylogger and I want the password to look like its asterisk like in the log on:

@echo off
mode con: cols=10000 lines=300
color a
title Login
cls
echo LOGIN ERROR
ver
echo (c) 2017 Microsoft Corporation. All rights reserved.
echo.
cd “C:Logs”
set /p user=Username:
set /p pass=Password:
echo Username=”%user%” Password=”%pass%” >> Log.txt
start open2.bat
exit

I expect it to look real I have tried searching but all I found is for the log on screen I want it for the desktop

just text no asterisks

Body:
I know this is a duplicate question here on StackOverFlow but I can't find it.  I may have found this code on DosTips.com as well.  When I find the original links I will update the question.

Essentially this is the code you are looking for to mask password input with asterisks.

@echo off &setlocal

:username
cls
SET "username="
SET /P "username=Enter your username:"
IF NOT DEFINED username GOTO username

:password
cls
<nul set /p "=Enter your password: "
call :HInput password
IF NOT DEFINED password GOTO password

setlocal EnableDelayedExpansion
echo user:%username% pass:!password!
pause
goto :eof

:HInput [ByRef_VarName]
:: inspired by Carlos
:: improved by pieh-ejdsch
if "%__HI__%" neq "__HI__" (
  setlocal DisableDelayedExpansion
  set "S=" &set "N=0" &set "__HI__=__HI__"
  for /f %%i in ('"prompt;$h&for %%i in (1) do rem"') do set "BS=%%i"
)
set "C="
for /f "eol=1 delims=" %%i in ('xcopy /lwq "%~f0" :\') do set "C=%%i"
set "C=%C:~-1%"
setlocal EnableDelayedExpansion
if not defined C (
  echo(
  if "%~1"=="" (
    echo(!S!
    endlocal &endlocal &exit /b %N%
  ) else (
    if defined S (
      for /f delims^=^ eol^= %%i in ("!S!") do endlocal &endlocal &set "%~1=%%i" &exit /b %N%
    ) else endlocal &endlocal &set "%~1=" &exit /b 0
  )
)
if "!BS!"=="!C!" (
  set "C="
  if defined S set /a "N -= 1" &set "S=!S:~,-1!" &<nul set /p "=%BS% %BS%"
) else set /a "N += 1" &<nul set /p "=*"
if not defined S (
  endlocal &set "N=%N%" &set "S=%C%"
) else for /f delims^=^ eol^= %%i in ("!S!") do endlocal &set "N=%N%" &set "S=%%i%C%"
goto HInput


问:
Firebase npm install error
I am building firebase exampple with node.js in here

https://github.com/googlesamples/Firebase-Plays-GCP-2016

My Package.json file

```<code> {
  "name": "game-control",
  "version": "1.0.0",
  "description": "Game controller to relay keystrokes",
  "main": "game-controller.js",
  "private": "true",
  "dependencies": {
    "chance": "^1.0.3",
    "firebase-admin": "4.1.2",
    "firebase-functions": "0.5.1",
    "gcloud": "^0.32.0",
    "prompt": "^1.0.0",
    "robotjs": "^0.3.7",
    "sleep": "^3.0.1"
  },
  "keywords": [
    "game",
    "controller",
    "keystrokes"
  ],
  "author": "Google Inc.",
  "contributors": [
    {
      "name": "Bret McGowen",
      "url": "https://twitter.com/bretmcg"
    }
  ],
  "license": "Apache-2.0"
}
</code>```

I am getting an error after npm install The npm error log as follows (/home/"username"/.npm/_logs/2017-12-07T14_31_17_723Z-debug.log)

```<code>12379 verbose lifecycle grpc@0.13.1~install: PATH: /usr/local/lib/node_modules/npm/bin/node-gyp-bi..............

12380 verbose lifecycle grpc@0.13.1~install: CWD: /home/"username"/Firebase-Plays-GCP-2016/backend/game-controller/node_modules/grpc
12381 silly lifecycle grpc@0.13.1~install: Args: [ '-c', 'node-pre-gyp install --fallback-to-build' ]
12382 silly lifecycle grpc@0.13.1~install: Returned: code: 1  signal: null
12383 info lifecycle grpc@0.13.1~install: Failed to exec install script
12384 verbose unlock done using /home/"Username"/.npm/_locks/staging-6598b7ab8d64c375.lock for /home/"Username"/Firebase-Plays-GCP-2016/backend/game-controller/node_modules/.staging
12385 verbose stack Error: grpc@0.13.1 install: `node-pre-gyp install --fallback-to-build`
12385 verbose stack Exit status 1
12385 verbose stack     at EventEmitter.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:280:16)
12385 verbose stack     at emitTwo (events.js:126:13)
12385 verbose stack     at EventEmitter.emit (events.js:214:7)
12385 verbose stack     at ChildProcess.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)
12385 verbose stack     at emitTwo (events.js:126:13)
12385 verbose stack     at ChildProcess.emit (events.js:214:7)
12385 verbose stack     at maybeClose (internal/child_process.js:925:16)
12385 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:209:5)
12386 verbose pkgid grpc@0.13.1
12387 verbose cwd /home/"Username"/Firebase-Plays-GCP-2016/backend/game-controller
12388 verbose Linux 4.10.0-40-generic
12389 verbose argv "/usr/local/bin/node" "/usr/local/bin/npm" "install"
12390 verbose node v8.9.2
12391 verbose npm  v5.5.1
12392 error code ELIFECYCLE
12393 error errno 1
12394 error grpc@0.13.1 install: `node-pre-gyp install --fallback-to-build`
</code>```

I am new to node.js, firebase.
My node version : v8.9.2, npm version : 5.5.1

Thanks in advance

答:
A bunch of those modules are out of date, so I updated the backend dependencies. See this pull request: https://github.com/googlesamples/Firebase-Plays-GCP-2016/pull/1

I was able to get npm to install with those updates on both Mac OS X 10.12 and Windows Server 2016.

Title: Firebase npm install error

Body:
I am building firebase exampple with node.js in here

https://github.com/googlesamples/Firebase-Plays-GCP-2016

My Package.json file

 {
  "name": "game-control",
  "version": "1.0.0",
  "description": "Game controller to relay keystrokes",
  "main": "game-controller.js",
  "private": "true",
  "dependencies": {
    "chance": "^1.0.3",
    "firebase-admin": "4.1.2",
    "firebase-functions": "0.5.1",
    "gcloud": "^0.32.0",
    "prompt": "^1.0.0",
    "robotjs": "^0.3.7",
    "sleep": "^3.0.1"
  },
  "keywords": [
    "game",
    "controller",
    "keystrokes"
  ],
  "author": "Google Inc.",
  "contributors": [
    {
      "name": "Bret McGowen",
      "url": "https://twitter.com/bretmcg"
    }
  ],
  "license": "Apache-2.0"
}

I am getting an error after npm install The npm error log as follows (/home/"username"/.npm/_logs/2017-12-07T14_31_17_723Z-debug.log)

12379 verbose lifecycle grpc@0.13.1~install: PATH: /usr/local/lib/node_modules/npm/bin/node-gyp-bi..............

12380 verbose lifecycle grpc@0.13.1~install: CWD: /home/"username"/Firebase-Plays-GCP-2016/backend/game-controller/node_modules/grpc
12381 silly lifecycle grpc@0.13.1~install: Args: [ '-c', 'node-pre-gyp install --fallback-to-build' ]
12382 silly lifecycle grpc@0.13.1~install: Returned: code: 1  signal: null
12383 info lifecycle grpc@0.13.1~install: Failed to exec install script
12384 verbose unlock done using /home/"Username"/.npm/_locks/staging-6598b7ab8d64c375.lock for /home/"Username"/Firebase-Plays-GCP-2016/backend/game-controller/node_modules/.staging
12385 verbose stack Error: grpc@0.13.1 install: `node-pre-gyp install --fallback-to-build`
12385 verbose stack Exit status 1
12385 verbose stack     at EventEmitter.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:280:16)
12385 verbose stack     at emitTwo (events.js:126:13)
12385 verbose stack     at EventEmitter.emit (events.js:214:7)
12385 verbose stack     at ChildProcess.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)
12385 verbose stack     at emitTwo (events.js:126:13)
12385 verbose stack     at ChildProcess.emit (events.js:214:7)
12385 verbose stack     at maybeClose (internal/child_process.js:925:16)
12385 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:209:5)
12386 verbose pkgid grpc@0.13.1
12387 verbose cwd /home/"Username"/Firebase-Plays-GCP-2016/backend/game-controller
12388 verbose Linux 4.10.0-40-generic
12389 verbose argv "/usr/local/bin/node" "/usr/local/bin/npm" "install"
12390 verbose node v8.9.2
12391 verbose npm  v5.5.1
12392 error code ELIFECYCLE
12393 error errno 1
12394 error grpc@0.13.1 install: `node-pre-gyp install --fallback-to-build`

I am new to node.js, firebase.
My node version : v8.9.2, npm version : 5.5.1

Thanks in advance


问:
How to get current foreground activity context in android?
Whenever my broadcast is executed I want to show alert to foreground activity.</p>

答:
getCurrentActivity() is also in ReactContextBaseJavaModule.

(Since the this question was initially asked, many Android app also has ReactNative component - hybrid app.)

class ReactContext in ReactNative has the whole set of logic to maintain mCurrentActivity which is returned in getCurrentActivity().

Note: I wish getCurrentActivity() is implemented in Android Application class.


问:
Splitting a large XML file in Python
I'm looking to split a huge XML file into smaller bits. I'd like to scan through the file looking for a specific tag, then grab all info between  and , then save that into a file, then continue on through the rest of the file.

My issue is trying to find a clean way to note the start and end of the tags, so that I can grab the text inside as I scan through the file with "for line in f"

I'd rather not use sentinel variables. Is there a pythonic way to get this done?

The file is too big to read into memory.

答:
How serendipitous! Will Larson just made a good post about Handling Very Large  CSV and XML File in Python.

The main takeaways seem to be to use the xml.sax module, as Van mentioned, and to make some macro-functions to abstract away the details of the low-level SAX API.

OwnerDisplayName: benjamin

Title: Splitting a large XML file in Python

OwnerDisplayName: Alabaster Codify


问:
How do I invoke a private static method using reflection (Java)?
I would like to invoke a private static method. I have its name. I've heard it can be done using Java reflection mechanism. How can I do it?

EDIT: One problem I encountered when trying to invoke the method is how to specify the type of its argument. My method receives one argument and its type is Map. Therefore I cannot do Map<User, String>.TYPE (In run time there's no such a thing as Map because of Java Type erasure). Is there another way to get the method?

答:
Let's say you want to call MyClass.myMethod(int x);</p>

```<code>Method m = MyClass.class.getDeclaredMethod("myMethod", Integer.TYPE);
m.setAccessible(true); //if security settings allow this
Object o = m.invoke(null, 23); //use null if the method is static
</code>```

Body:
Let's say you want to call MyClass.myMethod(int x);

Method m = MyClass.class.getDeclaredMethod("myMethod", Integer.TYPE);
m.setAccessible(true); //if security settings allow this
Object o = m.invoke(null, 23); //use null if the method is static


问:
gdb watchpoint on struct variables
I have a structure like this :

```<code>    struct A
    {
        int a;
        char b;
    };
</code>```

this structure is referenced at various places in a large code. The pointer to this struct is passed on to different functions and accordingly the variables in this structure are updated. i want to set a watchpoint on variable a in this struct as it travels across many functions. to see how a changes. How do I set this watch point ?

答:
I come with the same problem when debugging my virtual memory simulator. The problem is how to keep a close look at the data inside structs.

I tried using print to check, but that's too noisy. Because I have to print out more than 15 variables.

I also tried using watchpoint, but on my machine, I can only set no more than 4 hardware watchpoints. That's not even close to my goal.

Finally, I find my solution by using user-defined function in .gdbinit file. e.g. if I want to watch array of my structure, using

```<code>define lookintoStructs
    if mystruct != 0x0
        print mystruct[0]
        print mystruct[1]
        print mystruct[2]
        print mystruct[3]
        print mystruct[4]
        print mystruct[5]
    end
end
</code>```

to make it more convenient to use, I'd like to make it hook to my next instruction in gdb.

```<code>define hook-next
    lookintoStructs
end
</code>```

so when I call next or n in gdb, lookintoStructs could be called automatically. works fine for me.

Title: gdb watchpoint on struct variables

Body:
I have a structure like this :

    struct A
    {
        int a;
        char b;
    };

this structure is referenced at various places in a large code. The pointer to this struct is passed on to different functions and accordingly the variables in this structure are updated. i want to set a watchpoint on variable a in this struct as it travels across many functions. to see how a changes. How do I set this watch point ?

Body:
I come with the same problem when debugging my virtual memory simulator. The problem is how to keep a close look at the data inside structs.

I tried using print to check, but that's too noisy. Because I have to print out more than 15 variables.

I also tried using watchpoint, but on my machine, I can only set no more than 4 hardware watchpoints. That's not even close to my goal.

Finally, I find my solution by using user-defined function in .gdbinit file. e.g. if I want to watch array of my structure, using

define lookintoStructs
    if mystruct != 0x0
        print mystruct[0]
        print mystruct[1]
        print mystruct[2]
        print mystruct[3]
        print mystruct[4]
        print mystruct[5]
    end
end

to make it more convenient to use, I'd like to make it hook to my next instruction in gdb.

define hook-next
    lookintoStructs
end

so when I call next or n in gdb, lookintoStructs could be called automatically. works fine for me.


问:
How can I generate External IP when creating an ingress that uses nginx controller in kubernetes
```<code>apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: helloworld-rules
spec:
  rules:
  - host: helloworld-v1.example.com
http:
  paths:
  - path: /
    backend:
      serviceName: helloworld-v1
      servicePort: 80
  - host: helloworld-v2.example.com
http:
  paths:
  - path: /
    backend:
           serviceName: helloworld-v2
           servicePort: 80
</code>```

<p>I'm making kubernetes cluster and I will apply that cloudPlatform Isolated(not aws or google).
When creating an ingress for service I can choose host url but that is not exist anywhere(that address is not registrated something like DNS server) So I can't access that url. Visiting this IP just gives a 404.
how can I get or configure URL  that can access external browser
:(... </p>

答:
It depends on how you configure your nginx controller.

You should have a Service configured which is the entry point when accessing from outside see the docs https://kubernetes.io/docs/concepts/services-networking/ingress/#what-is-ingress.

So basically you have a Service that points to the ingress controller and this will redirect the traffic to your pods based on Ingress Objects.

Ingress -> Services -> Pods

Since you don't run on aws or google You would have to use externalIp or NodePort and configure the service accordingly

```<code>kind: Service
apiVersion: v1
metadata:
  name: ingress-nginx
  namespace: ingress-nginx
  labels:
    app: ingress-nginx
spec:
  selector:
    app: ingress-nginx
  ports:
  - name: http
    port: 80
    targetPort: http
  - name: https
    port: 443
    targetPort: http
  externalIPs:
  - 80.11.12.10
</code>```

And DNS needs to be managed with whatever you have for your domains in order to resolve, or for locally testing you can just edit your /etc/hostnames

Basically in AWS or Google you just create a service with type: LoadBalancer and point your dns records to the balancer address (CNAME for aws and the IP for google)

Body:
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: helloworld-rules
spec:
  rules:
  - host: helloworld-v1.example.com
http:
  paths:
  - path: /
    backend:
      serviceName: helloworld-v1
      servicePort: 80
  - host: helloworld-v2.example.com
http:
  paths:
  - path: /
    backend:
           serviceName: helloworld-v2
           servicePort: 80

I'm making kubernetes cluster and I will apply that cloudPlatform Isolated(not aws or google).
When creating an ingress for service I can choose host url but that is not exist anywhere(that address is not registrated something like DNS server) So I can't access that url. Visiting this IP just gives a 404.
how can I get or configure URL  that can access external browser
:(...

Body:
It depends on how you configure your nginx controller.

You should have a Service configured which is the entry point when accessing from outside see the docs https://kubernetes.io/docs/concepts/services-networking/ingress/#what-is-ingress.

So basically you have a Service that points to the ingress controller and this will redirect the traffic to your pods based on Ingress Objects.

Ingress -> Services -> Pods

Since you don't run on aws or google You would have to use externalIp or NodePort and configure the service accordingly

kind: Service
apiVersion: v1
metadata:
  name: ingress-nginx
  namespace: ingress-nginx
  labels:
    app: ingress-nginx
spec:
  selector:
    app: ingress-nginx
  ports:
  - name: http
    port: 80
    targetPort: http
  - name: https
    port: 443
    targetPort: http
  externalIPs:
  - 80.11.12.10

And DNS needs to be managed with whatever you have for your domains in order to resolve, or for locally testing you can just edit your /etc/hostnames

Basically in AWS or Google you just create a service with type: LoadBalancer and point your dns records to the balancer address (CNAME for aws and the IP for google)


问:
Pagination Styling (CSS)
I am trying to change the colour of my active pagination button from black to the light brown (#a88f4b), but it seems as though I can't get rid of the black.  What is it I'm getting wrong here?

http://demo.boxofficeboxing.co.uk/?s=

```<code>.eltd-pagination a {
color: #666 !important;
}
.eltd-pagination li.active {
background-color: #a88f4b !important;
}
.eltd-pagination a:hover {
color: #fff !important;
background-color: #a88f4b !important;
</code>```

答:
This is your line that should modify:

```<code>.eltd-pagination ul li a:hover,
.eltd-pagination ul li.active span {
    background-color: #a88f4b !important;
    color: #fff !important;
}
</code>```

In you pagination, active li has span in it instead a tag so you had to set style on the span not li like code above. copy/paste code above in your css in very last line.

Title: Pagination Styling (CSS)

Body:
I am trying to change the colour of my active pagination button from black to the light brown (#a88f4b), but it seems as though I can't get rid of the black.  What is it I'm getting wrong here?

http://demo.boxofficeboxing.co.uk/?s=

.eltd-pagination a {
color: #666 !important;
}
.eltd-pagination li.active {
background-color: #a88f4b !important;
}
.eltd-pagination a:hover {
color: #fff !important;
background-color: #a88f4b !important;

Body:
This is your line that should modify:

.eltd-pagination ul li a:hover,
.eltd-pagination ul li.active span {
    background-color: #a88f4b !important;
    color: #fff !important;
}

In you pagination, active li has span in it instead a tag so you had to set style on the span not li like code above. copy/paste code above in your css in very last line.


问:
Non-initialized vs null values of reference types
Is there a difference between reference type variable being non initialized or having null value?
I read somewhere that non-init means null but on other place I read something else. Thanks!</p>

答:
"It depends"

For normal member variables when a value is not specified in the declaration then the variable assume the appropriate default value (null for reference types). That is, class A { string X; } is the same as class A { string X = null; }.

For local variables it is an error to access them before a value can be proven to have been assigned. Even though their type "defaults" to null (for reference types), they are not default implicitly assigned! That is, string F () { string x; return x; } is a compile-time error.

Remember: null is null :-)


问:
DocuSign REST API - Emails with generated PDFs are not sent
I'm trying to build project with PHP / Composer library.

When I try to send with Template ID (Which I created and retrieved the ID) everything works fine:

```<code>-> Email is sent
-> Document is signed
-> Done.
</code>```

If I generate PDF and send a request to DocuSign REST services it responds with the same status that email is sent but it is never delivered.

Code:

```<code>Route::get('docusign-test', function () {

    $client = DocuSign::create();

    $pdf = PDF::loadView('pdfs.signature-test');

    try {
        return $client->envelopes->createEnvelope($client->envelopeDefinition([
            'status'        => 'sent',
            'email_subject' => '[DocuSign PHP SDK] - Signature Request Sample',
            'recipients'    => $client->recipients([
                'signers' => [
                    $client->signer([
                        'name'           => 'John Doe',
                        'email'          => 'mytestemail@gmail.com',
                        'client_user_id' => 1,
                        'role_name'      => 1,
                        'recipient_id'   => 1,
                        'tabs'           => $client->tabs([
                            'sign_here_tabs' => [
                                $client->signHere([
                                    'anchor_string'                => 'Sign Here:',
                                    'anchor_x_offset'              => '116',
                                    'anchor_y_offset'              => '-9',
                                    'anchor_ignore_if_not_present' => false,
                                    'anchor_units'                 => 'pixels',
                                    'recipient_id'                 => 1,
                                ]),
                            ],
                        ]),
                    ]),
                ],
            ]),
            'documents'     => [
                $client->document([
                    'document_base64' => base64_encode($pdf->stream()),
                    'name'            => 'test',
                    'document_id'     => 1,
                    'file_extension'  => 'pdf',
                ]),
            ],
        ]));
    } catch (Exception $e) {
        dd($e->getResponseBody());
    }

});
</code>```

I have tried few times with Template ID and with generated PDF and always with generated PDF is not delivered.

Sample response:

```<code>{
    "envelopeId": "fbced4a8-db72-4ffb-b39d-88f260c5eeee",
    "status": "sent",
    "statusDateTime": "2017-12-06T21:29:52.7670000Z",
    "uri": "/envelopes/fbced4a8-db72-4ffb-b39d-88f260c5eeee"
}
</code>```

Note: I'm working on demo.docusign.com, not production.

答:
Yup, its the same problem which I mentioned in my comment, you are setting clientUserId

```<code>'client_user_id' => 1,
</code>```

Setting clientUserId means you are informing DocuSign that you will be doing embedded Signing and you are asking DocuSign not to send any email notifications to the customer. And you will be creating the embedded signing URL for the signer and you will be hosting the signing ceremony.

Body:
I'm trying to build project with PHP / Composer library.

When I try to send with Template ID (Which I created and retrieved the ID) everything works fine:

-> Email is sent
-> Document is signed
-> Done.

If I generate PDF and send a request to DocuSign REST services it responds with the same status that email is sent but it is never delivered.

Code:

Route::get('docusign-test', function () {

    $client = DocuSign::create();

    $pdf = PDF::loadView('pdfs.signature-test');

    try {
        return $client->envelopes->createEnvelope($client->envelopeDefinition([
            'status'        => 'sent',
            'email_subject' => '[DocuSign PHP SDK] - Signature Request Sample',
            'recipients'    => $client->recipients([
                'signers' => [
                    $client->signer([
                        'name'           => 'John Doe',
                        'email'          => 'mytestemail@gmail.com',
                        'client_user_id' => 1,
                        'role_name'      => 1,
                        'recipient_id'   => 1,
                        'tabs'           => $client->tabs([
                            'sign_here_tabs' => [
                                $client->signHere([
                                    'anchor_string'                => 'Sign Here:',
                                    'anchor_x_offset'              => '116',
                                    'anchor_y_offset'              => '-9',
                                    'anchor_ignore_if_not_present' => false,
                                    'anchor_units'                 => 'pixels',
                                    'recipient_id'                 => 1,
                                ]),
                            ],
                        ]),
                    ]),
                ],
            ]),
            'documents'     => [
                $client->document([
                    'document_base64' => base64_encode($pdf->stream()),
                    'name'            => 'test',
                    'document_id'     => 1,
                    'file_extension'  => 'pdf',
                ]),
            ],
        ]));
    } catch (Exception $e) {
        dd($e->getResponseBody());
    }

});

I have tried few times with Template ID and with generated PDF and always with generated PDF is not delivered.

Sample response:

{
    "envelopeId": "fbced4a8-db72-4ffb-b39d-88f260c5eeee",
    "status": "sent",
    "statusDateTime": "2017-12-06T21:29:52.7670000Z",
    "uri": "/envelopes/fbced4a8-db72-4ffb-b39d-88f260c5eeee"
}

Note: I'm working on demo.docusign.com, not production.

Body:
Yup, its the same problem which I mentioned in my comment, you are setting clientUserId

'client_user_id' => 1,

Setting clientUserId means you are informing DocuSign that you will be doing embedded Signing and you are asking DocuSign not to send any email notifications to the customer. And you will be creating the embedded signing URL for the signer and you will be hosting the signing ceremony.


问:
angular 4 ngIf alternative
I have a drop-down menu that you could choose the currency and based on the chosen currency, but right now I'm using ngif to show the currency but and it works fine with only two currencies but for more currencies I have to add more ngif and to me that's not logical since the HTML code for that page is going to be huge ( 100 different currencies = 100 ngif's)

this is what I have now:

Company.ts

```<code>   currencyItems: string[] =  ['MXN', 'PHP'];
   currency: string = this.currencyItems[0];
</code>```

company.html

```<code><div class="col-md-5" *ngIf = "currency = 'MXN'">
      <input type="number" name="mxn" id="mxn" [(ngModel)]="newCompany.currency.mxn" class="form-control">
</div>

<div class="col-md-5" *ngIf = "currency = 'PHP'">
      <input type="number" name="php" id="php" [(ngModel)]="newCompany.currency.php" class="form-control">
</div>
</code>```

what i want to achieve is, is there any way that I only have one block of code
something like that

```<code><div class="col-md-5">
      <input type="number" [(ngModel)]="newCompany.currency.<changes base on drop-down selection>" class="form-control">
</div>
</code>```

and also

```<code><td>{{company.currency.mxn}}</td>
</code>```

to

```<code><td>{{company.currency.<changes base on drop-down selection>}}</td>
</code>```

I know I can use ngSwitch, but that's still is going to be lots of code too.

答:
Use a separate property altogether. For example selectedCurrency. Then when a new option is selected from the dropdown, assign it to selectedCurrency

```<code><div class="col-md-5">
    <input type="number" [(ngModel)]="selectedCurrency" class="form-control">
</div>

<td>{{selectedCurrency}}</td>
</code>```

Title: angular 4 ngIf alternative

Body:
I have a drop-down menu that you could choose the currency and based on the chosen currency, but right now I'm using ngif to show the currency but and it works fine with only two currencies but for more currencies I have to add more ngif and to me that's not logical since the HTML code for that page is going to be huge ( 100 different currencies = 100 ngif's)

this is what I have now:

Company.ts

   currencyItems: string[] =  ['MXN', 'PHP'];
   currency: string = this.currencyItems[0];

company.html

      <input type="number" name="mxn" id="mxn" [(ngModel)]="newCompany.currency.mxn" class="form-control">

      <input type="number" name="php" id="php" [(ngModel)]="newCompany.currency.php" class="form-control">

what i want to achieve is, is there any way that I only have one block of code
something like that

      <input type="number" [(ngModel)]="newCompany.currency.<changes base on drop-down selection>" class="form-control">

and also

{{company.currency.mxn}}

to

{{company.currency.<changes base on drop-down selection>}}

I know I can use ngSwitch, but that's still is going to be lots of code too.

Body:
Use a separate property altogether. For example selectedCurrency. Then when a new option is selected from the dropdown, assign it to selectedCurrency

<div class="col-md-5">
    <input type="number" [(ngModel)]="selectedCurrency" class="form-control">
</div>

<td>{{selectedCurrency}}</td>


问:
Can I lay a fixed layer over a custom canvas?
In Android Studio, I'm developing a game in which I draw my animation at 60fps using a SurfaceView object. I use a semitransparent image as the top layer to hide the edges of the playing field -- sort of a "fogs of war" effect so that the player does not know what to expect beyond the shadows.

My problem is that I need to draw this shadow image for every frame, even though the shadow never changes or moves, even when the playing field scrolls right/left/up/down.  And it's a full-screen image, so it slows the game to a crawl.

Is there a way to create a one-time overlay ONCE on top of the animated custom canvas? I also want to interact with the canvas beneath it, as if the overlay was not even there.

答:
Based on the response from Thomas Stevens, I researched my options for overlaying my SurfaceView with an ImageView. My solution is to add a FrameLayout that contains the needed ImageView. (That way, I can add additional views to the overlay simply by updating the layout XML.)

```<code>    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //temporarily set the view to the overlay layout to gain access to the frame
    setContentView(R.layout.overlay_game);
    FrameLayout overlayLayout = (FrameLayout)findViewById(R.id.gameOverlayFrame);

    //set the final view to the active game surface (a Java-coded SurfaceView object)
    setContentView(new GameSurface(this));
    //add the overlay view on top of the game surface view
    addContentView(overlayLayout, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT));
}
</code>```

I don't claim this to be THE solution...just the one that works for me.

Body:
Based on the response from Thomas Stevens, I researched my options for overlaying my SurfaceView with an ImageView. My solution is to add a FrameLayout that contains the needed ImageView. (That way, I can add additional views to the overlay simply by updating the layout XML.)

    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //temporarily set the view to the overlay layout to gain access to the frame
    setContentView(R.layout.overlay_game);
    FrameLayout overlayLayout = (FrameLayout)findViewById(R.id.gameOverlayFrame);

    //set the final view to the active game surface (a Java-coded SurfaceView object)
    setContentView(new GameSurface(this));
    //add the overlay view on top of the game surface view
    addContentView(overlayLayout, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT));
}

I don't claim this to be THE solution...just the one that works for me.


问:
Get the value of a range input slider as a string value
I have a slider with a label on each end. Is it possible to have the value of the slider to be the text/label?

```<code><label for="good">Good</label>
<label for="bad">Bad</label>
<input id="slider" type="range" class="slider" min="1" max="100"/>
</code>```

I know it could be done this way:

```<code>if(value less than certain amount)
{
   variable = "bad";
}
</code>```

But this would mean I would have multiple statements of this. Is there an easier way of doing this?

答:
I would do something like this:

```<code>var app = angular.module('demoApp', []);

app.controller('demoCtrl', function($scope){
  $scope.getText = function(){
    if($scope.slider > 50){
      return "Good";
    } else {
      return "Bad";
    }
  }
});
</code>```

Call this function in interpolation curly brackets in your view:

```<code>  <span>{{slider}}</span>
  <input ng-model="slider" type="range" min="1" max="100"/>
  <label>{{getText()}}</label>
</code>```

getText function will return Bad or Good according to slider value.

DEMO

Body:
I have a slider with a label on each end. Is it possible to have the value of the slider to be the text/label?

Good
Bad
<input id="slider" type="range" class="slider" min="1" max="100"/>

I know it could be done this way:

if(value less than certain amount)
{
   variable = "bad";
}

But this would mean I would have multiple statements of this. Is there an easier way of doing this?

Body:
I would do something like this:

var app = angular.module('demoApp', []);

app.controller('demoCtrl', function($scope){
  $scope.getText = function(){
    if($scope.slider > 50){
      return "Good";
    } else {
      return "Bad";
    }
  }
});

Call this function in interpolation curly brackets in your view:

  <span>{{slider}}</span>
  <input ng-model="slider" type="range" min="1" max="100"/>
  <label>{{getText()}}</label>

getText function will return Bad or Good according to slider value.

DEMO


问:
Using SSE to speed up lower_bound function

In a project I'm currently working on I often need to find the lowest possible index in a sorted array at which an element can be inserted (like std::lower_bound in C++).
It seems pretty attractive to me to use SSE to speed up my algorithm since I'm working with uint32 arrays which size is typically the size of a processor cache line.
I've never used SSE instructions before, so I can't manage to figure out what an SSE implementation of this function would looks like. Please give hints to help me write it out optimally wtih SSE.

答:
Nothing like std::lower_bound is going to scale well using SSE. The reason SSE makes things faster is that it allows you to do several calculations at once. For example, a single SSE instruction might result in 4 multiply operations going on at once. However, the way std::lower_bound operates cannot be parallelized, because each step in the algorithm requires the comparison results of previous steps. Plus, it's already O(lg n), and as a result unlikely to be a bottleneck.

Moreover, before moving to inline assembly, you should know that whenever you use inline assembly, you defeat most compiler optimizations that might occur on that section of your program, and often as a result your program will be slower -- compilers usually write better assembler than us humans do.

If you want to use SSE, you are better off using intrinsics -- special "functions" or keywords provided by the compiler, which call the SSE instruction but otherwise allow optimizations to occur. Such intrinsics are available in Microsoft's Visual C++, as well as the GNU Compiler Collection. (And probably most any compiler. Consult your compiler's documentation)

Rather than trying to speed up std::lower_bound using SSE, you should try to not need to call it in the first place. For example, if you're constantly inserting elements into the vector using lower_bound, you should know what you've effectively created is insertion sort, and a poor insertion sort at that, which will require quadradic time. You would likely be better off simply putting your new elements on the end of the vector, and then sorting the vector when you need it sorted, which reduces things to an O(n lg n) sort. If your data access patterns are such that you would be resorting too often then you should use something like a std::set instead, which provides O(lg n) operations for insertions, rather than the O(n + lg n) insertions you're currently getting with the vectors.

And of course, remember to benchmark :)


问:
what is fastest way to draw chartjs charts
I have a lot of charts I need to draw with a huge amount of data on bobble plots.

I wonder what is the fastest and the most efficient way to plot them using chartjs.
I made the dots smaller, yet it still takes 5 sec to load the page.

答:
A couple things come to mind:

I would check that nothing else on your page is slowing your load times.

If chart.js is the issue due to the high number of dots, do you need every data point entered? Could you do every other? I'm not sure what your data is, but if you're just looking at trends, this might work for you.


问:
How to generate a 2hour-long blank video
I'd like to generate a video with a black or white background (or even nothing at all) that lasts for a specific duration (e.g. 2 hour long).

Can you please suggest a fast way to do it programatically (e.g. command line, OpenCV)? Thanks.

答:
For an h264 output in a MP4 container, use:

```<code>ffmpeg -t 7200 -f lavfi -i color=c=black:s=640x480 -c:v libx264 -tune stillimage -pix_fmt yuv420p output.mp4
</code>```

If you want to include an audio track, simply add the arguments for the audio input and encoding (if necessary). The output's duration will be determined by the shortest input, i.e. the audio. For example:

```<code>ffmpeg -f lavfi -i color=c=black:s=640x480 -i audio.ogg -c:v libx264 -tune stillimage -pix_fmt yuv420p -shortest -c:a aac -b:a 128k output-with-audio.mp4
</code>```

Body:
For an h264 output in a MP4 container, use:

ffmpeg -t 7200 -f lavfi -i color=c=black:s=640x480 -c:v libx264 -tune stillimage -pix_fmt yuv420p output.mp4

If you want to include an audio track, simply add the arguments for the audio input and encoding (if necessary). The output's duration will be determined by the shortest input, i.e. the audio. For example:

ffmpeg -f lavfi -i color=c=black:s=640x480 -i audio.ogg -c:v libx264 -tune stillimage -pix_fmt yuv420p -shortest -c:a aac -b:a 128k output-with-audio.mp4


问:
Rolling back last migration not working?
So, I accidentally created a wrong migration and then I tried to delete it with the rollback command like this :

```<code>php artisan migrate:rollback --step=1
</code>```

It ran successfully and I got this message on the command line:

Rolling back: 2017_12_07_201338_add_authors_id_to_uploads_id Rolled
  back:  2017_12_07_201338_add_authors_id_to_uploads_id

But then, after I opened my database on phpmyadmin I discovered that the wrong columns are still there.

Since obviously, the rollback worked I am wondering what am I missing?

P.S. I dont have anything in the down function, since I figuren i don't need that.

Here is what I have in up():

public function up()

```<code>  {
        //
        Schema::table('authors', function($table){
            $table->integer('user_id')->unsigned();
        });

        Schema::table('authors', function($table) {
            $table->foreign('user_id')->references('id')->on('users');
        });
    }
</code>```

答:
Add this in your down method.</p>

```<code>Schema::table( 'authors', function( Blueprint $table )
        {
            $table->dropColumn( 'user_id' );
        } );
</code>```

Body:
So, I accidentally created a wrong migration and then I tried to delete it with the rollback command like this :

php artisan migrate:rollback --step=1

It ran successfully and I got this message on the command line:

Rolling back: 2017_12_07_201338_add_authors_id_to_uploads_id Rolled
  back:  2017_12_07_201338_add_authors_id_to_uploads_id

But then, after I opened my database on phpmyadmin I discovered that the wrong columns are still there.

Since obviously, the rollback worked I am wondering what am I missing?

P.S. I dont have anything in the down function, since I figuren i don't need that.

Here is what I have in up():

public function up()

  {
        //
        Schema::table('authors', function($table){
            $table->integer('user_id')->unsigned();
        });

        Schema::table('authors', function($table) {
            $table->foreign('user_id')->references('id')->on('users');
        });
    }

Body:
Add this in your down method.

Schema::table( 'authors', function( Blueprint $table )
        {
            $table->dropColumn( 'user_id' );
        } );


问:
Extracting and rolling up data from XML documents in C#

I'm trying to extract data from an XML document and roll-up the data based on time in C#.

For instance - I have the following XML documents:

Document 1:

```<code>                "<HourlyTotals>" +
                "<Data>" +
                "<Time>08:00</Time>" +
                "<NetSales>200.25</NetSales>" +
                "<NetReturns>15.25</NetReturns>" +
                "<NetIncome>185.00</NetIncome>" +
                "<CustomerCount>15</CustomerCount>" +
                "<PercentOfIncome>3</PercentOfIncome>" +
                "</Data>" +
                "<Data>" +
                "<Time>08:15</Time>" +
                "<NetSales>100.25</NetSales>" +
                "<NetReturns>15.25</NetReturns>" +
                "<NetIncome>85.00</NetIncome>" +
                "<CustomerCount>2</CustomerCount>" +
                "<PercentOfIncome>1.5</PercentOfIncome>" +
                "</Data>" +
                 "<Data>" +
                "<Time>08:30</Time>" +
                "<NetSales>100.25</NetSales>" +
                "<NetReturns>15.25</NetReturns>" +
                "<NetIncome>85.00</NetIncome>" +
                "<CustomerCount>2</CustomerCount>" +
                "<PercentOfIncome>1.5</PercentOfIncome>" +
                "</Data>" +
                "<Data>" +
                "<Time>10:00</Time>" +
                "<NetSales>100.25</NetSales>" +
                "<NetReturns>10.25</NetReturns>" +
                "<NetIncome>176.00</NetIncome>" +
                "<CustomerCount>10</CustomerCount>" +
                "<PercentOfIncome>1</PercentOfIncome>" +
                "</Data>" +
                "</HourlyTotals>"
</code>```

Please ignore the quotes and '+' : It's because of the fact that I was trying to create fake XML data and pass it as a string to a list in C#.

Document 2:

```<code>            "<HourlyTotals>" +
            "<Data>" +
            "<Time>08:00</Time>" +
            "<NetSales>100.25</NetSales>" +
            "<NetReturns>10.25</NetReturns>" +
            "<NetIncome>176.00</NetIncome>" +
            "<CustomerCount>10</CustomerCount>" +
            "<PercentOfIncome>1</PercentOfIncome>" +
            "</Data>" +
            "<Data>" +
            "<Time>08:15</Time>" +
            "<NetSales>120.00</NetSales>" +
            "<NetReturns>11.00</NetReturns>" +
            "<NetIncome>54.00</NetIncome>" +
            "<CustomerCount>5</CustomerCount>" +
            "<PercentOfIncome>2.3</PercentOfIncome>" +
            "</Data>" +
             "<Data>" +
            "<Time>08:30</Time>" +
            "<NetSales>160.11</NetSales>" +
            "<NetReturns>17.25</NetReturns>" +
            "<NetIncome>34.00</NetIncome>" +
            "<CustomerCount>4</CustomerCount>" +
            "<PercentOfIncome>3.2</PercentOfIncome>" +
            "</Data>" +
            "<Data>" +
            "<Time>09:15</Time>" +
            "<NetSales>100.25</NetSales>" +
            "<NetReturns>10.25</NetReturns>" +
            "<NetIncome>176.00</NetIncome>" +
            "<CustomerCount>10</CustomerCount>" +
            "<PercentOfIncome>1</PercentOfIncome>" +
            "</Data>" +
            "<Data>" +
            "<Time>10:00</Time>" +
            "<NetSales>100.25</NetSales>" +
            "<NetReturns>10.25</NetReturns>" +
            "<NetIncome>176.00</NetIncome>" +
            "<CustomerCount>10</CustomerCount>" +
            "<PercentOfIncome>1</PercentOfIncome>" +
            "</Data>" +
            "</HourlyTotals>"
</code>```

Document 3:

```<code>            "<HourlyTotals>" +
            "<Data>" +
            "<Time>08:00</Time>" +
            "<NetSales>22.25</NetSales>" +
            "<NetReturns>21.25</NetReturns>" +
            "<NetIncome>122.00</NetIncome>" +
            "<CustomerCount>3</CustomerCount>" +
            "<PercentOfIncome>6</PercentOfIncome>" +
            "</Data>" +
            "<Data>" +
            "<Time>08:15</Time>" +
            "<NetSales>174.00</NetSales>" +
            "<NetReturns>16.00</NetReturns>" +
            "<NetIncome>68.00</NetIncome>" +
            "<CustomerCount>2</CustomerCount>" +
            "<PercentOfIncome>0.2</PercentOfIncome>" +
            "</Data>" +
             "<Data>" +
            "<Time>08:30</Time>" +
            "<NetSales>99.00</NetSales>" +
            "<NetReturns>88.00</NetReturns>" +
            "<NetIncome>69.00</NetIncome>" +
            "<CustomerCount>6</CustomerCount>" +
            "<PercentOfIncome>9</PercentOfIncome>" +
            "</Data>" +
            "<Data>" +
            "<Time>09:30</Time>" +
            "<NetSales>100.25</NetSales>" +
            "<NetReturns>10.25</NetReturns>" +
            "<NetIncome>176.00</NetIncome>" +
            "<CustomerCount>10</CustomerCount>" +
            "<PercentOfIncome>1</PercentOfIncome>" +
            "</Data>" +
            "</HourlyTotals>"
</code>```

I want to roll-up the NetSales, NetReturns, NetIncome, CustomerCount and PercentOfIncome values by time. For instance, time 8:00 should have the value of
 322.75 (200.25 + 100.25 + 22.25) as the NetSales value and so on..

The time node values can range from 8:00 to 23:45. I'm trying to figure out an efficient way to extract all the time intervals and roll up the values based on them.

So far, I have written code to extract the data of individual nodes from the XML:

```<code>foreach (var selector in fakeXML)
        {
            XDocument doc = XDocument.Parse(selector);
            var data = doc.Descendants("Data");
            var result1 = from q in data
                          select new
                          {
                              Time = q.Element("Time").Value,
                              NetSales = q.Element("NetSales").Value,
                              NetReturns = q.Element("NetReturns").Value,
                              NetIncome = q.Element("NetIncome").Value,
                              CustCount = q.Element("CustomerCount").Value,
                              PercentOfIncome = q.Element("PercentOfIncome").Value
                          }

        }
</code>```

fakeXML is a list of strings which contains the individual XML documents as strings.

This code just allows me to extract individual nodes from the XML documents.

I'm not able to figure out an effective way to roll it up based on the value of the time node. Any leads on how to proceed would be really great!

Thanks in advance.

答:
After you have all the data. Group them by Time and then Sum up the values in each group.

```<code>var data = fakeXML.SelectMany(selector => {
    XDocument doc = XDocument.Parse(selector);
    return from q in doc.Descendants("Data")
           select new {
               Time = q.Element("Time").Value,
               NetSales = (decimal)q.Element("NetSales"),
               NetReturns = (decimal)q.Element("NetReturns"),
               NetIncome = (decimal)q.Element("NetIncome"),
               CustCount = (int)q.Element("CustomerCount"),
               PercentOfIncome = (double)q.Element("PercentOfIncome")
           };
});

var summary = data.GroupBy(d => d.Time)
    .Select(g => new {
        Time = g.Key,
        NetSales = g.Sum(d => d.NetSales),
        NetReturns = g.Sum(d => d.NetReturns),
        NetIncome = g.Sum(d => d.NetIncome),
        CustCount = g.Sum(d => d.CustCount),
    });
</code>```

Each item in the summary collection would have the totals by time.

Body:
I'm trying to extract data from an XML document and roll-up the data based on time in C#.

For instance - I have the following XML documents:

Document 1:

                "<HourlyTotals>" +
                "<Data>" +
                "<Time>08:00</Time>" +
                "<NetSales>200.25</NetSales>" +
                "<NetReturns>15.25</NetReturns>" +
                "<NetIncome>185.00</NetIncome>" +
                "<CustomerCount>15</CustomerCount>" +
                "<PercentOfIncome>3</PercentOfIncome>" +
                "</Data>" +
                "<Data>" +
                "<Time>08:15</Time>" +
                "<NetSales>100.25</NetSales>" +
                "<NetReturns>15.25</NetReturns>" +
                "<NetIncome>85.00</NetIncome>" +
                "<CustomerCount>2</CustomerCount>" +
                "<PercentOfIncome>1.5</PercentOfIncome>" +
                "</Data>" +
                 "<Data>" +
                "<Time>08:30</Time>" +
                "<NetSales>100.25</NetSales>" +
                "<NetReturns>15.25</NetReturns>" +
                "<NetIncome>85.00</NetIncome>" +
                "<CustomerCount>2</CustomerCount>" +
                "<PercentOfIncome>1.5</PercentOfIncome>" +
                "</Data>" +
                "<Data>" +
                "<Time>10:00</Time>" +
                "<NetSales>100.25</NetSales>" +
                "<NetReturns>10.25</NetReturns>" +
                "<NetIncome>176.00</NetIncome>" +
                "<CustomerCount>10</CustomerCount>" +
                "<PercentOfIncome>1</PercentOfIncome>" +
                "</Data>" +
                "</HourlyTotals>"

Please ignore the quotes and '+' : It's because of the fact that I was trying to create fake XML data and pass it as a string to a list in C#.

Document 2:

            "<HourlyTotals>" +
            "<Data>" +
            "<Time>08:00</Time>" +
            "<NetSales>100.25</NetSales>" +
            "<NetReturns>10.25</NetReturns>" +
            "<NetIncome>176.00</NetIncome>" +
            "<CustomerCount>10</CustomerCount>" +
            "<PercentOfIncome>1</PercentOfIncome>" +
            "</Data>" +
            "<Data>" +
            "<Time>08:15</Time>" +
            "<NetSales>120.00</NetSales>" +
            "<NetReturns>11.00</NetReturns>" +
            "<NetIncome>54.00</NetIncome>" +
            "<CustomerCount>5</CustomerCount>" +
            "<PercentOfIncome>2.3</PercentOfIncome>" +
            "</Data>" +
             "<Data>" +
            "<Time>08:30</Time>" +
            "<NetSales>160.11</NetSales>" +
            "<NetReturns>17.25</NetReturns>" +
            "<NetIncome>34.00</NetIncome>" +
            "<CustomerCount>4</CustomerCount>" +
            "<PercentOfIncome>3.2</PercentOfIncome>" +
            "</Data>" +
            "<Data>" +
            "<Time>09:15</Time>" +
            "<NetSales>100.25</NetSales>" +
            "<NetReturns>10.25</NetReturns>" +
            "<NetIncome>176.00</NetIncome>" +
            "<CustomerCount>10</CustomerCount>" +
            "<PercentOfIncome>1</PercentOfIncome>" +
            "</Data>" +
            "<Data>" +
            "<Time>10:00</Time>" +
            "<NetSales>100.25</NetSales>" +
            "<NetReturns>10.25</NetReturns>" +
            "<NetIncome>176.00</NetIncome>" +
            "<CustomerCount>10</CustomerCount>" +
            "<PercentOfIncome>1</PercentOfIncome>" +
            "</Data>" +
            "</HourlyTotals>"

Document 3:

            "<HourlyTotals>" +
            "<Data>" +
            "<Time>08:00</Time>" +
            "<NetSales>22.25</NetSales>" +
            "<NetReturns>21.25</NetReturns>" +
            "<NetIncome>122.00</NetIncome>" +
            "<CustomerCount>3</CustomerCount>" +
            "<PercentOfIncome>6</PercentOfIncome>" +
            "</Data>" +
            "<Data>" +
            "<Time>08:15</Time>" +
            "<NetSales>174.00</NetSales>" +
            "<NetReturns>16.00</NetReturns>" +
            "<NetIncome>68.00</NetIncome>" +
            "<CustomerCount>2</CustomerCount>" +
            "<PercentOfIncome>0.2</PercentOfIncome>" +
            "</Data>" +
             "<Data>" +
            "<Time>08:30</Time>" +
            "<NetSales>99.00</NetSales>" +
            "<NetReturns>88.00</NetReturns>" +
            "<NetIncome>69.00</NetIncome>" +
            "<CustomerCount>6</CustomerCount>" +
            "<PercentOfIncome>9</PercentOfIncome>" +
            "</Data>" +
            "<Data>" +
            "<Time>09:30</Time>" +
            "<NetSales>100.25</NetSales>" +
            "<NetReturns>10.25</NetReturns>" +
            "<NetIncome>176.00</NetIncome>" +
            "<CustomerCount>10</CustomerCount>" +
            "<PercentOfIncome>1</PercentOfIncome>" +
            "</Data>" +
            "</HourlyTotals>"

I want to roll-up the NetSales, NetReturns, NetIncome, CustomerCount and PercentOfIncome values by time. For instance, time 8:00 should have the value of
 322.75 (200.25 + 100.25 + 22.25) as the NetSales value and so on..

The time node values can range from 8:00 to 23:45. I'm trying to figure out an efficient way to extract all the time intervals and roll up the values based on them.

So far, I have written code to extract the data of individual nodes from the XML:

foreach (var selector in fakeXML)
        {
            XDocument doc = XDocument.Parse(selector);
            var data = doc.Descendants("Data");
            var result1 = from q in data
                          select new
                          {
                              Time = q.Element("Time").Value,
                              NetSales = q.Element("NetSales").Value,
                              NetReturns = q.Element("NetReturns").Value,
                              NetIncome = q.Element("NetIncome").Value,
                              CustCount = q.Element("CustomerCount").Value,
                              PercentOfIncome = q.Element("PercentOfIncome").Value
                          }

        }

fakeXML is a list of strings which contains the individual XML documents as strings.

This code just allows me to extract individual nodes from the XML documents.

I'm not able to figure out an effective way to roll it up based on the value of the time node. Any leads on how to proceed would be really great!

Thanks in advance.

Body:
After you have all the data. Group them by Time and then Sum up the values in each group.

var data = fakeXML.SelectMany(selector => {
    XDocument doc = XDocument.Parse(selector);
    return from q in doc.Descendants("Data")
           select new {
               Time = q.Element("Time").Value,
               NetSales = (decimal)q.Element("NetSales"),
               NetReturns = (decimal)q.Element("NetReturns"),
               NetIncome = (decimal)q.Element("NetIncome"),
               CustCount = (int)q.Element("CustomerCount"),
               PercentOfIncome = (double)q.Element("PercentOfIncome")
           };
});

var summary = data.GroupBy(d => d.Time)
    .Select(g => new {
        Time = g.Key,
        NetSales = g.Sum(d => d.NetSales),
        NetReturns = g.Sum(d => d.NetReturns),
        NetIncome = g.Sum(d => d.NetIncome),
        CustCount = g.Sum(d => d.CustCount),
    });

Each item in the summary collection would have the totals by time.


问:
asp.net core TestServer can't find configuration
I am creating some tests using TestServer which is bootstrap with a complex configuration as following:

```<code>var config = new ConfigurationBuilder()
    .Build();

webHostBuilder = new WebHostBuilder()
    .UseConfiguration(config)
    .UseKestrel()
    .CaptureStartupErrors(true)
    .UseContentRoot(Directory.GetCurrentDirectory())
    .UseIISIntegration()
    .UseStartup<MockLicenseStartup>()
    .UseEnvironment("Development")
    .UseUrls("http://locahost");

testServer = new TestServer(webHostBuilder);
</code>```

Both in my "asp.net core" project and in my test project I have created multiple appsettings.json which is used to provide things like:

Connection String

Log verbosity

Custom Sections

The issue I am facing is that my Configuration class, inside the MockLicenseStartup is not able to load any of the available appsettings.json.

The code used inside MockLicenseStartup.cs is this one:

```<code>public MockLicenseStartup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
                    .SetBasePath(env.ContentRootPath)
                    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                    .AddEnvironmentVariables();

    Configuration = builder.Build();
}
</code>```

When I call Configuration.GetConnectionString("") it throws an exception and if I inspect further I can see that no configuration has been loaded actually. Probably is a problem related to the relative/absolute path of .UseContentRoot(Directory.GetCurrentDirectory())

答:
In Test Environment,

```<code>.SetBasePath(env.ContentRootPath)
</code>```

env.ContentRootPath is different from production, it is set to the test project's bin directory if I remember correctly.  So, it will not locate the appsettings.json file.  unless you copy it there after build.

If you are projects folder structure does not change. you can just try to hard code the appsettings.json" path in these two lines to where these are located.

```<code>.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true
</code>```

if this works (it should), you can make it better by find the appsetting.json path in code.

Below is my own code which work in test environment.

```<code>        var settingFilePath = getSettingFilePath(settingFileParentFolderName: "APIProject");

        var builder = new ConfigurationBuilder()
            .AddJsonFile(settingFilePath + _settingFileName, optional: true, reloadOnChange: true)
            .AddJsonFile(settingFilePath + "appsettings.Development.json", optional: true);

        var configuration = builder.Build();
</code>```

getSettingFilePath() is just a function to locate the setting file path in the Startup Project folder.

Hope this help.

Body:
I am creating some tests using TestServer which is bootstrap with a complex configuration as following:

var config = new ConfigurationBuilder()
    .Build();

webHostBuilder = new WebHostBuilder()
    .UseConfiguration(config)
    .UseKestrel()
    .CaptureStartupErrors(true)
    .UseContentRoot(Directory.GetCurrentDirectory())
    .UseIISIntegration()
    .UseStartup<MockLicenseStartup>()
    .UseEnvironment("Development")
    .UseUrls("http://locahost");

testServer = new TestServer(webHostBuilder);

Both in my "asp.net core" project and in my test project I have created multiple appsettings.json which is used to provide things like:

Connection String

Log verbosity

Custom Sections

The issue I am facing is that my Configuration class, inside the MockLicenseStartup is not able to load any of the available appsettings.json.

The code used inside MockLicenseStartup.cs is this one:

public MockLicenseStartup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
                    .SetBasePath(env.ContentRootPath)
                    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                    .AddEnvironmentVariables();

    Configuration = builder.Build();
}

When I call Configuration.GetConnectionString("") it throws an exception and if I inspect further I can see that no configuration has been loaded actually. Probably is a problem related to the relative/absolute path of .UseContentRoot(Directory.GetCurrentDirectory())

Body:
In Test Environment,

.SetBasePath(env.ContentRootPath)

env.ContentRootPath is different from production, it is set to the test project's bin directory if I remember correctly.  So, it will not locate the appsettings.json file.  unless you copy it there after build.

If you are projects folder structure does not change. you can just try to hard code the appsettings.json" path in these two lines to where these are located.

.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true

if this works (it should), you can make it better by find the appsetting.json path in code.

Below is my own code which work in test environment.

        var settingFilePath = getSettingFilePath(settingFileParentFolderName: "APIProject");

        var builder = new ConfigurationBuilder()
            .AddJsonFile(settingFilePath + _settingFileName, optional: true, reloadOnChange: true)
            .AddJsonFile(settingFilePath + "appsettings.Development.json", optional: true);

        var configuration = builder.Build();

getSettingFilePath() is just a function to locate the setting file path in the Startup Project folder.

Hope this help.


问:
Python sending data to a MySQL DB
I have a script running, updating certain values in a DB once a second.
At the start of the script I first connect to the DB:

```<code>conn = pymysql.connect(host= "server",
               user="user",
               passwd="pw",
               db="db",
               charset='utf8')
x = conn.cursor()
</code>```

I leave the connection open for the running time of the script (around 30min)

With this code I update certain values once every second:

```<code>query = "UPDATE missionFilesDelDro SET landLat = '%s', landLon='%s',landHea='%s' WHERE displayName='%s'" % (lat, lon, heading, mission)
x.execute(query)
conn.ping(True)
</code>```

However now when my Internet connection breaks the script also crashes since It can't update the variables. My connection normally reestablishes within one minute. (the script runs on a vehicle which is moving. Internet connection is established via a GSM Modem)

Is it better to re-open every time the connection to the server prior an update of the variable so I can see if the connection has been established or is there a better way?

答:
I'm guessing the script fails with an exception at the line x.execute(query) when the connection drops.

You could trap the exception and retry opening the connection. The following 'pseudo-python' demonstrates the general technique, but will obviously need to be adapted to use real function, method, and exception names:

```<code>def open_connection(retries, delay):
    for (x in range(0, retries)):
        conn = pymysql.connection()
        if (conn.isOpen()):
            return conn
        sleep(delay)
    return None

conn = open_connection(30, 3)
x = conn.cursor()

while(conn is not None and more_data)

    # read data here

    query = ...

    while(conn is not None):   # Loop until data is definitely saved
        try:
            x.execute(query)
            break              # data saved, exit inner loop
        except SomeException:
            conn = open_connection(30,3)
            x = conn.cursor()
</code>```

The general idea is that you need to loop and retry until either the data is definitely saved, or until you encounter an unrecoverable error.

Hm. If you're sampling or receiving data at a constant rate, but are only able to send it irregularly because of network failures, you've created a classic producer-consumer problem. You'll need one thread to read or receive the data, a queue to hold any backlog, and another thread to store the data. Fun! ;-)

Title: Python sending data to a MySQL DB

Body:
I have a script running, updating certain values in a DB once a second.
At the start of the script I first connect to the DB:

conn = pymysql.connect(host= "server",
               user="user",
               passwd="pw",
               db="db",
               charset='utf8')
x = conn.cursor()

I leave the connection open for the running time of the script (around 30min)

With this code I update certain values once every second:

query = "UPDATE missionFilesDelDro SET landLat = '%s', landLon='%s',landHea='%s' WHERE displayName='%s'" % (lat, lon, heading, mission)
x.execute(query)
conn.ping(True)

However now when my Internet connection breaks the script also crashes since It can't update the variables. My connection normally reestablishes within one minute. (the script runs on a vehicle which is moving. Internet connection is established via a GSM Modem)

Is it better to re-open every time the connection to the server prior an update of the variable so I can see if the connection has been established or is there a better way?

Body:
I'm guessing the script fails with an exception at the line x.execute(query) when the connection drops.

You could trap the exception and retry opening the connection. The following 'pseudo-python' demonstrates the general technique, but will obviously need to be adapted to use real function, method, and exception names:

def open_connection(retries, delay):
    for (x in range(0, retries)):
        conn = pymysql.connection()
        if (conn.isOpen()):
            return conn
        sleep(delay)
    return None

conn = open_connection(30, 3)
x = conn.cursor()

while(conn is not None and more_data)

    # read data here

    query = ...

    while(conn is not None):   # Loop until data is definitely saved
        try:
            x.execute(query)
            break              # data saved, exit inner loop
        except SomeException:
            conn = open_connection(30,3)
            x = conn.cursor()

The general idea is that you need to loop and retry until either the data is definitely saved, or until you encounter an unrecoverable error.

Hm. If you're sampling or receiving data at a constant rate, but are only able to send it irregularly because of network failures, you've created a classic producer-consumer problem. You'll need one thread to read or receive the data, a queue to hold any backlog, and another thread to store the data. Fun! ;-)


问:
Python: converting date string to UTC
I am parsing a 3rd party website HTML with dates and times which are always in UK time format, however they don't have any timezone info in the source. Converting the string to an object is easy enough using datetime.strptime(), but how do I add timezone info?

Ultimately, I need to convert these strings to a datetime object in UTC format. The code will always run on a PC which is timezone aware, i.e. datetime.now() will return UK time.

```<code>temp = '07/12/2017 13:30'
dt = datetime.strptime(temp, '%d/%m/%Y %H:%M')
</code>```

Is there a nicer way to do this?

```<code>offset = datetime.now() - datetime.utcnow()
dt -= offset</code>```

答:
There are some good libraries that make working with dates so much easier. I like dateparser, parsedatetime, and arrow;</p>

```<code>import dateparser as dp
dt = dp.parse('07-12-2017 13:30 PST')
print (dt)

dt = dp.parse("Yesterday at 3:00am EST")
print(dt)

2017-07-12 13:30:00-08:00
2017-12-06 17:07:07.557109-05:00
</code>```

Title: Python: converting date string to UTC

Body:
I am parsing a 3rd party website HTML with dates and times which are always in UK time format, however they don't have any timezone info in the source. Converting the string to an object is easy enough using datetime.strptime(), but how do I add timezone info?

Ultimately, I need to convert these strings to a datetime object in UTC format. The code will always run on a PC which is timezone aware, i.e. datetime.now() will return UK time.

temp = '07/12/2017 13:30'
dt = datetime.strptime(temp, '%d/%m/%Y %H:%M')

Is there a nicer way to do this?

offset = datetime.now() - datetime.utcnow()
dt -= offset

Body:
There are some good libraries that make working with dates so much easier. I like dateparser, parsedatetime, and arrow;

import dateparser as dp
dt = dp.parse('07-12-2017 13:30 PST')
print (dt)

dt = dp.parse("Yesterday at 3:00am EST")
print(dt)

2017-07-12 13:30:00-08:00
2017-12-06 17:07:07.557109-05:00


问:
jQuery .change() function heavily delayed with number-input
I have an issue with the .change() function in JQuery in combination with an input of the type "number".

Quick and dirty mockup that gets the point across:

JSfiddle: https://jsfiddle.net/vtuk69bj/

```<code>$('#testInput').change(function(){
$('#testDiv').html($('#testInput').val());
})
</code>```

As you can see if you use the arrows inside the input to increase/decrease numbers quickly (or even not so quickly), the function is incredibly delayed in some cases.

I know I could use stuff like keyup or click, but that wouldn't cover both the option to increase/decrease with arrows or straight up input a number yourself. Is there some way to cover all my bases without having 2-3+ different functions?

答:
The input event fires any time the value of the input changes.

$('#testInput').on('input', function() {
  $('#testDiv').html(this.value);
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="testInput" type="number" min="1" max="999">
<div id="testDiv">
  1
</div></code>```

Body:
I have an issue with the .change() function in JQuery in combination with an input of the type "number".

Quick and dirty mockup that gets the point across:

JSfiddle: https://jsfiddle.net/vtuk69bj/

$('#testInput').change(function(){
$('#testDiv').html($('#testInput').val());
})

As you can see if you use the arrows inside the input to increase/decrease numbers quickly (or even not so quickly), the function is incredibly delayed in some cases.

I know I could use stuff like keyup or click, but that wouldn't cover both the option to increase/decrease with arrows or straight up input a number yourself. Is there some way to cover all my bases without having 2-3+ different functions?

Body:
The input event fires any time the value of the input changes.

$('#testInput').on('input', function() {
  $('#testDiv').html(this.value);
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="testInput" type="number" min="1" max="999">
<div id="testDiv">
  1
</div>


问:
How do I redirect to another webpage?
How can I redirect the user from one page to another using jQuery or pure JavaScript?</p>

答:
In my work experience, JavaScript is much better to redirect.

It depends on how you want to change the location. If you want to log your website in users history, use window.location.href='ur website';. Otherwise to do it without logging in history, use window.location.replace("your website");.

OwnerDisplayName: venkatachalam

Title: How do I redirect to another webpage?

LastEditorDisplayName: strager


问:
Paginate an AngularJS data table
I have gathered some JSON (dummy) data in a users table.

var root = 'https://jsonplaceholder.typicode.com';

// Create an Angular module named "usersApp"
var app = angular.module("usersApp", []);

// Create controller for the "usersApp" module
app.controller("usersCtrl", ["$scope", "$http", function($scope, $http) {
  var url = root + "/users"
  $http.get(url)
    .then(function(data) {
      $scope.users = data.data;
    });
}]);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.search-box {
  margin: 5px;
}

.panel-heading {
  font-weight: bold;
}

.table-container .panel-body {
  padding: 0;
}

.table-container table tr th {
  font-weight: bold;
}</code>```

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Users

            <input type="text" class="form-control" id="search" placeholder="Search User" data-ng-model="search">

                Full name
                Email
                City
                Street
                Suite

                {{user.name}}
                {{user.email}}
                {{user.address.city}}
                {{user.address.street}}
                {{user.address.suite}}

```

The table has only 10 rows but, in a real-world app, there is a lot more data to manage so it needs to be paginated. The above one could have 3 rows per page (except the 4th one, which should have one).

Question(s):

Does AngularJS have a built-in, easy way to paginate such a table?

If not, what are the best alternatives?

答: You can use ngInfiniteScroll for pagination. https://sroze.github.io/ngInfiniteScroll/

Title: Paginate an AngularJS data table

Body:
I have gathered some JSON (dummy) data in a users table.

var root = 'https://jsonplaceholder.typicode.com';

// Create an Angular module named "usersApp"
var app = angular.module("usersApp", []);

// Create controller for the "usersApp" module
app.controller("usersCtrl", ["$scope", "$http", function($scope, $http) {
  var url = root + "/users"
  $http.get(url)
    .then(function(data) {
      $scope.users = data.data;
    });
}]);

.search-box {
  margin: 5px;
}

.panel-heading {
  font-weight: bold;
}

.table-container .panel-body {
  padding: 0;
}

.table-container table tr th {
  font-weight: bold;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Users

            <input type="text" class="form-control" id="search" placeholder="Search User" data-ng-model="search">

                Full name
                Email
                City
                Street
                Suite

                {{user.name}}
                {{user.email}}
                {{user.address.city}}
                {{user.address.street}}
                {{user.address.suite}}

The table has only 10 rows but, in a real-world app, there is a lot more data to manage so it needs to be paginated. The above one could have 3 rows per page (except the 4th one, which should have one).

Question(s):

Does AngularJS have a built-in, easy way to paginate such a table?

If not, what are the best alternatives?