问:
React/JavaScript, can someone explain why setState doesn't seem to correctly update the state during the function?

searchProject(title, language, length, experience) {
        if (title !== "") {
            const projects = this.state.projectList.filter(
                p => p.title === title
            );
            this.setState({projectList : projects});
            }
        if (language !== "") {
            const projects = this.state.projectList.filter(
                p => p.language === language
            );
            this.setState({projectList : projects});
            }
        if (length !== 0) {
            const projects = this.state.projectList.filter(
                p => p.length === length
            );
            this.setState({projectList : projects});
            }
        if (experience !== "") {
            const projects = this.state.projectList.filter(
                p => p.experience === experience
            );
            this.setState({projectList : projects});
            }

        }```

I have this snippet of code in my JS file which doesn't seem to do what I want it to do. It should be a filtering function which filters projects which have the same parameters as I specify. I'm very new to JS, so I don't think this is at all the most efficient way to do things, but I thought it should work. The logic of the function is that it sets the projectList state to the projectList which only contains the specified title, then it sets that new state to a state which only contains the specified language and so on... But it seems to only work for the last parameter I set. So if I fill in the experience parameter, it would ignore all projects which don't have that specified experience only. It doesn't matter what title or language or length I set. I think it has something to do with how setState works but I'm not sure. Could someone explain to me how I could fix this problem? Thank you!

答:
From your code I am assuming that you call searchProject as an event handler. When you do that the state updates inside the function are batched.

Now since you have multiple if conditions within your code, you can have multiple blocks of state states that can happen together. and since all of them use this.state to filter, the last call to this.setState is what will be used by react after batching the results

The solution here is to call this.setState once like

searchProject(title, language, length, experience) {
  let projects = [...this.state.projectList];
  if (title !== "") {
      projects = projects.filter(
          p => p.title === title
      );
  }
  if (language !== "") {
      projects = projects.filter(
          p => p.language === language
      );
  }
  if (length !== 0) {
      projects = projects.filter(
          p => p.length === length
      );
  }
  if (experience !== "") {
      projects = projects.filter(
          p => p.experience === experience
      );
  }
  this.setState({ projectList: projects});

}
```

Body:
searchProject(title, language, length, experience) {
        if (title !== "") {
            const projects = this.state.projectList.filter(
                p => p.title === title
            );
            this.setState({projectList : projects});
            }
        if (language !== "") {
            const projects = this.state.projectList.filter(
                p => p.language === language
            );
            this.setState({projectList : projects});
            }
        if (length !== 0) {
            const projects = this.state.projectList.filter(
                p => p.length === length
            );
            this.setState({projectList : projects});
            }
        if (experience !== "") {
            const projects = this.state.projectList.filter(
                p => p.experience === experience
            );
            this.setState({projectList : projects});
            }

        }

I have this snippet of code in my JS file which doesn't seem to do what I want it to do. It should be a filtering function which filters projects which have the same parameters as I specify. I'm very new to JS, so I don't think this is at all the most efficient way to do things, but I thought it should work. The logic of the function is that it sets the projectList state to the projectList which only contains the specified title, then it sets that new state to a state which only contains the specified language and so on... But it seems to only work for the last parameter I set. So if I fill in the experience parameter, it would ignore all projects which don't have that specified experience only. It doesn't matter what title or language or length I set. I think it has something to do with how setState works but I'm not sure. Could someone explain to me how I could fix this problem? Thank you!


来源: stackexchange

问:
discord.py get member instance from name#discriminator
I have a string with the name of an user user = 'somename#1111' how can I mention him? (I get the name from google sheets that's why it's a string)

I tried with:

```<code>@client.command()
async def mention(ctx):
    user : discord.Member = 'somename#1111'
    await ctx.send(f"{user.mention} hello!")
</code>```

But it doesn't work

答:
I haven't used user.mention, but what I do is I get the user's id, then mention them like this:

await ctx.send(f'<@!{user.id}> hello!')
```

ContentLicense: CC BY-SA 4.0

Body:
I have a string with the name of an user user = 'somename#1111' how can I mention him? (I get the name from google sheets that's why it's a string)

I tried with:

@client.command()
async def mention(ctx):
    user : discord.Member = 'somename#1111'
    await ctx.send(f"{user.mention} hello!")

But it doesn't work


问:
React Navigation: best way to implement logout navigation?
I'm using react-navigation@4.0.10 in my React Native app, and have a Login screen and two TabNavigator screens. Logging in from the Login screen takes me to TabNavigator_1, and if I log out from TabNavigator_1 I just use this.props.navigation.goBack(). The problem is, to get to TabNavigator_2 I click a button in TabNavigator_1 which triggers this.props.navigation.navigate('TabNavigator_2'), so TabNavigator_2 is now on top of the stack, and calling this.props.navigation.goBack() would just take me back to TabNavigator_1 instead of Login.

What's the best way to approach this, so that clicking Log out from TabNavigator_1 and TabNavigator_2 takes me back to Login?

答:
You can try using :

```<code>this.props.navigation.navigate("Login")
</code>```

Based on this documentation:

React Navigation 4.x

It will be better if you clear the asyncStorage after user clicked the logout button.

Body:
You can try using :

this.props.navigation.navigate("Login")

Based on this documentation:

React Navigation 4.x

It will be better if you clear the asyncStorage after user clicked the logout button.


问:
Rxjs create an observable that emits when a function is called
I'm likely missing something simple but can't quite puzzle this out from the docs. I'd simply like to have a function that when called will emit a value on an rxjs observable.

Psuedocode:

```<code>const myFunction = () => true //or whatever value
const myObservable = ... emit true whenever myFunction is called

...use myFunction somewhere where it being called is a useful event so
observers of myObservable can process it
</code>```

What's the standard pattern to emit a value when a function is called with rxjs?

答:
You need a Subject for that https://www.learnrxjs.io/learn-rxjs/subjects

Here is the reworked example from the documentation:

```<code>import { Subject } from 'rxjs';

const myObservable = new Subject<number>();

const myFunction = () => {
  subject.next(1);
  subject.next(2);
}

myObservable.subscribe({
  next: (v) => console.log(`observerA: ${v}`)
});
myObservable.subscribe({
  next: (v) => console.log(`observerB: ${v}`)
});

// ...use myFunction somewhere where it being called is a useful event so
myFunction();
</code>```

Normally, you don't even need myFunction. Calling subject.next() would be enough.

Body:
I'm likely missing something simple but can't quite puzzle this out from the docs. I'd simply like to have a function that when called will emit a value on an rxjs observable.

Psuedocode:

const myFunction = () => true //or whatever value
const myObservable = ... emit true whenever myFunction is called

...use myFunction somewhere where it being called is a useful event so
observers of myObservable can process it

What's the standard pattern to emit a value when a function is called with rxjs?

Body:
You need a Subject for that https://www.learnrxjs.io/learn-rxjs/subjects

Here is the reworked example from the documentation:

import { Subject } from 'rxjs';

const myObservable = new Subject<number>();

const myFunction = () => {
  subject.next(1);
  subject.next(2);
}

myObservable.subscribe({
  next: (v) => console.log(`observerA: ${v}`)
});
myObservable.subscribe({
  next: (v) => console.log(`observerB: ${v}`)
});

// ...use myFunction somewhere where it being called is a useful event so
myFunction();

Normally, you don't even need myFunction. Calling subject.next() would be enough.


问:
Cakephp - Display list element inside if
I'm currently displaying a list using cakephp, but I've been unable to redirect on clicking in an specific elemnt component which has to disappear in some cases, this is what I have:

```<code><li><a href="<?php echo $this->Url->build(["controller" => "pages","action" => "index"]);?>">Top 20</a>
<?php
$a = true;
  if($a){
    $prod_pm= '<li><a href="<?= $this->Url->build(["controller" => "Catalogo","action" => "cat",11229])?
    >">Promotions</a>';
  }else{
    $prod_pm = '';
}?>
<?= $prod_pm ?>
<li><a href="<?= $this->Url->build(["controller" => "Catalogo","action" => "cat",11050]) ?>"></a>
</code>```

It seems that the php redirected after the href citation is not working that way, also I tried declaring a variable with the code outside and inserting in place of $this->Url->build(["controller" => "Catalogo","action" => "cat",11229])
but didn't work.

Thanks in advance for any hint or help.

答:
It seems like you are just inserting a string to the href attribute.

Try:

```<code>$prod_pm = '<li><a href="'.$this->Url->build(["controller" => "Catalogo","action" => "cat",11229]).'">Promotions</a>';
</code>```

Body:
I'm currently displaying a list using cakephp, but I've been unable to redirect on clicking in an specific elemnt component which has to disappear in some cases, this is what I have:

<a href="<?php echo $this->Url->build(["controller" => "pages","action" => "index"]);?>">Top 20
<?php
$a = true;
  if($a){
    $prod_pm= '
<a href="<?= $this->Url->build(["controller" => "Catalogo","action" => "cat",11229])?
    >">Promotions';
  }else{
    $prod_pm = '';
}?>
<?= $prod_pm ?>

<a href="<?= $this->Url->build(["controller" => "Catalogo","action" => "cat",11050]) ?>">

It seems that the php redirected after the href citation is not working that way, also I tried declaring a variable with the code outside and inserting in place of $this->Url->build(["controller" => "Catalogo","action" => "cat",11229])
but didn't work.

Thanks in advance for any hint or help.

Body:
It seems like you are just inserting a string to the href attribute.

Try:

$prod_pm = '<li><a href="'.$this->Url->build(["controller" => "Catalogo","action" => "cat",11229]).'">Promotions</a>';


问:
Bot Framework .Net, How I can get either the Username, Id, Token from my Web App to Bot
I created a Bot that will interact with the currently logged-in user from my Web(React-app). So in my Website if I am currently login and if I click the bot which I embedded using Web Chat. So I want to get that token/username/id which I saved in the cookies/state. How can I pass that data to the Bot? So that my Bot will know who he's talking to. Because I don't want my Bot to login again since he is already logged-in in my Web app. </p>

答:
I was able to find some resources and it worked on my end.

- https://github.com/Microsoft/BotFramework-WebChat

- (Another example) https://user-images.githubusercontent.com/42096464/82071374-a1fc8680-969b-11ea-8080-23c618163096.png


问:
Jquery / JavaScript get value from a td of table which is inside a div with id

                Firstname

                Secondname

                name1

                name2

```

This is my HTML structure and I need to get the values 'Firstname' and 'name1' from the table using Jquery or Javascript. Only the outer div has the id. Can someone help.

答:
Using Javascript

                Firstname

                Secondname

                name1

                name2

