问:
How can I remove rows starting with ' in a variant?
Following the answer to this question, I execute different queries stored in a .txt file using the following code:

```<code>   Dim vSql       As Variant
   Dim vSqls      As Variant
   Dim strSql     As String
   Dim intF       As Integer

   intF = FreeFile()
   Open "MyFile.txt" For Input As #intF
   strSql = Input(LOF(intF), #intF)
   Close intF
   vSql = Split(strSql, ";")

   On Error Resume Next
   For Each vSqls In vSql
      DoCmd.RunSQL vSqls
   Next
</code>```

The queries are separated by ;, and each query is preceded by a comment line, starting with ' and ending with ;(so that it gets split by vSql = Split(strSql, ";") ).

The resulting vSql variant is composed of valid SQL statements, interspersed with comment lines starting with '. The current code works, but I would like to remove the On Error Resume Next so that a faulty SQL statement returns an error instead of being ignored.

How can I remove the rows starting with ' in the variant before executing the For Each loop? Or is there another way to accomplish my goal? The comment character can be changed if necessary.

答:
Alternatively, this should do it to:</p>

```<code>For Each vSqls In vSql
    If Not CStr(vSqls) Like "'*" Then DoCmd.RunSQL vSqls
Next
</code>```

Body:
Following the answer to this question, I execute different queries stored in a .txt file using the following code:

   Dim vSql       As Variant
   Dim vSqls      As Variant
   Dim strSql     As String
   Dim intF       As Integer

   intF = FreeFile()
   Open "MyFile.txt" For Input As #intF
   strSql = Input(LOF(intF), #intF)
   Close intF
   vSql = Split(strSql, ";")

   On Error Resume Next
   For Each vSqls In vSql
      DoCmd.RunSQL vSqls
   Next

The queries are separated by ;, and each query is preceded by a comment line, starting with ' and ending with ;(so that it gets split by vSql = Split(strSql, ";") ).

The resulting vSql variant is composed of valid SQL statements, interspersed with comment lines starting with '. The current code works, but I would like to remove the On Error Resume Next so that a faulty SQL statement returns an error instead of being ignored.

How can I remove the rows starting with ' in the variant before executing the For Each loop? Or is there another way to accomplish my goal? The comment character can be changed if necessary.

Body:
Alternatively, this should do it to:

For Each vSqls In vSql
    If Not CStr(vSqls) Like "'*" Then DoCmd.RunSQL vSqls
Next


来源: stackexchange

问:
How to use webpack-dev-server with multiple webpack configs?
Imagine I have a project like this:

```<code>/moduleA/src...
/moduleB/src...
/mainApp/src...
</code>```

I have a separate webpack.config for each module and the main app.  The modules are libraries and the main app imports those libraries.

Is it possible to configure webpack-dev-server to serve all three?

What I want to avoid is having to stop the dev server, rebuild moduleA and moduleB, and restart the dev server, every time I want to make a change to moduleA or B.

答:
Not with webpack-dev-server only because that tool is built to watch and serve a single webpack application configuration only.

So the high level answer is: run webpack-dev-server for the application and a watcher for each package dependency, at the same time. A rebuild by one of the watchers will cause a subsequent rebuild of the application by webpack.

I recommend if you are not already managing your packages within a monorepo that you do so, because it makes this all a little bit less ugly.

Assumptions:

packages are managed within a monorepo using lerna

each package (and the application) has a webpack.config.js

you are using Yarn

Steps:

for each dependency package, e.g. moduleA:

install cross-env:

```<code>yarn add cross-env
</code>```

set up webpack as a watcher in development mode by adding watch to the config:

```<code>watch: process.env.NODE_ENV === "development"
</code>```

add an NPM script "start:dev":

```<code>"start:dev": "cross-env NODE_ENV=development webpack --config webpack.config.js"
</code>```

for the application package, e.g. mainApp:

install cross-env:

```<code>yarn add cross-env
</code>```

add an NPM script "start:dev":

```<code>"start:dev": "cross-env NODE_ENV=development webpack --config webpack.config.js"
</code>```

in the monorepo root:

install concurrently

```<code>yarn add concurrently
</code>```

add the NPM scripts* for calling the application and each dependency package's "start:dev" and a "start:dev" which uses them:

```<code>"watch:app": "cd packages/mainApp && npm run start:dev",
"watch:moduleA": "cd packages/moduleA && npm run start:dev",
"watch:moduleB": "cd packages/moduleB && npm run start:dev",
"start:dev": "
    concurrently
        \"npm run watch:app\"
        \"npm run watch:moduleA\"
        \"npm run watch:moduleB\"
"
</code>```

Steps to run (in the root of the monorepo):

bootstrap your monorepo with lerna:

```<code>lerna bootstrap
</code>```

start the app dev server and watchers for all of the dependency packages:

```<code>npm run start:dev
</code>```

navigate to your application dev server endpoint, e.g. localhost:8080

___

Addendum: if a monorepo is out of the question, you can look at a combination of using yarn link and an NPM script in your application's package.json that looks something like*:

```<code>{
    "start:dev": "
        concurrently
            \"cross-env NODE_ENV=development webpack --config webpack.config.js\"
            \"cd ./node_modules/moduleA && npm run start:dev\"
            \"cd ./node_modules/moduleB && npm run start:dev\"
     "
}
</code>```

___

*Note: newlines within NPM scripts are added for readability; you must collapse the newlines if you use these in your package.json.

ContentLicense: CC BY-SA 3.0

Body:
Imagine I have a project like this:

/moduleA/src...
/moduleB/src...
/mainApp/src...

I have a separate webpack.config for each module and the main app.  The modules are libraries and the main app imports those libraries.

Is it possible to configure webpack-dev-server to serve all three?

What I want to avoid is having to stop the dev server, rebuild moduleA and moduleB, and restart the dev server, every time I want to make a change to moduleA or B.

Body:
Not with webpack-dev-server only because that tool is built to watch and serve a single webpack application configuration only.

So the high level answer is: run webpack-dev-server for the application and a watcher for each package dependency, at the same time. A rebuild by one of the watchers will cause a subsequent rebuild of the application by webpack.

I recommend if you are not already managing your packages within a monorepo that you do so, because it makes this all a little bit less ugly.

Assumptions:

packages are managed within a monorepo using lerna

each package (and the application) has a webpack.config.js

you are using Yarn

Steps:

for each dependency package, e.g. moduleA:

install cross-env:

yarn add cross-env

set up webpack as a watcher in development mode by adding watch to the config:

watch: process.env.NODE_ENV === "development"

add an NPM script "start:dev":

"start:dev": "cross-env NODE_ENV=development webpack --config webpack.config.js"

for the application package, e.g. mainApp:

install cross-env:

yarn add cross-env

add an NPM script "start:dev":

"start:dev": "cross-env NODE_ENV=development webpack --config webpack.config.js"

in the monorepo root:

install concurrently

yarn add concurrently

add the NPM scripts* for calling the application and each dependency package's "start:dev" and a "start:dev" which uses them:

"watch:app": "cd packages/mainApp && npm run start:dev",
"watch:moduleA": "cd packages/moduleA && npm run start:dev",
"watch:moduleB": "cd packages/moduleB && npm run start:dev",
"start:dev": "
    concurrently
        \"npm run watch:app\"
        \"npm run watch:moduleA\"
        \"npm run watch:moduleB\"
"

Steps to run (in the root of the monorepo):

bootstrap your monorepo with lerna:

lerna bootstrap

start the app dev server and watchers for all of the dependency packages:

npm run start:dev

navigate to your application dev server endpoint, e.g. localhost:8080

___

Addendum: if a monorepo is out of the question, you can look at a combination of using yarn link and an NPM script in your application's package.json that looks something like*:

{
    "start:dev": "
        concurrently
            \"cross-env NODE_ENV=development webpack --config webpack.config.js\"
            \"cd ./node_modules/moduleA && npm run start:dev\"
            \"cd ./node_modules/moduleB && npm run start:dev\"
     "
}

___

*Note: newlines within NPM scripts are added for readability; you must collapse the newlines if you use these in your package.json.

ContentLicense: CC BY-SA 4.0


问:
Unable to Authenticate Users From Domain\Users Group
I'm trying to authenticate all users from a domain for my MVC application. At the moment I am testing with the user PC_NAME/Administrator.

I have tried authorising the user group from PC_NAME in my controller class as suggested in this answer.

[Authorize(Roles = "PC_NAME\\Domain Users")]
```
<p>This doesn't work, I'm just prompted to login by the browser.</p>
<p>I have also tried this in web.config instead</p>
<pre class="lang-xml prettyprint-override"><code><authorization>
      <allow roles="PC_NAME\Domain Users"/>
      <deny users="*"/>
</authorization>
</code>```

This is also unsuccessful

For the record I tried authenticating just the Users role without specifying a domain, and I was able to access my site

[Authorize(Roles = "Users")]
```
<p>It also works when I just specify a user name</p>
<pre class="lang-cs prettyprint-override"><code>[Authorize(User = "PC_NAME\\Administrator")]
</code>```

How can I authenticate all users from a single domain (in this case VSD-PROMETHEUS)?

答:
I got this working by creating a custom authorise attribute.

using System;
using System.Web;
using System.Web.Mvc;

///
/// Authorises User based on what domain they are on.
///
public class AuthorizeDomainAttribute : AuthorizeAttribute
{
    ///
    /// List of domains to authorise
    ///
    public string[] Domains { get; set; }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (httpContext == null)
        {
            throw new ArgumentNullException("httpContext");
        }

        // Get the domain part of the username
        string userDomain = httpContext.User.Identity.Name.Substring(0, httpContext.User.Identity.Name.LastIndexOf('\\'));

        // Check if the user is on any of the domains specified
        foreach(string domain in this.Domains)
        {
            if (userDomain == domain)
            {
                return true;
            }
        }

        // Otherwise don't authenticate them
        return false;
    }
}
```
<p>And then using this attribute on my controller.</p>
<pre class="lang-cs prettyprint-override"><code>[AuthorizeDomain(Domains = new[] { "PC_NAME")]
</code>```

Body:
I'm trying to authenticate all users from a domain for my MVC application. At the moment I am testing with the user PC_NAME/Administrator.

I have tried authorising the user group from PC_NAME in my controller class as suggested in this answer.

[Authorize(Roles = "PC_NAME\\Domain Users")]

This doesn't work, I'm just prompted to login by the browser.

I have also tried this in web.config instead

<authorization>
      <allow roles="PC_NAME\Domain Users"/>
      <deny users="*"/>
</authorization>

This is also unsuccessful

For the record I tried authenticating just the Users role without specifying a domain, and I was able to access my site

[Authorize(Roles = "Users")]

It also works when I just specify a user name

[Authorize(User = "PC_NAME\\Administrator")]

How can I authenticate all users from a single domain (in this case VSD-PROMETHEUS)?

Body:
I got this working by creating a custom authorise attribute.

using System;
using System.Web;
using System.Web.Mvc;

/// <summary>
/// Authorises User based on what domain they are on.
/// </summary>
public class AuthorizeDomainAttribute : AuthorizeAttribute
{
    /// <summary>
    /// List of domains to authorise
    /// </summary>
    public string[] Domains { get; set; }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (httpContext == null)
        {
            throw new ArgumentNullException("httpContext");
        }

        // Get the domain part of the username
        string userDomain = httpContext.User.Identity.Name.Substring(0, httpContext.User.Identity.Name.LastIndexOf('\\'));

