问:
python3 no longer works on Azure functions
I have had my function running for a while but suddenly nothing works any more. I followed the instructions found here https://prmadi.com/running-python-code-on-azure-functions-app/ with success. The code was automatically deployed from Github. However, a few weeks ago things went wrong. I have not solved my problem but I have figured some things out:

1) the modules (using pip) I installed are gone or can no longer be found. I managed to install them but they disappear within some hours.

2) the function runs 2.7. I guess that is because the PATH has been changed. Previously \home\site\tools was in the path. That is no longer the case. What worked previously was to install python 3 using nuget site-extension and then move it to the \home\site\tools folder. I have tried to move the python3 installation to e.g. /home/site/deployments/tools which is in the path.

Update: I tried to use the instructions here: https://lnx.azurewebsites.net/python-3-6-deployments-on-azure-function-apps/. I managed to get my function running python 3 and I managed to have Azure install the required modules. So in short I have the following following folder structure:

```<code>requirements.txt
├── function
    ├── deploy.cmd
    ├── .deployment
    ├── function.json
    ├── run.py
</code>```

deployment is

```<code>@if "%SCM_TRACE_LEVEL%" NEQ "4" @echo off

:: --------------------------------------------------------
:: KUDU Deployment Script for Python 3.6 on Azure Functions
:: Version: 0.1
:: --------------------------------------------------------

:: Prerequisites
:: -------------

:: Verify node.js installed
where node 2>nul >nul
IF %ERRORLEVEL% NEQ 0 (
  echo Missing node.js executable, please install node.js, if already installed make sure it can be reached from current environment.
  goto error
)

:: Setup
:: -----

setlocal enabledelayedexpansion

SET ARTIFACTS=%~dp0%..\artifacts

IF NOT DEFINED DEPLOYMENT_SOURCE (
  SET DEPLOYMENT_SOURCE=%~dp0%.
)

IF NOT DEFINED DEPLOYMENT_TARGET (
  SET DEPLOYMENT_TARGET=%ARTIFACTS%\wwwroot
)

IF NOT DEFINED NEXT_MANIFEST_PATH (
  SET NEXT_MANIFEST_PATH=%ARTIFACTS%\manifest

  IF NOT DEFINED PREVIOUS_MANIFEST_PATH (
    SET PREVIOUS_MANIFEST_PATH=%ARTIFACTS%\manifest
  )
)

IF NOT DEFINED KUDU_SYNC_CMD (
  :: Install kudu sync
  echo Installing Kudu Sync
  call npm install kudusync -g --silent
  IF !ERRORLEVEL! NEQ 0 goto error

  :: Locally just running "kuduSync" would also work
  SET KUDU_SYNC_CMD=%appdata%\npm\kuduSync.cmd
)
goto Deployment

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: Deployment
:: ----------

:Deployment
echo Handling python deployment.

:: 1. KuduSync
IF /I "%IN_PLACE_DEPLOYMENT%" NEQ "1" (
  call :ExecuteCmd "%KUDU_SYNC_CMD%" -v 50 -f "%DEPLOYMENT_SOURCE%" -t "%DEPLOYMENT_TARGET%" -n "%NEXT_MANIFEST_PATH%" -p "%PREVIOUS_MANIFEST_PATH%" -i ".git;.hg;.deployment;deploy.cmd"
  IF !ERRORLEVEL! NEQ 0 goto error
)

IF NOT EXIST "%DEPLOYMENT_TARGET%\requirements.txt" goto postPython
IF EXIST "%DEPLOYMENT_TARGET%\.skipPythonDeployment" goto postPython

echo Detected requirements.txt.  You can skip Python specific steps with a .skipPythonDeployment file.

pushd "%DEPLOYMENT_TARGET%"

:: 2. Create virtual environment
IF NOT EXIST "D:\home\site\tools\python36*" (

  echo Creating Python 3.6.1 x64 virtual environment...
  nuget.exe install -Source https://www.siteextensions.net/api/v2/ -OutputDirectory D:\home\site\tools python361x64
  mv /d/home/site/tools/python3*/content/python*/* /d/home/site/tools/
  IF !ERRORLEVEL! NEQ 0 goto error

) ELSE (
  echo Found compatible virtual environment.
)

:: 3. Install packages
echo Pip install requirements...
D:\home\site\tools\python.exe -m pip install -r "%DEPLOYMENT_TARGET%\requirements.txt"
IF !ERRORLEVEL! NEQ 0 goto error

popd

:postPython

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
goto end

:: Execute command routine that will echo out when error
:ExecuteCmd
setlocal
set _CMD_=%*
call %_CMD_%
if "%ERRORLEVEL%" NEQ "0" echo Failed exitCode=%ERRORLEVEL%, command=%_CMD_%
exit /b %ERRORLEVEL%

:error
endlocal
echo An error has occurred during web site deployment.
call :exitSetErrorLevel
call :exitFromFunction 2>nul

:exitSetErrorLevel
exit /b 1

:exitFromFunction
()

:end
endlocal
echo Finished successfully.
</code>```

This actually worked, but after a while I was either 1) back to python 2.7 and no packages or I get the error message

```<code>Exception while executing function: Functions.toc
Microsoft.Azure.WebJobs.Host.FunctionInvocationException : Exception while executing function: Functions.toc ---> System.ApplicationException
   at async Microsoft.Azure.WebJobs.Script.Description.ScriptFunctionInvoker.ExecuteScriptAsync(String path,String arguments,Object[] invocationParameters,FunctionInvocationContext context) at C:\projects\azure-webjobs-sdk-script\src\WebJobs.Script\Description\Script\ScriptFunctionInvoker.cs : 114
   at async Microsoft.Azure.WebJobs.Script.Description.ScriptFunctionInvoker.InvokeCore(Object[] parameters,FunctionInvocationContext context) at C:\projects\azure-webjobs-sdk-script\src\WebJobs.Script\Description\Script\ScriptFunctionInvoker.cs : 55
   at async Microsoft.Azure.WebJobs.Script.Description.FunctionInvokerBase.Invoke(Object[] parameters) at C:\projects\azure-webjobs-sdk-script\src\WebJobs.Script\Description\FunctionInvokerBase.cs : 95
   at async Microsoft.Azure.WebJobs.Host.Executors.VoidTaskMethodInvoker`2.InvokeAsync[TReflected,TReturnType](TReflected instance,Object[] arguments)
   at async Microsoft.Azure.WebJobs.Host.Executors.FunctionInvoker`2.InvokeAsync[TReflected,TReturnValue](Object instance,Object[] arguments)
   at async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.InvokeAsync(IFunctionInvoker invoker,ParameterHelper parameterHelper,CancellationTokenSource timeoutTokenSource,CancellationTokenSource functionCancellationTokenSource,Boolean throwOnTimeout,TimeSpan timerInterval,IFunctionInstance instance)
   at async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithWatchersAsync(IFunctionInstance instance,ParameterHelper parameterHelper,TraceWriter traceWriter,CancellationTokenSource functionCancellationTokenSource)
   at async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithLoggingAsync(??)
   at async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithLoggingAsync(??)
   End of inner…
</code>```

Despite that I can open a console and run the code without errors. So I tried to redeploy the function but with no luck. I guess that azure runs some cleanup or something at some intervals?

Best

答:
Problem solved. It was caused by a bug in Azure https://github.com/Azure/azure-webjobs-sdk-script/issues/1758

Essentially just roll back to an old version (e.g. 1.0.11296) in "function app settings" and everything works again :-)

Body:
I have had my function running for a while but suddenly nothing works any more. I followed the instructions found here https://prmadi.com/running-python-code-on-azure-functions-app/ with success. The code was automatically deployed from Github. However, a few weeks ago things went wrong. I have not solved my problem but I have figured some things out:

1) the modules (using pip) I installed are gone or can no longer be found. I managed to install them but they disappear within some hours.

2) the function runs 2.7. I guess that is because the PATH has been changed. Previously \home\site\tools was in the path. That is no longer the case. What worked previously was to install python 3 using nuget site-extension and then move it to the \home\site\tools folder. I have tried to move the python3 installation to e.g. /home/site/deployments/tools which is in the path.

Update: I tried to use the instructions here: https://lnx.azurewebsites.net/python-3-6-deployments-on-azure-function-apps/. I managed to get my function running python 3 and I managed to have Azure install the required modules. So in short I have the following following folder structure:

requirements.txt
├── function
    ├── deploy.cmd
    ├── .deployment
    ├── function.json
    ├── run.py

deployment is

@if "%SCM_TRACE_LEVEL%" NEQ "4" @echo off

:: --------------------------------------------------------
:: KUDU Deployment Script for Python 3.6 on Azure Functions
:: Version: 0.1
:: --------------------------------------------------------

:: Prerequisites
:: -------------

:: Verify node.js installed
where node 2>nul >nul
IF %ERRORLEVEL% NEQ 0 (
  echo Missing node.js executable, please install node.js, if already installed make sure it can be reached from current environment.
  goto error
)

:: Setup
:: -----

setlocal enabledelayedexpansion

SET ARTIFACTS=%~dp0%..\artifacts

IF NOT DEFINED DEPLOYMENT_SOURCE (
  SET DEPLOYMENT_SOURCE=%~dp0%.
)

IF NOT DEFINED DEPLOYMENT_TARGET (
  SET DEPLOYMENT_TARGET=%ARTIFACTS%\wwwroot
)

IF NOT DEFINED NEXT_MANIFEST_PATH (
  SET NEXT_MANIFEST_PATH=%ARTIFACTS%\manifest

  IF NOT DEFINED PREVIOUS_MANIFEST_PATH (
    SET PREVIOUS_MANIFEST_PATH=%ARTIFACTS%\manifest
  )
)

IF NOT DEFINED KUDU_SYNC_CMD (
  :: Install kudu sync
  echo Installing Kudu Sync
  call npm install kudusync -g --silent
  IF !ERRORLEVEL! NEQ 0 goto error

  :: Locally just running "kuduSync" would also work
  SET KUDU_SYNC_CMD=%appdata%\npm\kuduSync.cmd
)
goto Deployment

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: Deployment
:: ----------

:Deployment
echo Handling python deployment.

:: 1. KuduSync
IF /I "%IN_PLACE_DEPLOYMENT%" NEQ "1" (
  call :ExecuteCmd "%KUDU_SYNC_CMD%" -v 50 -f "%DEPLOYMENT_SOURCE%" -t "%DEPLOYMENT_TARGET%" -n "%NEXT_MANIFEST_PATH%" -p "%PREVIOUS_MANIFEST_PATH%" -i ".git;.hg;.deployment;deploy.cmd"
  IF !ERRORLEVEL! NEQ 0 goto error
)

IF NOT EXIST "%DEPLOYMENT_TARGET%\requirements.txt" goto postPython
IF EXIST "%DEPLOYMENT_TARGET%\.skipPythonDeployment" goto postPython

echo Detected requirements.txt.  You can skip Python specific steps with a .skipPythonDeployment file.

pushd "%DEPLOYMENT_TARGET%"