```

Body:
                Firstname

                Secondname

                name1

                name2

This is my HTML structure and I need to get the values 'Firstname' and 'name1' from the table using Jquery or Javascript. Only the outer div has the id. Can someone help.

Body:
Using Javascript

<div id="myDiv">
    <table>
        <tr>
            <td>
                Firstname
            </td>
            <td>
                Secondname
            </td>
        </tr>
        <tr>
            <td>
                name1
            </td>
            <td>
                name2
            </td>
        </tr>
    </table>
</div>

<script>
    const allTableRows = document.querySelectorAll('#myDiv table tr');
    const firstRow = allTableRows[0];
    const secondRow = allTableRows[1];
    const firstNameLabel = firstRow.getElementsByTagName('td')[0].innerHTML;
    const firstNameValue = secondRow.getElementsByTagName('td')[0].innerHTML;

    console.log(firstNameLabel.trim());
    console.log(firstNameValue.trim());
</script>


问:
C# Linq OrderBy based on condition
I have a foreach loop that I want to change:

foreach (var line in lines.OrderBy(x=> x.ColA))

If a condition is met, then instead of ordering by ColA, I want to order by ColB.

I know this could be done like the following:

```<code>var orderLines = new List<OrderLines>();
if (condition)
    orderLines = lines.OrderBy(x => x.ColB).ToList();
else
    orderLines = lines.OrderBy(x => x.ColA).ToList(); ;

foreach (var line in orderLines)
</code>```

But I am sure there is a more elegant solution.

答:
That is probably about as good as it gets.

Remember that behind that lambda expression magic happens which (effectively) binds to a Comparer<T> where T depends on the type of the columns being compared.

To make this more terse might make it less efficient.  Specifically converting and comparing strings makes it both slower and can get you into trouble (ints sort to 1,2,3,...10,11,... vs their strings to "1","10","11",..."19","2","20","21"...).

A "one-liner" is only elegant if it's behaviour is obvious, otherwise it is obfuscated.

Your code is fine.  (IMO;-)

Title: C# Linq OrderBy based on condition

Body:
I have a foreach loop that I want to change:

foreach (var line in lines.OrderBy(x=> x.ColA))

If a condition is met, then instead of ordering by ColA, I want to order by ColB.

I know this could be done like the following:

var orderLines = new List<OrderLines>();
if (condition)
    orderLines = lines.OrderBy(x => x.ColB).ToList();
else
    orderLines = lines.OrderBy(x => x.ColA).ToList(); ;

foreach (var line in orderLines)

But I am sure there is a more elegant solution.


问:
Prebuilt libraries not found for sharp while generating Gatsby starter
I try to generate a Gatsby blog starter using following command:

```<code>npx gatsby new my-blog-starter https://github.com/tomoyukikashiro/gatsby-starter-blog-amp-to-pwa
</code>```

While npm install is running the sharp thirdparty does not find its prebuilt binaries. Because of this it will be tried to be built on my PC, but it fails with following error.

```<code>info Installing packages...

> sharp@0.21.3 install C:\Repositories\my-blog-starter\node_modules\sharp
> (node install/libvips && node install/dll-copy && prebuild-install) || (node-gyp rebuild && node install/dll-copy)

info sharp Using cached C:\Users\Milan\AppData\Roaming\npm-cache\_libvips\libvips-8.7.0-win32-x64.tar.gz
info sharp Creating C:\Repositories\my-blog-starter\node_modules\sharp\build\Release
info sharp Copying DLLs from C:\Repositories\my-blog-starter\node_modules\sharp\vendor\lib to C:\Repositories\my-blog-st
arter\node_modules\sharp\build\Release
prebuild-install WARN install No prebuilt binaries found (target=12.17.0 runtime=node arch=x64 platform=win32)

C:\Repositories\my-blog-starter\node_modules\sharp>if not defined npm_config_node_gyp (node "C:\Program Files\nodejs\nod
e_modules\npm\node_modules\npm-lifecycle\node-gyp-bin\\..\..\node_modules\node-gyp\bin\node-gyp.js" rebuild )  else (nod
e "C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\bin\node-gyp.js" rebuild )
Building the projects in this solution one at a time. To enable parallel build, please add the "-m" switch.
  VError.cpp
  VInterpolate.cpp
  VImage.cpp
  win_delay_load_hook.cc
     Creating library C:\Repositories\my-blog-starter\node_modules\sharp\build\Release\libvips-cpp.lib and object C:\Re
  positories\my-blog-starter\node_modules\sharp\build\Release\libvips-cpp.exp
  libvips-cpp.vcxproj -> C:\Repositories\my-blog-starter\node_modules\sharp\build\Release\\libvips-cpp.dll
  common.cc
  metadata.cc
  stats.cc
  operations.cc
C:\Repositories\my-blog-starter\node_modules\nan\nan_implementation_12_inl.h(356,37): error C2660: 'v8::StringObject::N
ew': function does not take 1 arguments (compiling source file ..\src\metadata.cc) [C:\Repositories\my-blog-starter\nod
e_modules\sharp\build\sharp.vcxproj]
</code>```

Environment:

Node.js version 12.17.0

npm version 6.14.4

npx version 10.2.2

There is no corporate proxy that would block the requests for the prebuilt binaries.

Are there any tips, how can I solve this issue? For me it is also fine to build the thirdparty locally, but I don't see exactly what is missing.

答:
Your starter requires sharp version 0.21.3 (as shown in your error log)

Node 12 support on windows was introduced in version 0.22.1.

You could try upgrading gatsby-plugin-sharp and gatsby-transformer-sharp in your starter, but you might encounter other errors, as the starter hasn't been updated for a while.

Body:
I try to generate a Gatsby blog starter using following command:

npx gatsby new my-blog-starter https://github.com/tomoyukikashiro/gatsby-starter-blog-amp-to-pwa

While npm install is running the sharp thirdparty does not find its prebuilt binaries. Because of this it will be tried to be built on my PC, but it fails with following error.

info Installing packages...

> sharp@0.21.3 install C:\Repositories\my-blog-starter\node_modules\sharp
> (node install/libvips && node install/dll-copy && prebuild-install) || (node-gyp rebuild && node install/dll-copy)

info sharp Using cached C:\Users\Milan\AppData\Roaming\npm-cache\_libvips\libvips-8.7.0-win32-x64.tar.gz
info sharp Creating C:\Repositories\my-blog-starter\node_modules\sharp\build\Release
info sharp Copying DLLs from C:\Repositories\my-blog-starter\node_modules\sharp\vendor\lib to C:\Repositories\my-blog-st
arter\node_modules\sharp\build\Release
prebuild-install WARN install No prebuilt binaries found (target=12.17.0 runtime=node arch=x64 platform=win32)

C:\Repositories\my-blog-starter\node_modules\sharp>if not defined npm_config_node_gyp (node "C:\Program Files\nodejs\nod
e_modules\npm\node_modules\npm-lifecycle\node-gyp-bin\\..\..\node_modules\node-gyp\bin\node-gyp.js" rebuild )  else (nod
e "C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\bin\node-gyp.js" rebuild )
Building the projects in this solution one at a time. To enable parallel build, please add the "-m" switch.
  VError.cpp
  VInterpolate.cpp
  VImage.cpp
  win_delay_load_hook.cc
     Creating library C:\Repositories\my-blog-starter\node_modules\sharp\build\Release\libvips-cpp.lib and object C:\Re
  positories\my-blog-starter\node_modules\sharp\build\Release\libvips-cpp.exp
  libvips-cpp.vcxproj -> C:\Repositories\my-blog-starter\node_modules\sharp\build\Release\\libvips-cpp.dll
  common.cc
  metadata.cc
  stats.cc
  operations.cc
C:\Repositories\my-blog-starter\node_modules\nan\nan_implementation_12_inl.h(356,37): error C2660: 'v8::StringObject::N
ew': function does not take 1 arguments (compiling source file ..\src\metadata.cc) [C:\Repositories\my-blog-starter\nod
e_modules\sharp\build\sharp.vcxproj]

Environment:

Node.js version 12.17.0

npm version 6.14.4

npx version 10.2.2

There is no corporate proxy that would block the requests for the prebuilt binaries.

Are there any tips, how can I solve this issue? For me it is also fine to build the thirdparty locally, but I don't see exactly what is missing.


问:
I don't need/want a key!
I have some views that I want to use EF 4.1 to query. These are specific optimized views that will not have keys to speak of; there will be no deletions, updates, just good ol'e select.

But EF wants a key set on the model. Is there a way to tell EF to move on, there's nothing to worry about?

More Details

The main purpose of this is to query against a set of views that have been optimized by size, query parameters and joins. The underlying tables have their PKs, FKs and so on. It's indexed, statiscized (that a word?) and optimized.

I'd like to have a class like (this is a much smaller and simpler version of what I have...):

```<code>public MyObject //this is a view
{
   Name{get;set}
   Age{get;set;}
   TotalPimples{get;set;}
}
</code>```

and a repository, built off of EF 4.1 CF where I can just

```<code>public List<MyObject> GetPimply(int numberOfPimples)
{
    return db.MyObjects.Where(d=> d.TotalPimples > numberOfPimples).ToList();
}
</code>```

I could expose a key, but whats the real purpose of dislaying a 2 or 3 column natural key? That will never be used?

Current Solution

Seeming as their will be no EF CF solution, I have added a complex key to the model and I am exposing it in the model. While this goes "with the grain" on what one expects a "well designed" db model to look like, in this case, IMHO, it added nothing but more logic to the model builder, more bytes over the wire, and extra properties on a class. These will never be used.

答:
EF is looking for a unique way to identify records. I am not sure if you can force it to go counter to its nature of desiring something unique about objects.

But, this is an answer to the "show me how to solve my problem the way I want to solve it" question and not actually tackling your core business requirement.

If this is a "I don't want to show the user the key", then don't bind it when you bind the data to your form (web or windows). If this is a "I need to share these items, but don't want to give them the keys" issue, then map or surrogate the objects into an external domain model. Adds a bit of weight to the solution, but allows you to still do the heavy lifting with a drag and drop surface (EF).

The question is what is the business requirement that is pushing you to create a bunch of objects without a unique identifier (key).

ContentLicense: CC BY-SA 3.0

Title: I don't need/want a key!

Body:
I have some views that I want to use EF 4.1 to query. These are specific optimized views that will not have keys to speak of; there will be no deletions, updates, just good ol'e select.

But EF wants a key set on the model. Is there a way to tell EF to move on, there's nothing to worry about?

More Details

The main purpose of this is to query against a set of views that have been optimized by size, query parameters and joins. The underlying tables have their PKs, FKs and so on. It's indexed, statiscized (that a word?) and optimized.

I'd like to have a class like (this is a much smaller and simpler version of what I have...):

public MyObject //this is a view
{
   Name{get;set}
   Age{get;set;}
   TotalPimples{get;set;}
}

and a repository, built off of EF 4.1 CF where I can just

public List<MyObject> GetPimply(int numberOfPimples)
{
    return db.MyObjects.Where(d=> d.TotalPimples > numberOfPimples).ToList();
}

I could expose a key, but whats the real purpose of dislaying a 2 or 3 column natural key? That will never be used?

Current Solution

Seeming as their will be no EF CF solution, I have added a complex key to the model and I am exposing it in the model. While this goes "with the grain" on what one expects a "well designed" db model to look like, in this case, IMHO, it added nothing but more logic to the model builder, more bytes over the wire, and extra properties on a class. These will never be used.


问:
Spring dependencies not being injected into BeforeSuite method?
I am running a spring boot application that uses TestNG as the testing framework. My tests are set up like this:

A parent class, which is in charge of setup logic and takes care of all of the configuration stuffs:

```<code>@ContextConfiguration(classes = {TestingConfig.class}, initializers = ConfigFileApplicationContextInitializer.class)
@ContextConfiguration(classes = TestConfig.class)
@TestPropertySource(locations = "classpath:application.yml")
public abstract ParentTestClass extends AbstractTestNGSpringContextTests {

    @Autowired
    private ServiceClient serviceClient;

    @BeforeSuite
    public void beforeClass() {

        Assert.assertNotNull(serviceClient);

        serviceClient.doSomeSetupWork();
    }
}
</code>```

There are multiple child test classes. Each on inherits form the parent test class so that they share the same setup logic.

```<code>public ChildTestClass1 extends ParentTestClass {

    @Test
    public void someTest() {
    ...
    }

    // More tests not shown
}