        // Check if the user is on any of the domains specified
        foreach(string domain in this.Domains)
        {
            if (userDomain == domain)
            {
                return true;
            }
        }

        // Otherwise don't authenticate them
        return false;
    }
}

And then using this attribute on my controller.

[AuthorizeDomain(Domains = new[] { "PC_NAME")]


问:
vlookup is returning wrong value
I'm struggling trying to find why my vlookup is not returning the right value.

So I have 2 worksheets where I want to search a code bar in a table and if in that table is exists it returns the item no.

So my first worksheet have

```<code>ID      InternCode Desription                   CodeBar
10266   #N/D       NUTREA 12-4-6 1 LT           5600993900087
</code>```

ID, InterCode and CodeBar are field type number.

And in the other sheet (Mira), I have all the items internal code, codebar, description and Price.

```<code>Item No_    Barcode No_     Description         Price
1515150032  5600993900087   NUTREA 12.4.6 1L    1.20
</code>```

So I want to get the Item No_ "1515150032" and Price "1.20".

I set ItemNo, BarCode and Price as field number.

In order to get the item no i'm doing VLOOKUP(D4;Mira!A:D;1) and this returns value 9590900018 instead of 1515150032.

Why??

答:
Hard to be precise without knowing more about your precise set up, but the picture below should give you an idea. Adjust ranges to suit.

The formula in F2 is =INDEX(A$6:A$10,MATCH($D$2,$B$6:$B$10,0))

The formula in G2 is =INDEX(D$6:D$10,MATCH($D$2,$B$6:$B$10,0))

Title: vlookup is returning wrong value

Body:
I'm struggling trying to find why my vlookup is not returning the right value.

So I have 2 worksheets where I want to search a code bar in a table and if in that table is exists it returns the item no.

So my first worksheet have

ID      InternCode Desription                   CodeBar
10266   #N/D       NUTREA 12-4-6 1 LT           5600993900087

ID, InterCode and CodeBar are field type number.

And in the other sheet (Mira), I have all the items internal code, codebar, description and Price.

Item No_    Barcode No_     Description         Price
1515150032  5600993900087   NUTREA 12.4.6 1L    1.20

So I want to get the Item No_ "1515150032" and Price "1.20".

I set ItemNo, BarCode and Price as field number.

In order to get the item no i'm doing VLOOKUP(D4;Mira!A:D;1) and this returns value 9590900018 instead of 1515150032.

Why??


问:
Unique identifier for Racket objects?
Is there a way to get a unique identifier for an object in Racket? For instance, when we use Racket's eq? operator to check whether two variables refer to the same object, what identifier is it using to achieve this comparison?

I'm looking for something like python's id function or Ruby's object_id method, in other words, some function id such that (= (id obj) (id obj2)) means that (eq? obj obj2) is true.

Some relevant docs:

Object Identity and Comparisons

Variables and Locations

答:
Here is an implementation of such a function using a weak hash table.
Using a weak hash table ensures that objects are garbage collected correctly
even if we have given it an id.

```<code>#lang racket

(define ht (make-weak-hasheq))
(define next 0)

(define (get-id x)
  (define id (hash-ref ht x #f))
  (or id
      (begin0
        next
        (hash-set! ht x next)
        (set! next (+ next 1)))))

(get-id 'a)
(get-id 'b)
(get-id 'a)
</code>```

Note that Sylwester's advice is sound. The standard is to store the value directly.

Title: Unique identifier for Racket objects?

Body:
Here is an implementation of such a function using a weak hash table.
Using a weak hash table ensures that objects are garbage collected correctly
even if we have given it an id.

#lang racket

(define ht (make-weak-hasheq))
(define next 0)

(define (get-id x)
  (define id (hash-ref ht x #f))
  (or id
      (begin0
        next
        (hash-set! ht x next)
        (set! next (+ next 1)))))

(get-id 'a)
(get-id 'b)
(get-id 'a)

Note that Sylwester's advice is sound. The standard is to store the value directly.


问:
Easily strip alpha channel from images in Mathematica
What is the simplest way to strip the alpha channel (and possible convert images to greyscale) in Mathematica?

I would like to use ImageAssemble, but some of the images come with and some without an alpha channel.  Is there a simpler built-in way than manipulating the ImageData directly?

答:
Your second question (not sure it is) conversion to grayscale, is done with:</p>

```<code>ColorConvert[image, "Grayscale"]
</code>```

Body:
Your second question (not sure it is) conversion to grayscale, is done with:

ColorConvert[image, "Grayscale"]


问:
Unable to run xml test suite from command prompt
I have TestNG suite with 2 tests included into an XML file. Test Suite works just fine if launching via IDE ( Eclipse ). However, I do need to run via command prompt.  I try launching it using the following command:

```<code>java -cp C:\eclipse\plugins\org.testng.eclipse_6.9.5.201505251947\lib\*;C:\myworkspace\myproject\bin org.testng.TestNG MyTestSuite.xml
</code>```

The error that occurs is:

```<code>[TestNGClassFinder] Warning: Can't link and determine methods of class tests.Test1

[[TestNGClassFinder]] Unable to read methods on class tests.MyTest1 - unable to resolve class reference org/openqa/selenium/WebDriver

[TestNGClassFinder] Warning: Can't link and determine methods of class tests.Test2

[[TestNGClassFinder]] Unable to read methods on class tests.MyTest2 - unable to resolve class reference org/openqa/selenium/WebDriver
</code>```

TestNG also reports 0 test runs with 0 failures and 0 skips if that's relevant.

答:
Your command looks fine.

This should work for you :

After adding TestNG to your project library create one folder in
your Project names as lib ( name can be anything ).

Go to "C:\Program Files\Eclipse\eclipse-java-mars-R-win32-x86_64\eclipse\plugins" location and copy com.beust.jcommander_1.72.0.jar and org.testng_6.14.2.r20180216145.jar file to created folder (lib).

Note : Files are testng.jar and jcommander.jar

Body:
I have TestNG suite with 2 tests included into an XML file. Test Suite works just fine if launching via IDE ( Eclipse ). However, I do need to run via command prompt.  I try launching it using the following command:

java -cp C:\eclipse\plugins\org.testng.eclipse_6.9.5.201505251947\lib\*;C:\myworkspace\myproject\bin org.testng.TestNG MyTestSuite.xml

The error that occurs is:

[TestNGClassFinder] Warning: Can't link and determine methods of class tests.Test1

[[TestNGClassFinder]] Unable to read methods on class tests.MyTest1 - unable to resolve class reference org/openqa/selenium/WebDriver

[TestNGClassFinder] Warning: Can't link and determine methods of class tests.Test2

[[TestNGClassFinder]] Unable to read methods on class tests.MyTest2 - unable to resolve class reference org/openqa/selenium/WebDriver

TestNG also reports 0 test runs with 0 failures and 0 skips if that's relevant.


问:
Android Emulator "Chain Validation Failed" connecting developers machine with self-signed cert
I have an Android Studio project that calls a web based API service. When the service code is in dev, qa, prod etc. There are NO certificate issues but when trying to hit the web api developers box to test a new feature / bug fix / etc. I get:

No reply because of error:

javax.net.ssl.SSLHandshakeException: Chain validation failed

at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:361)

I had the self signed certificate exported from the service developers machine WITHOUT the private key DER encoded. I dropped onto the emulator and it "installed" but this did not work.

I took the same cert above and copied to the emulated sd card. Then installed from security settings in emulator. Same result. Chain validation failed.

Now my security / certificate knowledge is very basic. I think the error actually describes the problem. There is no chain in a self signed certificate...but I could be wrong.

Regardless, how do I work around this?

I desire to be able to run my Android code and hit the developers box for testing / debugging etc.

I have read post like this one only to have the corporate environment I am in blocking the sites for open SSL etc.

https://android.stackexchange.com/questions/61540/self-signed-certificate-install-claims-success-but-android-acts-as-if-cert-isn

I am accessing the service through a WebView.

答: I wiped out all the data of the emulator and booted it up again, installed the app and everything was working. But seen other solution I think now that it might been an overkill.</p>


问:
Dockerized Dotnet Core 2.1 throws Gdip exception when using Select.HtmlToPdf.NetCore
I am using Select.HtmlToPdf.NetCore(18.3.0) to convert Html to pdf in Dotnetcore 2.1. It is perfectly working in local environment but when hosted with Docker it throws an error saying,

{"fileName":"System.TypeInitializationException: The type initializer
  for 'Gdip' threw an exception. ---> System.DllNotFoundException:
  Unable to load shared library 'libdl' or one of its dependencies. In
  order to help diagnose loading problems, consider setting the LD_DEBUG
  environment variable: liblibdl: cannot open shared object file: No
  such file or directory\n   at Interop.Libdl.dlopen(String fileName,
  Int32 flag)\n   at
  System.Drawing.SafeNativeMethods.Gdip.LoadNativeLibrary()\n   at
  System.Drawing.SafeNativeMethods.Gdip..cctor()\n   --- End of inner
  exception stack trace ---\n   at
  System.Drawing.SafeNativeMethods.Gdip.GdipNewPrivateFontCollection(IntPtr&
  fontCollection)\n   at SelectPdf.Lib.ᡜ..ctor()\n   at
  SelectPdf.Lib.៞..ctor()\n   at SelectPdf.Lib.៞..ctor(ᡏ A_0, ᠝ A_1)\n

  at SelectPdf.HtmlToPdf.ᜁ(String A_0, String A_1, String A_2, String
  A_3, Boolean A_4)\n   at SelectPdf.HtmlToPdf.ConvertHtmlString(String
  htmlString)

I have tried by adding these set of lines in Dockerfile, but still having the same error.

```<code>FROM microsoft/dotnet:2.1-aspnetcore-runtime AS base
RUN apt-get update
RUN apt-get install -y apt-utils
RUN apt-get install -y libgdiplus
RUN ln -s /usr/lib/libgdiplus.so /usr/lib/gdiplus.dll
WORKDIR /app
EXPOSE 80
</code>```

答:
I know It is an old question but I encountered this problem lately and I would like to share with my solution.

Select.HtmlToPdf.NetCore do not work on linux

Just do not. If you already have generated string with html I would advise you to find this nuget: Haukcode.DinkToPdf

To find some tutorials just google DinkToPdf. Haukcode is just updated and more docker friendly version.

some dockerfile stuff:

FROM microsoft/aspnetcore:2.0.0 as Base
RUN apt-get update
RUN apt-get install -y apt-utils
RUN apt-get install -y libgdiplus
RUN apt-get install -y libc6-dev
RUN ln -s /usr/lib/libgdiplus.so/usr/lib/gdiplus.dll
...

I hope it will help someone :)

Body:
I am using Select.HtmlToPdf.NetCore(18.3.0) to convert Html to pdf in Dotnetcore 2.1. It is perfectly working in local environment but when hosted with Docker it throws an error saying,

{"fileName":"System.TypeInitializationException: The type initializer
  for 'Gdip' threw an exception. ---> System.DllNotFoundException:
  Unable to load shared library 'libdl' or one of its dependencies. In
  order to help diagnose loading problems, consider setting the LD_DEBUG
  environment variable: liblibdl: cannot open shared object file: No
  such file or directory\n   at Interop.Libdl.dlopen(String fileName,
  Int32 flag)\n   at
  System.Drawing.SafeNativeMethods.Gdip.LoadNativeLibrary()\n   at
  System.Drawing.SafeNativeMethods.Gdip..cctor()\n   --- End of inner
  exception stack trace ---\n   at
  System.Drawing.SafeNativeMethods.Gdip.GdipNewPrivateFontCollection(IntPtr&
  fontCollection)\n   at SelectPdf.Lib.ᡜ..ctor()\n   at
  SelectPdf.Lib.៞..ctor()\n   at SelectPdf.Lib.៞..ctor(ᡏ A_0, ᠝ A_1)\n

  at SelectPdf.HtmlToPdf.ᜁ(String A_0, String A_1, String A_2, String
  A_3, Boolean A_4)\n   at SelectPdf.HtmlToPdf.ConvertHtmlString(String
  htmlString)

I have tried by adding these set of lines in Dockerfile, but still having the same error.

FROM microsoft/dotnet:2.1-aspnetcore-runtime AS base
RUN apt-get update
RUN apt-get install -y apt-utils
RUN apt-get install -y libgdiplus
RUN ln -s /usr/lib/libgdiplus.so /usr/lib/gdiplus.dll
WORKDIR /app
EXPOSE 80


问:
Data binding - XML not updating after onActivityResult
Updating ObservableField inside onActivityResult(..) of activity but not reflecting that value to XML. If I call executePendingBindings() it will work. But the issue is, there are a lot of ObservableField and for every variable, I need to call executePendingBindings().

Anyone knows how to solve this issue ?

答:
If you don't want to create a SingleLiveEvent and prefer to keep your callback code in onActivityResult, and you have a base activity where all activities extend from, you can add a scheduleUpdateAfterOnActivityResult method to the base activity:

// When onActivityResult is run, the activity is still in Lifecycle.State.CREATED and
// bindings will not fire.  Schedule the update by creating a new MutableLiveData,
// which will fire observers when activity lifecycle is active.
// See also https://stackoverflow.com/questions/53104670/data-binding-xml-not-updating-after-onactivityresult/53107092
public <T> void scheduleUpdateAfterOnActivityResult(T data, Observer<T> observer) {
    final MutableLiveData<T> liveData = new MutableLiveData<>();
    liveData.observe(this, new Observer<T>() {
        @Override
        public void onChanged(@Nullable final T v) {
            observer.onChanged(v);
            liveData.removeObserver(this);
        }
    });
    liveData.postValue(data);
}
```

<p>then in
<code>onActivityResult</code> call <code>scheduleUpdateAfterOnActivityResult()</code>:</p>

<pre class="lang-java prettyprint-override"><code>@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_CODE_XXXX && data != null) {
        scheduleUpdateAfterOnActivityResult(data, bundle -> {
            // do something
        }
    }
    super.onActivityResult(requestCode, resultCode, data);
}
</code>```

Body:
If you don't want to create a SingleLiveEvent and prefer to keep your callback code in onActivityResult, and you have a base activity where all activities extend from, you can add a scheduleUpdateAfterOnActivityResult method to the base activity:

// When onActivityResult is run, the activity is still in Lifecycle.State.CREATED and
// bindings will not fire.  Schedule the update by creating a new MutableLiveData,
// which will fire observers when activity lifecycle is active.
// See also https://stackoverflow.com/questions/53104670/data-binding-xml-not-updating-after-onactivityresult/53107092
public <T> void scheduleUpdateAfterOnActivityResult(T data, Observer<T> observer) {
    final MutableLiveData<T> liveData = new MutableLiveData<>();
    liveData.observe(this, new Observer<T>() {
        @Override
        public void onChanged(@Nullable final T v) {
            observer.onChanged(v);
            liveData.removeObserver(this);
        }
    });
    liveData.postValue(data);
}

then in
onActivityResult call scheduleUpdateAfterOnActivityResult():

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_CODE_XXXX && data != null) {
        scheduleUpdateAfterOnActivityResult(data, bundle -> {
            // do something
        }
    }
    super.onActivityResult(requestCode, resultCode, data);
}


问:
Am I missing some important fact about interning symbols in LISP?
To be brief. Here is my several tries to intern and use a symbol in clisp.

```<code> [1]> (setq sym (intern "foo"))
 |foo|
 [2]> (eq sym 'foo)
 NIL
</code>```

Why???

```<code> [3]> (defun internup (me &optional (package *package*))
   (intern (string-upcase me) package))
 INTERNUP

 [4]> (eq 'abc (internup "abc"))
 T
</code>```

Probably must be upcase.

```<code> [12]>(let ((abc 2))
   (eval '(+ 2 abc)))

 *** - EVAL: variable ABC has no value
 The following restarts are available:
</code>```

ok

```<code> [18]> (let ((abc 2))
 (eval '(+ 2 'abc)))

 *** - +: ABC is not a number
 The following restarts are available:
</code>```

Interesting. Should I set it before.

```<code> [14]> (setq a (internup "abc"))
 ABC

 [15]> (let ((abc 2))
 (eval '(+ 2 a)))

 *** - +: ABC is not a number
 The following restarts are available:
</code>```

And again wrong. Hmm I must be missing some important fact about interning symbols in LISP. Can you help me ?

答: Eval evaluates the form in the null lexical environment, i.e. with no lexical bindings.  That has nothing to do with the interning of symbols.

Body:
To be brief. Here is my several tries to intern and use a symbol in clisp.

 [1]> (setq sym (intern "foo"))
 |foo|
 [2]> (eq sym 'foo)
 NIL

Why???

 [3]> (defun internup (me &optional (package *package*))
   (intern (string-upcase me) package))
 INTERNUP

 [4]> (eq 'abc (internup "abc"))
 T

Probably must be upcase.

 [12]>(let ((abc 2))
   (eval '(+ 2 abc)))

 *** - EVAL: variable ABC has no value
 The following restarts are available:

ok

 [18]> (let ((abc 2))
 (eval '(+ 2 'abc)))

 *** - +: ABC is not a number
 The following restarts are available:

Interesting. Should I set it before.

 [14]> (setq a (internup "abc"))
 ABC

 [15]> (let ((abc 2))
 (eval '(+ 2 a)))

 *** - +: ABC is not a number
 The following restarts are available:

And again wrong. Hmm I must be missing some important fact about interning symbols in LISP. Can you help me ?


问:
What is the correct order for the buttons on this window (for Windows operating system standards)?
I am aware that there are standards for placement of buttons and I usually follow this order:

OK | Do It | Yes

Don't Do It | No

Cancel

Apply

Help

However I have a couple of windows with different buttons:

Clearly some of these buttons need to be resorted as:

OK

Cancel

Help

But where should Print and Undo fall in this row?

Should the Order button be before the OK button?

答:
The positioning of the OK button was answered here already, but if I understood correctly, your convention is placing it on the left, so you should keep it to that.

Regarding the other buttons, the OK button should certainly not be between any buttons. It should either be first or last, depending on your convention. In this case, OK should be first and Cancel second, while the rest is completely up to you.


问:
Can I create (an how to) a single html link to a mobile app, that sends the user to itunes or gplay based on device?
as for the title.

I have to place a simple link to an app on a website. The app has 2 versions, ios and android, so I should put 2 links, one to itunes and the other to gplay. ok.

Is there a way to create a single link that will send the user to the proper store?

答:
User Firebase Dynamic Links which are match for your scenario.

As per firebase documentation:

With Dynamic Links, your users get the best available experience for
  the platform they open your link on. If a user opens a Dynamic Link on
  iOS or Android, they can be taken directly to the linked content in
  your native app. If a user opens the same Dynamic Link in a desktop
  browser, they can be taken to the equivalent content on your website.

Source: https://firebase.google.com/docs/dynamic-links


问:
How to convert int array to int?
What I would like to learn how to do is to convert an int array to an int in C#.

However I want to append the int with the values from the array.

Example:

```<code>int[] array = {5, 6, 2, 4};
</code>```

Would be converted into an int that equals 5624.

Thanks for any help in advance.

答:
In C# 3.0 and up:</p>

```<code>array.Select((t, i) => t * Convert.ToInt32(Math.Pow(10, array.Length - i - 1))).Sum();
</code>```

Title: How to convert int array to int?

Body:
What I would like to learn how to do is to convert an int array to an int in C#.

However I want to append the int with the values from the array.

Example:

int[] array = {5, 6, 2, 4};

Would be converted into an int that equals 5624.

Thanks for any help in advance.

Body:
In C# 3.0 and up:

array.Select((t, i) => t * Convert.ToInt32(Math.Pow(10, array.Length - i - 1))).Sum();


问:
Finding Non-Zero Values/Indexes in Numpy
I have a quite big numpy array with the shape of (12388, 4). The first two values are coordiantes and the second two key values. Some of the are zero. I want to filter through the array and find all indexes where both of the second two values are non-zeros.
My code looks like this:

```<code>slice_index,_ = np.where((slice[:,2:4]!=0))
slice_nonzero_values = slice[slice_index]
</code>```

The shape of the resulting array slice_nonzero_values is (18550,4). Thus something must have gone wrong, as the resulting array is bigger as the original one. Looking at the csv I realized np.where gives me the same index back multiple times if slice[:,2] and slice[:,3] are both non-zero. Thus I tried includenp.unique:

```<code>slice_index,_ = np.where((slice[:,2:4]!=0))
slice_index_unique = np.unique(slice_index)
slice_nonzero_values = slice[slice_index_unique]
</code>```

This results in a shape of (9669, 4). This looks a lot better. However, to be sure everything is fine now, I made this for-loop:

```<code>    test = []
    test_index = []
    for index, i in enumerate(slice):
        if i[2]!=0 or i[3]!=0:
            test.append(i)
            test_index.append(index)
    test = np.array(test)
    test_index = np.array(test_index)
</code>```

This loop results in the array test with the shape of (8881, 4). Now I am completely confused which of the two ways is correct. Based on the loop`s logic, the test array must be the rigth one. However, this is just once slice array of literally thousends. I cant leave the for-loop there. To summerize: I want to filter through the slice-array and get all entries which have non-zeros in either of the last two columns. In other words, if both values (slice[:,2] and slice[:,3]) are zero, the row gets out. If only one of them is zero and the other not, that´s fine.

Here is a sample of the slice array:

```<code>   array([[0.01032591, 0. , 0.               , 0.        ],
   [0.03256559, 0.00890732, 5.0000000e+00    , 0.        ],
   [0.0468626 , 0.01543951, 0.               , 0.        ],
   ...,
   [0.13899946, 0.8847985 , 0.               , 0.        ],
   [0.13899946, 0.8847985 , 4.0000000e+00    , 5.3900000e+02],
   [0.13899946, 0.8847985 , 0.               , 0.        ]], dtype=float32)
</code>```

答:
Here's a working demo. Create test data:

```<code>import numpy as np

X = np.random.rand(10,4)
X = np.vstack([X, np.zeros([2,4])])

>>> X
array([[0.09889965, 0.01169015, 0.30886119, 0.40204571],
       [0.67277149, 0.01654403, 0.17710642, 0.54201684],
       # ...
       [0.        , 0.        , 0.        , 0.        ],
       [0.        , 0.        , 0.        , 0.        ]])
</code>```

Find vectors the last two numbers are none zero:

```<code>idx = np.where(np.sum(X[:,2:], axis=1) != 0)[0]

# alternatively, use np.any
idx = np.where(np.any(X[:,2:], axis=1))[0]
</code>```

Retrieve filtered vectors:

```<code>X_none_zeros = X[idx]

>>> X_none_zeros
array([[0.09889965, 0.01169015, 0.30886119, 0.40204571],
       # ...
       [0.78279739, 0.84191242, 0.31685306, 0.54906034]])

>>> X_none_zeros.shape
(10, 4)

>>> X.shape
(12, 4)
</code>```

Explain: the actual codes are just two lines:

```<code># retrieve last 2 numbers for each vector in X
# and sum each vector horizontally, so you have
# [s1, s2, s3, ...]
# use the condition to filter indexes
idx = np.where(np.sum(X[:,2:], axis=1) != 0)[0]
# retrieve matched vectors accordingly
X_none_zeros = X[idx]
</code>```

Body:
I have a quite big numpy array with the shape of (12388, 4). The first two values are coordiantes and the second two key values. Some of the are zero. I want to filter through the array and find all indexes where both of the second two values are non-zeros.
My code looks like this:

slice_index,_ = np.where((slice[:,2:4]!=0))
slice_nonzero_values = slice[slice_index]

The shape of the resulting array slice_nonzero_values is (18550,4). Thus something must have gone wrong, as the resulting array is bigger as the original one. Looking at the csv I realized np.where gives me the same index back multiple times if slice[:,2] and slice[:,3] are both non-zero. Thus I tried includenp.unique:

slice_index,_ = np.where((slice[:,2:4]!=0))
slice_index_unique = np.unique(slice_index)
slice_nonzero_values = slice[slice_index_unique]

This results in a shape of (9669, 4). This looks a lot better. However, to be sure everything is fine now, I made this for-loop:

    test = []
    test_index = []
    for index, i in enumerate(slice):
        if i[2]!=0 or i[3]!=0:
            test.append(i)
            test_index.append(index)
    test = np.array(test)
    test_index = np.array(test_index)

This loop results in the array test with the shape of (8881, 4). Now I am completely confused which of the two ways is correct. Based on the loop`s logic, the test array must be the rigth one. However, this is just once slice array of literally thousends. I cant leave the for-loop there. To summerize: I want to filter through the slice-array and get all entries which have non-zeros in either of the last two columns. In other words, if both values (slice[:,2] and slice[:,3]) are zero, the row gets out. If only one of them is zero and the other not, that´s fine.

Here is a sample of the slice array:

   array([[0.01032591, 0. , 0.               , 0.        ],
   [0.03256559, 0.00890732, 5.0000000e+00    , 0.        ],
   [0.0468626 , 0.01543951, 0.               , 0.        ],
   ...,
   [0.13899946, 0.8847985 , 0.               , 0.        ],
   [0.13899946, 0.8847985 , 4.0000000e+00    , 5.3900000e+02],
   [0.13899946, 0.8847985 , 0.               , 0.        ]], dtype=float32)

Body:
Here's a working demo. Create test data:

import numpy as np

X = np.random.rand(10,4)
X = np.vstack([X, np.zeros([2,4])])

>>> X
array([[0.09889965, 0.01169015, 0.30886119, 0.40204571],
       [0.67277149, 0.01654403, 0.17710642, 0.54201684],
       # ...
       [0.        , 0.        , 0.        , 0.        ],
       [0.        , 0.        , 0.        , 0.        ]])

Find vectors the last two numbers are none zero:

idx = np.where(np.sum(X[:,2:], axis=1) != 0)[0]

# alternatively, use np.any
idx = np.where(np.any(X[:,2:], axis=1))[0]

Retrieve filtered vectors:

X_none_zeros = X[idx]

>>> X_none_zeros
array([[0.09889965, 0.01169015, 0.30886119, 0.40204571],
       # ...
       [0.78279739, 0.84191242, 0.31685306, 0.54906034]])

>>> X_none_zeros.shape
(10, 4)

>>> X.shape
(12, 4)

Explain: the actual codes are just two lines:

# retrieve last 2 numbers for each vector in X
# and sum each vector horizontally, so you have
# [s1, s2, s3, ...]
# use the condition to filter indexes
idx = np.where(np.sum(X[:,2:], axis=1) != 0)[0]
# retrieve matched vectors accordingly
X_none_zeros = X[idx]


问:
Send model value to observer.next();
I have a function like below. I am trying to figure out how to send userDetails to the observer.next()

```<code>  getUserDetails(userId: string): Observable<GetUserByIdModel> {
    const url = `${this.candidateUrl}/Get`;
    this._http.get<any>(url + '/' + userId).subscribe((resp) => {
      const userDetails: GetUserByIdModel = {
        firstname: 'Joyce',
        contactChannels: [
          { type: 1, value: 'test@gmail.com' },
          { type: 2, value: '0111111111' }
        ],
      };
    })

    return new Observable((observer) => {
      observer.next(userDetails);
      observer.complete();
    });

  }
</code>```

Currently I get "Cannot find name 'userDetails'" even if I change  const userDetails: GetUserByIdModel to a let/var userDetails: GetUserByIdModel

答:
What you're trying to do here is transform the response that you're getting from the API call. Which is a perfect situation to use the Rxjs map operator. Here's how:

```<code>import { map } from 'rxjs/operators';

...

getUserDetails(userId: string): Observable < GetUserByIdModel > {
  const url = `${this.candidateUrl}/Get`;
  return this._http.get < any > (url + '/' + userId).pipe(
    map(resp => {
      const userDetails: GetUserByIdModel = {
        firstname: 'Joyce',
        contactChannels: [{
            type: 1,
            value: 'test@gmail.com'
          },
          {
            type: 2,
            value: '0111111111'
          }
        ],
      };
      return userDetails;
    })
  );
}
</code>```

Title: Send model value to observer.next();

Body:
I have a function like below. I am trying to figure out how to send userDetails to the observer.next()

  getUserDetails(userId: string): Observable<GetUserByIdModel> {
    const url = `${this.candidateUrl}/Get`;
    this._http.get<any>(url + '/' + userId).subscribe((resp) => {
      const userDetails: GetUserByIdModel = {
        firstname: 'Joyce',
        contactChannels: [
          { type: 1, value: 'test@gmail.com' },
          { type: 2, value: '0111111111' }
        ],
      };
    })

    return new Observable((observer) => {
      observer.next(userDetails);
      observer.complete();
    });

  }

Currently I get "Cannot find name 'userDetails'" even if I change  const userDetails: GetUserByIdModel to a let/var userDetails: GetUserByIdModel

Body:
What you're trying to do here is transform the response that you're getting from the API call. Which is a perfect situation to use the Rxjs map operator. Here's how:

import { map } from 'rxjs/operators';

...

getUserDetails(userId: string): Observable < GetUserByIdModel > {
  const url = `${this.candidateUrl}/Get`;
  return this._http.get < any > (url + '/' + userId).pipe(
    map(resp => {
      const userDetails: GetUserByIdModel = {
        firstname: 'Joyce',
        contactChannels: [{
            type: 1,
            value: 'test@gmail.com'
          },
          {
            type: 2,
            value: '0111111111'
          }
        ],
      };
      return userDetails;
    })
  );
}


问:
focusing ng-select filter input on drop down open
I'm using ng-select and have a custom filter header template defined which contains an input.

I would like the input to receive focus when the dropdown is opened for the select, but I cant figure out how to.

I have an example here -> https://stackblitz.com/edit/angular-playground-f57jog

I did try attaching to the ng-select (open) output and calling focus() on my input element, but this fails for me.

Whats the correct approach here?
Thanks

答:
You can use this method:

in your html:

```<code><ng-select #api [items]="cars"
          [virtualScroll]="true"
          [loading]="loading"
          bindLabel="brand"
          bindValue="id"
          (scroll)="onScroll($event)"
          (scrollToEnd)="onScrollToEnd()"
          [dropdownPosition]="'bottom'"
          [searchable]="false"
          [(ngModel)]="selectedCar2"
          [searchFn]="customSearchFn"
          (change)="onChange($event)"
          (open)="focusInputField()">
</code>```

note the (open) changed.

in your .ts file you add:

```<code>    @ViewChild('filterInput') filterInput:ElementRef;

    focusInputField() {
      setTimeout(() => {
      this.filterInput.nativeElement.focus()
      }, 10)
    }
</code>```

This should work for both Chrome and Firefox.

Body:
You can use this method:

in your html:

<ng-select #api [items]="cars"
          [virtualScroll]="true"
          [loading]="loading"
          bindLabel="brand"
          bindValue="id"
          (scroll)="onScroll($event)"
          (scrollToEnd)="onScrollToEnd()"
          [dropdownPosition]="'bottom'"
          [searchable]="false"
          [(ngModel)]="selectedCar2"
          [searchFn]="customSearchFn"
          (change)="onChange($event)"
          (open)="focusInputField()">

note the (open) changed.

in your .ts file you add:

    @ViewChild('filterInput') filterInput:ElementRef;

    focusInputField() {
      setTimeout(() => {
      this.filterInput.nativeElement.focus()
      }, 10)
    }

This should work for both Chrome and Firefox.


问:
Unity NavMeshAgent not reaching target - moving around
I've created a simple scene and I'm now trying to make a rabbit move to the mouse-click position on a Plane.

So I've added a Rigidbody, a Nav Mesh Agent and a simple "Pathfinding" script to the rabbit.

The planes Mesh Renderer is set to "Navigation Static", "Generate OffMeshLinks" and "Walkable"

Now as soon as the rabbit gets close to the given destination, it will not stop but rather is "running around" in a very small circle around the destination.

Here is my script

```<code>using UnityEngine;
using UnityEngine.AI;

public class Pathfinding : MonoBehaviour {

private NavMeshAgent agent;
private Animator animator;

// Use this for initialization
void Start() {
    agent = GetComponent<NavMeshAgent>();
    animator = GetComponent<Animator>();
}

// Update is called once per frame
void Update() {
    RaycastHit hit;

    if(Input.GetMouseButtonDown(0)) {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if(Physics.Raycast(ray, out hit)) {
            agent.SetDestination(hit.point);
            animator.SetInteger("AnimIndex", 1);
            animator.SetBool("Next", true);
        }
    }
}
}
</code>```

and a picture of my rabbit object ;)

答: Stopping Distance should be > 0</p>

Body:
I've created a simple scene and I'm now trying to make a rabbit move to the mouse-click position on a Plane.

So I've added a Rigidbody, a Nav Mesh Agent and a simple "Pathfinding" script to the rabbit.

The planes Mesh Renderer is set to "Navigation Static", "Generate OffMeshLinks" and "Walkable"

Now as soon as the rabbit gets close to the given destination, it will not stop but rather is "running around" in a very small circle around the destination.

Here is my script

using UnityEngine;
using UnityEngine.AI;

public class Pathfinding : MonoBehaviour {

private NavMeshAgent agent;
private Animator animator;

// Use this for initialization
void Start() {
    agent = GetComponent<NavMeshAgent>();
    animator = GetComponent<Animator>();
}

// Update is called once per frame
void Update() {
    RaycastHit hit;

    if(Input.GetMouseButtonDown(0)) {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if(Physics.Raycast(ray, out hit)) {
            agent.SetDestination(hit.point);
            animator.SetInteger("AnimIndex", 1);
            animator.SetBool("Next", true);
        }
    }
}
}

and a picture of my rabbit object ;)

Body: Stopping Distance should be > 0


问:
Changing product name on checkout and order on WooCommerce with WPML
I am using WooCommerce with WPML plugin. I want to implement a feature on checkout when a customer under certain conditions can have an upgrade of his product but keeping the old product price.

The products are variable with many variable attributes.
So, more specifically, what I want is if a customer has selected a specific product variation with x price on checkout (under a certain condition) I could change his cart item with another product's variation but keep the x price.

What I tried first is to change only the name of the product using woocommerce_order_item_name hook but the change doesn't follow on the order. This is important because some order data are then sent to an API.

Afterwards I used "Changing WooCommerce cart item names" answer code, which worked perfectly for my purpose until I installed WPML. For some reason the WC_Cart method set_name() doesn't work with WPML. I opened a support thread but they still can't find a solution.

Can anyone suggest any other solution?

Update

I have tried an approach where I remove the product item on cart and then I add the one I need. After I use set_price() to change the price of the newly added item. The removal/addition seems to be working but the price is not changed on one language and it is not applied on both languages after placing order.
This is the code I use:

```<code>function berrytaxiplon_change_product_name( $cart ) {

if ( is_admin() && ! defined( 'DOING_AJAX' ) )
    return;

if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
    return;

    // Loop through cart items
    foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {

        // Get an instance of the WC_Product object
        $product = $cart_item['data'];

        // Get the product name (Added Woocommerce 3+ compatibility)
        $product_id = method_exists( $product, 'get_parent_id' ) ? $product->get_parent_id() : $product->post->post_parent;

        if ( ICL_LANGUAGE_CODE == 'en') {
            if (isset($cart_item['s-member-level']) && $cart_item['s-member-level'] == 3 && $product_id == 12) {

                $new_product = wc_get_product( 82 );
                $atrributes = $product->get_attributes('view');
                foreach ($atrributes as $atrribute_key => $atrribute_value) {
                    $new_attributes['attribute_' . $atrribute_key] = strtolower($atrribute_value);
                }
                $new_variation_id = find_matching_product_variation_id(82, $new_attributes);
                $cart->remove_cart_item( $cart_item_key );
                $cart->add_to_cart( 82, 1, $new_variation_id, $new_attributes, $cart_item );

                foreach ( WC()->cart->get_cart() as $new_item ) {

                    $new_item['data']->set_price( $cart_item['s-fare'] );
                }
            }
        } else {
            if (isset($cart_item['s-member-level']) && $cart_item['s-member-level'] == 3 && $product_id == 282) {

                $new_product = wc_get_product( 303 );

                $atrributes = $product->get_attributes('view');
                foreach ($atrributes as $atrribute_key => $atrribute_value) {
                    $new_attributes['attribute_' . $atrribute_key] = strtolower($atrribute_value);
                }
                $new_variation_id = find_matching_product_variation_id(303, $new_attributes);
                $cart->remove_cart_item( $cart_item_key );
                $cart->add_to_cart( 303, 1, $new_variation_id, $new_attributes, $cart_item );
                foreach ( WC()->cart->get_cart() as $new_item ) {
                    $new_item['data']->set_price( $cart_item['s-fare']);
                }

            }
        }

    }

}
add_action( 'woocommerce_before_calculate_totals', 'berrytaxiplon_change_product_name', 10, 1 );

</code>```

Any idea why the set_price() method is not applied?

Update 2

WPMl uses 'woocommerce_before_calculate_totals' and overrides the action added on functions.php

WPML support provided a solution using 3 filters:

https://wpml.org/forums/topic/cant-use-set_name-method-for-the-product-object-on-checkout/#post-3977153

答:
So this is a code that I am using in one of my projects to add a product variation to cart based off of some filters and the selected product:

```<code>$product = new WC_Product($product_id); //The main product whose variation has to be added
$product_name = $product->get_name(); //Name of the main product
$quantity = sanitize_text_field($cData['quantity']); //You can set this to 1
$variation_id = sanitize_text_field($cData['variation_id']); //I had the variation ID from filters
$variation = array(
    'pa_duration' => sanitize_text_field($cData['duration']) //The variation slug was also available for me.
);
$cart_item_data = array('custom_price' => sanitize_text_field($custom_price));
$cart = WC()->cart->add_to_cart( (int)$product_id, (int)$quantity, (int)$variation_id, $variation, $cart_item_data ); //This will add products to cart but with the actual price of the variation being added and meta data holding the custom price.
WC()->cart->calculate_totals();
WC()->cart->set_session();
WC()->cart->maybe_set_cart_cookies();
</code>```

Then you need to do a check on before cart totals are calculated and set the price to custom price like this:

```<code>function woocommerce_custom_price_to_cart_item( $cart_object ) {
    if( !WC()->session->__isset( "reload_checkout" )) {
        foreach ( $cart_object->cart_contents as $key => $value ) {
            if( isset( $value["custom_price"] ) ) {
                $value['data']->set_price($value["custom_price"]);
            }
        }
    }
}
add_action( 'woocommerce_before_calculate_totals', 'woocommerce_custom_price_to_cart_item', 99 );
</code>```

Body:
I am using WooCommerce with WPML plugin. I want to implement a feature on checkout when a customer under certain conditions can have an upgrade of his product but keeping the old product price.

The products are variable with many variable attributes.
So, more specifically, what I want is if a customer has selected a specific product variation with x price on checkout (under a certain condition) I could change his cart item with another product's variation but keep the x price.

What I tried first is to change only the name of the product using woocommerce_order_item_name hook but the change doesn't follow on the order. This is important because some order data are then sent to an API.

Afterwards I used "Changing WooCommerce cart item names" answer code, which worked perfectly for my purpose until I installed WPML. For some reason the WC_Cart method set_name() doesn't work with WPML. I opened a support thread but they still can't find a solution.

Can anyone suggest any other solution?

Update

I have tried an approach where I remove the product item on cart and then I add the one I need. After I use set_price() to change the price of the newly added item. The removal/addition seems to be working but the price is not changed on one language and it is not applied on both languages after placing order.
This is the code I use:

function berrytaxiplon_change_product_name( $cart ) {

if ( is_admin() && ! defined( 'DOING_AJAX' ) )
    return;

if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
    return;

    // Loop through cart items
    foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {

        // Get an instance of the WC_Product object
        $product = $cart_item['data'];

        // Get the product name (Added Woocommerce 3+ compatibility)
        $product_id = method_exists( $product, 'get_parent_id' ) ? $product->get_parent_id() : $product->post->post_parent;

        if ( ICL_LANGUAGE_CODE == 'en') {
            if (isset($cart_item['s-member-level']) && $cart_item['s-member-level'] == 3 && $product_id == 12) {

                $new_product = wc_get_product( 82 );
                $atrributes = $product->get_attributes('view');
                foreach ($atrributes as $atrribute_key => $atrribute_value) {
                    $new_attributes['attribute_' . $atrribute_key] = strtolower($atrribute_value);
                }
                $new_variation_id = find_matching_product_variation_id(82, $new_attributes);
                $cart->remove_cart_item( $cart_item_key );
                $cart->add_to_cart( 82, 1, $new_variation_id, $new_attributes, $cart_item );

                foreach ( WC()->cart->get_cart() as $new_item ) {

                    $new_item['data']->set_price( $cart_item['s-fare'] );
                }
            }
        } else {
            if (isset($cart_item['s-member-level']) && $cart_item['s-member-level'] == 3 && $product_id == 282) {

                $new_product = wc_get_product( 303 );

                $atrributes = $product->get_attributes('view');
                foreach ($atrributes as $atrribute_key => $atrribute_value) {
                    $new_attributes['attribute_' . $atrribute_key] = strtolower($atrribute_value);
                }
                $new_variation_id = find_matching_product_variation_id(303, $new_attributes);
                $cart->remove_cart_item( $cart_item_key );
                $cart->add_to_cart( 303, 1, $new_variation_id, $new_attributes, $cart_item );
                foreach ( WC()->cart->get_cart() as $new_item ) {
                    $new_item['data']->set_price( $cart_item['s-fare']);
                }

            }
        }

    }

}
add_action( 'woocommerce_before_calculate_totals', 'berrytaxiplon_change_product_name', 10, 1 );

Any idea why the set_price() method is not applied?

Update 2

WPMl uses 'woocommerce_before_calculate_totals' and overrides the action added on functions.php

WPML support provided a solution using 3 filters:

https://wpml.org/forums/topic/cant-use-set_name-method-for-the-product-object-on-checkout/#post-3977153

Body:
So this is a code that I am using in one of my projects to add a product variation to cart based off of some filters and the selected product:

$product = new WC_Product($product_id); //The main product whose variation has to be added
$product_name = $product->get_name(); //Name of the main product
$quantity = sanitize_text_field($cData['quantity']); //You can set this to 1
$variation_id = sanitize_text_field($cData['variation_id']); //I had the variation ID from filters
$variation = array(
    'pa_duration' => sanitize_text_field($cData['duration']) //The variation slug was also available for me.
);
$cart_item_data = array('custom_price' => sanitize_text_field($custom_price));
$cart = WC()->cart->add_to_cart( (int)$product_id, (int)$quantity, (int)$variation_id, $variation, $cart_item_data ); //This will add products to cart but with the actual price of the variation being added and meta data holding the custom price.
WC()->cart->calculate_totals();
WC()->cart->set_session();
WC()->cart->maybe_set_cart_cookies();

Then you need to do a check on before cart totals are calculated and set the price to custom price like this:

function woocommerce_custom_price_to_cart_item( $cart_object ) {
    if( !WC()->session->__isset( "reload_checkout" )) {
        foreach ( $cart_object->cart_contents as $key => $value ) {
            if( isset( $value["custom_price"] ) ) {
                $value['data']->set_price($value["custom_price"]);
            }
        }
    }
}
add_action( 'woocommerce_before_calculate_totals', 'woocommerce_custom_price_to_cart_item', 99 );


问:
What those F# functions are supposed to do?
Learning F# these days, I've noticed that in some libraries like this one or that one
there are some similar functions which seem to be common in F# but can't really decipher them, what are they doing, what are they for?

let ap x f =
    match f, x with
    | Ok f        , Ok x    -> Ok (f x)
    | Error e     , _       -> Error e
    | _           , Error e -> Error e
let inline (<*>) f x = ap x f
let inline (<!>) f x = Result.map f x
let inline lift2 f a b = f <!> a <*> b
```

<p>Even aggregating comments with them does not really help in my understanding:</p>

<pre class="lang-ml prettyprint-override"><code>/// Sequential application
/// If the wrapped function is a success and the given result is a success the function is applied on the value.
/// Otherwise the exisiting error messages are propagated.
let ap x f =
match f,x with
    | Ok f        , Ok x    -> Ok (f x)
    | Error e     , _       -> Error e
    | _           , Error e -> Error e

/// Sequential application
/// If the wrapped function is a success and the given result is a success the function is applied on the value.
/// Otherwise the exisiting error messages are propagated.
let inline (<*>) f x = ap x f

/// Infix map, lifts a function into a Result and applies it on the given result.
let inline (<!>) f x = Result.map f x

/// Promote a function to a monad/applicative, scanning the monadic/applicative arguments from left to right.
let inline lift2 f a b = f <!> a <*> b
</code>```

I don't even see an example of how they could be used, not sure also why inline has been used.

If there is somebody who could hint about how useful those functions are, I would greatly appreciate.

答:
These are called "applicative functors" (sometimes just "applicatives"). Their purpose is to combine data from multiple Something<'T> using a function. Basically, "lifting" a function of type 'Arg1 -> 'Arg2 -> ... -> 'Result into a function of type Something<'Arg1> -> Something<'Arg2> -> ... -> Something<'Result>.

For example, given the standard Result type:

```<code>type Result<'T, 'Err> = Ok of 'T | Error of 'Err
</code>```

you may have several Result values that you want to combine together. For example, say you have a form with inputs firstName, lastName and age. You also have a result type Person:

```<code>type Person = { firstName: string; lastName: string; age: int }

// string -> string -> int -> Person
let makePerson firstName lastName age =
    { firstName = firstName; lastName = lastName; age = age }
</code>```

The values coming from your actual form may have type Result<string, InputError> or Result<int, InputError>, which can be Error if eg. the user hasn't entered a value.

```<code>type InputError =
    | FieldMissing of fieldName: string
    // Other error cases...
</code>```

You want to combine them into a Result<Person, InputError>, which is Ok if all inputs are Ok, or Error if any input is Error. Using the applicative, you can do it like this:

```<code>// Result<string, InputError> -> Result<string, InputError> -> Result<int, InputError> -> Result<Person, InputError>
let makePersonResult firstName lastName age =
    makePerson <!> firstName <*> lastName <*> age

// Example uses:

makePersonResult (Ok "John") (Ok "Doe") (Ok 42)
// --> Ok { firstName = "John"; lastName = "Doe"; age = 42 }
makePersonResult (Error (FieldMissing "firstName")) (Ok "Doe") (Ok 42)
// --> Error (FieldMissing "firstName")
</code>```

A similar concept can be applied to many other types than Result, which is why it was given a name. For example, an applicative on Async<'T> could run all the argument Asyncs in parallel, and when they're finished, combine their results into an Async<'Result>. Another example, an applicative on 'T list would be equivalent to the standard library's List.map2 or List.map3 but generalizable to any number of argument lists.

Side note: if you look up "applicative functor", most of the results you'll find will be in Haskell, where the map operator, usually written <!> in F#, is written <$> instead.

Body:
Learning F# these days, I've noticed that in some libraries like this one or that one
there are some similar functions which seem to be common in F# but can't really decipher them, what are they doing, what are they for?

let ap x f =
    match f, x with
    | Ok f        , Ok x    -> Ok (f x)
    | Error e     , _       -> Error e
    | _           , Error e -> Error e
let inline (<*>) f x = ap x f
let inline (<!>) f x = Result.map f x
let inline lift2 f a b = f <!> a <*> b

Even aggregating comments with them does not really help in my understanding:

/// Sequential application
/// If the wrapped function is a success and the given result is a success the function is applied on the value.
/// Otherwise the exisiting error messages are propagated.
let ap x f =
match f,x with
    | Ok f        , Ok x    -> Ok (f x)
    | Error e     , _       -> Error e
    | _           , Error e -> Error e

/// Sequential application
/// If the wrapped function is a success and the given result is a success the function is applied on the value.
/// Otherwise the exisiting error messages are propagated.
let inline (<*>) f x = ap x f

/// Infix map, lifts a function into a Result and applies it on the given result.
let inline (<!>) f x = Result.map f x

/// Promote a function to a monad/applicative, scanning the monadic/applicative arguments from left to right.
let inline lift2 f a b = f <!> a <*> b

I don't even see an example of how they could be used, not sure also why inline has been used.

If there is somebody who could hint about how useful those functions are, I would greatly appreciate.

Body:
These are called "applicative functors" (sometimes just "applicatives"). Their purpose is to combine data from multiple Something<'T> using a function. Basically, "lifting" a function of type 'Arg1 -> 'Arg2 -> ... -> 'Result into a function of type Something<'Arg1> -> Something<'Arg2> -> ... -> Something<'Result>.

For example, given the standard Result type:

type Result<'T, 'Err> = Ok of 'T | Error of 'Err

you may have several Result values that you want to combine together. For example, say you have a form with inputs firstName, lastName and age. You also have a result type Person:

type Person = { firstName: string; lastName: string; age: int }

// string -> string -> int -> Person
let makePerson firstName lastName age =
    { firstName = firstName; lastName = lastName; age = age }

The values coming from your actual form may have type Result<string, InputError> or Result<int, InputError>, which can be Error if eg. the user hasn't entered a value.

type InputError =
    | FieldMissing of fieldName: string
    // Other error cases...

You want to combine them into a Result<Person, InputError>, which is Ok if all inputs are Ok, or Error if any input is Error. Using the applicative, you can do it like this:

// Result<string, InputError> -> Result<string, InputError> -> Result<int, InputError> -> Result<Person, InputError>
let makePersonResult firstName lastName age =
    makePerson <!> firstName <*> lastName <*> age

// Example uses:

makePersonResult (Ok "John") (Ok "Doe") (Ok 42)
// --> Ok { firstName = "John"; lastName = "Doe"; age = 42 }
makePersonResult (Error (FieldMissing "firstName")) (Ok "Doe") (Ok 42)
// --> Error (FieldMissing "firstName")

A similar concept can be applied to many other types than Result, which is why it was given a name. For example, an applicative on Async<'T> could run all the argument Asyncs in parallel, and when they're finished, combine their results into an Async<'Result>. Another example, an applicative on 'T list would be equivalent to the standard library's List.map2 or List.map3 but generalizable to any number of argument lists.

Side note: if you look up "applicative functor", most of the results you'll find will be in Haskell, where the map operator, usually written <!> in F#, is written <$> instead.


问:
Programmatically change sorting order in Perl
I'd like to give the user the possibility to change the sorting order (asc / desc) in a data structure. As far as I know, this is done changing the order of $a and $bin the code, but I'd like to programmatically change this to avoid redundant code.

I made a working example:

use 5.018;
use warnings;

# Supply any argument to change sorting order
my $sorting_direction = $ARGV[0];

my $data = {
          'item1' => {
                         'min'  => 4,
                         'size' => 825,
                         'max'  => 256,
                       },
          'item2' => {
                         'min'  => 4,
                         'size' => 130,
                         'max'  => 65,
                       },
        };

if (defined $sorting_direction) {
    foreach my $item (sort { $$data{$a}{'size'} <=> $$data{$b}{'size'} } keys %{$data} ) {
        say "$item\t", $$data{$item}{'size'};
    }
} else {
    foreach my $item (sort { $$data{$b}{'size'} <=> $$data{$a}{'size'} } keys %{$data} ) {
        say "$item\t", $$data{$item}{'size'};
    }
}
```

Giving any parameter will change the sorting_direction. Can I do this without the if conditional?

答:
As <=> has a value of -1, 0 or 1, you can multiply with -1 to get the opposite sorting order.

So if your $sorting_direction is 1 or  -1 use

```<code>$sorting_direction * ( $$data{$a}{'size'} <=> $$data{$b}{'size'} )
</code>```

Body:
I'd like to give the user the possibility to change the sorting order (asc / desc) in a data structure. As far as I know, this is done changing the order of $a and $bin the code, but I'd like to programmatically change this to avoid redundant code.

I made a working example:

use 5.018;
use warnings;

# Supply any argument to change sorting order
my $sorting_direction = $ARGV[0];

my $data = {
          'item1' => {
                         'min'  => 4,
                         'size' => 825,
                         'max'  => 256,
                       },
          'item2' => {
                         'min'  => 4,
                         'size' => 130,
                         'max'  => 65,
                       },
        };

if (defined $sorting_direction) {
    foreach my $item (sort { $$data{$a}{'size'} <=> $$data{$b}{'size'} } keys %{$data} ) {
        say "$item\t", $$data{$item}{'size'};
    }
} else {
    foreach my $item (sort { $$data{$b}{'size'} <=> $$data{$a}{'size'} } keys %{$data} ) {
        say "$item\t", $$data{$item}{'size'};
    }
}

Giving any parameter will change the sorting_direction. Can I do this without the if conditional?

Body:
As <=> has a value of -1, 0 or 1, you can multiply with -1 to get the opposite sorting order.

So if your $sorting_direction is 1 or  -1 use

$sorting_direction * ( $$data{$a}{'size'} <=> $$data{$b}{'size'} )


问:
Apache Ignite programmatically destroy persistent cache
I am developing a Java application that uses Apache Ignite caches with persistent storage.

Since I am still in development, I occasionally need to change some of the cached classes and, when I do this, the Ignite cluster fails to start.  At these times, I need to go into my file system and delete the persistent cache.

Is there any way to do this automatically in my program?  Ideally, I would like to:

Try to start the Ignite cluster

If there is some kind of problem

destroy the persistent cache

try to start the Ignite cluster again

I'd like to do this via Ignite APIs (e.g. not just using Java to delete the files).

How can I do this?

答:
You will have to remove marshaller/, db/ and wal/ directories via Java file APIs, since Ignite does not have corresponding calls.

In fact it does, but only in tests running code. So you will have to implement it yourself.


问:
What is wrong with this template declaration?
```<code>template<class T> void Insert(T*, T) { *T = T; }
</code>```

produces error

```<code>"T: illegal use of this type as an expression"
</code>```

答:
The body of this function template tries to dereference and assign the type T. This is not possible, you need to change it to

```<code>template<class T> void insert(T* t1, T t2)
{
    *t1 = t2;
}
</code>```

Body:
template<class T> void Insert(T*, T) { *T = T; }

produces error

"T: illegal use of this type as an expression"

Body:
The body of this function template tries to dereference and assign the type T. This is not possible, you need to change it to

template<class T> void insert(T* t1, T t2)
{
    *t1 = t2;
}


问:
Why does replicate() return a matrix?
```<code>> n_toss = 3; # Number of Tosses
> n_trial = 10; # Number of Trials
>
> mySamples <- sample(c(1,0), n_toss, replace = T, prob=c(0.5,0.5))
> mySamples
[1] 1 0 1
>
> mySamples <- replicate(n_trial,
+              {
+                  mySamples <- sample(c(1,0), n_toss, replace = T, prob=c(0.5,0.5))
+              })
> mySamples
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,]    0    1    1    0    1    0    0    0    0     0
[2,]    1    0    1    1    1    0    0    0    0     0
[3,]    0    0    0    0    1    1    1    1    0     1
>
</code>```

I have two questions here:

Why does mySamples return a matrix? Shouldn't it return the last (10th) vector as R keeps the last statement being evaluated?

Is it possible to keep mySamples <- sample(c(1,0), n_toss, replace = T, prob=c(0.5,0.5)) this statement in a separate function and still obtain a same result?

答:
replicate is a wrapper around sapply, so it will essentially in your case:

evaluate and return the results of the expression

do this n times - in your case n_trial = 10 times

combine those 10 results together - by default it will simplify them (into a matrix in your case). If you do not want the results simplified, use simplify = FALSE - in which case you would get a list (of 10 elements), one for each of the 10 replications.

So to answer your questions directly:

1) Yes, R does return the result of the last statement, but does this n_trial times and combines those results together. This is why you get a matrix (or a list, if you use simplify = FALSE in the call to replicate).

2) Yes, you can do that, for example like so:

```<code>n_toss <- 3
n_trial <- 10

sampleFun <- function(n_toss) {
  sample(c(1, 0), n_toss, replace = TRUE, prob = c(0.5, 0.5))
}

mySamples <- replicate(n_trial, sampleFun(n_toss = n_toss))
</code>```

Title: Why does replicate() return a matrix?

Body:
> n_toss = 3; # Number of Tosses
> n_trial = 10; # Number of Trials
>
> mySamples <- sample(c(1,0), n_toss, replace = T, prob=c(0.5,0.5))
> mySamples
[1] 1 0 1
>
> mySamples <- replicate(n_trial,
+              {
+                  mySamples <- sample(c(1,0), n_toss, replace = T, prob=c(0.5,0.5))
+              })
> mySamples
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,]    0    1    1    0    1    0    0    0    0     0
[2,]    1    0    1    1    1    0    0    0    0     0
[3,]    0    0    0    0    1    1    1    1    0     1
>

I have two questions here:

Why does mySamples return a matrix? Shouldn't it return the last (10th) vector as R keeps the last statement being evaluated?

Is it possible to keep mySamples <- sample(c(1,0), n_toss, replace = T, prob=c(0.5,0.5)) this statement in a separate function and still obtain a same result?

Body:
replicate is a wrapper around sapply, so it will essentially in your case:

evaluate and return the results of the expression

do this n times - in your case n_trial = 10 times

combine those 10 results together - by default it will simplify them (into a matrix in your case). If you do not want the results simplified, use simplify = FALSE - in which case you would get a list (of 10 elements), one for each of the 10 replications.

So to answer your questions directly:

1) Yes, R does return the result of the last statement, but does this n_trial times and combines those results together. This is why you get a matrix (or a list, if you use simplify = FALSE in the call to replicate).

2) Yes, you can do that, for example like so:

n_toss <- 3
n_trial <- 10

sampleFun <- function(n_toss) {
  sample(c(1, 0), n_toss, replace = TRUE, prob = c(0.5, 0.5))
}

mySamples <- replicate(n_trial, sampleFun(n_toss = n_toss))


问:
How to use email as a username in Spring Security?
I have to remove a login field from my User class and use email as a username in SecurityUtils

I've already changed j_username parameter in a frontend, but now the issue remains on a backend

```<code>public static String getCurrentUserLogin() {
        SecurityContext securityContext = SecurityContextHolder.getContext();
        Authentication authentication = securityContext.getAuthentication();
        String userName = null;
        if (authentication != null) {
            if (authentication.getPrincipal() instanceof UserDetails) {
                UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal();
                userName = springSecurityUser.getUsername();
            } else if (authentication.getPrincipal() instanceof String) {
                userName = (String) authentication.getPrincipal();
            }
        }
        return userName;
    }
</code>```

and as a result userName is null, becauseUserDetails and Authentication don't have email. How could I set the field email as a 'j_username'? I've tried this

How to login by email instead of username in spring security

solution but it's not enough since I use an anonymousUser

Also, I have an implementation of UserDetailsService but when debugging it's not called when being the anonymousUser

```<code>public class DomainUserDetailsService implements UserDetailsService {

    private final UserRepository userRepository;

    public DomainUserDetailsService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public UserDetails loadUserByUsername(final String login) {
        String lowercaseLogin = login.toLowerCase(Locale.ENGLISH);
        Optional<User> userFromDatabase = userRepository.findOneByLogin(lowercaseLogin);
        return userFromDatabase.map(user -> {
            if (!user.getActivated()) {
                throw new UserNotActivatedException("User " + lowercaseLogin + " was not activated");
            }
            List<GrantedAuthority> grantedAuthorities = user.getAuthorities().stream()
                .map(authority -> new SimpleGrantedAuthority(authority.getName()))
                .collect(Collectors.toList());
            return new org.springframework.security.core.userdetails.User(lowercaseLogin,
                user.getPassword(),
                grantedAuthorities);
        }).orElseThrow(() -> new UsernameNotFoundException("User " + lowercaseLogin + " was not found in the " +
            "database"));
    }
}
</code>```

答:
In order to achieve your goal you will have to control anonymous user behavior. I had that issue before and when the user is logged in the queries are working fine. As M. Denim suggested you should search by email here -> Optional<User> userFromDatabase = userRepository.findOneByEmail(lowercaseLogin);

But in case of anonymous user in getCurrentUserLogin() you have to write an if statement to return anonymous@localhost in case the userName = anonymousUser

Body:
I have to remove a login field from my User class and use email as a username in SecurityUtils

I've already changed j_username parameter in a frontend, but now the issue remains on a backend

public static String getCurrentUserLogin() {
        SecurityContext securityContext = SecurityContextHolder.getContext();
        Authentication authentication = securityContext.getAuthentication();
        String userName = null;
        if (authentication != null) {
            if (authentication.getPrincipal() instanceof UserDetails) {
                UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal();
                userName = springSecurityUser.getUsername();
            } else if (authentication.getPrincipal() instanceof String) {
                userName = (String) authentication.getPrincipal();
            }
        }
        return userName;
    }

and as a result userName is null, becauseUserDetails and Authentication don't have email. How could I set the field email as a 'j_username'? I've tried this

How to login by email instead of username in spring security

solution but it's not enough since I use an anonymousUser

Also, I have an implementation of UserDetailsService but when debugging it's not called when being the anonymousUser

public class DomainUserDetailsService implements UserDetailsService {

    private final UserRepository userRepository;

    public DomainUserDetailsService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public UserDetails loadUserByUsername(final String login) {
        String lowercaseLogin = login.toLowerCase(Locale.ENGLISH);
        Optional<User> userFromDatabase = userRepository.findOneByLogin(lowercaseLogin);
        return userFromDatabase.map(user -> {
            if (!user.getActivated()) {
                throw new UserNotActivatedException("User " + lowercaseLogin + " was not activated");
            }
            List<GrantedAuthority> grantedAuthorities = user.getAuthorities().stream()
                .map(authority -> new SimpleGrantedAuthority(authority.getName()))
                .collect(Collectors.toList());
            return new org.springframework.security.core.userdetails.User(lowercaseLogin,
                user.getPassword(),
                grantedAuthorities);
        }).orElseThrow(() -> new UsernameNotFoundException("User " + lowercaseLogin + " was not found in the " +
            "database"));
    }
}


问:
How to i insert a JSON object into an array?
I have a JSON

```<code>"passengers": [{
        "accompaniedByInfant": true,
        "birthDate": {
            "day": 6,
            "fractionalSecond": 0.000,
            "hour": 0,
            "minute": 0,
            "month": 9,
            "orig_day": 6,
            "orig_fracSeconds": 0.000,
            "orig_hour": 0,
            "orig_minute": 0,
            "orig_month": 9,
            "orig_second": 0,
            "orig_timezone": 330,
            "orig_year": 1991,
            "second": 0,
            "timezone": 330,
            "year": 1991
        },
        "hasStrecher": false,
        "parentSequence": 0,
        "passengerTypeCode": "ADLT",
                "gender":"M"
        "personName": {
            "givenName": "v",
            "nameTitle": "MR",
            "shareMarketInd": false,
            "surname": "j"
        },
        "requestedSeatCount": 1,
        "shareMarketInd": false,
        "unaccompaniedMinor": false
    }, {
        "accompaniedByInfant": false,
        "birthDate": {
            "day": 10,
            "fractionalSecond": 0.000,
            "hour": 0,
            "minute": 0,
            "month": 10,
            "orig_day": 10,
            "orig_fracSeconds": 0.000,
            "orig_hour": 0,
            "orig_minute": 0,
            "orig_month": 10,
            "orig_second": 0,
            "orig_timezone": 330,
            "orig_year": 2010,
            "second": 0,
            "timezone": 330,
            "year": 2010
        },
        "hasStrecher": false,
        "parentSequence": 0,
        "passengerTypeCode": "CHLD",
        "personName": {
            "givenName": "some",
            "shareMarketInd": false,
            "surname": "child"
        },
        "requestedSeatCount": 1,
        "shareMarketInd": false,
        "unaccompaniedMinor": false
    },

</code>```

and so on depending on the number of passengers.

I have to sent this to the server in

```<code>let param : [String: Any] =[ "passengers":passengerparameterarray,"pwd": password,"requestPurpose": "MODIFY_PERMANENTLY_AND_CALC","unm": username ]
</code>```

Here passengerparameterarray is an array of type string.(here is the issue). I stored details of each passenger in an array
paramarray and whenever user finishes adding details, paramarray is added to the passengerparameterarray on position depending on the indexPath. (1 passenger = added on 0th index, 2 = on 0th and 1st index and so on).

But when I send it to server it goes like

```<code>"passengers" : [ [ .....  ] ]
</code>```

This gives me error as I have an array inside of the array. How do I fix this? I try changing to string but that gives me error as String isn't JSON object because of the " coming before { .

I converted each array to JSON Object. But how do i JSON Object the main array? As the Main array is [String]() . If i try changing to [String:Any]() , things like

```<code>array.insert()
</code>```

Wont work.

How do I fix this? I want to add the JSON object into an array and then sent it to the server.

答:
This was a stupid question. This all happened because originally my array was

```<code>var passengerparameterarray = [Array<Any>]()
</code>```

instead of

```<code>var passengerparameterarray = Array<[String: Any]>()
</code>```

Which as expected stopped me from inserting JSON object which is in the form of "String:Any"

Body:
I have a JSON

"passengers": [{
        "accompaniedByInfant": true,
        "birthDate": {
            "day": 6,
            "fractionalSecond": 0.000,
            "hour": 0,
            "minute": 0,
            "month": 9,
            "orig_day": 6,
            "orig_fracSeconds": 0.000,
            "orig_hour": 0,
            "orig_minute": 0,
            "orig_month": 9,
            "orig_second": 0,
            "orig_timezone": 330,
            "orig_year": 1991,
            "second": 0,
            "timezone": 330,
            "year": 1991
        },
        "hasStrecher": false,
        "parentSequence": 0,
        "passengerTypeCode": "ADLT",
                "gender":"M"
        "personName": {
            "givenName": "v",
            "nameTitle": "MR",
            "shareMarketInd": false,
            "surname": "j"
        },
        "requestedSeatCount": 1,
        "shareMarketInd": false,
        "unaccompaniedMinor": false
    }, {
        "accompaniedByInfant": false,
        "birthDate": {
            "day": 10,
            "fractionalSecond": 0.000,
            "hour": 0,
            "minute": 0,
            "month": 10,
            "orig_day": 10,
            "orig_fracSeconds": 0.000,
            "orig_hour": 0,
            "orig_minute": 0,
            "orig_month": 10,
            "orig_second": 0,
            "orig_timezone": 330,
            "orig_year": 2010,
            "second": 0,
            "timezone": 330,
            "year": 2010
        },
        "hasStrecher": false,
        "parentSequence": 0,
        "passengerTypeCode": "CHLD",
        "personName": {
            "givenName": "some",
            "shareMarketInd": false,
            "surname": "child"
        },
        "requestedSeatCount": 1,
        "shareMarketInd": false,
        "unaccompaniedMinor": false
    },

and so on depending on the number of passengers.

I have to sent this to the server in

let param : [String: Any] =[ "passengers":passengerparameterarray,"pwd": password,"requestPurpose": "MODIFY_PERMANENTLY_AND_CALC","unm": username ]

Here passengerparameterarray is an array of type string.(here is the issue). I stored details of each passenger in an array
paramarray and whenever user finishes adding details, paramarray is added to the passengerparameterarray on position depending on the indexPath. (1 passenger = added on 0th index, 2 = on 0th and 1st index and so on).

But when I send it to server it goes like

"passengers" : [ [ .....  ] ]

This gives me error as I have an array inside of the array. How do I fix this? I try changing to string but that gives me error as String isn't JSON object because of the " coming before { .

I converted each array to JSON Object. But how do i JSON Object the main array? As the Main array is [String]() . If i try changing to [String:Any]() , things like

array.insert()

Wont work.

How do I fix this? I want to add the JSON object into an array and then sent it to the server.

Body:
This was a stupid question. This all happened because originally my array was

var passengerparameterarray = [Array<Any>]()

instead of

var passengerparameterarray = Array<[String: Any]>()

Which as expected stopped me from inserting JSON object which is in the form of "String:Any"


问:
WPF Binding: Fallback to value defined in Style
How can a WPF color binding fall back to the default value?

Here is what I am trying to do:

<TextBox Text="Some Binding"/>
```

<p>Will produce a Textbox with some background color defined elsewhere.</p>

<pre class="lang-xaml prettyprint-override"><code><Textbox Text="Some Binding"
  Background = "{Binding Path=Status,
  TargetNullValue='Same color as the Textbox above, please',
  Converter=***}"/>
</code>```

This textbox is supposed to change its color based on the status (which works fine) but for certain values I want the background to revert back to the color which would be used without the binding at all.

Additional info: I use these Textboxes in a resource dictionary.

<ResourceDictionary>

答:
This will not work, as the second setter for Background will always overwrite the first:

```<code><!-- Set the background based on the level into the tree. -->
<Setter Property="Background" Value="{Binding DataItem.Level, Converter={StaticResource IntegerToBrushConverter}}"/>
<!-- Row is red if no live updates received for N seconds -->
<Setter Property="Background" Value="{Binding DataItem.IsStale, Converter={StaticResource IsStaleToBackgroundConverter}}"/>
</code>```

To fix, wrap in a DataTrigger, so the second setter for Background is not even evaluated if the value is False:

```<code><Setter Property="Background" Value="{Binding DataItem.Level, Converter={StaticResource IntegerToBrushConverter}}"/>
<!-- Row is red if no live updates received for N seconds -->
<Style.Triggers>
    <DataTrigger Binding="{Binding DataItem.IsStale}" Value="True">
        <Setter Property="Background" Value="{Binding DataItem.IsStale, Converter={StaticResource IsStaleToBackgroundConverter}}"/>
    </DataTrigger>
</Style.Triggers>
</code>```

This means that the first setter for Background will be applied, and the second setter will be ignored if the IsStale value is false.

Appendix A: Supporting Source Code

Converter:

```<code>public class BooleanToBrushConverter : ValueConverterBase
{
    public Brush TrueBrush { get; set; }

    public Brush FalseBrush { get; set; }

    public Brush DefaultBrush { get; set; }

    public override object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        try
        {
            if (value==null)
            {
                return null;
            }

            var booleanValue = (bool)value;

            return booleanValue ? this.TrueBrush : this.FalseBrush;
        }
        catch (InvalidCastException)
        {
            return this.DefaultBrush;
        }
    }
}
</code>```

And this goes between the .Resources tags:

```<code><colorBrushes:BooleanToBrushConverter x:Key="IsStaleToBackgroundConverter"
                                      TrueBrush="{StaticResource RedStaleBrush}"
                                      FalseBrush="{StaticResource TransparentBrush}"
                                      DefaultBrush="{StaticResource TransparentBrush}" />
</code>```

You will also have to define the colors, or replace them with a constant, e.g. DefaultBrush="Green".

Body:
How can a WPF color binding fall back to the default value?

Here is what I am trying to do:

<TextBox Text="Some Binding"/>

Will produce a Textbox with some background color defined elsewhere.

<Textbox Text="Some Binding"
  Background = "{Binding Path=Status,
  TargetNullValue='Same color as the Textbox above, please',
  Converter=***}"/>

This textbox is supposed to change its color based on the status (which works fine) but for certain values I want the background to revert back to the color which would be used without the binding at all.

Additional info: I use these Textboxes in a resource dictionary.

<ResourceDictionary>

Body:
This will not work, as the second setter for Background will always overwrite the first:

<!-- Set the background based on the level into the tree. -->
<Setter Property="Background" Value="{Binding DataItem.Level, Converter={StaticResource IntegerToBrushConverter}}"/>
<!-- Row is red if no live updates received for N seconds -->
<Setter Property="Background" Value="{Binding DataItem.IsStale, Converter={StaticResource IsStaleToBackgroundConverter}}"/>

To fix, wrap in a DataTrigger, so the second setter for Background is not even evaluated if the value is False:

<Setter Property="Background" Value="{Binding DataItem.Level, Converter={StaticResource IntegerToBrushConverter}}"/>
<!-- Row is red if no live updates received for N seconds -->
<Style.Triggers>
    <DataTrigger Binding="{Binding DataItem.IsStale}" Value="True">
        <Setter Property="Background" Value="{Binding DataItem.IsStale, Converter={StaticResource IsStaleToBackgroundConverter}}"/>
    </DataTrigger>
</Style.Triggers>

This means that the first setter for Background will be applied, and the second setter will be ignored if the IsStale value is false.

Appendix A: Supporting Source Code

Converter:

public class BooleanToBrushConverter : ValueConverterBase
{
    public Brush TrueBrush { get; set; }

    public Brush FalseBrush { get; set; }

    public Brush DefaultBrush { get; set; }

    public override object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        try
        {
            if (value==null)
            {
                return null;
            }

            var booleanValue = (bool)value;

            return booleanValue ? this.TrueBrush : this.FalseBrush;
        }
        catch (InvalidCastException)
        {
            return this.DefaultBrush;
        }
    }
}

And this goes between the .Resources tags:

<colorBrushes:BooleanToBrushConverter x:Key="IsStaleToBackgroundConverter"
                                      TrueBrush="{StaticResource RedStaleBrush}"
                                      FalseBrush="{StaticResource TransparentBrush}"
                                      DefaultBrush="{StaticResource TransparentBrush}" />

You will also have to define the colors, or replace them with a constant, e.g. DefaultBrush="Green".


问:
How can I get the format of an image?
I have an image in my drawable folder and I want to know which format it is. How can I do this?</p>

答:
I think you can't do this. As i know all drawables are "precomplied" and there are no info about initial drawable type.

Why are you bothering about format?

Title: How can I get the format of an image?


问:
Visual Studio hangs when clicking "Close & Update" in Tabular model
I am going crazy now with a tabular project in Visual Studio.

When I try to update a table through the Source Data property:

and then clicking on Design and then refresh the query and afterwards clicking on Home -> Close and Update the window turns grey and it hangs forever. I have to end the VS process from Task Manager in order to continue working.

There is no extra steps applied or some other logic going on in the M query (autogenerated) but still freezes and will not update the data/columns.

I have also tried doing that from the Partitions window as proposed
here on MSDN
but it still freezes.

Visual Studio Enterprise 2015 version, Update 3

Please save me :)

答:
The solution could be to use the Partitions window instead of the Source Data
It won't freeze that often when clicking "Close & Update"

Edit:
Visual Studion 2017 works much better and since I started using it, I haven't got this bug so thumbs up for fixing it :)


问:
Typescript, from us currency to es currency
I'm trying to convert an us currency to a spanish currency (ok) but when I try to get again the us currency I get a Nan. What's wrong?

Thanks

```<code>const esp = Number('5000.55').toLocaleString(); // esp = '5.000,55'
const us = Number('5.000,55').toLocaleString('en-US'); // us = 'NaN'
</code>```

答:
This is because Number('5.000,55') is not correct -> it returns NaN.

There is no native js function to get the number from the .toLocaleString() result.

What you could do :

1 - Save the initial value into a variable :

```<code>const init = '5000.55';
const esp = Number(init).toLocaleString(); // esp = '5.000,55'
const us = Number(init).toLocaleString('en-US'); // us = '5,000.55'
</code>```

2 - Use some 3rd party library that deal with number manipulation.

3 - Create your own function that parses the result into whatever you like (might be hard to deal with all cases...)

Body:
I'm trying to convert an us currency to a spanish currency (ok) but when I try to get again the us currency I get a Nan. What's wrong?

Thanks

const esp = Number('5000.55').toLocaleString(); // esp = '5.000,55'
const us = Number('5.000,55').toLocaleString('en-US'); // us = 'NaN'

Body:
This is because Number('5.000,55') is not correct -> it returns NaN.

There is no native js function to get the number from the .toLocaleString() result.

What you could do :

1 - Save the initial value into a variable :

const init = '5000.55';
const esp = Number(init).toLocaleString(); // esp = '5.000,55'
const us = Number(init).toLocaleString('en-US'); // us = '5,000.55'

2 - Use some 3rd party library that deal with number manipulation.

3 - Create your own function that parses the result into whatever you like (might be hard to deal with all cases...)


问:
How to make sure that the character length/set length in a field is set to a particular number when using php?
I have a form field which requires only numbers to be filled and the user should enter 8 digits in order to submit the form. What is the command that I need to use when writing my php/html code?

Tried using max but that also means I can enter 0 and still submit the form. Any thoughts on how to set a length so that you are forced to enter those number digits?

```<code><label>Line Number</label>
 <input type="number" name="Line" class="form-control" max="999" placeholder="Enter Line Number" value="<?php echo $Line; ?>" />
</code>```

I expect the answer to have 3 digits entered. Nothing less and nothing more. So can be 000 to 999. So even if you want to say 0 you need to enter 000 to submit the form.

if(empty($_POST["Line"])) {
    $error .= '
Please Enter Line Number
';
} else {
    $Line = clean_text($_POST["Line"]);
}
```

答:
All input-values in the $_POST array are strings. So just check the length of the string, by doing strlen($_POST["Line") != 3. You can also check if the string is purely numeric by using ctype_digit().

if (empty($_POST["Line"])) {
    $error .= '
Please Enter Line Number
';
} elseif (strlen($_POST["Line") != 3) {
   // Do something here, it was not 3 characters long
} elseif (!ctype_digit($_POST["Line"])) {
   // The string does not contain only numbers
} else {
    $Line = clean_text($_POST["Line"]);
}
```

Body:
I have a form field which requires only numbers to be filled and the user should enter 8 digits in order to submit the form. What is the command that I need to use when writing my php/html code?

Tried using max but that also means I can enter 0 and still submit the form. Any thoughts on how to set a length so that you are forced to enter those number digits?

Line Number
 <input type="number" name="Line" class="form-control" max="999" placeholder="Enter Line Number" value="<?php echo $Line; ?>" />

I expect the answer to have 3 digits entered. Nothing less and nothing more. So can be 000 to 999. So even if you want to say 0 you need to enter 000 to submit the form.

if(empty($_POST["Line"])) {
    $error .= '
Please Enter Line Number
';
} else {
    $Line = clean_text($_POST["Line"]);
}

Body:
All input-values in the $_POST array are strings. So just check the length of the string, by doing strlen($_POST["Line") != 3. You can also check if the string is purely numeric by using ctype_digit().

if (empty($_POST["Line"])) {
    $error .= '<p><label class="text-danger">Please Enter Line Number</label></p>';
} elseif (strlen($_POST["Line") != 3) {
   // Do something here, it was not 3 characters long
} elseif (!ctype_digit($_POST["Line"])) {
   // The string does not contain only numbers
} else {
    $Line = clean_text($_POST["Line"]);
}