:: 2. Create virtual environment
IF NOT EXIST "D:\home\site\tools\python36*" (

  echo Creating Python 3.6.1 x64 virtual environment...
  nuget.exe install -Source https://www.siteextensions.net/api/v2/ -OutputDirectory D:\home\site\tools python361x64
  mv /d/home/site/tools/python3*/content/python*/* /d/home/site/tools/
  IF !ERRORLEVEL! NEQ 0 goto error

) ELSE (
  echo Found compatible virtual environment.
)

:: 3. Install packages
echo Pip install requirements...
D:\home\site\tools\python.exe -m pip install -r "%DEPLOYMENT_TARGET%\requirements.txt"
IF !ERRORLEVEL! NEQ 0 goto error

popd

:postPython

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
goto end

:: Execute command routine that will echo out when error
:ExecuteCmd
setlocal
set _CMD_=%*
call %_CMD_%
if "%ERRORLEVEL%" NEQ "0" echo Failed exitCode=%ERRORLEVEL%, command=%_CMD_%
exit /b %ERRORLEVEL%

:error
endlocal
echo An error has occurred during web site deployment.
call :exitSetErrorLevel
call :exitFromFunction 2>nul

:exitSetErrorLevel
exit /b 1

:exitFromFunction
()

:end
endlocal
echo Finished successfully.

This actually worked, but after a while I was either 1) back to python 2.7 and no packages or I get the error message

Exception while executing function: Functions.toc
Microsoft.Azure.WebJobs.Host.FunctionInvocationException : Exception while executing function: Functions.toc ---> System.ApplicationException
   at async Microsoft.Azure.WebJobs.Script.Description.ScriptFunctionInvoker.ExecuteScriptAsync(String path,String arguments,Object[] invocationParameters,FunctionInvocationContext context) at C:\projects\azure-webjobs-sdk-script\src\WebJobs.Script\Description\Script\ScriptFunctionInvoker.cs : 114
   at async Microsoft.Azure.WebJobs.Script.Description.ScriptFunctionInvoker.InvokeCore(Object[] parameters,FunctionInvocationContext context) at C:\projects\azure-webjobs-sdk-script\src\WebJobs.Script\Description\Script\ScriptFunctionInvoker.cs : 55
   at async Microsoft.Azure.WebJobs.Script.Description.FunctionInvokerBase.Invoke(Object[] parameters) at C:\projects\azure-webjobs-sdk-script\src\WebJobs.Script\Description\FunctionInvokerBase.cs : 95
   at async Microsoft.Azure.WebJobs.Host.Executors.VoidTaskMethodInvoker`2.InvokeAsync[TReflected,TReturnType](TReflected instance,Object[] arguments)
   at async Microsoft.Azure.WebJobs.Host.Executors.FunctionInvoker`2.InvokeAsync[TReflected,TReturnValue](Object instance,Object[] arguments)
   at async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.InvokeAsync(IFunctionInvoker invoker,ParameterHelper parameterHelper,CancellationTokenSource timeoutTokenSource,CancellationTokenSource functionCancellationTokenSource,Boolean throwOnTimeout,TimeSpan timerInterval,IFunctionInstance instance)
   at async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithWatchersAsync(IFunctionInstance instance,ParameterHelper parameterHelper,TraceWriter traceWriter,CancellationTokenSource functionCancellationTokenSource)
   at async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithLoggingAsync(??)
   at async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithLoggingAsync(??)
   End of inner…

Despite that I can open a console and run the code without errors. So I tried to redeploy the function but with no luck. I guess that azure runs some cleanup or something at some intervals?

Best


来源: stackexchange

问:
Excel Formatting Numbers in Cell
I have a column of data in Excel;

```<code>07902555018
07902556019
07902557020
07902558021
07902559022
...
</code>```

The values change but the placement of three zeros is constant. I am trying to remove the First Zero, Second Zero and the Zero in the 3rd to last position.

```<code>792555518
792555619
792555720
...
</code>```

After the values are changed I am trying to add two hyphens

```<code>79-25555-18
79-25556-19
19-25557-20
</code>```

I tried using: =TEXT(--SUBSTITUTE(--E2,"0","",2),"00-00000-00")
However a problem occurs:

079020638020 becomes 792-06380-20
However 79-20638-20 is the value I want returned in instances like these.

答:
If you only know that the placement of the zeros is constant then use REPLACE rather than SUBSTITUTE. This replaces (removes) the 1st, 4th and 9th zeros:

```<code>=TEXT(REPLACE(REPLACE(REPLACE(A1,1,1,""),3,1,""),8,1,""),"00-00000-00")
</code>```

ContentLicense: CC BY-SA 3.0

Title: Excel Formatting Numbers in Cell

Body:
I have a column of data in Excel;

07902555018
07902556019
07902557020
07902558021
07902559022
...

The values change but the placement of three zeros is constant. I am trying to remove the First Zero, Second Zero and the Zero in the 3rd to last position.

792555518
792555619
792555720
...

After the values are changed I am trying to add two hyphens

79-25555-18
79-25556-19
19-25557-20

I tried using: =TEXT(--SUBSTITUTE(--E2,"0","",2),"00-00000-00")
However a problem occurs:

079020638020 becomes 792-06380-20
However 79-20638-20 is the value I want returned in instances like these.

Body:
If you only know that the placement of the zeros is constant then use REPLACE rather than SUBSTITUTE. This replaces (removes) the 1st, 4th and 9th zeros:

=TEXT(REPLACE(REPLACE(REPLACE(A1,1,1,""),3,1,""),8,1,""),"00-00000-00")


问:
Akka: First message going to dead letters, from second message it is all fine
I have supervisor actor which selects child actor based on command received, whenever it creates a new child actor and sends message(ask pattern) it timesout as child actor tries to send back response but it goes to dead letters.

Here is the child actor code

```<code>class IdActor(id: String, injector: Injector) extends Actor {
  override def receive: Receive = {
    case cmd: GenerateIdCmd =>
      val parent = sender()
      ...
      Future(idEvent) pipeTo sender //Issue is here going to dead letters
      //Future(idEvent) pipeTo parent //This also leads to same problem
      //parent ! idEvent // Same issue
  }
}
</code>```

Here is supervisor code

```<code>class IdSupervisor(injector: Injector) extends Actor {
  override def receive: Receive = {
    case cmd: GenerateIdCmd =>
      ...
      val ref = context.child(cmd.id).getOrElse {
        context.actorOf(Props(classOf[IdActor], cmd.id, injector), cmd.id)
      }
      ask(ref, cmd) pipeTo sender
  }
}
</code>```

Second message is flowing back to originator, first response from all new child actors going to dead letters from there afterwards going good.

Working Solution
Issue is with Supervisor, fixed code

```<code>class IdSupervisor(injector: Injector) extends Actor {
      override def receive: Receive = {
        case cmd: GenerateIdCmd =>
          val originator = sender
          ...
          val ref = context.child(cmd.id).getOrElse {
            context.actorOf(Props(classOf[IdActor], cmd.id, injector), cmd.id)
          }
          ask(ref, cmd) pipeTo originator
      }
    }
</code>```

答:
Never ever pipe directly to sender from future inside actor, sender is def and at the moment when future is completed, it might be already different one than you expect. One of solution is to store sender before future call:

```<code>class IdActor(id: String, injector: Injector) extends Actor {
  override def receive: Receive = {
    case cmd: GenerateIdCmd =>
      ...
      val originalSender = sender
      Future(idEvent) pipeTo originalSender
  }
}
</code>```

Body:
I have supervisor actor which selects child actor based on command received, whenever it creates a new child actor and sends message(ask pattern) it timesout as child actor tries to send back response but it goes to dead letters.

Here is the child actor code

class IdActor(id: String, injector: Injector) extends Actor {
  override def receive: Receive = {
    case cmd: GenerateIdCmd =>
      val parent = sender()
      ...
      Future(idEvent) pipeTo sender //Issue is here going to dead letters
      //Future(idEvent) pipeTo parent //This also leads to same problem
      //parent ! idEvent // Same issue
  }
}

Here is supervisor code

class IdSupervisor(injector: Injector) extends Actor {
  override def receive: Receive = {
    case cmd: GenerateIdCmd =>
      ...
      val ref = context.child(cmd.id).getOrElse {
        context.actorOf(Props(classOf[IdActor], cmd.id, injector), cmd.id)
      }
      ask(ref, cmd) pipeTo sender
  }
}

Second message is flowing back to originator, first response from all new child actors going to dead letters from there afterwards going good.

Working Solution
Issue is with Supervisor, fixed code

class IdSupervisor(injector: Injector) extends Actor {
      override def receive: Receive = {
        case cmd: GenerateIdCmd =>
          val originator = sender
          ...
          val ref = context.child(cmd.id).getOrElse {
            context.actorOf(Props(classOf[IdActor], cmd.id, injector), cmd.id)
          }
          ask(ref, cmd) pipeTo originator
      }
    }

Body:
Never ever pipe directly to sender from future inside actor, sender is def and at the moment when future is completed, it might be already different one than you expect. One of solution is to store sender before future call:

class IdActor(id: String, injector: Injector) extends Actor {
  override def receive: Receive = {
    case cmd: GenerateIdCmd =>
      ...
      val originalSender = sender
      Future(idEvent) pipeTo originalSender
  }
}


问:
Check if UIColor is dark or bright?
I need to determine whether a selected UIColor (picked by the user) is dark or bright, so I can change the color of a line of text that sits on top of that color, for better readability.

Here's an example in Flash/Actionscript (with demo):
http://web.archive.org/web/20100102024448/http://theflashblog.com/?p=173

Any thoughts?

Cheers,
Andre

UPDATE

Thanks to everyone's suggestions, here's the working code:

```<code>- (void) updateColor:(UIColor *) newColor
{
    const CGFloat *componentColors = CGColorGetComponents(newColor.CGColor);

    CGFloat colorBrightness = ((componentColors[0] * 299) + (componentColors[1] * 587) + (componentColors[2] * 114)) / 1000;
    if (colorBrightness < 0.5)
    {
        NSLog(@"my color is dark");
    }
    else
    {
        NSLog(@"my color is light");
    }
}
</code>```

Thanks once again :)

答:
Swift 4 Version</p>

```<code>extension UIColor {
    func isLight() -> Bool {
        guard let components = cgColor.components, components.count > 2 else {return false}
        let brightness = ((components[0] * 299) + (components[1] * 587) + (components[2] * 114)) / 1000
        return (brightness > 0.5)
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Check if UIColor is dark or bright?

Body:
I need to determine whether a selected UIColor (picked by the user) is dark or bright, so I can change the color of a line of text that sits on top of that color, for better readability.

Here's an example in Flash/Actionscript (with demo):
http://web.archive.org/web/20100102024448/http://theflashblog.com/?p=173

Any thoughts?

Cheers,
Andre

UPDATE

Thanks to everyone's suggestions, here's the working code:

- (void) updateColor:(UIColor *) newColor
{
    const CGFloat *componentColors = CGColorGetComponents(newColor.CGColor);

    CGFloat colorBrightness = ((componentColors[0] * 299) + (componentColors[1] * 587) + (componentColors[2] * 114)) / 1000;
    if (colorBrightness < 0.5)
    {
        NSLog(@"my color is dark");
    }
    else
    {
        NSLog(@"my color is light");
    }
}

Thanks once again :)

Body:
Swift 4 Version

extension UIColor {
    func isLight() -> Bool {
        guard let components = cgColor.components, components.count > 2 else {return false}
        let brightness = ((components[0] * 299) + (components[1] * 587) + (components[2] * 114)) / 1000
        return (brightness > 0.5)
    }
}


问:
How do i scale a Label in LibGdx
i am trying to code a HUD for my game but i cannot figure out how to scale a Label properly I am using this code:

```<code>Label hpLabel = new Label("HP: ",new Label.LabelStyle(new BitmapFont(),Color.BROWN));
    table.add(hpLabel);
    viewport = new FitViewport(Gdx.graphics.getWidth()/ FacultyWars.PPM, Gdx.graphics.getHeight()/ FacultyWars.PPM, cam);
    stage = new Stage(viewport, batch);
    stage.addActor(table);
//other ellements added after this
</code>```

The HP tag is enormous on the screen. I tried using setScale on the label and on the table to no avail. Any help is appreciated!
Thanks

Here is a picture of the current screen https://gyazo.com/57c190a9d7516bb8b2256bf1a7d17b4c

答:
Simply add the Label to a Group then apply the scale to the group.

```<code>    Label label = new Label("hello", skin);
    Group group = new Group();
    group.addActor(label);
    group.setScale(2f, 2f);
</code>```

I only scale Groups with Labels in animations where at the end of the animation the scale is 1. One should not scale fonts, because it looks pixelated. For example, a simple scale up scale down animation:

```<code>group.addAction(Actions.sequence(Actions.scaleTo(2f, 2f, 1f), Actions.scaleTo(1f, 1f, 1f)));
</code>```

Title: How do i scale a Label in LibGdx

Body:
i am trying to code a HUD for my game but i cannot figure out how to scale a Label properly I am using this code:

Label hpLabel = new Label("HP: ",new Label.LabelStyle(new BitmapFont(),Color.BROWN));
    table.add(hpLabel);
    viewport = new FitViewport(Gdx.graphics.getWidth()/ FacultyWars.PPM, Gdx.graphics.getHeight()/ FacultyWars.PPM, cam);
    stage = new Stage(viewport, batch);
    stage.addActor(table);
//other ellements added after this

The HP tag is enormous on the screen. I tried using setScale on the label and on the table to no avail. Any help is appreciated!
Thanks

Here is a picture of the current screen https://gyazo.com/57c190a9d7516bb8b2256bf1a7d17b4c

Body:
Simply add the Label to a Group then apply the scale to the group.

    Label label = new Label("hello", skin);
    Group group = new Group();
    group.addActor(label);
    group.setScale(2f, 2f);

I only scale Groups with Labels in animations where at the end of the animation the scale is 1. One should not scale fonts, because it looks pixelated. For example, a simple scale up scale down animation:

group.addAction(Actions.sequence(Actions.scaleTo(2f, 2f, 1f), Actions.scaleTo(1f, 1f, 1f)));


问:
How can I write the docker -it option in Dockerfile?
I want create a Dockerfile for CMD line:

```<code>docker run --rm -it -v $(pwd):/data -p 8080:80 klokantech/openmaptiles-server
</code>```

How I do -it in Dockerfile?

答: You can't control the "interactive" (-i) and "tty" (-t) runtime options from the Dockerfile at build time. You'll need to include that in the documentation for how to use your image.

Body:
I want create a Dockerfile for CMD line:

docker run --rm -it -v $(pwd):/data -p 8080:80 klokantech/openmaptiles-server

How I do -it in Dockerfile?


问:
Build Nested Object in Javascript
I trying to build a nested object, I'll try to make myself clear.

I have this json structure:

```<code> {
      "origin.geo.country": "USA",
      "origin.geo.state": "NY",
      "origin.geo.zip": 4444,
      "user.name": "Michael",
      "user.surname": "Jordan"
}
</code>```

And I need a function that outputs something like this:

```<code>{
     origin: {
         geo: {
             country: "USA",
             state: "NY",
             zip: 4444
         }
     },
     user: {
         name: "Michael",
         surname: "Jordan"
     }
 }
</code>```

I know i have to use recursion to achieve this, but I'm not able to code it.
Can you guys help me with this?

Thanks.

答:
So guys,

@Ben Beck answer helped me.

I just need to make some minor changes to the function:

```<code>function (path,value,obj) {

    var parts = path.split("."), part;

    //reference the parent object
    var parent = obj;

    while(part = parts.shift()) {

        // here I check if the property already exists
        if( !obj.hasOwnProperty(part) ) obj[part] = {};

        // if is the last index i set the prop value
        if(parts.length === 0) obj[part] = value;

        obj = obj[part]; // update "pointer"
    }

    //finally return the populated object
    return parent;

}
</code>```

Title: Build Nested Object in Javascript

Body:
I trying to build a nested object, I'll try to make myself clear.

I have this json structure:

 {
      "origin.geo.country": "USA",
      "origin.geo.state": "NY",
      "origin.geo.zip": 4444,
      "user.name": "Michael",
      "user.surname": "Jordan"
}

And I need a function that outputs something like this:

{
     origin: {
         geo: {
             country: "USA",
             state: "NY",
             zip: 4444
         }
     },
     user: {
         name: "Michael",
         surname: "Jordan"
     }
 }

I know i have to use recursion to achieve this, but I'm not able to code it.
Can you guys help me with this?

Thanks.

Body:
So guys,

@Ben Beck answer helped me.

I just need to make some minor changes to the function:

function (path,value,obj) {

    var parts = path.split("."), part;

    //reference the parent object
    var parent = obj;

    while(part = parts.shift()) {

        // here I check if the property already exists
        if( !obj.hasOwnProperty(part) ) obj[part] = {};

        // if is the last index i set the prop value
        if(parts.length === 0) obj[part] = value;

        obj = obj[part]; // update "pointer"
    }

    //finally return the populated object
    return parent;

}


问:
find all classes and interfaces a class extends or implements recursively
I was wondering if there was an easy way of determining the complete list of Types that a Java class extends or implements recursively?

for instance:

```<code>class Foo extends Bar implements I1, I2 {...}
class Bar implements I3 {...}
interface I1 extends I4, I5 {...}
interface I2 {...}
interface I3 {...}
interface I4 {...}
interface I5 {...}

class ClassUtil {
    public static Set<Class<?>> getAllExtendedOrImplementedTypesRecursively(Class<?> clazz){
        ???
    }
}

import static org.junit.Assert.*;
public class ClassUtilTest {
    @Test
    public void shouldEqualClasses(){
        Set<Class<?>> types = ClassUtil.getAllExtendedOrImplementedTypesRecursively(Foo.class);
        Set<Class<?>> checklist = new HashSet<>();
        checklist.add(Foo.class);
        checklist.add(Bar.class);
        checklist.add(I1.class);
        checklist.add(I2.class);
        checklist.add(I3.class);
        checklist.add(I4.class);
        checklist.add(I5.class);
        assertTrue(checklist.containsAll(types));
        assertTrue(types.containsAll(checklist));
    }
}
</code>```

Think Arquillian ShrinkWrap creation helper.

UPDATE: due to the Class object not implementing Comparable> I also need to find a way of creating a Set (or similar class) without implementing the Comparable interface (for instance, solely relying on the hashcode of the class object).

UPDATE: changed the test to use hashset. derp.

答:
In Java8

```<code>import java.util.Arrays;
import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class ClassUtil {
    public static Set<Class<?>> getAllExtendedOrImplementedTypesRecursively(final Class<?> clazz) {
        return walk(clazz)
                .filter(Predicate.isEqual(java.lang.Object.class).negate())
                .collect(Collectors.toSet());
    }

    public static Stream<Class<?>> walk(final Class<?> c) {
        return Stream.concat(Stream.of(c),
                Stream.concat(
                        Optional.ofNullable(c.getSuperclass()).map(Stream::of).orElseGet(Stream::empty),
                        Arrays.stream(c.getInterfaces())
                ).flatMap(ClassUtil::walk));
    }
}
</code>```

Test Code:

```<code>import java.util.Set;

class Test {
    public static void main(String[] args) {
        final Set<Class<?>> set = ClassUtil.getAllExtendedOrImplementedTypesRecursively(Foo.class);
        set.stream().map(Class::getName).forEach(System.out::println);
    }

    class Foo extends Bar implements I1, I2 {}
    class Bar implements I3 {}
    interface I1 extends I4, I5 {}
    interface I2 {}
    interface I3 {}
    interface I4 {}
    interface I5 {}
}
</code>```

Output:

```
Test$Foo
Test$Bar
Test$I2
Test$I5
Test$I1
Test$I3
Test$I4

```

Body:
I was wondering if there was an easy way of determining the complete list of Types that a Java class extends or implements recursively?

for instance:

class Foo extends Bar implements I1, I2 {...}
class Bar implements I3 {...}
interface I1 extends I4, I5 {...}
interface I2 {...}
interface I3 {...}
interface I4 {...}
interface I5 {...}

class ClassUtil {
    public static Set<Class<?>> getAllExtendedOrImplementedTypesRecursively(Class<?> clazz){
        ???
    }
}

import static org.junit.Assert.*;
public class ClassUtilTest {
    @Test
    public void shouldEqualClasses(){
        Set<Class<?>> types = ClassUtil.getAllExtendedOrImplementedTypesRecursively(Foo.class);
        Set<Class<?>> checklist = new HashSet<>();
        checklist.add(Foo.class);
        checklist.add(Bar.class);
        checklist.add(I1.class);
        checklist.add(I2.class);
        checklist.add(I3.class);
        checklist.add(I4.class);
        checklist.add(I5.class);
        assertTrue(checklist.containsAll(types));
        assertTrue(types.containsAll(checklist));
    }
}

Think Arquillian ShrinkWrap creation helper.

UPDATE: due to the Class object not implementing Comparable> I also need to find a way of creating a Set (or similar class) without implementing the Comparable interface (for instance, solely relying on the hashcode of the class object).

UPDATE: changed the test to use hashset. derp.

Body:
In Java8

import java.util.Arrays;
import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class ClassUtil {
    public static Set<Class<?>> getAllExtendedOrImplementedTypesRecursively(final Class<?> clazz) {
        return walk(clazz)
                .filter(Predicate.isEqual(java.lang.Object.class).negate())
                .collect(Collectors.toSet());
    }

    public static Stream<Class<?>> walk(final Class<?> c) {
        return Stream.concat(Stream.of(c),
                Stream.concat(
                        Optional.ofNullable(c.getSuperclass()).map(Stream::of).orElseGet(Stream::empty),
                        Arrays.stream(c.getInterfaces())
                ).flatMap(ClassUtil::walk));
    }
}

Test Code:

import java.util.Set;

class Test {
    public static void main(String[] args) {
        final Set<Class<?>> set = ClassUtil.getAllExtendedOrImplementedTypesRecursively(Foo.class);
        set.stream().map(Class::getName).forEach(System.out::println);
    }

    class Foo extends Bar implements I1, I2 {}
    class Bar implements I3 {}
    interface I1 extends I4, I5 {}
    interface I2 {}
    interface I3 {}
    interface I4 {}
    interface I5 {}
}

Output:

Test$Foo
Test$Bar
Test$I2
Test$I5
Test$I1
Test$I3
Test$I4


问:
Bash Check for Git Updates on Login
I am attempting to check my git repo if there are updates.
I need to do this when I login to my Ubuntu server, so I figured I would modify the /etc/update-motd.d/90-updates-available script with the following

It is supposed to cd into my repo once it is found, and then compare it to the remote repo, if remote is newer, print the notice.

```<code>#!/bin/sh

stamp="/var/lib/update-notifier/updates-available"

[ ! -r "$stamp" ] || cat "$stamp"

cd $(find / -wholename '*-Commander*/.git' | xargs -n 1 dirname)

UPSTREAM=${1:-'@{u}'}
LOCAL=$(git rev-parse @)
REMOTE=$(git rev-parse "$UPSTREAM")
BASE=$(git merge-base @ "$UPSTREAM")
echo "----------------------------------------------------------"
echo ""
if [ $LOCAL = $BASE ]; then
    echo "Repo Need to be Updated"
    MEM=$(free -m | grep -oP '\d+' | head -n 1);
    if [ $MEM -lt 2048 ]; then
        echo "Low Mem Check"
    fi;
fi;
echo ""
echo "----------------------------------------------------------"
</code>```

what I am finding is, no matter what.. on login to the machine, it still shows Repo Need to be Updated, even if it is up to date.

Note, the repo was pulled as a sudoer, logging into the machine does logs in as a normal user at first.

What am I doing wrong?

答:
The test should be:</p>

```<code>if [ "$LOCAL" == "$BASE" ]; then
</code>```

Title: Bash Check for Git Updates on Login

Body:
I am attempting to check my git repo if there are updates.
I need to do this when I login to my Ubuntu server, so I figured I would modify the /etc/update-motd.d/90-updates-available script with the following

It is supposed to cd into my repo once it is found, and then compare it to the remote repo, if remote is newer, print the notice.

#!/bin/sh

stamp="/var/lib/update-notifier/updates-available"

[ ! -r "$stamp" ] || cat "$stamp"

cd $(find / -wholename '*-Commander*/.git' | xargs -n 1 dirname)

UPSTREAM=${1:-'@{u}'}
LOCAL=$(git rev-parse @)
REMOTE=$(git rev-parse "$UPSTREAM")
BASE=$(git merge-base @ "$UPSTREAM")
echo "----------------------------------------------------------"
echo ""
if [ $LOCAL = $BASE ]; then
    echo "Repo Need to be Updated"
    MEM=$(free -m | grep -oP '\d+' | head -n 1);
    if [ $MEM -lt 2048 ]; then
        echo "Low Mem Check"
    fi;
fi;
echo ""
echo "----------------------------------------------------------"

what I am finding is, no matter what.. on login to the machine, it still shows Repo Need to be Updated, even if it is up to date.

Note, the repo was pulled as a sudoer, logging into the machine does logs in as a normal user at first.

What am I doing wrong?

Body:
The test should be:

if [ "$LOCAL" == "$BASE" ]; then


问:
How do I save a level layout in a variable
Currently, My next project is going to be a platformer and when I look around stackoverflow for research on several mechanics, I see many people doing the same thing: They save a layout with some variable, then go and unload it somewhere and it just renders in the game. I was interested, so I looked further and I found nothing on how to load/unload states like that, or maybe I'm just not wording my search correctly.

Either way, How do I do this?

ex: I would save a level layout as either an array or a single multi-line string and then somehow generate a single tile sprite for each letter, like T.

```<code>import pygame

# Storage method A
level = '''
X X X X X
X X X X X
T T X X X
X X X T T
T T T T T
'''

# Storage Method B

level2 = [
    'XXXXX',
    'XXXXX',
    'TTXXX',
    'XXXTT',
    'TTTTT'
]

# X is blank space, T is tiles

# Then what? Thats what I need to know.
# If someone already answered this and I'm just not using the right keywords let me know.
</code>```

答:
You could iterate over the enumerated rows and characters in the layout, create the tile instances and add them to a sprite group.

In the example I just give the tiles different colors depending on the character in the layout (X=blue, T=green) before I add them to the group, but you could also create completely different Tile types or subclasses if the character is a 'T' or an 'X'.

```<code>import pygame

class Tile(pygame.sprite.Sprite):

    def __init__(self, pos, color):
        super().__init__()
        self.image = pygame.Surface((50, 50))
        self.image.fill(color)
        self.rect = self.image.get_rect(topleft=pos)

def create_tile_group(layout):
    """Turn the layout into a sprite group with Tile instances."""
    group = pygame.sprite.Group()
    for y, row in enumerate(layout):
        for x, tile in enumerate(row):
            if tile == 'T':
                color = (50, 150, 50)
            else:
                color = (0, 0, 200)
            group.add(Tile((x*tile_size, y*tile_size), color))
    return group

pygame.init()
screen = pygame.display.set_mode((250, 250))
clock = pygame.time.Clock()

layout1 = [
    'XXXXX',
    'XTXXX',
    'XXXXT',
    'XXXXX',
    'TTTTT',
    ]

tile_size = 50
tile_group = create_tile_group(layout1)

loop = True
while loop:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            loop = False

    tile_group.update()

    screen.fill((30, 30, 30))
    tile_group.draw(screen)

    pygame.display.flip()
    clock.tick(30)
</code>```

If you get performance problems because you blit too many small surfaces, you could blit them onto a big background surface before the while loop starts and then just blit the background once each frame.

Body:
Currently, My next project is going to be a platformer and when I look around stackoverflow for research on several mechanics, I see many people doing the same thing: They save a layout with some variable, then go and unload it somewhere and it just renders in the game. I was interested, so I looked further and I found nothing on how to load/unload states like that, or maybe I'm just not wording my search correctly.

Either way, How do I do this?

ex: I would save a level layout as either an array or a single multi-line string and then somehow generate a single tile sprite for each letter, like T.

import pygame

# Storage method A
level = '''
X X X X X
X X X X X
T T X X X
X X X T T
T T T T T
'''

# Storage Method B

level2 = [
    'XXXXX',
    'XXXXX',
    'TTXXX',
    'XXXTT',
    'TTTTT'
]

# X is blank space, T is tiles

# Then what? Thats what I need to know.
# If someone already answered this and I'm just not using the right keywords let me know.

Body:
You could iterate over the enumerated rows and characters in the layout, create the tile instances and add them to a sprite group.

In the example I just give the tiles different colors depending on the character in the layout (X=blue, T=green) before I add them to the group, but you could also create completely different Tile types or subclasses if the character is a 'T' or an 'X'.

import pygame

class Tile(pygame.sprite.Sprite):

    def __init__(self, pos, color):
        super().__init__()
        self.image = pygame.Surface((50, 50))
        self.image.fill(color)
        self.rect = self.image.get_rect(topleft=pos)

def create_tile_group(layout):
    """Turn the layout into a sprite group with Tile instances."""
    group = pygame.sprite.Group()
    for y, row in enumerate(layout):
        for x, tile in enumerate(row):
            if tile == 'T':
                color = (50, 150, 50)
            else:
                color = (0, 0, 200)
            group.add(Tile((x*tile_size, y*tile_size), color))
    return group

pygame.init()
screen = pygame.display.set_mode((250, 250))
clock = pygame.time.Clock()

layout1 = [
    'XXXXX',
    'XTXXX',
    'XXXXT',
    'XXXXX',
    'TTTTT',
    ]

tile_size = 50
tile_group = create_tile_group(layout1)

loop = True
while loop:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            loop = False

    tile_group.update()

    screen.fill((30, 30, 30))
    tile_group.draw(screen)

    pygame.display.flip()
    clock.tick(30)

If you get performance problems because you blit too many small surfaces, you could blit them onto a big background surface before the while loop starts and then just blit the background once each frame.


问:
How do I modify a spring service to produce jsonl
I have a service consumer who wants my service to produce line delimited JSONL. How can I modify the Jackson parser or provide a custom serializer so that a retuned array of objects is serialized as JSONL and not JSON.

For example the following code

```<code>import java.util.Arrays;

import org.apache.commons.lang3.tuple.Pair;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class JsonlServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(JsonlServiceApplication.class, args);
    }

    @GetMapping("jsonl")
    private ResponseEntity<?> getJsonl(){
        Pair<String, String> p1 = Pair.of("foo", "baa");
        Pair<String, Integer> p2 = Pair.of("key", 10);

        return new ResponseEntity(Arrays.asList(p1, p2), HttpStatus.OK);
    }
}
</code>```

Will produce this JSON:

```<code>[
  {
    "foo": "baa"
  },
  {
    "key": 10
  }
]
</code>```

But the consumer would like:

```<code>{"foo": "baa"}
{"key": 10}
</code>```

答:
Maybe you can parse your json into an Object[] and iterate on each elem ? like that :</p>

```<code>public static void main(String[] args) {
        String json = "[{\"foo\":\"baa\"},{\"key\":10}]";
        Gson gson = new Gson();
        Object yourObj[] = gson.fromJson(json, Object[].class);
        Arrays.stream(yourObj).forEach(e -> {
            System.out.println(e);
        });
    }