public ChildTestClass2 extends ParentTestClass {

    @Test
    public void anotherTest() {
    ...
    }

    // More tests not shown
}
</code>```

The serviceClient is a client for one of the web services that the test suite depends on. I am making calls with the service client to set up the data in the other service before running the test cases.

The problem is this: previously I was using the @BeforeClass annotation, which meant that the parent class's setup method was being run once for every child test class. This was ok, but it was really slow waiting for the same setup to be run multiple times.

So I thought to myself: I'll just change the @BeforeClass annotations in the ParentTestClass to be @BeforeSuite instead! That will solve all of my problems!

Wrong.

Now when I run it, the Assert.assertNotNull(serviceClient); line in the beforeClass() method of the parent class fails. In short, Spring dependencies aren't being injected into the @BeforeSuite annotated method, even tho they were being injected in the method when it was annotated with @BeforeClass.

Any thoughts here? I'd really appreciate it!

答:
Here is the solution to all your problem.

```<code>@Override
@BeforeSuite
protected void springTestContextPrepareTestInstance() throws Exception {
super.springTestContextPrepareTestInstance();
}
</code>```

Hope this helps you to inject the dependencies.

Body:
I am running a spring boot application that uses TestNG as the testing framework. My tests are set up like this:

A parent class, which is in charge of setup logic and takes care of all of the configuration stuffs:

@ContextConfiguration(classes = {TestingConfig.class}, initializers = ConfigFileApplicationContextInitializer.class)
@ContextConfiguration(classes = TestConfig.class)
@TestPropertySource(locations = "classpath:application.yml")
public abstract ParentTestClass extends AbstractTestNGSpringContextTests {

    @Autowired
    private ServiceClient serviceClient;

    @BeforeSuite
    public void beforeClass() {

        Assert.assertNotNull(serviceClient);

        serviceClient.doSomeSetupWork();
    }
}

There are multiple child test classes. Each on inherits form the parent test class so that they share the same setup logic.

public ChildTestClass1 extends ParentTestClass {

    @Test
    public void someTest() {
    ...
    }

    // More tests not shown
}

public ChildTestClass2 extends ParentTestClass {

    @Test
    public void anotherTest() {
    ...
    }

    // More tests not shown
}

The serviceClient is a client for one of the web services that the test suite depends on. I am making calls with the service client to set up the data in the other service before running the test cases.

The problem is this: previously I was using the @BeforeClass annotation, which meant that the parent class's setup method was being run once for every child test class. This was ok, but it was really slow waiting for the same setup to be run multiple times.

So I thought to myself: I'll just change the @BeforeClass annotations in the ParentTestClass to be @BeforeSuite instead! That will solve all of my problems!

Wrong.

Now when I run it, the Assert.assertNotNull(serviceClient); line in the beforeClass() method of the parent class fails. In short, Spring dependencies aren't being injected into the @BeforeSuite annotated method, even tho they were being injected in the method when it was annotated with @BeforeClass.

Any thoughts here? I'd really appreciate it!

Body:
Here is the solution to all your problem.

@Override
@BeforeSuite
protected void springTestContextPrepareTestInstance() throws Exception {
super.springTestContextPrepareTestInstance();
}

Hope this helps you to inject the dependencies.


问:
Update columns of spark dataframe which are of type Map with desired key and value
I have a following spark dataframe where all the columns (except for primary key column emp_id) consist of a map (with keys 'from' and 'to' which can have null values). I want to evaluate 'from' and 'to' of each column(except emp_id) and add a new key to the map(named 'change') which has a value of
a) 'insert' if 'from' value is null and 'to' is not null
b) 'delete' if 'to' value is null and 'from' is not null
b) 'update' if 'from' and 'to' are not null & 'from' value is different from 'to' value

Note: columns which have null value will remain untouched.

Important Note: The type of these columns is not Map[String, String] but instead something lie Map[String, Any] meaning the value can be of other struct objects

How can we achieve this in Scala.

```<code>|emp_id|emp_city             |emp_name                    |emp_phone            |emp_sal                    |emp_site                          |

|1     |null                 |[from -> Will, to -> Watson]|null                 |[from -> 1000, to -> 8000]|[from ->, to -> Seattle]          |
|3     |null                 |[from -> Norman, to -> Nate]|null                 |[from -> 1000, to -> 8000]|[from -> CherryHill, to -> Newark]|
|4     |[from ->, to -> Iowa]|[from ->, to -> Ian]        |[from ->, to -> 1004]|[from ->, to -> 8000]     |[from ->, to -> Des Moines]       |
</code>```

Expected:

```<code>|emp_id|emp_city             |emp_name                    |emp_phone            |emp_sal                    |emp_site                          |

|1     |null                 |[from -> Will, to -> Watson, change -> update]|null                 |[from -> 1000, to -> 8000, change -> update]|[from ->, to -> Seattle, change -> insert]          |
|3     |null                 |[from -> Norman, to -> Nate, change -> update]|null                 |[from -> 1000, to -> 8000, change -> update]|[from -> CherryHill, to -> Newark, change -> update]|
|4     |[from ->, to -> Iowa, change -> insert]|[from ->, to -> Ian, change -> insert]        |[from ->, to -> 1004, change -> insert]|[from ->, to -> 8000, change -> insert]     |[from ->, to -> Des Moines, change -> insert]       |
</code>```

答:
You can do this via Row mapper function as below,
Please find the code explanation inline</p>

```<code>import org.apache.spark.sql.Row
object MapUpdater {

  def main(args: Array[String]): Unit = {

    val spark = Constant.getSparkSess

    import spark.implicits._

    //Load your data
    val df = List(
      (1,null,Map("from" ->"Will","to"-> "Watson"),null,Map("from" ->"1000","to"-> "8000"),Map("from" ->null,"to"-> "Seattle")),
      (2,null,Map("from" ->"Norman","to"-> "Nate"),null,Map("from" ->"1000","to"-> "8000"),Map("from" ->"CherryHill","to"-> "Newark")),
      (3,Map("from" ->null,"to"-> "Iowa"),Map("from" ->null,"to"-> "Ian"),Map("from" ->null,"to"-> "1004"),Map("from" ->"1000","to"-> "8000"),Map("from" ->null,"to"-> "Des Moines"))
    ).toDF("emp_id","emp_city","emp_name","emp_phone","emp_sal","emp_site")

    //Map each of your row
    df.map(row => {

      val new_emp_city = mapUpdater(row,1)
      val new_emp_name = mapUpdater(row,2)
      val new_emp_phone = mapUpdater(row,3)
      val new_emp_sal = mapUpdater(row,4)
      val new_emp_site = mapUpdater(row,5)

      (row.getInt(0),new_emp_city,new_emp_name,new_emp_phone,new_emp_sal,new_emp_site)

    }).toDF("emp_id","emp_city","emp_name","emp_phone","emp_sal","emp_site")
      .show(false)

  }

  //Row mapper function
  private def mapUpdater(row: Row,colId:Int): Map[String, String] = {
    val old_map = row.getAs[Map[String, String]](colId)

    val new_map: Map[String, String] = if (null != old_map) {
      if (null == old_map.getOrElse("from", null) && null != old_map.getOrElse("to", null)) {
        old_map + ("change" -> "Insert")
      } else if (null != old_map.getOrElse("from", null) && null == old_map.getOrElse("to", null)) {
        old_map + ("change" -> "Delete")
      } else old_map

    } else old_map
    (new_map)
  }
}
</code>```

Body:
I have a following spark dataframe where all the columns (except for primary key column emp_id) consist of a map (with keys 'from' and 'to' which can have null values). I want to evaluate 'from' and 'to' of each column(except emp_id) and add a new key to the map(named 'change') which has a value of
a) 'insert' if 'from' value is null and 'to' is not null
b) 'delete' if 'to' value is null and 'from' is not null
b) 'update' if 'from' and 'to' are not null & 'from' value is different from 'to' value

Note: columns which have null value will remain untouched.

Important Note: The type of these columns is not Map[String, String] but instead something lie Map[String, Any] meaning the value can be of other struct objects

How can we achieve this in Scala.

|emp_id|emp_city             |emp_name                    |emp_phone            |emp_sal                    |emp_site                          |

|1     |null                 |[from -> Will, to -> Watson]|null                 |[from -> 1000, to -> 8000]|[from ->, to -> Seattle]          |
|3     |null                 |[from -> Norman, to -> Nate]|null                 |[from -> 1000, to -> 8000]|[from -> CherryHill, to -> Newark]|
|4     |[from ->, to -> Iowa]|[from ->, to -> Ian]        |[from ->, to -> 1004]|[from ->, to -> 8000]     |[from ->, to -> Des Moines]       |

Expected:

|emp_id|emp_city             |emp_name                    |emp_phone            |emp_sal                    |emp_site                          |

|1     |null                 |[from -> Will, to -> Watson, change -> update]|null                 |[from -> 1000, to -> 8000, change -> update]|[from ->, to -> Seattle, change -> insert]          |
|3     |null                 |[from -> Norman, to -> Nate, change -> update]|null                 |[from -> 1000, to -> 8000, change -> update]|[from -> CherryHill, to -> Newark, change -> update]|
|4     |[from ->, to -> Iowa, change -> insert]|[from ->, to -> Ian, change -> insert]        |[from ->, to -> 1004, change -> insert]|[from ->, to -> 8000, change -> insert]     |[from ->, to -> Des Moines, change -> insert]       |

Body:
You can do this via Row mapper function as below,
Please find the code explanation inline

import org.apache.spark.sql.Row
object MapUpdater {

  def main(args: Array[String]): Unit = {

    val spark = Constant.getSparkSess

    import spark.implicits._

    //Load your data
    val df = List(
      (1,null,Map("from" ->"Will","to"-> "Watson"),null,Map("from" ->"1000","to"-> "8000"),Map("from" ->null,"to"-> "Seattle")),
      (2,null,Map("from" ->"Norman","to"-> "Nate"),null,Map("from" ->"1000","to"-> "8000"),Map("from" ->"CherryHill","to"-> "Newark")),
      (3,Map("from" ->null,"to"-> "Iowa"),Map("from" ->null,"to"-> "Ian"),Map("from" ->null,"to"-> "1004"),Map("from" ->"1000","to"-> "8000"),Map("from" ->null,"to"-> "Des Moines"))
    ).toDF("emp_id","emp_city","emp_name","emp_phone","emp_sal","emp_site")

    //Map each of your row
    df.map(row => {

      val new_emp_city = mapUpdater(row,1)
      val new_emp_name = mapUpdater(row,2)
      val new_emp_phone = mapUpdater(row,3)
      val new_emp_sal = mapUpdater(row,4)
      val new_emp_site = mapUpdater(row,5)

      (row.getInt(0),new_emp_city,new_emp_name,new_emp_phone,new_emp_sal,new_emp_site)

    }).toDF("emp_id","emp_city","emp_name","emp_phone","emp_sal","emp_site")
      .show(false)

  }

  //Row mapper function
  private def mapUpdater(row: Row,colId:Int): Map[String, String] = {
    val old_map = row.getAs[Map[String, String]](colId)

    val new_map: Map[String, String] = if (null != old_map) {
      if (null == old_map.getOrElse("from", null) && null != old_map.getOrElse("to", null)) {
        old_map + ("change" -> "Insert")
      } else if (null != old_map.getOrElse("from", null) && null == old_map.getOrElse("to", null)) {
        old_map + ("change" -> "Delete")
      } else old_map

    } else old_map
    (new_map)
  }
}


问:
Looking for a simpler Objective-C solution
Maybe simpler isn't the proper word; terse might do as well. I'm well-aware that Objective-C is a verbose language; I'm just wondering if it has to be as verbose as it is in the solution I'm showing below. I'm relatively new to the language.

This piece of code counts the number of each type of field in a record, pursuant to generating a  variable-height UITableViewCell containing one label per field. My question isn't about how to do this -- I've already figured that out -- I'm just wondering: isn't there a simpler or less verbose way of doing this in Objective-C, using an NSDictionary object? Is this as terse as it gets using an NSDictionary? Solutions using other collection-type objects are also welcome.

Here's my -PartsRecord.countFields method. I've simplified the code slightly.

```<code>-(NSDictionary*) countFields {
NSDictionary* dict = [[NSDictionary alloc] initWithObjectAndKeys:
     @"s", [NSNumber numberWithUnsignedInt: [self.struts count]],
     @"h", [NSNumber numberWithUnsignedInt: [self.headAssemblies count]],
     @"l", (self.leftVent == nil) ?   [NSNumber numberWithUnsignedInt: 0] :
                                      [NSNumber numberWithUnsignedInt: 1],
     @"r", (self.rightVent == nil) ?  [NSNumber numberWithUnsignedInt: 0] :
                                      [NSNumber numberWithUnsignedInt: 1],
     nil ];
return dict;
</code>```

}

Any errors in the above code are errors in transcription , not actual errors in the code.

TIA,

Howard

答:
I think that using macros are quite ok to simplify typing and increase the readability

```<code>#define SET_KEY_NUMBER( _key, _value ) \
  [NSNumber numberWithUnsignedInt:_value], _key
#define SET_KEY_BOOL( _key, _bool ) \
  [NSNumber numberWithUnsignedInt: (_bool) ? 1 : 0], _key

-(NSDictionary*) countFields {
    NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:
      SET_KEY_NUMBER( @"s", [self.struts count] ),
      SET_KEY_NUMBER( @"h", [self.headAssemblies count] ),
      SET_KEY_BOOL(   @"l", self.leftVent == nil ),
      SET_KEY_BOOL(   @"r", self. rightVent == nil ),
      nil ];
    return dict;
}
</code>```

...and @Matt Ball is correct, when returning a object it should be autoreleased

ContentLicense: CC BY-SA 2.5

Body:
Maybe simpler isn't the proper word; terse might do as well. I'm well-aware that Objective-C is a verbose language; I'm just wondering if it has to be as verbose as it is in the solution I'm showing below. I'm relatively new to the language.

This piece of code counts the number of each type of field in a record, pursuant to generating a  variable-height UITableViewCell containing one label per field. My question isn't about how to do this -- I've already figured that out -- I'm just wondering: isn't there a simpler or less verbose way of doing this in Objective-C, using an NSDictionary object? Is this as terse as it gets using an NSDictionary? Solutions using other collection-type objects are also welcome.

Here's my -PartsRecord.countFields method. I've simplified the code slightly.

-(NSDictionary*) countFields {
NSDictionary* dict = [[NSDictionary alloc] initWithObjectAndKeys:
     @"s", [NSNumber numberWithUnsignedInt: [self.struts count]],
     @"h", [NSNumber numberWithUnsignedInt: [self.headAssemblies count]],
     @"l", (self.leftVent == nil) ?   [NSNumber numberWithUnsignedInt: 0] :
                                      [NSNumber numberWithUnsignedInt: 1],
     @"r", (self.rightVent == nil) ?  [NSNumber numberWithUnsignedInt: 0] :
                                      [NSNumber numberWithUnsignedInt: 1],
     nil ];
return dict;

}

Any errors in the above code are errors in transcription , not actual errors in the code.

TIA,

Howard

Body:
I think that using macros are quite ok to simplify typing and increase the readability

#define SET_KEY_NUMBER( _key, _value ) \
  [NSNumber numberWithUnsignedInt:_value], _key
#define SET_KEY_BOOL( _key, _bool ) \
  [NSNumber numberWithUnsignedInt: (_bool) ? 1 : 0], _key

-(NSDictionary*) countFields {
    NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:
      SET_KEY_NUMBER( @"s", [self.struts count] ),
      SET_KEY_NUMBER( @"h", [self.headAssemblies count] ),
      SET_KEY_BOOL(   @"l", self.leftVent == nil ),
      SET_KEY_BOOL(   @"r", self. rightVent == nil ),
      nil ];
    return dict;
}

...and @Matt Ball is correct, when returning a object it should be autoreleased

OwnerDisplayName: epatel

LastEditorDisplayName: epatel


问:
Mock my database for all unit tests in PHPUnit
I've just recently started looking into unit testing with PHPUnit and was wondering if it is possible to mock my entire database for all my tests. My model classes (Table Row objects wrapped to provde an ActiveRecord implementation) are rooted to the database and some models have many levels of other model classes so mocking all of this seems like its gona be a pain in the rear end.

Is it possible to get PHPUnit to use data from a CSV file to act as my database and run my tests against the data there without having to touch my DAOs? I've read the section on database testing in PHPUnit but I'm not sure this is what I want because its not so much that I want to test the database or code interacting with the database, its more the fact that my model classes are very tied to the database and it would be a pain having to mock things all the time. If I could give it a CSV file to act as my database then I can just put my data into the CSV file and carry on as normal.

Not sure if I'm making myself clear so please ask for clarification. If it is possible to achieve this then that would be fantastic. Without this unit testing this beast may not be practical but I really want to bring in unit testing to the project.

Thanks

Ziad

答: What about using your database but not committing changes? Or rolling back after the tests are run? We use a copy of our production site as a test environment on a separate server and do all of our testing there. </p>


问:
Convert input language while typing in
I have an input field that accepts two languages Arabic and English, what i want is when i type Arabic numbers into this input to convert them into English while the user is typing, i want them to be converted from ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'] to ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], how can i do that? here is my input code:

<input type="text" placeholder="Numbers should be converted from Arabic to English here">```

答:
for all input that have text type
use jQuery Library</p>

```<code>var arabics = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'];
var engs = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];

$(document).on('keyup', 'input[type=text]', function (e) {

    var insideText = (e.key);
    var index = arabics.indexOf(insideText);
    if (index >= 0) {
        var value = $(this).val();
        value.substr(0, value.length - 1) != null ? value = value.substr(0, value.length - 1) + engs[index] : value = engs[index];
        $(this).val(value);
    }

});
</code>```

Title: Convert input language while typing in

Body:
for all input that have text type
use jQuery Library

var arabics = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'];
var engs = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];

$(document).on('keyup', 'input[type=text]', function (e) {

    var insideText = (e.key);
    var index = arabics.indexOf(insideText);
    if (index >= 0) {
        var value = $(this).val();
        value.substr(0, value.length - 1) != null ? value = value.substr(0, value.length - 1) + engs[index] : value = engs[index];
        $(this).val(value);
    }

});


问:
React not fetching data from mysql
I build a react app using nodejs and mysql. I want to update an entry from react but the following code doesn't working and I can't understan what is the problem. Any suggestions are much appreciated.

// from index.js

```<code>script.get('/updatepost/:id', (req, res) => {
    let sql = `UPDATE posts SET name = '${req.body.name}', school='${req.body.school}' WHERE id = ${req.params.id}`;
    let query = connection.query(sql, (err, result) => {
        if(err) {
            return err;
        }
        console.log(result);
        res.send('Post updated...');
    })
});
</code>```

//from react component

```<code>axios(`http://localhost:4000/updatepost/${userId}`, {
method: 'PATCH',
data: qs.stringify(data);
})
</code>```

答:
I think you are using patch to send the data (from React), but you are using "get" to receive it (from node).

Try:

```<code>script.patch('/updatepost/:id', (req, res) => {
    let sql = `UPDATE posts SET name = '${req.body.name}', school='${req.body.school}' WHERE id = ${req.params.id}`;
    let query = connection.query(sql, (err, result) => {
        if(err) {
            return err;
        }
        console.log(result);
        res.send('Post updated...');
    })
});
</code>```

I think you must mistake use the bodyParser middleware. Try installing body-parser on nodejs and adding it before the script patch, as following:

```<code>    var bodyParser = require('body-parser')

    script.use(bodyParser.json())

    script.patch('/updatepost/:id', (req, res) => {
    let sql = `UPDATE posts SET name = '${req.body.name}', school='${req.body.school}' WHERE id = ${req.params.id}`;
    let query = connection.query(sql, (err, result) => {
        if(err) {
            return err;
        }
        console.log(result);
        res.send('Post updated...');
    })
});
</code>```

Title: React not fetching data from mysql

Body:
I build a react app using nodejs and mysql. I want to update an entry from react but the following code doesn't working and I can't understan what is the problem. Any suggestions are much appreciated.

// from index.js

script.get('/updatepost/:id', (req, res) => {
    let sql = `UPDATE posts SET name = '${req.body.name}', school='${req.body.school}' WHERE id = ${req.params.id}`;
    let query = connection.query(sql, (err, result) => {
        if(err) {
            return err;
        }
        console.log(result);
        res.send('Post updated...');
    })
});

//from react component

axios(`http://localhost:4000/updatepost/${userId}`, {
method: 'PATCH',
data: qs.stringify(data);
})