</code>```

Body:
I have a service consumer who wants my service to produce line delimited JSONL. How can I modify the Jackson parser or provide a custom serializer so that a retuned array of objects is serialized as JSONL and not JSON.

For example the following code

import java.util.Arrays;

import org.apache.commons.lang3.tuple.Pair;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class JsonlServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(JsonlServiceApplication.class, args);
    }

    @GetMapping("jsonl")
    private ResponseEntity<?> getJsonl(){
        Pair<String, String> p1 = Pair.of("foo", "baa");
        Pair<String, Integer> p2 = Pair.of("key", 10);

        return new ResponseEntity(Arrays.asList(p1, p2), HttpStatus.OK);
    }
}

Will produce this JSON:

[
  {
    "foo": "baa"
  },
  {
    "key": 10
  }
]

But the consumer would like:

{"foo": "baa"}
{"key": 10}

Body:
Maybe you can parse your json into an Object[] and iterate on each elem ? like that :

public static void main(String[] args) {
        String json = "[{\"foo\":\"baa\"},{\"key\":10}]";
        Gson gson = new Gson();
        Object yourObj[] = gson.fromJson(json, Object[].class);
        Arrays.stream(yourObj).forEach(e -> {
            System.out.println(e);
        });
    }


问:
Sum values in one column of all rows which match one or more of multiple criteria
I have some table data in which I'd like to sum all the values in a specific column of all rows where column A contains string A and/or column B contains string B. How can I achieve this?

This works for one criterium:

```<code>=SUM(FILTER(G:G,REGEXMATCH(F:F,"stringA")))
</code>```

I tried this, but it didn't work:

```<code>=SUM(FILTER(G:G,OR(ISTEXT(REGEXMATCH(F:F,"stringA")),ISTEXT(REGEXMATCH(C:C,"stringB")))))
</code>```

答:
```<code>=SUM(FILTER(G:G,REGEXMATCH(F:F&C:C,"stringA|stringB")))
</code>```

OR is denoted by |

 EDIT     Added &C:C to denote different Columns

Body:
I have some table data in which I'd like to sum all the values in a specific column of all rows where column A contains string A and/or column B contains string B. How can I achieve this?

This works for one criterium:

=SUM(FILTER(G:G,REGEXMATCH(F:F,"stringA")))

I tried this, but it didn't work:

=SUM(FILTER(G:G,OR(ISTEXT(REGEXMATCH(F:F,"stringA")),ISTEXT(REGEXMATCH(C:C,"stringB")))))

Body:
=SUM(FILTER(G:G,REGEXMATCH(F:F&C:C,"stringA|stringB")))

OR is denoted by |

 EDIT     Added &C:C to denote different Columns


问:
What's the most elegant way of commenting / uncommenting blocks of ruby code in Vim?
In VIM, at the moment when I need to comment out a section of Ruby code:

I navigate to the first column in the row I want to comment out

I press CTRL-v to enter visual block mode

I navigate down till the place I want to end the operation

I type r<space> if I want to uncomment the code or r# if I want to comment it out.

This workflow seems ok to me, are there any ways of improving this process? Are there any other tricks for commenting or uncommenting ruby code sections in vim?

答:
I do almost the same thing as you.

commenting:

visual block select with CTRL-V then I# (insert # in the begining)

uncommenting:

visual block select with CTRL-V then X (delete the first symbol on the line)

Please note uppercase I and X.

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: jetxee


问:
what is the most pythonic way to split a 2d array to arrays of each row?
I have a function foo that returns an array with the shape (1000, 2)
how can I split it to two arrays a(1000) and b(1000)
I'm looking for something like this:

```<code>a;b = foo()
</code>```

I'm looking for an answer that can easily generalize to the case in which the shape is (1000, 5) or so.

答:
The zip(*...) idiom transposes a traditional more-dimensional Python list:

```<code>x = [[1,2], [3,4], [5,6]]