Body:
I think you are using patch to send the data (from React), but you are using "get" to receive it (from node).

Try:

script.patch('/updatepost/:id', (req, res) => {
    let sql = `UPDATE posts SET name = '${req.body.name}', school='${req.body.school}' WHERE id = ${req.params.id}`;
    let query = connection.query(sql, (err, result) => {
        if(err) {
            return err;
        }
        console.log(result);
        res.send('Post updated...');
    })
});

I think you must mistake use the bodyParser middleware. Try installing body-parser on nodejs and adding it before the script patch, as following:

    var bodyParser = require('body-parser')

    script.use(bodyParser.json())

    script.patch('/updatepost/:id', (req, res) => {
    let sql = `UPDATE posts SET name = '${req.body.name}', school='${req.body.school}' WHERE id = ${req.params.id}`;
    let query = connection.query(sql, (err, result) => {
        if(err) {
            return err;
        }
        console.log(result);
        res.send('Post updated...');
    })
});


问:
How to whitelist IP addresses on Amazon Lightsail
I used Amazon Lightsail to deploy a wordpress site and it worked like a charm. Now I have the need to restrict the IP addresses that can access on port 80 to the ones associated to the Firewall from SiteLock, and I am looking for the best and cleanest solution.

It looks like in Lightsail simplified version of the world, I can only open a port for public access, or close it.

My only idea now is logging in via SSH and use iptables, but I wanted to understand if that's the only way I can do this, or there is something "smarter".

答:
now, IPs can be whitelisted from AWS console itself. Go to your Lightsail instance in console, then networking. there you can choose ports to open, and to whitelist IP, check Restrict to IP. then enter whielisted IP or range and save.

reference: https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-editing-firewall-rules


问:
React/JavaScript, can someone explain why setState doesn't seem to correctly update the state during the function?

searchProject(title, language, length, experience) {
        if (title !== "") {
            const projects = this.state.projectList.filter(
                p => p.title === title
            );
            this.setState({projectList : projects});
            }
        if (language !== "") {
            const projects = this.state.projectList.filter(
                p => p.language === language
            );
            this.setState({projectList : projects});
            }
        if (length !== 0) {
            const projects = this.state.projectList.filter(
                p => p.length === length
            );
            this.setState({projectList : projects});
            }
        if (experience !== "") {
            const projects = this.state.projectList.filter(
                p => p.experience === experience
            );
            this.setState({projectList : projects});
            }

        }```

I have this snippet of code in my JS file which doesn't seem to do what I want it to do. It should be a filtering function which filters projects which have the same parameters as I specify. I'm very new to JS, so I don't think this is at all the most efficient way to do things, but I thought it should work. The logic of the function is that it sets the projectList state to the projectList which only contains the specified title, then it sets that new state to a state which only contains the specified language and so on... But it seems to only work for the last parameter I set. So if I fill in the experience parameter, it would ignore all projects which don't have that specified experience only. It doesn't matter what title or language or length I set. I think it has something to do with how setState works but I'm not sure. Could someone explain to me how I could fix this problem? Thank you!

答:
I would load projectList once, filter it, then set state:

```<code>searchProject(title, language, length, experience) {
  let projects = this.state.projectList;

  if (title) { // Empty string is falsy, so this is the same as (title !== "")
    projects = projects.filter(...)
  }

  if (language) {
    projects  = projects.filter(...)
  }

  ...

  this.setState({projectList: projects});

}

</code>```

Body:
searchProject(title, language, length, experience) {
        if (title !== "") {
            const projects = this.state.projectList.filter(
                p => p.title === title
            );
            this.setState({projectList : projects});
            }
        if (language !== "") {
            const projects = this.state.projectList.filter(
                p => p.language === language
            );
            this.setState({projectList : projects});
            }
        if (length !== 0) {
            const projects = this.state.projectList.filter(
                p => p.length === length
            );
            this.setState({projectList : projects});
            }
        if (experience !== "") {
            const projects = this.state.projectList.filter(
                p => p.experience === experience
            );
            this.setState({projectList : projects});
            }

        }

I have this snippet of code in my JS file which doesn't seem to do what I want it to do. It should be a filtering function which filters projects which have the same parameters as I specify. I'm very new to JS, so I don't think this is at all the most efficient way to do things, but I thought it should work. The logic of the function is that it sets the projectList state to the projectList which only contains the specified title, then it sets that new state to a state which only contains the specified language and so on... But it seems to only work for the last parameter I set. So if I fill in the experience parameter, it would ignore all projects which don't have that specified experience only. It doesn't matter what title or language or length I set. I think it has something to do with how setState works but I'm not sure. Could someone explain to me how I could fix this problem? Thank you!

Body:
I would load projectList once, filter it, then set state:

searchProject(title, language, length, experience) {
  let projects = this.state.projectList;

  if (title) { // Empty string is falsy, so this is the same as (title !== "")
    projects = projects.filter(...)
  }

  if (language) {
    projects  = projects.filter(...)
  }

  ...

  this.setState({projectList: projects});

}


问:
Why does MariaDB (MySQL) treat numeric literals as strings?
Something odd me and my colleague noticed today. If we do this:

```<code>select id from table
</code>```

where id is integer, then the result set contains the IDs as integers. All is nice. However when we do this:

```<code>select 1
</code>```

Then the result set contains the string "1". The actual scenario that led to this was more complicated and involved ifnull(), however this is the simplest thing that reproduces the issue.

We're using NodeJS (+Typescript) and TypeORM if it matters. I remember noticing something similar in PHP too, but since PHP is so lax with types anyway, I didn't care much. This time however we're passing the data out to external systems as JSON, so now we need to add parseInt() in order to convert the stringly typed numbers back to actual numbers.

But - wtf? Why this behavior?

答:
```<code>WHERE id = 123      -- fine
WHERE id = "123"    -- also fine; the string is converted to a number
WHERE text = "123"  -- also fine (assuming `text` is VARCHAR or TEXT)
WHERE text = 123    -- inefficient because it converts each text to numeric
</code>```

Many APIs "bind" values into queries.  Many of them blindly quote things, regardless of the target.  Note that the above things say that quoting always works "fine".

So, I think that is the "why" that you asked.

And, as you say, PHP, Perl, and other interpreted languages somewhat dominate the space here.

Body:
Something odd me and my colleague noticed today. If we do this:

select id from table

where id is integer, then the result set contains the IDs as integers. All is nice. However when we do this:

select 1

Then the result set contains the string "1". The actual scenario that led to this was more complicated and involved ifnull(), however this is the simplest thing that reproduces the issue.

We're using NodeJS (+Typescript) and TypeORM if it matters. I remember noticing something similar in PHP too, but since PHP is so lax with types anyway, I didn't care much. This time however we're passing the data out to external systems as JSON, so now we need to add parseInt() in order to convert the stringly typed numbers back to actual numbers.

But - wtf? Why this behavior?

Body:
WHERE id = 123      -- fine
WHERE id = "123"    -- also fine; the string is converted to a number
WHERE text = "123"  -- also fine (assuming `text` is VARCHAR or TEXT)
WHERE text = 123    -- inefficient because it converts each text to numeric

Many APIs "bind" values into queries.  Many of them blindly quote things, regardless of the target.  Note that the above things say that quoting always works "fine".

So, I think that is the "why" that you asked.

And, as you say, PHP, Perl, and other interpreted languages somewhat dominate the space here.


问:
How to do a replace for given example in Sql?
I want to replace always the last node in the string-

```<code>root/node1/node2
</code>```

If I pass node3 as the parameter it should do a replace like this -

```<code> root/node1/node3
</code>```

Can anyone help me do this say the column name was lineage and I have the id. So, the query would be -

```<code>Update
   tree
set
  lineage= -- replace(lineage,node3)  -- this is what i need  ?
where
  id=2
</code>```

答:
You could do some string manipulation to find the last occurrence of a /, and then strip everything after that point... and then append your new node parameter to that value

```<code>Update
   tree
set
  lineage = LEFT(Lineage, LEN(Lineage) - CHARINDEX('/', REVERSE(Lineage)) + 1) + @NewNode
where
  id=2
</code>```

Body:
I want to replace always the last node in the string-

root/node1/node2

If I pass node3 as the parameter it should do a replace like this -

 root/node1/node3

Can anyone help me do this say the column name was lineage and I have the id. So, the query would be -

Update
   tree
set
  lineage= -- replace(lineage,node3)  -- this is what i need  ?
where
  id=2

Body:
You could do some string manipulation to find the last occurrence of a /, and then strip everything after that point... and then append your new node parameter to that value

Update
   tree
set
  lineage = LEFT(Lineage, LEN(Lineage) - CHARINDEX('/', REVERSE(Lineage)) + 1) + @NewNode
where
  id=2


问:
Possible to render react component within mapboxgl.Popup() in .setHTML or .setDOMContent?
I am wondering if it is possible to render a react component within a mapboxgl.Popup(). Something like this:

```<code>    componentDidMount() {
            new mapboxgl.Popup()
            .setLngLat(coordinates)
            .setHTML(`<div>${<MapPopup />}<p>${moreText}</p></div>`)
            //.setDOMContent(`${<MapPopup />}`) ?????
            .addTo(this.props.mapboxMap)
    })
</code>```

Or should this be done using ReactDOM.render?

```<code>ReactDOM.render(<MapPopup />, document.getElementById('root'))
</code>```

This project will have buttons and inputs in the popup that connect to a redux store.

Thanks for any input!

答:
You can try to implement React component:

```<code>export const Popup = ({ children, latitude, longitude, ...mapboxPopupProps }) => {
    // this is a mapbox map instance, you can pass it via props
    const { map } = useContext(MapboxContext);
    const popupRef = useRef();

    useEffect(() => {
        const popup = new MapboxPopup(mapboxPopupProps)
            .setLngLat([longitude, latitude])
            .setDOMContent(popupRef.current)
            .addTo(map);

        return popup.remove;
    }, [children, mapboxPopupProps, longitude, latitude]);

    return (
        /**
         * This component has to have 2 divs.
         * Because if you remove outter div, React has some difficulties
         * with unmounting this component.
         * Also `display: none` is solving that map does not jump when hovering
         * ¯\_(ツ)_/¯
         */
        <div style={{ display: 'none' }}>
            <div ref={popupRef}>
                {children}
            </div>
        </div>
    );
};
</code>```

After some testing, I have realized that Popup component was not rendering properly on the map. And also unmounting the component was unsuccessful. That is why there are two divs in return. However, it may happen only in my environment.

See https://docs.mapbox.com/mapbox-gl-js/api/#popup for additional mapboxPopupProps

useEffect dependencies make sure that MapboxPopup gets re-created every time something of that list changes & cleaning up the previous popup instance with return popup.remove;

Body:
I am wondering if it is possible to render a react component within a mapboxgl.Popup(). Something like this:

    componentDidMount() {
            new mapboxgl.Popup()
            .setLngLat(coordinates)
            .setHTML(`<div>${<MapPopup />}<p>${moreText}</p></div>`)
            //.setDOMContent(`${<MapPopup />}`) ?????
            .addTo(this.props.mapboxMap)
    })

Or should this be done using ReactDOM.render?

ReactDOM.render(<MapPopup />, document.getElementById('root'))

This project will have buttons and inputs in the popup that connect to a redux store.

Thanks for any input!

Body:
You can try to implement React component:

export const Popup = ({ children, latitude, longitude, ...mapboxPopupProps }) => {
    // this is a mapbox map instance, you can pass it via props
    const { map } = useContext(MapboxContext);
    const popupRef = useRef();

    useEffect(() => {
        const popup = new MapboxPopup(mapboxPopupProps)
            .setLngLat([longitude, latitude])
            .setDOMContent(popupRef.current)
            .addTo(map);

        return popup.remove;
    }, [children, mapboxPopupProps, longitude, latitude]);

    return (
        /**
         * This component has to have 2 divs.
         * Because if you remove outter div, React has some difficulties
         * with unmounting this component.
         * Also `display: none` is solving that map does not jump when hovering
         * ¯\_(ツ)_/¯
         */
        <div style={{ display: 'none' }}>
            <div ref={popupRef}>
                {children}
            </div>
        </div>
    );
};

After some testing, I have realized that Popup component was not rendering properly on the map. And also unmounting the component was unsuccessful. That is why there are two divs in return. However, it may happen only in my environment.

See https://docs.mapbox.com/mapbox-gl-js/api/#popup for additional mapboxPopupProps

useEffect dependencies make sure that MapboxPopup gets re-created every time something of that list changes & cleaning up the previous popup instance with return popup.remove;


问:
ERROR 1045 (28000): Access denied for user 'user'@'%' (using password: YES)
Does anyone know why I get this error when running mysqlimport?

```<code>mysqlimport: Error: 1045, Access denied for user 'user'@'%' (using password: YES), when using table: XXX
</code>```

I have tried so many options. Also I am not able to run the below command as referred by some sites:

```<code>mysql> GRANT FILE ON *.* to 'user'@'%';

ERROR 1045 (28000): Access denied for user 'user'@'%' (using password: YES)
</code>```

答:
try this

step 1

```<code>GRANT ALL PRIVILEGES ON *.* TO 'user'@'%' IDENTIFIED BY '' WITH GRANT OPTION;
</code>```

step 2

```<code>FLUSH PRIVILEGES;
</code>```

if you want to add password

step 1

```<code>GRANT ALL PRIVILEGES ON *.* TO 'user'@'%' IDENTIFIED BY 'yourpassword' WITH GRANT OPTION;
</code>```

step 2

```<code>FLUSH PRIVILEGES;
</code>```

for more details ref

in hear I add ALL PRIVILEGES for all databases if you want to change it refer I added link

without executing FLUSH PRIVILEGES you can restart SQL server I think to execute FLUSH PRIVILEGES is better

Body:
Does anyone know why I get this error when running mysqlimport?

mysqlimport: Error: 1045, Access denied for user 'user'@'%' (using password: YES), when using table: XXX

I have tried so many options. Also I am not able to run the below command as referred by some sites:

mysql> GRANT FILE ON *.* to 'user'@'%';

ERROR 1045 (28000): Access denied for user 'user'@'%' (using password: YES)

Body:
try this

step 1

GRANT ALL PRIVILEGES ON *.* TO 'user'@'%' IDENTIFIED BY '' WITH GRANT OPTION;

step 2

FLUSH PRIVILEGES;

if you want to add password

step 1

GRANT ALL PRIVILEGES ON *.* TO 'user'@'%' IDENTIFIED BY 'yourpassword' WITH GRANT OPTION;

step 2

FLUSH PRIVILEGES;

for more details ref

in hear I add ALL PRIVILEGES for all databases if you want to change it refer I added link

without executing FLUSH PRIVILEGES you can restart SQL server I think to execute FLUSH PRIVILEGES is better


问:
async await does not work as i expect i am new to node js
here is my async await code it does not work as i expected can anyone help me please
my results are bellow

```<code>Start
end
waiting for 3000 miliseconds
</code>```

but i expect it to work like this

```<code>Start
waiting for 3000 miliseconds
end
</code>```

```<code>
 function start(){
 console.log ('Start')
}

async function waittime(){
  let respone =await  setTimeout(()=>  {
      console.log('waiting for 3000 miliseconds')
    }, 3000);
    return respone
}

 function end(){
 console.log('end')
}

start();
waittime();
end();

</code>```

答:
As mentioned before setTimeout doesn't return a promise so awaiting it is redundant. You can wrap it into a new Promise constructor and return the result of the timeout on a resolve(). But still you would have the following:

NodeJS doesn't support high level await. Means you have to wrap it into an async function that always returns a Promise. This will make it impossible to call it in the same way.
You can however do this with two ways:

// using then().catch() which you can use because async functions return Promises
start().then(() => waittime()).then(() => end());

// using an IIFE
(async function() {
   start();
   await waittime();
   end();
})()
```

I recommend you to read more about Promises and async/await there are some caveats that are important to know :)

Body:
here is my async await code it does not work as i expected can anyone help me please
my results are bellow

Start
end
waiting for 3000 miliseconds

but i expect it to work like this

Start
waiting for 3000 miliseconds
end

 function start(){
 console.log ('Start')
}

async function waittime(){
  let respone =await  setTimeout(()=>  {
      console.log('waiting for 3000 miliseconds')
    }, 3000);
    return respone
}

 function end(){
 console.log('end')
}

start();
waittime();
end();

Body:
As mentioned before setTimeout doesn't return a promise so awaiting it is redundant. You can wrap it into a new Promise constructor and return the result of the timeout on a resolve(). But still you would have the following:

NodeJS doesn't support high level await. Means you have to wrap it into an async function that always returns a Promise. This will make it impossible to call it in the same way.
You can however do this with two ways:

// using then().catch() which you can use because async functions return Promises
start().then(() => waittime()).then(() => end());

// using an IIFE
(async function() {
   start();
   await waittime();
   end();
})()

I recommend you to read more about Promises and async/await there are some caveats that are important to know :)


问:
Python for loop save only last value to csv?
Used below lines of code for contour detection and its corresponding area calculation during printing the area all values are printed but while saving only last value got saved in CSV file

for cnt in contours:

    M= cv2.moments(cnt)
        #print(M)

    if M["m00"] != 0:

        cx = int(M["m10"] / M["m00"])
        cy = int(M["m01"] / M["m00"])
    else:
        cx, cy = 0,0

    center = (cx,cy)

    area = cv2.contourArea(cnt)
    #V1 = np.asarray(area)
    print(area)

    df = pd.DataFrame()
    df['Area'] = area

    df.to_csv("C:\pfm\dataframe_csv\L501.csv")
```

答:
In every iteration of the loop, you create a new, empty DataFrame, put one thing into it, and write it out to a file.  Each time, it writes over the previous output and what is left at the end is the last one.  This happens because the file is opened in write mode by default.

(If "write mode" means nothing to you, you should review Python file open modes in your favorite language reference.)

Fortunately, the to_csv function has a mode parameter that you can set to 'a' to open the file for appending.  If you do that, each write should append to the end of the file.

Alternately, you could accumulate all the output in one big DataFrame and write the whole thing out once after the loop terminates.  This would probably be faster, but would require more memory.


问:
I am trying to use elastic search with logstash and kibana but im unable to run a logstash file?
I have installed elastic search,logstash and kibana successfully. I have also installed jdk. Elastic search is running on port 9200 properly I am trying to run the logstash.conf file it is giving me following error
[it is giving me following error

This is the code i am trying to run

and i am trying to run code with following Two commands
1)logstash -f logstash.py
2)logstash -e 'input{stdin{}}output{stdout{}}'

答:
According to this message, one instance of Logstash is already running and you are trying to start another one. It is not a big problem if they are completely separated from each other. But you are starting the 2nd instance that uses the same database as the 1st one.

If this was not your intention, then first stop the 1st instance before starting the 2nd one.

If you really need multiple instances simultaneously, configure them correspondingly: database, ports.


问:
Error: Invariant failed: You should not use <Link> outside a <Router> ,No Navigation occurs
I am trying to use Link Component to enable client side rendering of my app. Below is my component.

```<code>/**@jsx jsx */
import { css, jsx } from '@emotion/core';
import { fontFamily, fontSize, gray1, gray2, gray5 } from './../Styles';
import UserIcon from './UserIcon';
import { ChangeEvent } from 'react';
import { Link, BrowserRouter } from 'react-router-dom';