# get columns
a, b = zip(*x)   # zip(*foo())
# a, b = map(list, zip(*x))  # if you prefer lists over tuples
a
# (1, 3, 5)

# get rows
a, b, c = x
a
# [1, 2]
</code>```

Body:
I have a function foo that returns an array with the shape (1000, 2)
how can I split it to two arrays a(1000) and b(1000)
I'm looking for something like this:

a;b = foo()

I'm looking for an answer that can easily generalize to the case in which the shape is (1000, 5) or so.

Body:
The zip(*...) idiom transposes a traditional more-dimensional Python list:

x = [[1,2], [3,4], [5,6]]

# get columns
a, b = zip(*x)   # zip(*foo())
# a, b = map(list, zip(*x))  # if you prefer lists over tuples
a
# (1, 3, 5)

# get rows
a, b, c = x
a
# [1, 2]


问:
Why is the asp:ImageButton not firing the OnClick event?
I don't know why the  OnClick event is not working:

```<code><div  class="col-sm-1 pull-left" style="margin-top:20px">
    <asp:ImageButton ID="delete_file"
                     OnClientClick="return confirm('Are you Sure ?');"
                     OnClick="delete_file_Click"
                     CausesValidation="false"
                     Visible="false"
                     class="btn btn-lg btn-default pull-left"
                     runat="server"
                     ImageUrl="~/img/del.png" />
</div>
</code>```

c# code :

```<code> protected void delete_file_Click(object sender, ImageClickEventArgs e)
    {

        int index = GridView2.SelectedIndex;
        GridView2.DeleteRow(index);

    }
</code>```

答:
You have visible set to false.  So the image button does not get rendered to the page. It does not really exist.

try set style="display:none;"

Body:
I don't know why the  OnClick event is not working:

    <asp:ImageButton ID="delete_file"
                     OnClientClick="return confirm('Are you Sure ?');"
                     OnClick="delete_file_Click"
                     CausesValidation="false"
                     Visible="false"
                     class="btn btn-lg btn-default pull-left"
                     runat="server"
                     ImageUrl="~/img/del.png" />

c# code :

 protected void delete_file_Click(object sender, ImageClickEventArgs e)
    {

        int index = GridView2.SelectedIndex;
        GridView2.DeleteRow(index);

    }


问:
Vector of strings reports the error "str does not have a constant size known at compile time"
When trying to print out the contents of a multidimensional vector in Rust, it seems as though you cannot use the type Vec<Vec<str>> for the vector.

```<code>fn print_multidimensional_array(multi: &Vec<Vec<str>>) {
    for y in 0..multi.len() {
        for x in 0..multi[y].len() {
            print!("{} ", multi[y][x]);
        }
        println!("");
    }
}
</code>```

With this code, I get the output:

error[E0277]: the trait bound `str: std::marker::Sized` is not satisfied
 --> src/main.rs:1:1
  |
1 | / fn print_multidimensional_array(multi: &Vec<Vec<str>>) {
2 | |     for y in 0..multi.len() {
3 | |         for x in 0..multi[y].len() {
4 | |             print!("{} ", multi[y][x]);
... |
7 | |     }
8 | | }
  | |_^ `str` does not have a constant size known at compile-time
  |
  = help: the trait `std::marker::Sized` is not implemented for `str`
  = note: required by `std::vec::Vec`
```

What type of vector could I use for this to work?

答:
Use Vec<Vec<&str>>.

```<code>fn print_multidimensional_array(multi: &[Vec<&str>]) {
    for y in multi {
        for v in y {
            print!("{} ", v);
        }
        println!();
    }
}

fn main() {
    let v = vec![vec!["a", "b"], vec!["c", "d"]];
    print_multidimensional_array(&v);
}
</code>```

See also:

What does “`str` does not have a constant size known at compile-time” mean, and what's the simplest way to fix it?

What does "Sized is not implemented" mean?

Why is it discouraged to accept a reference to a String (&String), Vec (&Vec), or Box (&Box) as a function argument?

Passing Vec<String> as IntoIterator<&'a str>

What are the differences between Rust's `String` and `str`?

Because I like to make things overly generic...

```<code>fn print_multidimensional_array<I>(multi: I)
where
    I: IntoIterator,
    I::Item: IntoIterator,
    <I::Item as IntoIterator>::Item: AsRef<str>,
{
    for y in multi {
        for v in y {
            print!("{} ", v.as_ref());
        }
        println!();
    }
}

fn main() {
    let v1 = vec![vec!["a", "b"], vec!["c", "d"]];
    let v2 = vec![["a", "b"], ["c", "d"]];
    let v3 = [vec!["a", "b"], vec!["c", "d"]];
    let v4 = [["a", "b"], ["c", "d"]];

    print_multidimensional_array(&v1);
    print_multidimensional_array(&v2);
    print_multidimensional_array(&v3);
    print_multidimensional_array(&v4);
}
</code>```

Body:
When trying to print out the contents of a multidimensional vector in Rust, it seems as though you cannot use the type Vec<Vec<str>> for the vector.

fn print_multidimensional_array(multi: &Vec<Vec<str>>) {
    for y in 0..multi.len() {
        for x in 0..multi[y].len() {
            print!("{} ", multi[y][x]);
        }
        println!("");
    }
}

With this code, I get the output:

error[E0277]: the trait bound `str: std::marker::Sized` is not satisfied
 --> src/main.rs:1:1
  |