export const Header = () => {
    const handleSearchInputChange = (e: ChangeEvent<HTMLInputElement>) => {
        console.log(e.currentTarget.value);
    };
    return (
        <div
            css={css`
                position: fixed;
                box-sizing: border-box;
                top: 0;
                width: 100%;
                display: flex;
                align-items: center;
                justify-content: space-between;
                padding: 10px 20px;
                background-color: #fff;
                border-bottom: 1px solid ${gray5};
                box-shadow: 0 3px 7px 0 rgba(110, 112, 114, 0.21);
            `}
        >
            <Link
                to="./"
                css={css`
                    font-size: 24px;
                    font-weight: bold;
                    color: ${gray1};
                    text-decoration: none;
                `}
            >
                Q & A
            </Link>
            <input
                type="text"
                placeholder="Search..."
                css={css`
                    box-sizing: border-box;
                    font-family: ${fontFamily};
                    font-size: ${fontSize};
                    padding: 8px 10px;
                    border: 1px solid ${gray5};
                    border-radius: 3px;
                    color: ${gray2};
                    background-color: white;
                    width: 200px;
                    height: 30px;
                    :focus {
                        outline-color: ${gray5};
                    }
                `}
                onChange={handleSearchInputChange}
            />
            <Link
                to="./signin"
                css={css`
                    font-family: ${fontFamily};
                    font-size: ${fontSize};
                    padding: 5px 10px;
                    background-color: transparent;
                    color: ${gray2};
                    text-decoration: none;
                    cursor: pointer;
                    span {
                        margin-left: 10px;
                    }
                    :focus {
                        outline-color: ${gray5};
                    }
                `}
            >
                <UserIcon />
                <span>Sign In</span>
            </Link>
        </div>
    );
};
</code>```

I am using BrowserRouter in my App.tsx as below

```<code>const App = () => (
    <div
        className="App"
        css={css`
            font-family: ${fontFamily};
            font-size: ${fontSize};
            color: ${gray2};
        `}
    >
        <Header />
        <BrowserRouter>
            <Switch>
                <Redirect from="/home" to="/" />
                <Route exact path="/" component={HomePage} />
                <Route exact path="/search" component={SearchPage} />
                <Route exact path="/ask" component={AskPage} />
                <Route exact path="/signin" component={SignInPage} />
                <Route component={NotFoundPage} />
            </Switch>
        </BrowserRouter>
    </div>
);
export default App;
</code>```

Now when I run my app, I get the Error as

```<code>Error: Invariant failed: You should not use <Link> outside a <Router>
▶ 25 stack frames were collapsed.
</code>```

My App runs when I use BrowserRouter in my Header.tsx around the Link component, but when I click my links, just the URL changes and app stays at home page. Not sure what am I missing here.

答:
Your Header component which uses Link is rendered outside of the BrowserRouter component which is why it is throwing the error. You can render it as a child of BrowserRouter and as a default Route so that it receives the router props and is able to use Link correctly

```<code>const App = () => (
    <div
        className="App"
        css={css`
            font-family: ${fontFamily};
            font-size: ${fontSize};
            color: ${gray2};
        `}
    >

        <BrowserRouter>
            <Route component={Header} />
            <Switch>
                <Redirect from="/home" to="/" />
                <Route exact path="/" component={HomePage} />
                <Route exact path="/search" component={SearchPage} />
                <Route exact path="/ask" component={AskPage} />
                <Route exact path="/signin" component={SignInPage} />
                <Route component={NotFoundPage} />
            </Switch>
        </BrowserRouter>
    </div>
);
export default App;
</code>```

Body:
I am trying to use Link Component to enable client side rendering of my app. Below is my component.

/**@jsx jsx */
import { css, jsx } from '@emotion/core';
import { fontFamily, fontSize, gray1, gray2, gray5 } from './../Styles';
import UserIcon from './UserIcon';
import { ChangeEvent } from 'react';
import { Link, BrowserRouter } from 'react-router-dom';

export const Header = () => {
    const handleSearchInputChange = (e: ChangeEvent<HTMLInputElement>) => {
        console.log(e.currentTarget.value);
    };
    return (

            <Link
                to="./"
                css={css`
                    font-size: 24px;
                    font-weight: bold;
                    color: ${gray1};
                    text-decoration: none;
                `}
            >
                Q & A
            </Link>
            <input
                type="text"
                placeholder="Search..."
                css={css`
                    box-sizing: border-box;
                    font-family: ${fontFamily};
                    font-size: ${fontSize};
                    padding: 8px 10px;
                    border: 1px solid ${gray5};
                    border-radius: 3px;
                    color: ${gray2};
                    background-color: white;
                    width: 200px;
                    height: 30px;
                    :focus {
                        outline-color: ${gray5};
                    }
                `}
                onChange={handleSearchInputChange}
            />
            <Link
                to="./signin"
                css={css`
                    font-family: ${fontFamily};
                    font-size: ${fontSize};
                    padding: 5px 10px;
                    background-color: transparent;
                    color: ${gray2};
                    text-decoration: none;
                    cursor: pointer;
                    span {
                        margin-left: 10px;
                    }
                    :focus {
                        outline-color: ${gray5};
                    }
                `}
            >
                <UserIcon />
                Sign In
            </Link>

    );
};

I am using BrowserRouter in my App.tsx as below

const App = () => (

        <BrowserRouter>
            <Switch>
                <Redirect from="/home" to="/" />
                <Route exact path="/" component={HomePage} />
                <Route exact path="/search" component={SearchPage} />
                <Route exact path="/ask" component={AskPage} />
                <Route exact path="/signin" component={SignInPage} />
                <Route component={NotFoundPage} />
            </Switch>
        </BrowserRouter>

);
export default App;

Now when I run my app, I get the Error as

Error: Invariant failed: You should not use <Link> outside a <Router>
▶ 25 stack frames were collapsed.

My App runs when I use BrowserRouter in my Header.tsx around the Link component, but when I click my links, just the URL changes and app stays at home page. Not sure what am I missing here.

Body:
Your Header component which uses Link is rendered outside of the BrowserRouter component which is why it is throwing the error. You can render it as a child of BrowserRouter and as a default Route so that it receives the router props and is able to use Link correctly

const App = () => (
    <div
        className="App"
        css={css`
            font-family: ${fontFamily};
            font-size: ${fontSize};
            color: ${gray2};
        `}
    >

        <BrowserRouter>
            <Route component={Header} />
            <Switch>
                <Redirect from="/home" to="/" />
                <Route exact path="/" component={HomePage} />
                <Route exact path="/search" component={SearchPage} />
                <Route exact path="/ask" component={AskPage} />
                <Route exact path="/signin" component={SignInPage} />
                <Route component={NotFoundPage} />
            </Switch>
        </BrowserRouter>
    </div>
);
export default App;


问:
Customize .NET framework generated exception messages?
I was wondering if there was a reasonable way to customize messages on exceptions that are thrown by the .NET framework?  Below is a chunk of code that I write often, in many different scenarios to achieve the effect of providing reasonable exception messages to my users.

```<code>public string GetMetadata(string metaDataKey)
{
  // As you can see, I am doing what the dictionary itself will normally do, but my exception message has some context, and is therefore more descriptive of the actual problem.
  if (!_Metadata.ContainsKey(metaDataKey))
  {
    throw new KeyNotFoundException(string.Format("There is no metadata that contains the key '{0}'!", metaDataKey));
  }

  // This will throw a 'KeyNotFoundException' in normal cases, which I want, but the message "The key is not present in the dictionary" is not very informative.  This is the exception who's message I wish to alter.
  string val = _Metadata[metaDataKey].TrimEnd();
  return val;
}
</code>```

As you can see, I am essentially producing duplicate code just to use a different (better) message.

Edit:

What I am looking for, essentially is something like this:

```<code>KeyNotFoundException.SetMessage("this is my custom message!")
{
// OK, now this will send off the message I want when the exception appears!
// Now I can avoid all of that silly boilerplate!
string val = _Metadata[metaDataKey].TrimEnd();
}
</code>```

At any rate, i don't think that such a feature exists, but if it did I would be very pleased indeed.  Has anyone tackled this type of problem before?  It's looking like I am going to wind up needed some type of extension method in the end...

答:
Just inherit from the KeyNotFoundException class and override the Message property to generate a more meaningful message and then use your own exception class with a proper constructor. This is exactly what inheritance was meant for, adding value. i.e.

```<code>throw new MetaDataKeyNotFoundException(string metaDataKey);
</code>```

Body:
I was wondering if there was a reasonable way to customize messages on exceptions that are thrown by the .NET framework?  Below is a chunk of code that I write often, in many different scenarios to achieve the effect of providing reasonable exception messages to my users.

public string GetMetadata(string metaDataKey)
{
  // As you can see, I am doing what the dictionary itself will normally do, but my exception message has some context, and is therefore more descriptive of the actual problem.
  if (!_Metadata.ContainsKey(metaDataKey))
  {
    throw new KeyNotFoundException(string.Format("There is no metadata that contains the key '{0}'!", metaDataKey));
  }

  // This will throw a 'KeyNotFoundException' in normal cases, which I want, but the message "The key is not present in the dictionary" is not very informative.  This is the exception who's message I wish to alter.
  string val = _Metadata[metaDataKey].TrimEnd();
  return val;
}

As you can see, I am essentially producing duplicate code just to use a different (better) message.

Edit:

What I am looking for, essentially is something like this:

KeyNotFoundException.SetMessage("this is my custom message!")
{
// OK, now this will send off the message I want when the exception appears!
// Now I can avoid all of that silly boilerplate!
string val = _Metadata[metaDataKey].TrimEnd();
}

At any rate, i don't think that such a feature exists, but if it did I would be very pleased indeed.  Has anyone tackled this type of problem before?  It's looking like I am going to wind up needed some type of extension method in the end...

Body:
Just inherit from the KeyNotFoundException class and override the Message property to generate a more meaningful message and then use your own exception class with a proper constructor. This is exactly what inheritance was meant for, adding value. i.e.

throw new MetaDataKeyNotFoundException(string metaDataKey);


问:
What is maintenanceWindow attribute in Azure redis cache patch schedule condiguration?
The documentation doesn't explain what is the maintenanceWindow is, as during patching a node switch happens, why this window length matter at all? Could it impact the duration that the Redis cache is not available to use?

答:
What is the maintenance window?
When scheduling updates for Azure Redis Cache, you can decide the day of the week, start UTC hour and maintenance window.
Setting a maintenance window allows you to minimize the impact on your application and users.
Only Redis server updates are made during the scheduled maintenance window. The maintenance window does not apply to Azure updates or updates to the VM operating system.

What is the impact of setting a shorter or longer window?
The default and minimum, maintenance window for updates is five hours. The actual time required for maintenance depends on exactly what’s taking place.
You could always set it to a longer timespan, but we recommend selecting a timespan that would have the least impact on your business.


问:
VBA send file in binary code to API via POST method
I have last problem with my code. Code sending via POST variables from Outlook to API.

My last problem is how to send variables and mail attachment in one POST request to API.

first 7zip comprimation for mail attachement:

```<code>strSource = cstrFileAttachment & "*.*"
strTarget = cstrFileattachment & "Zip\attachment.zip"
strPassword = randomPassword(cintLongPassword)
strCommand = """" & PathZipProgram & """ a -tzip """ & strTarget & _
    """ -p" & strPassword & " """ & strSource & """"
</code>```

Now i have c:\attachment\attachment.zip

Next part is send variables to API:

```<code>    Dim SendDataToApi As String

    strFrom = 1

    Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")

    URL = "https://url.domain.com/api/data"

    objHTTP.Open "POST", URL, False
    objHTTP.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded"

    SendDataToApi = "mail_from=" & strFrom & "&mail_to=" & strKomu & "&file_attachment=" & fileAttachment & "&url_attribute=" & strWebLink & "&sms_code=" & strHeslo & "&id_message=" & IdMessage & "&mobile_phone=" & strPhone & "&date_send=" & strDateSend & "&date_expiration=" & strDateExp

    objHTTP.Send SendDataToApi