1 | / fn print_multidimensional_array(multi: &Vec<Vec<str>>) {
2 | |     for y in 0..multi.len() {
3 | |         for x in 0..multi[y].len() {
4 | |             print!("{} ", multi[y][x]);
... |
7 | |     }
8 | | }
  | |_^ `str` does not have a constant size known at compile-time
  |
  = help: the trait `std::marker::Sized` is not implemented for `str`
  = note: required by `std::vec::Vec`

What type of vector could I use for this to work?

Body:
Use Vec<Vec<&str>>.

fn print_multidimensional_array(multi: &[Vec<&str>]) {
    for y in multi {
        for v in y {
            print!("{} ", v);
        }
        println!();
    }
}

fn main() {
    let v = vec![vec!["a", "b"], vec!["c", "d"]];
    print_multidimensional_array(&v);
}

See also:

What does “`str` does not have a constant size known at compile-time” mean, and what's the simplest way to fix it?

What does "Sized is not implemented" mean?

Why is it discouraged to accept a reference to a String (&String), Vec (&Vec), or Box (&Box) as a function argument?

Passing Vec<String> as IntoIterator<&'a str>

What are the differences between Rust's `String` and `str`?

Because I like to make things overly generic...

fn print_multidimensional_array<I>(multi: I)
where
    I: IntoIterator,
    I::Item: IntoIterator,
    <I::Item as IntoIterator>::Item: AsRef<str>,
{
    for y in multi {
        for v in y {
            print!("{} ", v.as_ref());
        }
        println!();
    }
}

fn main() {
    let v1 = vec![vec!["a", "b"], vec!["c", "d"]];
    let v2 = vec![["a", "b"], ["c", "d"]];
    let v3 = [vec!["a", "b"], vec!["c", "d"]];
    let v4 = [["a", "b"], ["c", "d"]];

    print_multidimensional_array(&v1);
    print_multidimensional_array(&v2);
    print_multidimensional_array(&v3);
    print_multidimensional_array(&v4);
}


问:
Binding an Angular Material Selection List
I am creating a Toolbar with a selection list (checkboxes with each list item) using Angular Material 2. I just cannot figure out how to set the checkboxes before the list is displayed and then get the selected items following user interaction.

I am trying the control within a Form thinking I may need this to bind to ngModel, but this doesn't seem to help. My html so far is:

<form
  novalidate
  #areaSelectForm="ngForm">

    <mat-selection-list
                        #areasList="ngModel"
                        [(ngModel)]="model"
                        id="areaListControl"
                        name="areaListControl"
                        (ngModelChange)="onAreaListControlChanged($event)">
        <mat-list-option *ngFor="let tta of taskTypeAreas" (click)="onCheckboxClick($event)" [value]="tta">
            {{tta}}
        </mat-list-option>
    </mat-selection-list>

</form>
```

This must be a well trodden path but the documentation is difficult to interpret and I cannot seem to find any suitable examples.

Any guidance very welcome please.

答:
As of version 5.0.0, angular material now supports ngModel for selection list.

So the code can be simplified to

<mat-selection-list #list [(ngModel)]="selectedOptions" (ngModelChange)="onNgModelChange($event)">
    <mat-list-option *ngFor="let tta of taskTypeAreas" [value]="tta.name">
        {{tta.name}}
    </mat-list-option>
</mat-selection-list>
```

<p>The release also exposes an <code>ngModelChange</code> event for selection list. Here is the updated stack blitz</p>

<hr>

<p><em>(Original answer before Angular 5.0.0)</em></p>

<p>It appears mat-selection-list does not currently support ngModel (https://github.com/angular/material2/pull/7456), but it looks like it will be supported in the near future. In the meantime you can use a reference variable <code>#list</code> to grab the selected options.</p>

```// component.html
```

<pre class="lang-xml prettyprint-override"><code><mat-selection-list #list>
    <mat-list-option *ngFor="let tta of taskTypeAreas" [selected]="tta.selected"
        (click)="onAreaListControlChanged(list)" [value]="tta.name">
        {{tta.name}}
    </mat-list-option>
</mat-selection-list>
</code>```

Then pass in the reference variable to your onAreaListControlChanged(list) method so you can parse out the selected options.

```<code>// component.ts
</code>```

onAreaListControlChanged(list){
    this.selectedOptions = list.selectedOptions.selected.map(item => item.value);
}
```

<p>To select the checkboxes on load, you can use the <code>[selected]</code> property of each <code><mat-list-option></code>. </p>

<pre class="lang-xml prettyprint-override"><code><mat-list-option ... [selected]="tta.selected" ...>
</code>```

To do this you'll need to add another property to your array.

```<code>// component.ts
</code>```

taskTypeAreas: {
    name: string;
    selected: boolean;
}[] = [
    {
        name: 'Area 1',
        selected: false
    },
    {
        name: 'Area 2',
        selected: false
    },
    {
        name: 'Area 3',
        selected: true
    },
];
```

This will make Area 3 be selected on load. Here is a stackblitz demoing this.

Body:
I am creating a Toolbar with a selection list (checkboxes with each list item) using Angular Material 2. I just cannot figure out how to set the checkboxes before the list is displayed and then get the selected items following user interaction.

I am trying the control within a Form thinking I may need this to bind to ngModel, but this doesn't seem to help. My html so far is:

<form
  novalidate
  #areaSelectForm="ngForm">

    <mat-selection-list
                        #areasList="ngModel"
                        [(ngModel)]="model"
                        id="areaListControl"
                        name="areaListControl"
                        (ngModelChange)="onAreaListControlChanged($event)">
        <mat-list-option *ngFor="let tta of taskTypeAreas" (click)="onCheckboxClick($event)" [value]="tta">
            {{tta}}
        </mat-list-option>
    </mat-selection-list>

</form>

This must be a well trodden path but the documentation is difficult to interpret and I cannot seem to find any suitable examples.

Any guidance very welcome please.

Body:
As of version 5.0.0, angular material now supports ngModel for selection list.

So the code can be simplified to

<mat-selection-list #list [(ngModel)]="selectedOptions" (ngModelChange)="onNgModelChange($event)">
    <mat-list-option *ngFor="let tta of taskTypeAreas" [value]="tta.name">
        {{tta.name}}
    </mat-list-option>
</mat-selection-list>

The release also exposes an ngModelChange event for selection list. Here is the updated stack blitz

(Original answer before Angular 5.0.0)

It appears mat-selection-list does not currently support ngModel (https://github.com/angular/material2/pull/7456), but it looks like it will be supported in the near future. In the meantime you can use a reference variable #list to grab the selected options.

// component.html

<mat-selection-list #list>
    <mat-list-option *ngFor="let tta of taskTypeAreas" [selected]="tta.selected"
        (click)="onAreaListControlChanged(list)" [value]="tta.name">
        {{tta.name}}
    </mat-list-option>
</mat-selection-list>

Then pass in the reference variable to your onAreaListControlChanged(list) method so you can parse out the selected options.

// component.ts

onAreaListControlChanged(list){
    this.selectedOptions = list.selectedOptions.selected.map(item => item.value);
}

To select the checkboxes on load, you can use the [selected] property of each <mat-list-option>.

<mat-list-option ... [selected]="tta.selected" ...>

To do this you'll need to add another property to your array.

// component.ts

taskTypeAreas: {
    name: string;
    selected: boolean;
}[] = [
    {
        name: 'Area 1',
        selected: false
    },
    {
        name: 'Area 2',
        selected: false
    },
    {
        name: 'Area 3',
        selected: true
    },
];

This will make Area 3 be selected on load. Here is a stackblitz demoing this.


问:
EF Core 1.1 Soft (or logical) Delete
I'm trying to implement Soft Delete in a .NET Core 1.1.* Web App, backed by Entity Framework Core 1.1.*. I'm using Sql Server as my DB.

Migrating to .NET core 2.* is not an option at the moment.

After reading books, tuts and 3ds, I've implemented this feature using a Discriminator column. The deletion procedure is apparently working as expected. What's wrong is the data retrieval: deleted entities are still shown within my EF query results.

Current situation

Here's some C# code. I'll keep things as simple as possible

The interfaces:

```<code>// Soft deletion interface
public intercace ISoftDeletable
{}

// Another interface for some shadow properties
public interface IEntity
{}
</code>```

The base class:

```<code>public abstract class Entity : IEntity, ISoftDeletable
{
   public int MyBaseProp { get; set; }
}
</code>```

One of my derived classes:

```<code>public class MyDerivedEntity: Entity
{
   public string Name { get; set; }

   public IList<MyChildEntity> Children { get; set; }

}

public class MyChildEntity: Entity
{
    public string MyChildProp { get; set; }
}
</code>```

The Context

```<code>public class MyContext: DbContext
{
   public MyContext(DbContextOptions<MyContext> options)
            : base(options)
   { }

   public DbSet<MyDerivedEntity> EntitiesToUse { get; set; }

   protected override void OnModelCreating(ModelBuilder builder)
   {
      foreach (var entity in builder.Model.GetEntityTypes())
      {
         if (typeof(IEntity).IsAssignableFrom(entity.ClrType))
         {
           builder.Entity(entity.ClrType).Property<string>("MyShadowProperty");
         }

         if (typeof(ISoftDeletable).IsAssignableFrom(entity.ClrType))
         {
            // Discriminator column
            builder.Entity(entity.ClrType).HasDiscriminator("IsDeleted", typeof(bool)).HasValue(false);
            // Shadow Property
            builder.Entity(entity.ClrType).Property(typeof(bool), "IsDeleted").IsRequired(true).HasDefaultValue(false);

            builder.Entity(entity.ClrType).Property(typeof(bool), "IsDeleted").Metadata.IsReadOnlyAfterSave = false;
         }
      }

      // Other model configurations

      base.OnModelCreating(builder);
   }

   // SaveChangesAsync are almost the same
   public override int SaveChanges()
   {
       AuditEntities();

       return base.SaveChanges();
   }

   private void AuditEntities()
   {

      foreach (EntityEntry<IEntity> entry in ChangeTracker.Entries<IEntity>())
      {
         // do something with MyShadowProperty...
      }
      foreach (EntityEntry<ISoftDeletable> entry in changeTracker.Entries<ISoftDeletable>().Where(w => w.State == EntityState.Deleted))
      {
        // Set the entity as Softly Deleted
        entry.Property("IsDeleted").CurrentValue = true;
        // Ensure the entity state is modified to prevend hard deletion
        entry.State = EntityState.Modified;
      }
   }
}
</code>```

The Problem

Everything works as expected, except the data retrieval.
Here's a sample call:

```<code>var results = await _context.EntitiesToUse.Include(e => e.SomeChildEntity).AsNoTracking();
</code>```

I expect the results to include only available myDerivedEntities with .IsDeleted == false. The problem is that my deleted entities are not filtered out. Why?

Please, what's wrong with my code? Am I missing something?

Thank you all so much!

答:
Entity Framework Core 2.0 supports Global Query Filter

```<code>protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<ISoftDeletable>().HasQueryFilter(e => !e.IsDeleted);

    base.OnModelCreating(modelBuilder);
}
</code>```

You can find more info and examples here

I recommend you the built-in EF Core Global Query Filter but in some situations, Entity Framework Plus could also help.

Disclaimer: I'm the owner of this project

EF+ Query Filter allows you to filter DbSet Globally and by Instance.

```<code>// using Z.EntityFramework.Plus; // Don't forget to include this.
var ctx = new EntitiesContext();

ctx.Filter<IUser>(q => q.Where(x => !x.IsSystemUser ));

// SELECT * FROM Customers WHERE IsSystemUser = FALSE
var list = ctx.Customers.ToList();
</code>```

Wiki: EF+ Query Filter

EDIT: Answer sub-question

Please, Is your library compatible with EF Core 1.1

Yes, it should be compatible with .NET Standard 1.3

Title: EF Core 1.1 Soft (or logical) Delete

Body:
I'm trying to implement Soft Delete in a .NET Core 1.1.* Web App, backed by Entity Framework Core 1.1.*. I'm using Sql Server as my DB.

Migrating to .NET core 2.* is not an option at the moment.

After reading books, tuts and 3ds, I've implemented this feature using a Discriminator column. The deletion procedure is apparently working as expected. What's wrong is the data retrieval: deleted entities are still shown within my EF query results.

Current situation

Here's some C# code. I'll keep things as simple as possible

The interfaces:

// Soft deletion interface
public intercace ISoftDeletable
{}

// Another interface for some shadow properties
public interface IEntity
{}

The base class:

public abstract class Entity : IEntity, ISoftDeletable
{
   public int MyBaseProp { get; set; }
}

One of my derived classes:

public class MyDerivedEntity: Entity
{
   public string Name { get; set; }

   public IList<MyChildEntity> Children { get; set; }

}

public class MyChildEntity: Entity
{
    public string MyChildProp { get; set; }
}

The Context

public class MyContext: DbContext
{
   public MyContext(DbContextOptions<MyContext> options)
            : base(options)
   { }

   public DbSet<MyDerivedEntity> EntitiesToUse { get; set; }

   protected override void OnModelCreating(ModelBuilder builder)
   {
      foreach (var entity in builder.Model.GetEntityTypes())
      {
         if (typeof(IEntity).IsAssignableFrom(entity.ClrType))
         {
           builder.Entity(entity.ClrType).Property<string>("MyShadowProperty");
         }

         if (typeof(ISoftDeletable).IsAssignableFrom(entity.ClrType))
         {
            // Discriminator column
            builder.Entity(entity.ClrType).HasDiscriminator("IsDeleted", typeof(bool)).HasValue(false);
            // Shadow Property
            builder.Entity(entity.ClrType).Property(typeof(bool), "IsDeleted").IsRequired(true).HasDefaultValue(false);

            builder.Entity(entity.ClrType).Property(typeof(bool), "IsDeleted").Metadata.IsReadOnlyAfterSave = false;
         }
      }

      // Other model configurations

      base.OnModelCreating(builder);
   }

   // SaveChangesAsync are almost the same
   public override int SaveChanges()
   {
       AuditEntities();

       return base.SaveChanges();
   }

   private void AuditEntities()
   {

      foreach (EntityEntry<IEntity> entry in ChangeTracker.Entries<IEntity>())
      {
         // do something with MyShadowProperty...
      }
      foreach (EntityEntry<ISoftDeletable> entry in changeTracker.Entries<ISoftDeletable>().Where(w => w.State == EntityState.Deleted))
      {
        // Set the entity as Softly Deleted
        entry.Property("IsDeleted").CurrentValue = true;
        // Ensure the entity state is modified to prevend hard deletion
        entry.State = EntityState.Modified;
      }
   }
}

The Problem

Everything works as expected, except the data retrieval.
Here's a sample call:

var results = await _context.EntitiesToUse.Include(e => e.SomeChildEntity).AsNoTracking();

I expect the results to include only available myDerivedEntities with .IsDeleted == false. The problem is that my deleted entities are not filtered out. Why?

Please, what's wrong with my code? Am I missing something?

Thank you all so much!

Body:
Entity Framework Core 2.0 supports Global Query Filter

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<ISoftDeletable>().HasQueryFilter(e => !e.IsDeleted);

    base.OnModelCreating(modelBuilder);
}

You can find more info and examples here

I recommend you the built-in EF Core Global Query Filter but in some situations, Entity Framework Plus could also help.

Disclaimer: I'm the owner of this project

EF+ Query Filter allows you to filter DbSet Globally and by Instance.

// using Z.EntityFramework.Plus; // Don't forget to include this.
var ctx = new EntitiesContext();

ctx.Filter<IUser>(q => q.Where(x => !x.IsSystemUser ));

// SELECT * FROM Customers WHERE IsSystemUser = FALSE
var list = ctx.Customers.ToList();

Wiki: EF+ Query Filter

EDIT: Answer sub-question

Please, Is your library compatible with EF Core 1.1

Yes, it should be compatible with .NET Standard 1.3


问:
How can I use Data Objects instead of a String[][]
I'm calling a RESTful api which gives me the following response:

```<code>{
    "asks": [
        [
            "219.82",
            "2.19"
        ],
        [
            "219.83",
            "6.05"
        ]
    ],
    "bids": [
        [
            "219.40",
            "17.46"
        ],
        [
            "219.13",
            "53.93"
        ]
    ]
}
</code>```

My data object implementation looks now like this:

```<code>public class OrderBook implements Serializable {

    /**
     * list containing the price and amount of all bid orders
     */
    private String[][] bids;

    /**
     * list containing the price and amount
     * of all ask orders
     */
    private String[][] asks;
}
</code>```

How can I replace this String[][] with a data object and ensure that GSON can still parse it?

The api is external and I cant there change anything. The result is an array of an array with two properties. Instead of parsing this in java with GSON in a String[][], I'd like to have a Asks and Bids class. The Asks class should contain an array of the object Ask and the object Ask should have two variables: which are value and amount as String. This is what I'd like to have in my java code.

答:
If I understand you correctly, you want to change the type of bids from String[][] to Object.

If you do that, you would have to look into creating a custom deserializer for that class. See here for details.

But then: don't do that. Why do you want give up on type safety? The quality of your Java source code does not improve when you willingly reduce the type information.

Body:
I'm calling a RESTful api which gives me the following response:

{
    "asks": [
        [
            "219.82",
            "2.19"
        ],
        [
            "219.83",
            "6.05"
        ]
    ],
    "bids": [
        [
            "219.40",
            "17.46"
        ],
        [
            "219.13",
            "53.93"
        ]
    ]
}

My data object implementation looks now like this:

public class OrderBook implements Serializable {

    /**
     * list containing the price and amount of all bid orders
     */
    private String[][] bids;

    /**
     * list containing the price and amount
     * of all ask orders
     */
    private String[][] asks;
}

How can I replace this String[][] with a data object and ensure that GSON can still parse it?

The api is external and I cant there change anything. The result is an array of an array with two properties. Instead of parsing this in java with GSON in a String[][], I'd like to have a Asks and Bids class. The Asks class should contain an array of the object Ask and the object Ask should have two variables: which are value and amount as String. This is what I'd like to have in my java code.


问:
.Net Application extrem slow. After killing svchost.exe it runs again fast. Any idea?
I've a C# .Net 3.5 Application (x86) running on Windows7 x64.

For any reason after a few days or weeks the App runs extremly slow.

All other Apps runs normal (also another C# .Net 3.5 Application (x86)).

After killing a few svchost.exe the Application runs normal again. Rebooting without killing svchost.exe also doesn't help. Probably Windows saves the state of svchost.exe. If I logoff the user and login again it also works again, without killing the svchost. On logoff the svchost is probably cleared.

Does anybody have an idea how to solve the problem?

Greets
Wowa

EDIT:

The Main-Form is just an MDI-Container with a Treeview on the left-side with static nodes.

The Application checks on start for Updates via networkpath (checks files creationdate), but this can't be the problem, because all other PC works without a problem.

After the Update every MDI-child-form takes 1-2 minutes to start, even a empty form.

EDIT:
Sorry, i've forgot, that the updating is no more done by this application, but by another, which has nothing to do with the app which runs slow.

The app which updates the slow app runs normal. It only updates the slow app if it isn't running.

But the slow App removes files in the local Temp-path. System.IO.File.Delete()

答:
Same thing has been weighing us down.
Acrobat InDesign CS5 ME ver. (x86 app)
We have tried and tried again (Win7 64; 2gb; 1gb video card). I have noticed scvhost @ 50,000 sitting in Taskmanager; killed it, but comes back. We haven't upgraded yet because of this.
We run the same app on XP-32, and also have some trouble, but that i more likely because of only 128mb video memory (2 P4 chips, 4gb mem).
I have peeked in ProExp but didn't know HOW to look. Thanks for the tip.
Hey, I'm a plain guy, not a pro programmer.</p>


问:
Sliders not showing up: setREVStartSize is not defined
After I upgrade my Revolution slider plugin (5.4.5.1) for Wordpress (4.8) I start to get this error: setREVStartSize is not defined

I'm trying differents approaches to fix this but without success. Is this a specific js file to be loaded in order to fix this? I don't if my theme is loading all assets.

Thanks!

答: Another possible cause is your setting in RevSlider Global settings. Turning off 'Include RevSlider libraries globally' and then trying to include a slider on a page that is not explicitly defined by ID in the field 'Pages to include RevSlider libraries' will trigger this error. The latter field does not take page slugs, so it should be a comma separated list of IDs and/or homepage.


问:
Iterate java set for first 1000 objects to create custom sql query
I'm trying to write an sql query which runs over a set and sees if the id is in the set but it gives the error that only 1000 items can be in the array. I'm trying to solve it but I got stuck here:

```<code>        for (int i = 0; i < e.getEmployeeSet().size(); i+=1000) {
                sqlQuery.append("AND employee.id");
            if(!e.incudeEmployee()){
                sqlQuery.append("NOT ");
            }
            sqlQuery.append("IN (");
            for(Employee employee: e.getEmployeeSet().){
                sqlQuery.append(employee.getEmployeeId())
                        .append(",");
            }
            sqlQuery.deleteCharAt(sqlQuery.length()-1)
                    .append(") ");
        }
</code>```

I still have to figure out that the first time it has to be AND id.., the other times it has to be OR ... and I have to go over the set in a way that the first time I only go over the first 1000 employee's and so on. Any clean way to fix this?

答:
You can modify your sql to be like:

```<code>SELECT /* or UPDATE (whatever you do) */
...
WHERE
 employee.id IN (... first thousand elements ...)
 OR
 employee.id IN (... next thousand elements ...)
 OR
 ... and so on ...
</code>```

Your Java code will be slightly different to produce "OR employee.id IN" block for each thousand of ids

UPD: to make it just introduce another counter to do like (pseudo code):

```<code>counter=0;
for each employeeId {
  if counter equals 1000 {
    complete current IN block;
    counter=0;
    if not first thousand {
      start new OR block;
    }
    start new IN block;
  }
  add employeeId into IN block;
  counter++;
}
</code>```

but important: I do not recommend go the way as you do either with or without OR blocks

It is because construct SQL as you do is direct way to SQL injection.
To avoid it just follow simple rule:

No any actual data must be inline in SQL String. All data must be passed to Query as parameters

You have to use prepared SQL statement with parameters for employee.id values.

Also: Simple way is to run separate query for each 1000 ids in the loop

Body:
I'm trying to write an sql query which runs over a set and sees if the id is in the set but it gives the error that only 1000 items can be in the array. I'm trying to solve it but I got stuck here:

        for (int i = 0; i < e.getEmployeeSet().size(); i+=1000) {
                sqlQuery.append("AND employee.id");
            if(!e.incudeEmployee()){
                sqlQuery.append("NOT ");
            }
            sqlQuery.append("IN (");
            for(Employee employee: e.getEmployeeSet().){
                sqlQuery.append(employee.getEmployeeId())
                        .append(",");
            }
            sqlQuery.deleteCharAt(sqlQuery.length()-1)
                    .append(") ");
        }

I still have to figure out that the first time it has to be AND id.., the other times it has to be OR ... and I have to go over the set in a way that the first time I only go over the first 1000 employee's and so on. Any clean way to fix this?

Body:
You can modify your sql to be like:

SELECT /* or UPDATE (whatever you do) */
...
WHERE
 employee.id IN (... first thousand elements ...)
 OR
 employee.id IN (... next thousand elements ...)
 OR
 ... and so on ...

Your Java code will be slightly different to produce "OR employee.id IN" block for each thousand of ids

UPD: to make it just introduce another counter to do like (pseudo code):

counter=0;
for each employeeId {
  if counter equals 1000 {
    complete current IN block;
    counter=0;
    if not first thousand {
      start new OR block;
    }
    start new IN block;
  }
  add employeeId into IN block;
  counter++;
}

but important: I do not recommend go the way as you do either with or without OR blocks

It is because construct SQL as you do is direct way to SQL injection.
To avoid it just follow simple rule:

No any actual data must be inline in SQL String. All data must be passed to Query as parameters

You have to use prepared SQL statement with parameters for employee.id values.

Also: Simple way is to run separate query for each 1000 ids in the loop


问:
Can
 be used as a flexbox container?

serves as a good flexbox container for
.

However, when I try to use
 as a container for other inline items like  or  it doesn't work.

Am I doing something wrong (example below) or does the
 not make a good flexbox container?

See this example pen in action: http://codepen.io/bobtabor/pen/PWyZBQ

Here is my DESIRED result:

HOWEVER this is my ACTUAL result:

In this example, I want the font-awesome pencil icon aligned to the right of each
.  I would expect to define a class with the align-self: flex-end property like so:

```<code>.fa-pencil {
  align-self: flex-end;
}
</code>```

... to take care of this.  However, when I run this in Chrome or Edge on Windows, the .fa-pencil aligns to the left (the start).

I have simple HTML markup:

```<code><section>
  <ul>
    <li>
      <i class="fa fa-bars"></i>
      <span>Item 1</span>
      <i class="fa fa-pencil"></i>
    </li>

    <li>
      <i class="fa fa-bars"></i>
      <span>Item 2</span>
      <i class="fa fa-pencil"></i>
    </li>

    <li>
      <i class="fa fa-bars"></i>
      <span>Item 3</span>
      <i class="fa fa-pencil"></i>
    </li>
  </ul>
</section>
</code>```

And here's the relevant CSS:

```<code>ul, li {
  list-style-type: none;
  list-style-position:inside;
  margin:0;
  padding:0;
}

ul {
  display: flex;
  flex-direction: column;
}

li {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  border: 1px solid black;
  margin-bottom: 10px;
  padding: 20px;
  font-size: 1.5em;
}

.fa-bars {
}

.fa-pencil {
  align-self: flex-end;
}
</code>```

I've been able to confirm that
's children are, in fact, responding to Flexbox because I can set the order of .fa-bars like so:

```<code>.fa-bars {
  order: 2;
}
</code>```

... and see the bars icon respond accordingly.

答:
You can do it using justify-content: space-between; even better.

Modified code on codepen

Title: Can <li> be used as a flexbox container?

Body:
serves as a good flexbox container for
.

However, when I try to use
 as a container for other inline items like  or  it doesn't work.

Am I doing something wrong (example below) or does the
 not make a good flexbox container?

See this example pen in action: http://codepen.io/bobtabor/pen/PWyZBQ

Here is my DESIRED result:

HOWEVER this is my ACTUAL result:

In this example, I want the font-awesome pencil icon aligned to the right of each
.  I would expect to define a class with the align-self: flex-end property like so:

.fa-pencil {
  align-self: flex-end;
}

... to take care of this.  However, when I run this in Chrome or Edge on Windows, the .fa-pencil aligns to the left (the start).

I have simple HTML markup:

      Item 1

      Item 2

      Item 3

And here's the relevant CSS:

ul, li {
  list-style-type: none;
  list-style-position:inside;
  margin:0;
  padding:0;
}

ul {
  display: flex;
  flex-direction: column;
}

li {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  border: 1px solid black;
  margin-bottom: 10px;
  padding: 20px;
  font-size: 1.5em;
}

.fa-bars {
}

.fa-pencil {
  align-self: flex-end;
}

I've been able to confirm that
's children are, in fact, responding to Flexbox because I can set the order of .fa-bars like so:

.fa-bars {
  order: 2;
}

... and see the bars icon respond accordingly.


问:
On ENTER keyup - Execute Function inside form and not submit the form
I have a table with filterable data using the jQuery DataTables library.
This table is inside a form that, when rows are CHECKED (in one column there is a checkbox), the SUBMIT button will add them to a collection.

Attached to the table is a custom search filter that functions like the built-in search filter that comes with DataTables, but instead of a "filter as you type" functionality, I have a submit button attached so that it will not filter the table results until you click the button.  There is some functionality added to that search filter that actually runs an ajax call to a database, and to reduce the amount of calls to the database, I put the button on the search filter and disabled the "filter as you type" functionality.

I STILL want to be able to click the ENTER key on my keyboard when I have finished typing in my search filter to execute this custom search, but I am unable to stop the form from submitting.  I have the custom search filter in a function called "tableFilter()". The ID of the form is "#addtitle"

```<code>$("#addTitle").on('keyup', function(e){
        var keyCode = e.keyCode || e.which;
        console.log('keyup');
        if (keyCode == 13){
            console.log('ENTER PRESSED');
            if ($("#dataTables_filter_input").is(":focus")){
                console.log('FILTER FOCUS');
                tableFilter();
                e.preventDefault();
                return false;
            }
        }
    });
</code>```

I figured that if the input field of the search was still in focus, that would be enough of a difference for the code to know that when I click ENTER, it would execute the search filter and not submit the form - yet the form still submits.

Do I have things out of order? Am I not calling the right functions?

答:
```<code>let cancelEvent = function (e) {
  e.preventDefault();
  return false;
};

let filter = document.getElementById('dataTables_filter_input');
let addTitle = document.getElementById('addTitle');
let form = document.querySelector('form');

form.addEventListener('submit', cancelEvent);

addTitle.addEventListener('keyup', function(e) {
  let keyCode = e.keyCode || e.which;

  console.log('KEYUP');

  if (keyCode !== 13 || !filter.is(':focus')) {
    console.log('NOT ENTER PRESSED OR FILTER NOT FOCUS');
    return true;
  }

  tableFilter();
  e.preventDefault();
  return false;
});
</code>```

Body:
I have a table with filterable data using the jQuery DataTables library.
This table is inside a form that, when rows are CHECKED (in one column there is a checkbox), the SUBMIT button will add them to a collection.

Attached to the table is a custom search filter that functions like the built-in search filter that comes with DataTables, but instead of a "filter as you type" functionality, I have a submit button attached so that it will not filter the table results until you click the button.  There is some functionality added to that search filter that actually runs an ajax call to a database, and to reduce the amount of calls to the database, I put the button on the search filter and disabled the "filter as you type" functionality.

I STILL want to be able to click the ENTER key on my keyboard when I have finished typing in my search filter to execute this custom search, but I am unable to stop the form from submitting.  I have the custom search filter in a function called "tableFilter()". The ID of the form is "#addtitle"

$("#addTitle").on('keyup', function(e){
        var keyCode = e.keyCode || e.which;
        console.log('keyup');
        if (keyCode == 13){
            console.log('ENTER PRESSED');
            if ($("#dataTables_filter_input").is(":focus")){
                console.log('FILTER FOCUS');
                tableFilter();
                e.preventDefault();
                return false;
            }
        }
    });

I figured that if the input field of the search was still in focus, that would be enough of a difference for the code to know that when I click ENTER, it would execute the search filter and not submit the form - yet the form still submits.

Do I have things out of order? Am I not calling the right functions?


问:
Date type object gets converted into String while returning using res.json
I have a date object, lets say var myDate = new Date().

Now when I am returning it using res.json({msg: {myDate: myDate}}) the myDate object gets converted into string.I want that the type of myDate should persist. I am using mongoose ODM and express.

答: JSON doesn't have a date type, which means you have to convert it to date when it reaches the front-end. The JSON spec is here.</p>


问:
dlclose a library loaded with RTLD_NODELETE
I can't understand the full sense of closing with dlclose a library opened with dlopen and the RTLD_NODELETE. If I correctly understand RTLD_NODELETE makes the library stay in memory until the end of program execution, so dlclosing it has no effect on memory occupancy. So is it really a bad practice not calling dlclose in this case? If so, why?
Thanks.</p>

答:
As for the original question, the answer is no - you don't need to call dlclose on RTLD_NODELETE library as it won't do anything.

On the other hand instead of keeping all your plugins loaded forever (wasting resources e.g. memory) you could link them all to a helper shared library that would hold shared state (i.e. global symbol you mentioned). This library would get loaded with the first plugin and unloaded with the last one.


问:
Expanding fields not working fully on SharePoint Lists
I am following the documentation for Get metadata for a list.

Querying using either PowerShell or the Graph Explorer fails to fully expand the fields for items in a SharePoint list.

An example of this is a lookup field called Responsible that looks up users in Azure Active Directory (or in SharePoint terms, the column is a Person or Group column, limited to people only).

Once selected via the GUI, it's populated with a display name (although I'd hope for more definitive information to be stored on the back end, like UPN).

When querying the Graph API using the form:

$Uri = "https://graph.microsoft.com/v1.0/sites/$($SPSite.id)/lists/$($ServiceList.id)/items?expand=fields"
$Data = Invoke-RestMethod -Headers @{Authorization = "Bearer $accesstoken"} -Uri $Uri -Method Get -ErrorAction Stop
```

<p>we get something like this:</p>

<pre class="lang-ps prettyprint-override"><code>@odata.etag               : "REMOVED"
Title                     : Storage Platform
Description               : Central storage platform
ResponsibleLookupId       : 14
Responsible2LookupId      : 13
AccountableLookupId       : 3
Features                  : NFS
AudienceLookupId          : 92
RequestProcess            : {@{LookupId=1; LookupValue=Service Desk}}
Support                   : {@{LookupId=1; LookupValue=Service Desk}}
AvailabilityLookupId      : 1
DependsOn                 : {}
O365GroupLookupId         : 87
LifecycleStageLookupId    : 2
ConsultLookupId           : 88
id                        : 1
ContentType               : Item
Modified                  : 2017-11-17T10:47:07Z
Created                   : 2017-11-17T10:47:07Z
_UIVersionString          : 1.0
Attachments               : False
Edit                      :
LinkTitleNoMenu           : Storage Platform
LinkTitle                 : Storage Platform
ItemChildCount            : 0
FolderChildCount          : 0
_ComplianceFlags          :
_ComplianceTag            :
_ComplianceTagWrittenTime :
_ComplianceTagUserId      :
</code>```

You can see that the field ResponsibleLookupId just gives a value of 14 which is not useful. Other fields link to Office 365 Groups, but again return values. As such it's impossible to link any of this data to users/groups and is very limited in value except when looking at it through the portal.

How do we expand this data? Will it be provided by the API call at a later date, or do we have to perform further look ups?

答:
By default, Microsoft Graph will return the LookupId for lookup fields. You can ask it to provide the actual value by specifically requesting that field in a $select parameter.

Using the following query will return the displayName rather than the LookupId for Responsible:

```<code>...items?expand=fields($select=Responsible)
</code>```

You can read about how this works in the documentation for FieldValueSet.

As for returning the userPrincipalName, currently you can't control which value it returns (it's either LookupId or displayName).I recommend visiting the UserVoice and adding your suggestion.

Body:
I am following the documentation for Get metadata for a list.

Querying using either PowerShell or the Graph Explorer fails to fully expand the fields for items in a SharePoint list.

An example of this is a lookup field called Responsible that looks up users in Azure Active Directory (or in SharePoint terms, the column is a Person or Group column, limited to people only).

Once selected via the GUI, it's populated with a display name (although I'd hope for more definitive information to be stored on the back end, like UPN).

When querying the Graph API using the form:

$Uri = "https://graph.microsoft.com/v1.0/sites/$($SPSite.id)/lists/$($ServiceList.id)/items?expand=fields"
$Data = Invoke-RestMethod -Headers @{Authorization = "Bearer $accesstoken"} -Uri $Uri -Method Get -ErrorAction Stop

we get something like this:

@odata.etag               : "REMOVED"
Title                     : Storage Platform
Description               : Central storage platform
ResponsibleLookupId       : 14
Responsible2LookupId      : 13
AccountableLookupId       : 3
Features                  : NFS
AudienceLookupId          : 92
RequestProcess            : {@{LookupId=1; LookupValue=Service Desk}}
Support                   : {@{LookupId=1; LookupValue=Service Desk}}
AvailabilityLookupId      : 1
DependsOn                 : {}
O365GroupLookupId         : 87
LifecycleStageLookupId    : 2
ConsultLookupId           : 88
id                        : 1
ContentType               : Item
Modified                  : 2017-11-17T10:47:07Z
Created                   : 2017-11-17T10:47:07Z
_UIVersionString          : 1.0
Attachments               : False
Edit                      :
LinkTitleNoMenu           : Storage Platform
LinkTitle                 : Storage Platform
ItemChildCount            : 0
FolderChildCount          : 0
_ComplianceFlags          :
_ComplianceTag            :
_ComplianceTagWrittenTime :
_ComplianceTagUserId      :

You can see that the field ResponsibleLookupId just gives a value of 14 which is not useful. Other fields link to Office 365 Groups, but again return values. As such it's impossible to link any of this data to users/groups and is very limited in value except when looking at it through the portal.

How do we expand this data? Will it be provided by the API call at a later date, or do we have to perform further look ups?

Body:
By default, Microsoft Graph will return the LookupId for lookup fields. You can ask it to provide the actual value by specifically requesting that field in a $select parameter.

Using the following query will return the displayName rather than the LookupId for Responsible:

...items?expand=fields($select=Responsible)

You can read about how this works in the documentation for FieldValueSet.

As for returning the userPrincipalName, currently you can't control which value it returns (it's either LookupId or displayName).I recommend visiting the UserVoice and adding your suggestion.