</code>```

Variables are sended, but fileAttachment is send as a string, so API get path where file is saved.

My question is how implement code below (found on internet) to my code sendDataToApi and POST attachment.zip as a binary insteed of string.

```<code>    Private Function Upload(strUploadUrl, strFilePath, strFileField, strDataPairs)
    'Uses POST to upload a file and miscellaneous form data
    strUploadUrl = "https://url.domain.com/api/data"
    strFilePath = cstrFilepathAttachment & "Zip\attachment.zip"
    'strFileField is the web page equivalent form field name for the file (File1)
    'strDataPairs are pipe-delimited form data pairs (foo=bar|snap=crackle)
    Const MULTIPART_BOUNDARY = "---------------------------0123456789012"
    Dim ado, rs
    Dim lngCount
    Dim bytFormData, bytFormStart, bytFormEnd, bytFile
    Dim strFormStart, strFormEnd, strDataPair
    Dim web
    Const adLongVarBinary = 205
        'Read the file into a byte array
        Set ado = CreateObject("ADODB.Stream")
        ado.Type = 1
        ado.Open
        ado.LoadFromFile strFilePath
        bytFile = ado.Read
        ado.Close
        'Create the multipart form data.
        'Define the end of form
        strFormEnd = vbCrLf & "--" & MULTIPART_BOUNDARY & "--" & vbCrLf
        'First add any ordinary form data pairs
        strFormStart = ""
        For Each strDataPair In Split(strDataPairs, "|")
            strFormStart = strFormStart & "--" & MULTIPART_BOUNDARY & vbCrLf
            strFormStart = strFormStart & "Content-Disposition: form-data; "
            strFormStart = strFormStart & "name=""" & Split(strDataPair, "=")(0) & """"
            strFormStart = strFormStart & vbCrLf & vbCrLf
            strFormStart = strFormStart & Split(strDataPair, "=")(1)
            strFormStart = strFormStart & vbCrLf
        Next
        'Now add the header for the uploaded file
        strFormStart = strFormStart & "--" & MULTIPART_BOUNDARY & vbCrLf
        strFormStart = strFormStart & "Content-Disposition: form-data; "
        strFormStart = strFormStart & "name=""" & strFileField & """; "
        strFormStart = strFormStart & "filename=""" & Mid(strFilePath, InStrRev(strFilePath, "\") + 1) & """"
        strFormStart = strFormStart & vbCrLf
        strFormStart = strFormStart & "Content-Type: application/upload" 'bogus, but it works
        strFormStart = strFormStart & vbCrLf & vbCrLf
        'Create a recordset large enough to hold everything
        Set rs = CreateObject("ADODB.Recordset")
        rs.Fields.Append "FormData", adLongVarBinary, Len(strFormStart) + LenB(bytFile) + Len(strFormEnd)
        rs.Open
        rs.AddNew
        'Convert form data so far to zero-terminated byte array
        For lngCount = 1 To Len(strFormStart)
            bytFormStart = bytFormStart & ChrB(Asc(Mid(strFormStart, lngCount, 1)))
        Next
        rs("FormData").AppendChunk bytFormStart & ChrB(0)
        bytFormStart = rs("formData").GetChunk(Len(strFormStart))
        rs("FormData") = ""
        'Get the end boundary as a zero-terminated byte array
        For lngCount = 1 To Len(strFormEnd)
            bytFormEnd = bytFormEnd & ChrB(Asc(Mid(strFormEnd, lngCount, 1)))
        Next
        rs("FormData").AppendChunk bytFormEnd & ChrB(0)
        bytFormEnd = rs("formData").GetChunk(Len(strFormEnd))
        rs("FormData") = ""
        'Now merge it all
        rs("FormData").AppendChunk bytFormStart
        rs("FormData").AppendChunk bytFile
        rs("FormData").AppendChunk bytFormEnd
        bytFormData = rs("FormData")
        rs.Close
        'Upload it
        Set web = CreateObject("WinHttp.WinHttpRequest.5.1")
        web.Open "POST", strUploadUrl, False
        web.SetRequestHeader "Content-Type", "multipart/form-data; boundary=" & MULTIPART_BOUNDARY
        web.Send bytFormData
    End Function
</code>```

UPDATE:

when i added part of code from @Tim Williams

in my database is saved file as /tmp/phpAJOtVw what do i doing wrong ?

答:
Upload is a standalone method, so you should be able to call it something like this:

```<code>sUrl = "https://url.domain.com/api/data"  'API endpoint

fPath = "c:\attachment\attachment.zip"    'attachment location

FileFieldName = "checkYourApiForThis"     'API specifies this

DataPairs = "mail_from=" & strFrom & _
                "&mail_to=" & strKomu & _
                "&file_attachment=" & fileAttachment & _
                "&url_attribute=" & strWebLink & _
                "&sms_code=" & strHeslo & _
                "&id_message=" & IdMessage & _
                "&mobile_phone=" & strPhone & _
                "&date_send=" & strDateSend & _
                "&date_expiration=" & strDateExp

'call the function
'expects |-delimited name/value pairs, not &, so do a replace
Upload sUrl, fPath, FileFieldName, Replace(DataPairs, "&", "|")
</code>```

You should remove these hard-coded values from the top of Upload:

```<code>strUploadUrl = "https://url.domain.com/api/data"
strFilePath = cstrFilepathAttachment & "Zip\attachment.zip"
</code>```

Body:
I have last problem with my code. Code sending via POST variables from Outlook to API.

My last problem is how to send variables and mail attachment in one POST request to API.

first 7zip comprimation for mail attachement:

strSource = cstrFileAttachment & "*.*"
strTarget = cstrFileattachment & "Zip\attachment.zip"
strPassword = randomPassword(cintLongPassword)
strCommand = """" & PathZipProgram & """ a -tzip """ & strTarget & _
    """ -p" & strPassword & " """ & strSource & """"

Now i have c:\attachment\attachment.zip

Next part is send variables to API:

    Dim SendDataToApi As String

    strFrom = 1

    Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")

    URL = "https://url.domain.com/api/data"

    objHTTP.Open "POST", URL, False
    objHTTP.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded"

    SendDataToApi = "mail_from=" & strFrom & "&mail_to=" & strKomu & "&file_attachment=" & fileAttachment & "&url_attribute=" & strWebLink & "&sms_code=" & strHeslo & "&id_message=" & IdMessage & "&mobile_phone=" & strPhone & "&date_send=" & strDateSend & "&date_expiration=" & strDateExp

    objHTTP.Send SendDataToApi

Variables are sended, but fileAttachment is send as a string, so API get path where file is saved.

My question is how implement code below (found on internet) to my code sendDataToApi and POST attachment.zip as a binary insteed of string.

    Private Function Upload(strUploadUrl, strFilePath, strFileField, strDataPairs)
    'Uses POST to upload a file and miscellaneous form data
    strUploadUrl = "https://url.domain.com/api/data"
    strFilePath = cstrFilepathAttachment & "Zip\attachment.zip"
    'strFileField is the web page equivalent form field name for the file (File1)
    'strDataPairs are pipe-delimited form data pairs (foo=bar|snap=crackle)
    Const MULTIPART_BOUNDARY = "---------------------------0123456789012"
    Dim ado, rs
    Dim lngCount
    Dim bytFormData, bytFormStart, bytFormEnd, bytFile
    Dim strFormStart, strFormEnd, strDataPair
    Dim web
    Const adLongVarBinary = 205
        'Read the file into a byte array
        Set ado = CreateObject("ADODB.Stream")
        ado.Type = 1
        ado.Open
        ado.LoadFromFile strFilePath
        bytFile = ado.Read
        ado.Close
        'Create the multipart form data.
        'Define the end of form
        strFormEnd = vbCrLf & "--" & MULTIPART_BOUNDARY & "--" & vbCrLf
        'First add any ordinary form data pairs
        strFormStart = ""
        For Each strDataPair In Split(strDataPairs, "|")
            strFormStart = strFormStart & "--" & MULTIPART_BOUNDARY & vbCrLf
            strFormStart = strFormStart & "Content-Disposition: form-data; "
            strFormStart = strFormStart & "name=""" & Split(strDataPair, "=")(0) & """"
            strFormStart = strFormStart & vbCrLf & vbCrLf
            strFormStart = strFormStart & Split(strDataPair, "=")(1)
            strFormStart = strFormStart & vbCrLf
        Next
        'Now add the header for the uploaded file
        strFormStart = strFormStart & "--" & MULTIPART_BOUNDARY & vbCrLf
        strFormStart = strFormStart & "Content-Disposition: form-data; "
        strFormStart = strFormStart & "name=""" & strFileField & """; "
        strFormStart = strFormStart & "filename=""" & Mid(strFilePath, InStrRev(strFilePath, "\") + 1) & """"
        strFormStart = strFormStart & vbCrLf
        strFormStart = strFormStart & "Content-Type: application/upload" 'bogus, but it works
        strFormStart = strFormStart & vbCrLf & vbCrLf
        'Create a recordset large enough to hold everything
        Set rs = CreateObject("ADODB.Recordset")
        rs.Fields.Append "FormData", adLongVarBinary, Len(strFormStart) + LenB(bytFile) + Len(strFormEnd)
        rs.Open
        rs.AddNew
        'Convert form data so far to zero-terminated byte array
        For lngCount = 1 To Len(strFormStart)
            bytFormStart = bytFormStart & ChrB(Asc(Mid(strFormStart, lngCount, 1)))
        Next
        rs("FormData").AppendChunk bytFormStart & ChrB(0)
        bytFormStart = rs("formData").GetChunk(Len(strFormStart))
        rs("FormData") = ""
        'Get the end boundary as a zero-terminated byte array
        For lngCount = 1 To Len(strFormEnd)
            bytFormEnd = bytFormEnd & ChrB(Asc(Mid(strFormEnd, lngCount, 1)))
        Next
        rs("FormData").AppendChunk bytFormEnd & ChrB(0)
        bytFormEnd = rs("formData").GetChunk(Len(strFormEnd))
        rs("FormData") = ""
        'Now merge it all
        rs("FormData").AppendChunk bytFormStart
        rs("FormData").AppendChunk bytFile
        rs("FormData").AppendChunk bytFormEnd
        bytFormData = rs("FormData")
        rs.Close
        'Upload it
        Set web = CreateObject("WinHttp.WinHttpRequest.5.1")
        web.Open "POST", strUploadUrl, False
        web.SetRequestHeader "Content-Type", "multipart/form-data; boundary=" & MULTIPART_BOUNDARY
        web.Send bytFormData
    End Function

UPDATE:

when i added part of code from @Tim Williams

in my database is saved file as /tmp/phpAJOtVw what do i doing wrong ?

Body:
Upload is a standalone method, so you should be able to call it something like this:

sUrl = "https://url.domain.com/api/data"  'API endpoint

fPath = "c:\attachment\attachment.zip"    'attachment location

FileFieldName = "checkYourApiForThis"     'API specifies this

DataPairs = "mail_from=" & strFrom & _
                "&mail_to=" & strKomu & _
                "&file_attachment=" & fileAttachment & _
                "&url_attribute=" & strWebLink & _
                "&sms_code=" & strHeslo & _
                "&id_message=" & IdMessage & _
                "&mobile_phone=" & strPhone & _
                "&date_send=" & strDateSend & _
                "&date_expiration=" & strDateExp

'call the function
'expects |-delimited name/value pairs, not &, so do a replace
Upload sUrl, fPath, FileFieldName, Replace(DataPairs, "&", "|")

You should remove these hard-coded values from the top of Upload:

strUploadUrl = "https://url.domain.com/api/data"
strFilePath = cstrFilepathAttachment & "Zip\attachment.zip"