问:
Using Variables and/or Properties with Simple Data Writer in JMeter
Using JMeter v5.1.1, I am setting a dynamic file path and name to be used with Simple Data Writer.  I've tried this every way I can think of to no avail.  Things I've tried:

JSR223 PreProcessor (scoped to same thread group) which stores dynamic path/name in variables, and use variable in Simple Data Writer

Execute thread groups consecutively.  Use StartUp Thread with JSR223 Sampler which stores dynamic path/name in properties, and use __P function in Simple Data Writer to retrieve path/name.  This method will pull the property values from the previous run if I do not remove the properties at the end of the test.

Execute thread groups consecutively.  Use StartUp Thread with JSR223 Sampler which stores dynamic path/name in properties.  Run JSR223 PreProcessor which stores global properties as variables in thread group, and use variables in Simple Data Writer to retrieve path/name.  I've also tried the __V function with this approach.  This method will pull the property values from the previous run if I do not remove the properties at the end of the test.

I can see in the JSR223 scripts that the path/name are being set correctly using log.info.  I can also see them set when using a debug sampler, but for some reason the Simple Data Writer does not seem to be picking them up.  If I set the variables before running, it works fine.  This seems like an order of operations problem, or asynchronous/multi-thread issue, but am not sure how to proceed.  Any guidance would be much appreciated.

Here's a sample to reproduce the behavior:

<?xml version="1.0" encoding="UTF-8"?>
<jmeterTestPlan version="1.2" properties="5.0" jmeter="5.1.1 r1855137">
  <hashTree>
    <TestPlan guiclass="TestPlanGui" testclass="TestPlan" testname="Data Writer Issue" enabled="true">
      <stringProp name="TestPlan.comments"></stringProp>
      <boolProp name="TestPlan.functional_mode">false</boolProp>
      <boolProp name="TestPlan.tearDown_on_shutdown">true</boolProp>
      <boolProp name="TestPlan.serialize_threadgroups">true</boolProp>
      <elementProp name="TestPlan.user_defined_variables" elementType="Arguments" guiclass="ArgumentsPanel" testclass="Arguments" testname="User Defined Variables" enabled="true">
        <collectionProp name="Arguments.arguments"/>
      </elementProp>
      <stringProp name="TestPlan.user_define_classpath"></stringProp>
    </TestPlan>
    <hashTree>
      <SetupThreadGroup guiclass="SetupThreadGroupGui" testclass="SetupThreadGroup" testname="setUp Thread Group" enabled="true">
        <stringProp name="ThreadGroup.on_sample_error">continue</stringProp>
        <elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController" testname="Loop Controller" enabled="true">
          <boolProp name="LoopController.continue_forever">false</boolProp>
          <stringProp name="LoopController.loops">1</stringProp>
        </elementProp>
        <stringProp name="ThreadGroup.num_threads">1</stringProp>
        <stringProp name="ThreadGroup.ramp_time">1</stringProp>
        <boolProp name="ThreadGroup.scheduler">false</boolProp>
        <stringProp name="ThreadGroup.duration"></stringProp>
        <stringProp name="ThreadGroup.delay"></stringProp>
      </SetupThreadGroup>
      <hashTree>
        <JSR223Sampler guiclass="TestBeanGUI" testclass="JSR223Sampler" testname="Set Path to Store Results" enabled="true">
          <stringProp name="scriptLanguage">groovy</stringProp>
          <stringProp name="parameters"></stringProp>
          <stringProp name="filename"></stringProp>
          <stringProp name="cacheKey">true</stringProp>
          <stringProp name="script">import org.apache.jmeter.services.FileServer;

// Get the separator for current OS
String separator = File.separator;

// Use {{current directory}}/csv for path
String path = FileServer.getFileServer().getBaseDir() + separator + "csv" + separator;

// Create directory if doesn't already exist
(new File(path)).mkdirs();

log.info(path);

// Save path to property
props.put("data-file-path", path);</stringProp>
        </JSR223Sampler>
        <hashTree/>
        <JSR223Sampler guiclass="TestBeanGUI" testclass="JSR223Sampler" testname="Set FileName to Store Results" enabled="true">
          <stringProp name="scriptLanguage">groovy</stringProp>
          <stringProp name="parameters"></stringProp>
          <stringProp name="filename"></stringProp>
          <stringProp name="cacheKey">true</stringProp>
          <stringProp name="script">import org.apache.jmeter.services.FileServer;
import java.time.*;
import java.time.format.*;

// Get current date/time formatted as yyyyMMddHHmm
String formattedDateTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yMMddHHmm"));

// Get name of currently-running script
String scriptName = FileServer.getFileServer().getScriptName();

// Save fileName as scriptName (minus file extension) with timestamp at end
String fileName = scriptName.take(scriptName.lastIndexOf('.'))  + "_" + formattedDateTime + ".csv";

log.info(fileName);

// Set filename as property
props.put("data-file-name", fileName);</stringProp>
        </JSR223Sampler>
        <hashTree/>
      </hashTree>
      <ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="Sample GET Requests" enabled="true">
        <stringProp name="ThreadGroup.on_sample_error">continue</stringProp>
        <elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController" testname="Loop Controller" enabled="true">
          <boolProp name="LoopController.continue_forever">false</boolProp>
          <stringProp name="LoopController.loops">1</stringProp>
        </elementProp>
        <stringProp name="ThreadGroup.num_threads">2</stringProp>
        <stringProp name="ThreadGroup.ramp_time">1</stringProp>
        <boolProp name="ThreadGroup.scheduler">false</boolProp>
        <stringProp name="ThreadGroup.duration"></stringProp>
        <stringProp name="ThreadGroup.delay"></stringProp>
        <boolProp name="ThreadGroup.same_user_on_next_iteration">true</boolProp>
        <boolProp name="ThreadGroup.delayedStart">true</boolProp>
      </ThreadGroup>
      <hashTree>
        <DebugSampler guiclass="TestBeanGUI" testclass="DebugSampler" testname="Debug Sampler" enabled="true">
          <boolProp name="displayJMeterProperties">true</boolProp>
          <boolProp name="displayJMeterVariables">true</boolProp>
          <boolProp name="displaySystemProperties">false</boolProp>
        </DebugSampler>
        <hashTree/>
        <ResultCollector guiclass="SimpleDataWriter" testclass="ResultCollector" testname="Save Results to CSV File" enabled="true">
          <boolProp name="ResultCollector.error_logging">false</boolProp>
          <objProp>
            <name>saveConfig</name>
            <value class="SampleSaveConfiguration">
              <time>true</time>
              <latency>true</latency>
              <timestamp>true</timestamp>
              <success>true</success>
              true
              true
              <message>true</message>
              <threadName>true</threadName>
              <dataType>true</dataType>
              <encoding>false</encoding>
              <assertions>false</assertions>
              <subresults>true</subresults>
              <responseData>false</responseData>
              <samplerData>false</samplerData>
              <xml>false</xml>
              <fieldNames>true</fieldNames>
              <responseHeaders>false</responseHeaders>
              <requestHeaders>false</requestHeaders>
              <responseDataOnError>false</responseDataOnError>
              <saveAssertionResultsFailureMessage>true</saveAssertionResultsFailureMessage>
              <assertionsResultsToSave>0</assertionsResultsToSave>
              <bytes>true</bytes>
              <sentBytes>true</sentBytes>
              <url>true</url>
              <threadCounts>true</threadCounts>
              <idleTime>true</idleTime>
              <connectTime>true</connectTime>
            </value>
          </objProp>
          <stringProp name="filename">${__P(data-file-path)}${__P(data-file-name)}</stringProp>
        </ResultCollector>
        <hashTree/>
        <HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="Get ToDo" enabled="true">
          <elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" testname="User Defined Variables" enabled="true">
            <collectionProp name="Arguments.arguments"/>
          </elementProp>
          <stringProp name="HTTPSampler.domain">jsonplaceholder.typicode.com</stringProp>
          <stringProp name="HTTPSampler.port"></stringProp>
          <stringProp name="HTTPSampler.protocol">https</stringProp>
          <stringProp name="HTTPSampler.contentEncoding"></stringProp>
          <stringProp name="HTTPSampler.path">/todos/1</stringProp>
          <stringProp name="HTTPSampler.method">GET</stringProp>
          <boolProp name="HTTPSampler.follow_redirects">true</boolProp>
          <boolProp name="HTTPSampler.auto_redirects">false</boolProp>
          <boolProp name="HTTPSampler.use_keepalive">true</boolProp>
          <boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp>
          <stringProp name="HTTPSampler.embedded_url_re"></stringProp>
          <stringProp name="HTTPSampler.connect_timeout"></stringProp>
          <stringProp name="HTTPSampler.response_timeout"></stringProp>
          <stringProp name="TestPlan.comments">"groupNames": ["${__P(GroupNames_${__Random(1,${__property(GroupNames_matchNr)})})}"]</stringProp>
        </HTTPSamplerProxy>
        <hashTree/>
      </hashTree>
      <PostThreadGroup guiclass="PostThreadGroupGui" testclass="PostThreadGroup" testname="tearDown Thread Group" enabled="true">
        <stringProp name="ThreadGroup.on_sample_error">continue</stringProp>
        <elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController" testname="Loop Controller" enabled="true">
          <boolProp name="LoopController.continue_forever">false</boolProp>
          <stringProp name="LoopController.loops">1</stringProp>
        </elementProp>
        <stringProp name="ThreadGroup.num_threads">1</stringProp>
        <stringProp name="ThreadGroup.ramp_time">1</stringProp>
        <boolProp name="ThreadGroup.scheduler">false</boolProp>
        <stringProp name="ThreadGroup.duration"></stringProp>
        <stringProp name="ThreadGroup.delay"></stringProp>
      </PostThreadGroup>
      <hashTree>
        <JSR223Sampler guiclass="TestBeanGUI" testclass="JSR223Sampler" testname="Clear Dynamic Properties" enabled="true">
          <stringProp name="scriptLanguage">groovy</stringProp>
          <stringProp name="parameters"></stringProp>
          <stringProp name="filename"></stringProp>
          <stringProp name="cacheKey">true</stringProp>
          <stringProp name="script">props.remove("data-file-path");
props.remove("data-file-name");</stringProp>
        </JSR223Sampler>
        <hashTree/>
      </hashTree>
      <ResultCollector guiclass="ViewResultsFullVisualizer" testclass="ResultCollector" testname="View Results Tree" enabled="true">
        <boolProp name="ResultCollector.error_logging">false</boolProp>
        <objProp>
          <name>saveConfig</name>
          <value class="SampleSaveConfiguration">
            <time>true</time>
            <latency>true</latency>
            <timestamp>true</timestamp>
            <success>true</success>
            true
            true
            <message>true</message>
            <threadName>true</threadName>
            <dataType>true</dataType>
            <encoding>false</encoding>
            <assertions>true</assertions>
            <subresults>true</subresults>
            <responseData>false</responseData>
            <samplerData>false</samplerData>
            <xml>false</xml>
            <fieldNames>true</fieldNames>
            <responseHeaders>false</responseHeaders>
            <requestHeaders>false</requestHeaders>
            <responseDataOnError>false</responseDataOnError>
            <saveAssertionResultsFailureMessage>true</saveAssertionResultsFailureMessage>
            <assertionsResultsToSave>0</assertionsResultsToSave>
            <bytes>true</bytes>
            <sentBytes>true</sentBytes>
            <url>true</url>
            <threadCounts>true</threadCounts>
            <idleTime>true</idleTime>
            <connectTime>true</connectTime>
          </value>
        </objProp>
        <stringProp name="filename"></stringProp>
      </ResultCollector>
      <hashTree/>
    </hashTree>
  </hashTree>
</jmeterTestPlan>

```

答:
I don't think you can use __P() function in the Simple Data Writer's filename field, in fact you can, but it will return default value of 1 so when you run your test file with the name of 11 is being generated in the folder where you run your tests from and this is where your results go.

In general you should not be using Listeners for anything but tests development and/or debugging because they don't add any value and just consuming valuable system resources. Neither you should run your test in GUI mode

Assuming above points I would recommend reconsidering your approach and use -l command-line argument to specify the .jtl results file location. If you want to add timestamp for this - go for operating system date and time commands, for example:

Windows:

```<code>jmeter -n -t test.jmx -l csv/%date:~10,4%%date:~4,2%%date:~7,2%%time:~0,2%%time:~3,2%.csv
</code>```

Unix and derivatives:

```<code>jmeter -n -t test.jmx -l csv/`date +%Y%m%d%H%M`.csv
</code>```

Body:
I don't think you can use __P() function in the Simple Data Writer's filename field, in fact you can, but it will return default value of 1 so when you run your test file with the name of 11 is being generated in the folder where you run your tests from and this is where your results go.

In general you should not be using Listeners for anything but tests development and/or debugging because they don't add any value and just consuming valuable system resources. Neither you should run your test in GUI mode

Assuming above points I would recommend reconsidering your approach and use -l command-line argument to specify the .jtl results file location. If you want to add timestamp for this - go for operating system date and time commands, for example:

Windows:

jmeter -n -t test.jmx -l csv/%date:~10,4%%date:~4,2%%date:~7,2%%time:~0,2%%time:~3,2%.csv

Unix and derivatives:

jmeter -n -t test.jmx -l csv/`date +%Y%m%d%H%M`.csv


来源: stackexchange

问:
Uncaught (in promise) TypeError: _this is not a function
I'm making a simple axios call and on success, call a toast. The toast function is also there and working fine because I am using it at 100 different places.

console log shows {data: "Payment Successful", status: 200, statusText: "OK", headers: {…}, config: {…}, …} means the call is working fine, it's just the this is not ...

```<code>this.razorPayOptions = {
    'key': process.env.MIX_RAZORPAY_KEY,
    'name': process.env.MIX_APP_NAME,
    'description': 'Details ...',
    'handler': function (request) {
        axios.post('/api/transaction/complete', request)
            .then(response => {
                console.log(response);
                this.toast(response.data, response.status); // this is where the error occurs
            });
    }
}
</code>```

Error: Uncaught (in promise) TypeError: _this.toast is not a function

I've searched on internet for past 2 days but couldn't find anything. Some suggested to use async/await but no luck either. As always, stack overflow is my last resort. If you need more info, please add a comment below.

Thank You.

答:
Switch your handler to an arrow function to avoid changing the scope:

this.razorPayOptions = {
    'key': process.env.MIX_RAZORPAY_KEY,
    'name': process.env.MIX_APP_NAME,
    'description': 'Details ...',
    'handler': (request) => {
        axios.post('/api/transaction/complete', request)
            .then(response => {
                console.log(response);
                this.toast(response.data, response.status); // this is where the error occurs
            });
    }
}
```

Check out this answer for more context

ContentLicense: CC BY-SA 4.0

Body:
I'm making a simple axios call and on success, call a toast. The toast function is also there and working fine because I am using it at 100 different places.

console log shows {data: "Payment Successful", status: 200, statusText: "OK", headers: {…}, config: {…}, …} means the call is working fine, it's just the this is not ...

this.razorPayOptions = {
    'key': process.env.MIX_RAZORPAY_KEY,
    'name': process.env.MIX_APP_NAME,
    'description': 'Details ...',
    'handler': function (request) {
        axios.post('/api/transaction/complete', request)
            .then(response => {
                console.log(response);
                this.toast(response.data, response.status); // this is where the error occurs
            });
    }
}

Error: Uncaught (in promise) TypeError: _this.toast is not a function

I've searched on internet for past 2 days but couldn't find anything. Some suggested to use async/await but no luck either. As always, stack overflow is my last resort. If you need more info, please add a comment below.

Thank You.

Body:
Switch your handler to an arrow function to avoid changing the scope:

this.razorPayOptions = {
    'key': process.env.MIX_RAZORPAY_KEY,
    'name': process.env.MIX_APP_NAME,
    'description': 'Details ...',
    'handler': (request) => {
        axios.post('/api/transaction/complete', request)
            .then(response => {
                console.log(response);
                this.toast(response.data, response.status); // this is where the error occurs
            });
    }
}

Check out this answer for more context


问:
How to add authorization in header by Glide in Android Studio?
I am using Glide version = 4.7.1

I have no idea how to authenticate an image by glide.
This code is what I did.

I created:

```<code> private static final String AUTHORIZATION = "ss-id=doa3cx8OV3aGLThRrpnh;";
private static final String ABC = "application/json";

public static GlideUrl getUrlWithHeaders(String url){
    return new GlideUrl(url, new LazyHeaders.Builder()
            .addHeader("Cookie", AUTHORIZATION)
            .addHeader("Accept", ABC)
            .build());
}
</code>```

}

```<code>String s = "http://192.168.1.144/api/download/" + mImageIds.get(position);
        GlideApp
                .with(mContext)
                .load(Headers.getUrlWithHeaders(s))
                .centerCrop()
                .transition(DrawableTransitionOptions.withCrossFade())
                .into((imageView));
</code>```

Any helps,

答:
Kotlin

```<code>val url:String="https://URL.com/" + data[position].image_path;

val glideUrl = GlideUrl(
            url,
            LazyHeaders.Builder()
                .addHeader("Authorization", "Bearer $token")
                .build()
)

 Glide.with(mContext)
  .load(glideUrl)
  .into(holder.binding.img);
</code>```

Body:
I am using Glide version = 4.7.1

I have no idea how to authenticate an image by glide.
This code is what I did.

I created:

 private static final String AUTHORIZATION = "ss-id=doa3cx8OV3aGLThRrpnh;";
private static final String ABC = "application/json";

public static GlideUrl getUrlWithHeaders(String url){
    return new GlideUrl(url, new LazyHeaders.Builder()
            .addHeader("Cookie", AUTHORIZATION)
            .addHeader("Accept", ABC)
            .build());
}

}

String s = "http://192.168.1.144/api/download/" + mImageIds.get(position);
        GlideApp
                .with(mContext)
                .load(Headers.getUrlWithHeaders(s))
                .centerCrop()
                .transition(DrawableTransitionOptions.withCrossFade())
                .into((imageView));

Any helps,

Body:
Kotlin

val url:String="https://URL.com/" + data[position].image_path;

val glideUrl = GlideUrl(
            url,
            LazyHeaders.Builder()
                .addHeader("Authorization", "Bearer $token")
                .build()
)

 Glide.with(mContext)
  .load(glideUrl)
  .into(holder.binding.img);


问:
Copy rows from one table to another in MySQL
I have two tables with the same structure. I need to select data from one table and have to store them into the other.

How can I do that?

答:
```<code>insert into blacklist
select *
from newblacklist
</code>```

for uploading any single number

```<code>insert into blacklist
select *
from newblacklist
where numbers ='123456'
</code>```

Body:
insert into blacklist
select *
from newblacklist

for uploading any single number

insert into blacklist
select *
from newblacklist
where numbers ='123456'

ContentLicense: CC BY-SA 3.0


问:
Auto Layout TextField. Center, top
I try to understand auto layout. I have a Text field with 3 constraints:
- Align Center X to: Superview
- Top Space to: Superview 50
- Width Equals: 150
I have a warning: Equal constraints may cause clipping

If I change to
- Width Greater Than or Equal 150
I have the warning: Width and horizontal position are ambiguous.

I am confused. In fact, those Constraints work well for a button or a label.
- Why is it different for a TextField?

- How to position a TextField horizontal center, top 50, and width 150?

(It seems that I have to add a leading and trailing Greater Than or Equal. That seems redundant to the Width Greater Than or Equal 150. That works to silence the warning but that seems a solution too complicated and redundant. is that right?)

答:
It's because UILabel and UIButton adjusts its size according to its content. In this case, you need to specify a proper width or you can give a leading and trailing anchor with the desired padding.

Here's is how you can resolve your constraint issue in this particular case. Give the text field the following constraints:

50 points from the top.

Leading from the super view with padding.

Trailing anchor from the super view with padding.

The last two anchors can be replaced with these two constraints:

Width constraint for the text field.

Centre horizontally to the super view.

Here's how you achieve this on a story-board:

Title: Auto Layout TextField. Center, top


问:
How to configure $default path in AWS API gateway?
We are trying to leverage the $default path in AWS API gateway as per https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-routes.html

configured api gateway like this leveraging the $default as one of the routes

```<code>/
 /-default
   ANY
 /api
  /{proxy=}
</code>```

when we are trying to invoke the api gateway on the $default path and GET call

```<code>https://apigateway.amazonaws.com/prod/test
</code>```

we assumed it will invoke the default path but it didn't

```<code>message: "Missing Authentication Token"
</code>```

but when we do

```<code>https://apigateway.amazonaws.com/prod/api/test
</code>```

the api integration is invoked

Note : we already tried configuring greedy path{proxy+} instead of $default that does not work as the greedy path always takes precedence and /api routes also get routed to greedy path

Any help from the community in pointing us in the right direction would be of great help

答:
It seems like you have not set up your API Gateway HTTP API routes correctly causing the routing to not work as expected. Would also like to mention that HTTP APIs and REST APIs are different types of API Gateway APIs, so do confirm that you have configured your API correctly.

Coming to how the routing would work, as a sample, here's how the routes for the API look:

Request to GET https://xxxx.execute-api.xxxx.amazonaws.com/prod/test : Routed to $default path

Request to GET https://xxxx.execute-api.xxxx.amazonaws.com/prod/api/test : Routed to /api/{proxy+} path

Further, if you have a greedy path at ANY /{proxy+}, then as you mentioned, this greedy path will take priority over the $default route. However, this would not take precedence over the ANY /api route if the request matches to the route, for example: GET https://xxxx.execute-api.xxxx.amazonaws.com/prod/api : would be routed to /api path and not /{proxy+}

The routing priority is also explained here

After selecting a stage, API Gateway selects a route. API Gateway selects the route with the most-specific match, using the following priorities:

Full match for a route and method.

Match for a route and method with a greedy path variable ({proxy+}).

The $default route.

If no routes match a request, API Gateway returns {"message":"Not Found"} to the client.

EDIT:

To create the $default route, just specify the path as $default when creating the route

Body:
We are trying to leverage the $default path in AWS API gateway as per https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-routes.html

configured api gateway like this leveraging the $default as one of the routes

/
 /-default
   ANY
 /api
  /{proxy=}

when we are trying to invoke the api gateway on the $default path and GET call

https://apigateway.amazonaws.com/prod/test

we assumed it will invoke the default path but it didn't

message: "Missing Authentication Token"

but when we do

https://apigateway.amazonaws.com/prod/api/test

the api integration is invoked

Note : we already tried configuring greedy path{proxy+} instead of $default that does not work as the greedy path always takes precedence and /api routes also get routed to greedy path

Any help from the community in pointing us in the right direction would be of great help


问:
Append a string item to lists in a Pandas Column
For a pandas dataframe:

```<code>Name:        Tags:
'One'        ['tag1', 'tag3']
'Two'        []
'Three'      ['tag1']
</code>```

How can 'tag2' be appended to the tags lists?

I have tried the following (addtag2 is another df):

```<code>df['Tags'] = df['Tags'].astype(str) + ', ' + addtag2['Tags'].astype(str)
</code>```

and

```<code>df['Tags'] = df['Tags'].add(addtag2['Tags'].astype(str))
</code>```

But they append the string outside the list eg ['tag1'], tag2 or ['tag1']tag2

The desired output would be:

```<code>Name:        Tags:
'One'        ['tag1', 'tag3', 'tag2']
'Two'        ['tag2']
'Three'      ['tag1', 'tag2']
</code>```

答:
Or you can do this using append:

```<code>df['Tags'] = df['Tags'].apply(lambda x: x.append('tag2') or x)
</code>```

Output:

```<code>    Name                Tags
0    One  [tag1, tag3, tag2]
1    Two              [tag2]
2  three        [tag1, tag2]
</code>```

Body:
For a pandas dataframe:

Name:        Tags:
'One'        ['tag1', 'tag3']
'Two'        []
'Three'      ['tag1']

How can 'tag2' be appended to the tags lists?

I have tried the following (addtag2 is another df):

df['Tags'] = df['Tags'].astype(str) + ', ' + addtag2['Tags'].astype(str)

and

df['Tags'] = df['Tags'].add(addtag2['Tags'].astype(str))

But they append the string outside the list eg ['tag1'], tag2 or ['tag1']tag2

The desired output would be:

Name:        Tags:
'One'        ['tag1', 'tag3', 'tag2']
'Two'        ['tag2']
'Three'      ['tag1', 'tag2']

Body:
Or you can do this using append:

df['Tags'] = df['Tags'].apply(lambda x: x.append('tag2') or x)

Output:

    Name                Tags
0    One  [tag1, tag3, tag2]
1    Two              [tag2]
2  three        [tag1, tag2]


问:
Run DatePickerDialog in non-main activity
I'm getting an issue like that:

```<code>2020-06-02 18:22:49.454 1829-1829/com.bartosz.piekny.lprtracker E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.bartosz.piekny.lprtracker, PID: 1829
    android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
        at android.view.ViewRootImpl.setView(ViewRootImpl.java:765)
        at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:356)
        at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:92)
        at android.app.Dialog.show(Dialog.java:330)
        at com.bartosz.piekny.lprtracker.AddNote.onClick(AddNote.java:147)
        at android.view.View.performClick(View.java:6256)
        at android.view.View$PerformClick.run(View.java:24701)
        at android.os.Handler.handleCallback(Handler.java:789)
        at android.os.Handler.dispatchMessage(Handler.java:98)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6541)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
</code>```

While trying to open date picker In non-main activity:

```<code>       context = getApplicationContext();
       dateButton = (TextView) findViewById(R.id.dateTextView);
        final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {

            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear,
                                  int dayOfMonth) {
                int monthNumber = monthOfYear + 1;
                dateButton.setText(dayOfMonth + "." + monthNumber + "." + year);
                dateTime = LocalDateTime.now().withYear(year).withMonth(monthNumber).withDayOfMonth(dayOfMonth);
                mDateTimeListener.onDateTimeChanged(dateTime);
            }
        };

        dateButton.setOnClickListener( new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                final Calendar c = Calendar.getInstance();
                int mYear = c.get(Calendar.YEAR);
                int mMonth = c.get(Calendar.MONTH);
                int mDay = c.get(Calendar.DAY_OF_MONTH);
                new DatePickerDialog(context, date, mYear, mMonth, mDay).show();
            }
        });
</code>```

Anyone know what I'm doing wrong?:) I was googling it but all which I've found was related to popups not to time picker. I want to have a really simple solution.

答:
I've just figured it out. Instead of calling:

```<code>context = getApplicationContext();
</code>```

I need:

```<code>context = this;
</code>```

Body:
I'm getting an issue like that:

2020-06-02 18:22:49.454 1829-1829/com.bartosz.piekny.lprtracker E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.bartosz.piekny.lprtracker, PID: 1829
    android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
        at android.view.ViewRootImpl.setView(ViewRootImpl.java:765)
        at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:356)
        at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:92)
        at android.app.Dialog.show(Dialog.java:330)
        at com.bartosz.piekny.lprtracker.AddNote.onClick(AddNote.java:147)
        at android.view.View.performClick(View.java:6256)
        at android.view.View$PerformClick.run(View.java:24701)
        at android.os.Handler.handleCallback(Handler.java:789)
        at android.os.Handler.dispatchMessage(Handler.java:98)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6541)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

While trying to open date picker In non-main activity:

       context = getApplicationContext();
       dateButton = (TextView) findViewById(R.id.dateTextView);
        final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {

            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear,
                                  int dayOfMonth) {
                int monthNumber = monthOfYear + 1;
                dateButton.setText(dayOfMonth + "." + monthNumber + "." + year);
                dateTime = LocalDateTime.now().withYear(year).withMonth(monthNumber).withDayOfMonth(dayOfMonth);
                mDateTimeListener.onDateTimeChanged(dateTime);
            }
        };

        dateButton.setOnClickListener( new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                final Calendar c = Calendar.getInstance();
                int mYear = c.get(Calendar.YEAR);
                int mMonth = c.get(Calendar.MONTH);
                int mDay = c.get(Calendar.DAY_OF_MONTH);
                new DatePickerDialog(context, date, mYear, mMonth, mDay).show();
            }
        });

Anyone know what I'm doing wrong?:) I was googling it but all which I've found was related to popups not to time picker. I want to have a really simple solution.

Body:
I've just figured it out. Instead of calling:

context = getApplicationContext();

I need:

context = this;


问:
How to set flutter POST method using DIO?
This is my code below, i'm stuck please help. How to set flutter POST method using DIO?

```<code>Map<String, dynamic> toJson() {
    return {
        'id': id,
         "name": name,
         "telNumber": telNumber,
         "email": email,
         "age": age
      };
   }

String postToJson(Post data){
      final dyn = data.toJson();
      return json.encode(dyn);
}

Future<http.Response> createPost(Post post) async {
          final response = await http.post(
               "$baseUrl/users",
              headers: {
                  "content-type": "application"
                    },
              body: postToJson(post));
              return response;
            }
</code>```

This method works in http

答:
```<code> BaseOptions options = new BaseOptions(
     baseUrl: $baseUrl,
     connectTimeout: 10000,
     receiveTimeout: 10000,);
final dioClient = Dio(options);
try{
   final response = await dioClient.post("/users", data: FormData.fromMap(
      postToJson(post))
    ),);
   return response;
} catch (e) {
  throw (e);
}
</code>```

Put this code inside the function

Body:
This is my code below, i'm stuck please help. How to set flutter POST method using DIO?

Map<String, dynamic> toJson() {
    return {
        'id': id,
         "name": name,
         "telNumber": telNumber,
         "email": email,
         "age": age
      };
   }

String postToJson(Post data){
      final dyn = data.toJson();
      return json.encode(dyn);
}

Future<http.Response> createPost(Post post) async {
          final response = await http.post(
               "$baseUrl/users",
              headers: {
                  "content-type": "application"
                    },
              body: postToJson(post));
              return response;
            }

This method works in http

Body:
 BaseOptions options = new BaseOptions(
     baseUrl: $baseUrl,
     connectTimeout: 10000,
     receiveTimeout: 10000,);
final dioClient = Dio(options);
try{
   final response = await dioClient.post("/users", data: FormData.fromMap(
      postToJson(post))
    ),);
   return response;
} catch (e) {
  throw (e);
}

Put this code inside the function


问:
Writing SF Dataframe to Microsoft SQL Server Crashes R and Fails to Write Data
Using the sample data provided, I am trying to write an sf dataframe out to a Microsoft SQL Server table, following the instructions found here, however, whenever I do so, the R Session crashes and gives the error shown in the screen shot below.

I am wondering if anyone else has seen this problem and what they did to resolve it?

As always, thank you in advance.

-nate

Error From Terminal:

```<code>Note: method with signature ‘DBIObject#sf’ chosen for function ‘dbDataType’,
 target signature ‘Microsoft SQL Server#sf’.
 "OdbcConnection#ANY" would also be valid

 *** caught segfault ***
address 0x21, cause 'memory not mapped'

Traceback:
 1: result_insert_dataframe(rs@ptr, values, batch_rows)
 2: tryCatchList(expr, classes, parentenv, handlers)
 3: tryCatch(result_insert_dataframe(rs@ptr, values, batch_rows),     finally = dbClearResult(rs))
 4: .local(conn, name, value, ...)
 5: dbWriteTable(conn, name, to_postgis(conn, value, binary), ...,     row.names = row.names, overwrite = overwrite, append = append,     field.types = field.types)
 6: dbWriteTable(conn, name, to_postgis(conn, value, binary), ...,     row.names = row.names, overwrite = overwrite, append = append,     field.types = field.types)
 7: .local(conn, name, value, ...)
 8: DBI::dbWriteTable(conn = con, name = the_table_name, value = polygon_db,     row.names = FALSE, overwrite = TRUE, binary = TRUE)
 9: DBI::dbWriteTable(conn = con, name = the_table_name, value = polygon_db,     row.names = FALSE, overwrite = TRUE, binary = TRUE)
An irrecoverable exception occurred. R is aborting now ...
Segmentation fault: 11
</code>```

Session Info:

```<code>R version 3.6.3 (2020-02-29)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS Catalina 10.15.4

Matrix products: default
BLAS:   /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.6/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] odbc_1.2.2   DBI_1.1.0    magrittr_1.5 sf_0.9-3

loaded via a namespace (and not attached):
 [1] Rcpp_1.0.4.6       class_7.3-16       packrat_0.5.0      grid_3.6.3         e1071_1.7-3        units_0.6-6        KernSmooth_2.23-16 rlang_0.4.6        blob_1.2.1         vctrs_0.2.4        tools_3.6.3        bit64_0.9-7
[13] bit_1.1-15.2       hms_0.5.3          compiler_3.6.3     pkgconfig_2.0.3    classInt_0.4-3
</code>```

Sample Data (Apologies for long lines):

polygon_sf_df <- structure(
  list(leaf_id = c(1234, 2222),
       db_label = c("Middle of Nothing", "Somewhere in Florida"),
       division = c("Mountain", "South Atlantic"),
       geometry = structure(list(
         structure(list(structure(c(-114.806444, -114.326789, -114.08946, -114.898877, -114.806444, 39.236959, 39.219554, 38.961837, 38.829708, 39.236959), .Dim = c(5L, 2L))), class = c("XY", "POLYGON", "sfg")),
         structure(list(structure(c(-81.806444, -81.326789, -81.08946, -81.898877, -81.806444, 29.236959, 29.219554, 28.961837, 28.829708, 29.236959), .Dim = c(5L, 2L))), class = c("XY", "POLYGON", "sfg"))),
         class = c("sfc_POLYGON", "sfc"), precision = 0,
         bbox = structure(c(xmin = -114.898877, ymin = 28.829708, xmax = -81.08946, ymax = 39.236959), class = "bbox"),
         crs = structure(list(input = "EPSG:4326", wkt = "GEOGCS[\"WGS 84\",\n    DATUM[\"WGS_1984\",\n        SPHEROID[\"WGS 84\",6378137,298.257223563,\n            AUTHORITY[\"EPSG\",\"7030\"]],\n        AUTHORITY[\"EPSG\",\"6326\"]],\n    PRIMEM[\"Greenwich\",0,\n        AUTHORITY[\"EPSG\",\"8901\"]],\n    UNIT[\"degree\",0.0174532925199433,\n        AUTHORITY[\"EPSG\",\"9122\"]],\n    AUTHORITY[\"EPSG\",\"4326\"]]"), class = "crs"), n_empty = 0L)),
  sf_column = "geometry", agr = structure(c(leaf_id = NA_integer_, db_label = NA_integer_, division = NA_integer_), .Label = c("constant", "aggregate", "identity"), class = "factor"),
  row.names = 1:2, class = c("sf", "data.frame"))
```

<p>Quick Package Installs:</p>

<pre class="lang-r prettyprint-override"><code>options(scipen = 999)
ipak <- function(pkg){
  new.pkg <- pkg[!(pkg %in% installed.packages()[, "Package"])]
  if (length(new.pkg))
    install.packages(new.pkg, dependencies = TRUE)
  sapply(pkg, require, character.only = TRUE)
}
packages<- c("sf", "magrittr","DBI", "odbc")
ipak(packages)
</code>```

Connection & Writing Method:

con <- DBI::dbConnect(odbc::odbc(),
                      Driver   = "ODBC Driver 17 for SQL Server",
                      Server   = "some_database_server.windows.net",
                      Database = "dev_db",
                      UID      = "<User ID Here>",
                      PWD      = "<PW HERE>",
                      Port     = 1433,
                      maxvarcharsize = 0)
# Fails Here
DBI::dbWriteTable(conn = con, name = "the_sf_polygon_table_name", value = polygon_sf_df, row.names=FALSE, overwrite=TRUE, binary=TRUE)
```

<p>The Schema of the table (as per comments below)</p>

```structure(list(TABLE_CATALOG = c("analytics_dev", "analytics_dev",
"analytics_dev", "analytics_dev"), TABLE_SCHEMA = c("dbo", "dbo",
"dbo", "dbo"), TABLE_NAME = c("test_polygon_table", "test_polygon_table",
"test_polygon_table", "test_polygon_table"), COLUMN_NAME = c("leaf_id",
"db_label", "division", "geometry"), ORDINAL_POSITION = 1:4,
    COLUMN_DEFAULT = c(NA_character_, NA_character_, NA_character_,
    NA_character_), IS_NULLABLE = c("YES", "YES", "YES", "YES"
    ), DATA_TYPE = c("float", "varchar", "varchar", "geometry"
    ), CHARACTER_MAXIMUM_LENGTH = c(NA, 255L, 255L, -1L), CHARACTER_OCTET_LENGTH = c(NA,
    255L, 255L, -1L), NUMERIC_PRECISION = c(53L, NA, NA, NA),
    NUMERIC_PRECISION_RADIX = c(2L, NA, NA, NA), NUMERIC_SCALE = c(NA_integer_,
    NA_integer_, NA_integer_, NA_integer_), DATETIME_PRECISION = c(NA_integer_,
    NA_integer_, NA_integer_, NA_integer_), CHARACTER_SET_CATALOG = c(NA_character_,
    NA_character_, NA_character_, NA_character_), CHARACTER_SET_SCHEMA = c(NA_character_,
    NA_character_, NA_character_, NA_character_), CHARACTER_SET_NAME = c(NA,
    "iso_1", "iso_1", NA), COLLATION_CATALOG = c(NA_character_,
    NA_character_, NA_character_, NA_character_), COLLATION_SCHEMA = c(NA_character_,
    NA_character_, NA_character_, NA_character_), COLLATION_NAME = c(NA,
    "SQL_Latin1_General_CP1_CI_AS", "SQL_Latin1_General_CP1_CI_AS",
    NA), DOMAIN_CATALOG = c(NA_character_, NA_character_, NA_character_,
    NA_character_), DOMAIN_SCHEMA = c(NA_character_, NA_character_,
    NA_character_, NA_character_), DOMAIN_NAME = c(NA_character_,
    NA_character_, NA_character_, NA_character_)), class = "data.frame", row.names = c(NA,
-4L))
```

答:
This is a hack, to be honest, since I'm not familiar or proficient with sf (R package) or geometry (sql server data type). Up front, I wonder if geography (sql server data type) might be more appropriate for you, since it alleges to be for GPS-like coordinates (datums, etc) ... but I think this process might translate just as well.

Either way, I first show how R and SQL Server agree on the shapes (spoiler: character), and then how to read and push those to the database in proper data types.

Query

If you step through the examples in https://learn.microsoft.com/en-us/sql/t-sql/spatial-geometry/spatial-types-geometry-transact-sql and then run a query, notice what it returns:

# con <- DBI::dbConnect(...) # sql server
DBI::dbExecute(con, "
CREATE TABLE SpatialTable
    ( id int IDENTITY (1,1),
    GeomCol1 geometry,
    GeomCol2 AS GeomCol1.STAsText() )")

DBI::dbExecute(con, "
INSERT INTO SpatialTable (GeomCol1)
VALUES (geometry::STGeomFromText('LINESTRING (100 100, 20 180, 180 180)', 0));
INSERT INTO SpatialTable (GeomCol1)
VALUES (geometry::STGeomFromText('POLYGON ((0 0, 150 0, 150 150, 0 150, 0 0))', 0));  ")

ret <- DBI::dbGetQuery(con, "select * from SpatialTable")
str(ret)
# 'data.frame': 2 obs. of  3 variables:
#  $ id      : int  1 2
#  $ GeomCol1: chr  "" ""
#  $ GeomCol2: chr  "LINESTRING (100 100, 20 180, 180 180)" "POLYGON ((0 0, 150 0, 150 150, 0 150, 0 0))"
```

<p>Not a surprise (to me), DBI treats this like a string. Note, though, that it's returning something for <code>GeomCol2</code>, which is a text-translation of the actual blob-like field <code>GeomCol1</code>. And nothing for <code>GeomCol1</code>. Okay, let's only retrieve what we need, and since the "id" if a geometry is not intended to be numerical, let's convert it to a string then confirm it plots:</p>

<pre class="lang-r prettyprint-override"><code>ret <- DBI::dbGetQuery(con, "select id, GeomCol2 from SpatialTable")
ret$id <- as.character(ret$id)
plot(sf::st_as_sf(ret, wkt="GeomCol2"))
</code>```

Upload

In order to upload your data to SQL Server, we need to character-ize it.

tempdat <- as.data.frame(polygon_sf_df)[,c("leaf_id", "geometry")]
tempdat$geometry <- sapply(tempdat$geometry, format, width = 0)
names(tempdat)[1] <- "id"
str(tempdat)
# 'data.frame': 2 obs. of  2 variables:
#  $ id      : num  1234 2222
#  $ geometry: chr  "POLYGON ((-114.8064 39.23696, -114.3268 39.21955, -114.0895 38.96184, -114.8989 38.82971, -114.8064 39.23696))" "POLYGON ((-81.80644 29.23696, -81.32679 29.21955, -81.08946 28.96184, -81.89888 28.82971, -81.80644 29.23696))"
```

<p>Now we can upload it to a temp table:</p>

<pre class="lang-r prettyprint-override"><code>### write *character* shapes to a temp table
DBI::dbWriteTable(con, "temptable", tempdat, create = TRUE)
### convert those *character* shapes to real *geometries*
DBI::dbExecute(con, "
insert into SpatialTable (GeomCol1)
select geometry::STGeomFromText(geometry, 0) as GeomCol1
from temptable")
DBI::dbExecute(con, "drop table temptable")
</code>```

Now we can query those shapes:

ret2 <- DBI::dbGetQuery(con, "select id, GeomCol2 from SpatialTable where id > 2")
ret2$id <- as.character(ret2$id)
ret2 <- sf::st_as_sf(ret2, wkt="GeomCol2")
ret2
# Simple feature collection with 2 features and 1 field
# geometry type:  POLYGON
# dimension:      XY
# bbox:           xmin: -114.8989 ymin: 28.82971 xmax: -81.08946 ymax: 39.23696
# CRS:            NA
#   id                       GeomCol2
# 1  3 POLYGON ((-114.8064 39.2369...
# 2  4 POLYGON ((-81.80644 29.2369...

plot(ret2)
```

Note about data size

Without extensive testing, my guess is that this text field (when queried) will be "large" in the SQL Server sense; this is a "known thing" in that Microsoft's ODBC driver intentionally breaks when "large fields" are not last in the selection of columns. For this, then, make sure that the geometry-text field is among the last columns in your query (not before any not-large fields).

References:

ODBC driver comments, https://learn.microsoft.com/en-us/sql/odbc/reference/develop-app/getting-long-data, it is known and apparently by-design, so a "feature"

odbc package discussion, https://github.com/r-dbi/odbc/issues/112, external to the package so not going to be fixed

nanodbc (library used by the odbc package`) has discussed this twice and concluded that it is also not their problem to fix (#8 and #149)

Body:
Using the sample data provided, I am trying to write an sf dataframe out to a Microsoft SQL Server table, following the instructions found here, however, whenever I do so, the R Session crashes and gives the error shown in the screen shot below.

I am wondering if anyone else has seen this problem and what they did to resolve it?

As always, thank you in advance.

-nate

Error From Terminal:

Note: method with signature ‘DBIObject#sf’ chosen for function ‘dbDataType’,
 target signature ‘Microsoft SQL Server#sf’.
 "OdbcConnection#ANY" would also be valid

 *** caught segfault ***
address 0x21, cause 'memory not mapped'

Traceback:
 1: result_insert_dataframe(rs@ptr, values, batch_rows)
 2: tryCatchList(expr, classes, parentenv, handlers)
 3: tryCatch(result_insert_dataframe(rs@ptr, values, batch_rows),     finally = dbClearResult(rs))
 4: .local(conn, name, value, ...)
 5: dbWriteTable(conn, name, to_postgis(conn, value, binary), ...,     row.names = row.names, overwrite = overwrite, append = append,     field.types = field.types)
 6: dbWriteTable(conn, name, to_postgis(conn, value, binary), ...,     row.names = row.names, overwrite = overwrite, append = append,     field.types = field.types)
 7: .local(conn, name, value, ...)
 8: DBI::dbWriteTable(conn = con, name = the_table_name, value = polygon_db,     row.names = FALSE, overwrite = TRUE, binary = TRUE)
 9: DBI::dbWriteTable(conn = con, name = the_table_name, value = polygon_db,     row.names = FALSE, overwrite = TRUE, binary = TRUE)
An irrecoverable exception occurred. R is aborting now ...
Segmentation fault: 11

Session Info:

R version 3.6.3 (2020-02-29)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS Catalina 10.15.4

Matrix products: default
BLAS:   /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.6/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] odbc_1.2.2   DBI_1.1.0    magrittr_1.5 sf_0.9-3

loaded via a namespace (and not attached):
 [1] Rcpp_1.0.4.6       class_7.3-16       packrat_0.5.0      grid_3.6.3         e1071_1.7-3        units_0.6-6        KernSmooth_2.23-16 rlang_0.4.6        blob_1.2.1         vctrs_0.2.4        tools_3.6.3        bit64_0.9-7
[13] bit_1.1-15.2       hms_0.5.3          compiler_3.6.3     pkgconfig_2.0.3    classInt_0.4-3

Sample Data (Apologies for long lines):

polygon_sf_df <- structure(
  list(leaf_id = c(1234, 2222),
       db_label = c("Middle of Nothing", "Somewhere in Florida"),
       division = c("Mountain", "South Atlantic"),
       geometry = structure(list(
         structure(list(structure(c(-114.806444, -114.326789, -114.08946, -114.898877, -114.806444, 39.236959, 39.219554, 38.961837, 38.829708, 39.236959), .Dim = c(5L, 2L))), class = c("XY", "POLYGON", "sfg")),
         structure(list(structure(c(-81.806444, -81.326789, -81.08946, -81.898877, -81.806444, 29.236959, 29.219554, 28.961837, 28.829708, 29.236959), .Dim = c(5L, 2L))), class = c("XY", "POLYGON", "sfg"))),
         class = c("sfc_POLYGON", "sfc"), precision = 0,
         bbox = structure(c(xmin = -114.898877, ymin = 28.829708, xmax = -81.08946, ymax = 39.236959), class = "bbox"),
         crs = structure(list(input = "EPSG:4326", wkt = "GEOGCS[\"WGS 84\",\n    DATUM[\"WGS_1984\",\n        SPHEROID[\"WGS 84\",6378137,298.257223563,\n            AUTHORITY[\"EPSG\",\"7030\"]],\n        AUTHORITY[\"EPSG\",\"6326\"]],\n    PRIMEM[\"Greenwich\",0,\n        AUTHORITY[\"EPSG\",\"8901\"]],\n    UNIT[\"degree\",0.0174532925199433,\n        AUTHORITY[\"EPSG\",\"9122\"]],\n    AUTHORITY[\"EPSG\",\"4326\"]]"), class = "crs"), n_empty = 0L)),
  sf_column = "geometry", agr = structure(c(leaf_id = NA_integer_, db_label = NA_integer_, division = NA_integer_), .Label = c("constant", "aggregate", "identity"), class = "factor"),
  row.names = 1:2, class = c("sf", "data.frame"))

Quick Package Installs:

options(scipen = 999)
ipak <- function(pkg){
  new.pkg <- pkg[!(pkg %in% installed.packages()[, "Package"])]
  if (length(new.pkg))
    install.packages(new.pkg, dependencies = TRUE)
  sapply(pkg, require, character.only = TRUE)
}
packages<- c("sf", "magrittr","DBI", "odbc")
ipak(packages)

Connection & Writing Method:

con <- DBI::dbConnect(odbc::odbc(),
                      Driver   = "ODBC Driver 17 for SQL Server",
                      Server   = "some_database_server.windows.net",
                      Database = "dev_db",
                      UID      = "<User ID Here>",
                      PWD      = "<PW HERE>",
                      Port     = 1433,
                      maxvarcharsize = 0)
# Fails Here
DBI::dbWriteTable(conn = con, name = "the_sf_polygon_table_name", value = polygon_sf_df, row.names=FALSE, overwrite=TRUE, binary=TRUE)

The Schema of the table (as per comments below)

structure(list(TABLE_CATALOG = c("analytics_dev", "analytics_dev",
"analytics_dev", "analytics_dev"), TABLE_SCHEMA = c("dbo", "dbo",
"dbo", "dbo"), TABLE_NAME = c("test_polygon_table", "test_polygon_table",
"test_polygon_table", "test_polygon_table"), COLUMN_NAME = c("leaf_id",
"db_label", "division", "geometry"), ORDINAL_POSITION = 1:4,
    COLUMN_DEFAULT = c(NA_character_, NA_character_, NA_character_,
    NA_character_), IS_NULLABLE = c("YES", "YES", "YES", "YES"
    ), DATA_TYPE = c("float", "varchar", "varchar", "geometry"
    ), CHARACTER_MAXIMUM_LENGTH = c(NA, 255L, 255L, -1L), CHARACTER_OCTET_LENGTH = c(NA,
    255L, 255L, -1L), NUMERIC_PRECISION = c(53L, NA, NA, NA),
    NUMERIC_PRECISION_RADIX = c(2L, NA, NA, NA), NUMERIC_SCALE = c(NA_integer_,
    NA_integer_, NA_integer_, NA_integer_), DATETIME_PRECISION = c(NA_integer_,
    NA_integer_, NA_integer_, NA_integer_), CHARACTER_SET_CATALOG = c(NA_character_,
    NA_character_, NA_character_, NA_character_), CHARACTER_SET_SCHEMA = c(NA_character_,
    NA_character_, NA_character_, NA_character_), CHARACTER_SET_NAME = c(NA,
    "iso_1", "iso_1", NA), COLLATION_CATALOG = c(NA_character_,
    NA_character_, NA_character_, NA_character_), COLLATION_SCHEMA = c(NA_character_,
    NA_character_, NA_character_, NA_character_), COLLATION_NAME = c(NA,
    "SQL_Latin1_General_CP1_CI_AS", "SQL_Latin1_General_CP1_CI_AS",
    NA), DOMAIN_CATALOG = c(NA_character_, NA_character_, NA_character_,
    NA_character_), DOMAIN_SCHEMA = c(NA_character_, NA_character_,
    NA_character_, NA_character_), DOMAIN_NAME = c(NA_character_,
    NA_character_, NA_character_, NA_character_)), class = "data.frame", row.names = c(NA,
-4L))

Body:
This is a hack, to be honest, since I'm not familiar or proficient with sf (R package) or geometry (sql server data type). Up front, I wonder if geography (sql server data type) might be more appropriate for you, since it alleges to be for GPS-like coordinates (datums, etc) ... but I think this process might translate just as well.

Either way, I first show how R and SQL Server agree on the shapes (spoiler: character), and then how to read and push those to the database in proper data types.

Query

If you step through the examples in https://learn.microsoft.com/en-us/sql/t-sql/spatial-geometry/spatial-types-geometry-transact-sql and then run a query, notice what it returns:

# con <- DBI::dbConnect(...) # sql server
DBI::dbExecute(con, "
CREATE TABLE SpatialTable
    ( id int IDENTITY (1,1),
    GeomCol1 geometry,
    GeomCol2 AS GeomCol1.STAsText() )")

DBI::dbExecute(con, "
INSERT INTO SpatialTable (GeomCol1)
VALUES (geometry::STGeomFromText('LINESTRING (100 100, 20 180, 180 180)', 0));
INSERT INTO SpatialTable (GeomCol1)
VALUES (geometry::STGeomFromText('POLYGON ((0 0, 150 0, 150 150, 0 150, 0 0))', 0));  ")

ret <- DBI::dbGetQuery(con, "select * from SpatialTable")
str(ret)
# 'data.frame': 2 obs. of  3 variables:
#  $ id      : int  1 2
#  $ GeomCol1: chr  "" ""
#  $ GeomCol2: chr  "LINESTRING (100 100, 20 180, 180 180)" "POLYGON ((0 0, 150 0, 150 150, 0 150, 0 0))"

Not a surprise (to me), DBI treats this like a string. Note, though, that it's returning something for GeomCol2, which is a text-translation of the actual blob-like field GeomCol1. And nothing for GeomCol1. Okay, let's only retrieve what we need, and since the "id" if a geometry is not intended to be numerical, let's convert it to a string then confirm it plots:

ret <- DBI::dbGetQuery(con, "select id, GeomCol2 from SpatialTable")
ret$id <- as.character(ret$id)
plot(sf::st_as_sf(ret, wkt="GeomCol2"))

Upload

In order to upload your data to SQL Server, we need to character-ize it.

tempdat <- as.data.frame(polygon_sf_df)[,c("leaf_id", "geometry")]
tempdat$geometry <- sapply(tempdat$geometry, format, width = 0)
names(tempdat)[1] <- "id"
str(tempdat)
# 'data.frame': 2 obs. of  2 variables:
#  $ id      : num  1234 2222
#  $ geometry: chr  "POLYGON ((-114.8064 39.23696, -114.3268 39.21955, -114.0895 38.96184, -114.8989 38.82971, -114.8064 39.23696))" "POLYGON ((-81.80644 29.23696, -81.32679 29.21955, -81.08946 28.96184, -81.89888 28.82971, -81.80644 29.23696))"

Now we can upload it to a temp table:

### write *character* shapes to a temp table
DBI::dbWriteTable(con, "temptable", tempdat, create = TRUE)
### convert those *character* shapes to real *geometries*
DBI::dbExecute(con, "
insert into SpatialTable (GeomCol1)
select geometry::STGeomFromText(geometry, 0) as GeomCol1
from temptable")
DBI::dbExecute(con, "drop table temptable")

Now we can query those shapes:

ret2 <- DBI::dbGetQuery(con, "select id, GeomCol2 from SpatialTable where id > 2")
ret2$id <- as.character(ret2$id)
ret2 <- sf::st_as_sf(ret2, wkt="GeomCol2")
ret2
# Simple feature collection with 2 features and 1 field
# geometry type:  POLYGON
# dimension:      XY
# bbox:           xmin: -114.8989 ymin: 28.82971 xmax: -81.08946 ymax: 39.23696
# CRS:            NA
#   id                       GeomCol2
# 1  3 POLYGON ((-114.8064 39.2369...
# 2  4 POLYGON ((-81.80644 29.2369...

plot(ret2)

Note about data size

Without extensive testing, my guess is that this text field (when queried) will be "large" in the SQL Server sense; this is a "known thing" in that Microsoft's ODBC driver intentionally breaks when "large fields" are not last in the selection of columns. For this, then, make sure that the geometry-text field is among the last columns in your query (not before any not-large fields).

References:

ODBC driver comments, https://learn.microsoft.com/en-us/sql/odbc/reference/develop-app/getting-long-data, it is known and apparently by-design, so a "feature"

odbc package discussion, https://github.com/r-dbi/odbc/issues/112, external to the package so not going to be fixed

nanodbc (library used by the odbc package`) has discussed this twice and concluded that it is also not their problem to fix (#8 and #149)


问:
Junit5 : ClassNotFoundException: org.junit.platform.launcher.core.LauncherFactory
I am trying to run basic JUnit5 program. Using Eclipse Oxygen.3a(4.7.3a) with OpenJdk9. Getting error as below -

```<code>java.lang.NoClassDefFoundError: org/junit/platform/launcher/core/LauncherFactory
    at org.eclipse.jdt.internal.junit5.runner.JUnit5TestLoader.<init>(JUnit5TestLoader.java:31)
.
.
.
Caused by: java.lang.ClassNotFoundException: org.junit.platform.launcher.core.LauncherFactory
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
</code>```

I had a look at this - Eclipse No tests found using JUnit 5 caused by NoClassDefFoundError for LauncherFactory
But since my IDE is up-to-date not sure what I am missing now.

My code is as below :

Main Class

```<code>package io.javabrains;
public class MathUtils {
    public int add(int a, int b) { return a + b;}
}
</code>```

TestClass

```<code>package io.javabrains;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
class MathUtilsTest {
    @Test
    void test() {
        System.out.println("This test ran successfully");
        //fail("Not yet implemented");
    }
}
</code>```

POM

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>io.javabrains</groupId>
  <artifactId>junit-5-basics</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>junit-5-basics</name>

  <properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <junit.jupiter.version>5.4.0</junit.jupiter.version>
  </properties>

   <dependencies>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>${junit.jupiter.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>${junit.jupiter.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

</code>```

答:
Eclipse and JUnit can sometimes clash across the moving versions

To fix your example, add JUnit 5 to your classpath IN ECLIPSE

Maven will run and pass as it does not use the missing launcher

Eclipse needs the sub-library that has the Launcher

CAVEAT: Its better to add the missing library to the pom as the problem persists in cross IDE projects (not everyone uses eclipse)

Body:
I am trying to run basic JUnit5 program. Using Eclipse Oxygen.3a(4.7.3a) with OpenJdk9. Getting error as below -

java.lang.NoClassDefFoundError: org/junit/platform/launcher/core/LauncherFactory
    at org.eclipse.jdt.internal.junit5.runner.JUnit5TestLoader.<init>(JUnit5TestLoader.java:31)
.
.
.
Caused by: java.lang.ClassNotFoundException: org.junit.platform.launcher.core.LauncherFactory
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)

I had a look at this - Eclipse No tests found using JUnit 5 caused by NoClassDefFoundError for LauncherFactory
But since my IDE is up-to-date not sure what I am missing now.

My code is as below :

Main Class

package io.javabrains;
public class MathUtils {
    public int add(int a, int b) { return a + b;}
}

TestClass

package io.javabrains;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
class MathUtilsTest {
    @Test
    void test() {
        System.out.println("This test ran successfully");
        //fail("Not yet implemented");
    }
}

POM

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>io.javabrains</groupId>
  <artifactId>junit-5-basics</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>junit-5-basics</name>

  <properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <junit.jupiter.version>5.4.0</junit.jupiter.version>
  </properties>

   <dependencies>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>${junit.jupiter.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>${junit.jupiter.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>


问:
What's the point of providing input and output operands if they are not specified in ASM template?
I found the following piece of code in u-boot/arch/arm/lib/semihosting.c that uses bkpt and other instructions and provides input and output operands even though they are not specified in the ASM template:

```<code>static noinline long smh_trap(unsigned int sysnum, void *addr)
{
    register long result asm("r0");
#if defined(CONFIG_ARM64)
    asm volatile ("hlt #0xf000" : "=r" (result) : "0"(sysnum), "r"(addr));
#elif defined(CONFIG_CPU_V7M)
    asm volatile ("bkpt #0xAB" : "=r" (result) : "0"(sysnum), "r"(addr));
#else
    /* Note - untested placeholder */
    asm volatile ("svc #0x123456" : "=r" (result) : "0"(sysnum), "r"(addr));
#endif
    return result;
}
</code>```

Minimal, verifiable example:

```<code>#include <stdio.h>
#include <stdlib.h>

int main(void)
{
  register long result asm("r0");
  void *addr = 0;
  unsigned int sysnum = 0;
  __asm__ volatile ("bkpt #0xAB" : "=r" (result) : "0"(sysnum), "r"(addr));

  return EXIT_SUCCESS;
}
</code>```

According to ARM Architecture Reference Manual bkpt instruction
takes a single imm parameter and according to my reading of GCC manual
section on inline assembly GCC does not allow providing operands if they
are not specified in the template.  Output assembly generated with -S:

```<code>    .arch armv6
    .eabi_attribute 28, 1
    .eabi_attribute 20, 1
    .eabi_attribute 21, 1
    .eabi_attribute 23, 3
    .eabi_attribute 24, 1
    .eabi_attribute 25, 1
    .eabi_attribute 26, 2
    .eabi_attribute 30, 6
    .eabi_attribute 34, 1
    .eabi_attribute 18, 4
    .file   "bkpt-so.c"
    .text
    .align  2
    .global main
    .arch armv6
    .syntax unified
    .arm
    .fpu vfp
    .type   main, %function
main:
    @ args = 0, pretend = 0, frame = 8
    @ frame_needed = 1, uses_anonymous_args = 0
    @ link register save eliminated.
    str fp, [sp, #-4]!
    add fp, sp, #0
    sub sp, sp, #12
    mov r3, #0
    str r3, [fp, #-8]
    mov r3, #0
    str r3, [fp, #-12]
    ldr r2, [fp, #-12]
    ldr r3, [fp, #-8]
    mov r0, r2
    .syntax divided
@ 10 "bkpt-so.c" 1
    bkpt #0xAB
@ 0 "" 2
    .arm
    .syntax unified
    mov r3, #0
    mov r0, r3
    add sp, fp, #0
    @ sp needed
    ldr fp, [sp], #4
    bx  lr
    .size   main, .-main
    .ident  "GCC: (Raspbian 8.3.0-6+rpi1) 8.3.0"
    .section    .note.GNU-stack,"",%progbits
</code>```

So what's the point of "=r" (result) : "0"(sysnum), "r"(addr) in this line:

```<code>__asm__ volatile ("bkpt #0xAB" : "=r" (result) : "0"(sysnum), "r"(addr));
</code>```

?

答:
Despite the fact that this code exists in a well known project like U-BOOT does not instill confidence. The code is relying on the fact that with the ARM architectures that the ABI (call standard) passes the first 4 scalar arguments in r0 (argument 1), r1 (argument 2), r2 (argument 3), and r3 (argument 4).

Table 6.1 summarizes the ABI:

The assumption that the U-BOOT code is making is that addr which was passed to the function in r1 is still the same value when the inline assembly is generated. I consider this dangerous because even with a simple non-inlined function GCC doesn't guarantee this behaviour. My view is that this code is fragile although it probably has never presented a problem but in theory it could. Relying on underlying compiler code generation behaviour is not a good idea.

I believe it would have been better written as:

```<code>static noinline long smh_trap(unsigned int sysnum, void *addr)
{
    register long result asm("r0");
    register void *reg_r1 asm("r1") = addr;
#if defined(CONFIG_ARM64)
    asm volatile ("hlt #0xf000" : "=r" (result) : "0"(sysnum), "r"(reg_r1) : "memory");
#elif defined(CONFIG_CPU_V7M)
    asm volatile ("bkpt #0xAB" : "=r" (result) : "0"(sysnum), "r"(reg_r1) : "memory");
#else
    /* Note - untested placeholder */
    asm volatile ("svc #0x123456" : "=r" (result) : "0"(sysnum), "r"(reg_r1) : "memory");
#endif
    return result;
}
</code>```

This code passes addr through a variable (reg_r1) that will be put into register r1 for the purposes of an inline assembly constraint. On higher optimizations levels the compiler would not generate any extra code with the extra variable. I have also placed a memory clobber because it is not a good idea to pass a memory address through a register in this way without one. This poses an issue if someone were to make an inlined version of this function. The memory clobber will ensure that any data is realized into memory before the inline assembly is run and if necessary reloaded when necessary afterwards.

As for the question about what "=r" (result) : "0"(sysnum), "r"(addr) does is:

"=r"(result) is an output constraint that tells compiler that the value in register r0 after the inline assembly completes will be placed in variable addr

"0"(sysnum) is an input constraint that tells compiler that sysnum will be passed into the inline assembly code through the same register as constraint 0 (constraint 0 is using register r0).

"r"(addr) passes addr through a register and the assumption is that it will be in r1 with the U-BOOT code. In my version it is explicitly defined that way.

Information on operands and constraints for extended inline assembly can be found in the GCC documentation. You can find additional machine specific constraints here.

hlt, bkpt, and svc are all being used as system calls to have a system service performed through the debugger (semihosting). You can find more documentation on semihosting here. The different ARM architectures use a slightly different mechanism. The convention for a semihosting system call is that r0 contains the system call number; r1 contains the first argument of the system call; the system call places a return value in r0 before returning to user code.

Body:
I found the following piece of code in u-boot/arch/arm/lib/semihosting.c that uses bkpt and other instructions and provides input and output operands even though they are not specified in the ASM template:

static noinline long smh_trap(unsigned int sysnum, void *addr)
{
    register long result asm("r0");
#if defined(CONFIG_ARM64)
    asm volatile ("hlt #0xf000" : "=r" (result) : "0"(sysnum), "r"(addr));
#elif defined(CONFIG_CPU_V7M)
    asm volatile ("bkpt #0xAB" : "=r" (result) : "0"(sysnum), "r"(addr));
#else
    /* Note - untested placeholder */
    asm volatile ("svc #0x123456" : "=r" (result) : "0"(sysnum), "r"(addr));
#endif
    return result;
}

Minimal, verifiable example:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
  register long result asm("r0");
  void *addr = 0;
  unsigned int sysnum = 0;
  __asm__ volatile ("bkpt #0xAB" : "=r" (result) : "0"(sysnum), "r"(addr));

  return EXIT_SUCCESS;
}

According to ARM Architecture Reference Manual bkpt instruction
takes a single imm parameter and according to my reading of GCC manual
section on inline assembly GCC does not allow providing operands if they
are not specified in the template.  Output assembly generated with -S:

    .arch armv6
    .eabi_attribute 28, 1
    .eabi_attribute 20, 1
    .eabi_attribute 21, 1
    .eabi_attribute 23, 3
    .eabi_attribute 24, 1
    .eabi_attribute 25, 1
    .eabi_attribute 26, 2
    .eabi_attribute 30, 6
    .eabi_attribute 34, 1
    .eabi_attribute 18, 4
    .file   "bkpt-so.c"
    .text
    .align  2
    .global main
    .arch armv6
    .syntax unified
    .arm
    .fpu vfp
    .type   main, %function
main:
    @ args = 0, pretend = 0, frame = 8
    @ frame_needed = 1, uses_anonymous_args = 0
    @ link register save eliminated.
    str fp, [sp, #-4]!
    add fp, sp, #0
    sub sp, sp, #12
    mov r3, #0
    str r3, [fp, #-8]
    mov r3, #0
    str r3, [fp, #-12]
    ldr r2, [fp, #-12]
    ldr r3, [fp, #-8]
    mov r0, r2
    .syntax divided
@ 10 "bkpt-so.c" 1
    bkpt #0xAB
@ 0 "" 2
    .arm
    .syntax unified
    mov r3, #0
    mov r0, r3
    add sp, fp, #0
    @ sp needed
    ldr fp, [sp], #4
    bx  lr
    .size   main, .-main
    .ident  "GCC: (Raspbian 8.3.0-6+rpi1) 8.3.0"
    .section    .note.GNU-stack,"",%progbits

So what's the point of "=r" (result) : "0"(sysnum), "r"(addr) in this line:

__asm__ volatile ("bkpt #0xAB" : "=r" (result) : "0"(sysnum), "r"(addr));

?

Body:
Despite the fact that this code exists in a well known project like U-BOOT does not instill confidence. The code is relying on the fact that with the ARM architectures that the ABI (call standard) passes the first 4 scalar arguments in r0 (argument 1), r1 (argument 2), r2 (argument 3), and r3 (argument 4).

Table 6.1 summarizes the ABI:

The assumption that the U-BOOT code is making is that addr which was passed to the function in r1 is still the same value when the inline assembly is generated. I consider this dangerous because even with a simple non-inlined function GCC doesn't guarantee this behaviour. My view is that this code is fragile although it probably has never presented a problem but in theory it could. Relying on underlying compiler code generation behaviour is not a good idea.

I believe it would have been better written as:

static noinline long smh_trap(unsigned int sysnum, void *addr)
{
    register long result asm("r0");
    register void *reg_r1 asm("r1") = addr;
#if defined(CONFIG_ARM64)
    asm volatile ("hlt #0xf000" : "=r" (result) : "0"(sysnum), "r"(reg_r1) : "memory");
#elif defined(CONFIG_CPU_V7M)
    asm volatile ("bkpt #0xAB" : "=r" (result) : "0"(sysnum), "r"(reg_r1) : "memory");
#else
    /* Note - untested placeholder */
    asm volatile ("svc #0x123456" : "=r" (result) : "0"(sysnum), "r"(reg_r1) : "memory");
#endif
    return result;
}

This code passes addr through a variable (reg_r1) that will be put into register r1 for the purposes of an inline assembly constraint. On higher optimizations levels the compiler would not generate any extra code with the extra variable. I have also placed a memory clobber because it is not a good idea to pass a memory address through a register in this way without one. This poses an issue if someone were to make an inlined version of this function. The memory clobber will ensure that any data is realized into memory before the inline assembly is run and if necessary reloaded when necessary afterwards.

As for the question about what "=r" (result) : "0"(sysnum), "r"(addr) does is:

"=r"(result) is an output constraint that tells compiler that the value in register r0 after the inline assembly completes will be placed in variable addr

"0"(sysnum) is an input constraint that tells compiler that sysnum will be passed into the inline assembly code through the same register as constraint 0 (constraint 0 is using register r0).

"r"(addr) passes addr through a register and the assumption is that it will be in r1 with the U-BOOT code. In my version it is explicitly defined that way.

Information on operands and constraints for extended inline assembly can be found in the GCC documentation. You can find additional machine specific constraints here.

hlt, bkpt, and svc are all being used as system calls to have a system service performed through the debugger (semihosting). You can find more documentation on semihosting here. The different ARM architectures use a slightly different mechanism. The convention for a semihosting system call is that r0 contains the system call number; r1 contains the first argument of the system call; the system call places a return value in r0 before returning to user code.


问:
Azure Kusto :: Convert Time in 12 Hour Format to 24 Hour Format
I want to convert the following 12 hour time format to 24 time format using Azure Kusto language. I would expect the output to be converted from 07:00:00 AM to 07:00:00 and 07:00:00 PM to 19:00:00. Executing the below query is not resulting into correct output, sure i am missing something. Can anyone help please.</p>

```<code>datatable (Date:string, Event:string)
    ['07:00:00 AM', "Morning",
     '07:00:00 PM', "Evening"]
     | extend val = todatetime(Date), val2 = format_datetime(todatetime(strcat('1900-01-01, ',Date)),'HH:mm:ss')
</code>```

答:
a. if you want to create a datetime value, you could try something like this:

parse the parts out of the string (hours, minutes, ...).

adjust the hours part to be in 24-hour format

create a datetime value out of those, using make_datetime(), or using datetime / timespan arithmetic.

for example:

```<code>datatable (TimeOfDay:string, Event:string)
[
    '07:00:01 AM', "Morning",
    '07:01:23 PM', "Evening"
]
| parse TimeOfDay with hours:int ":" minutes:int ":" seconds:int " " am_pm
| extend hours = case(am_pm == "AM" and hours == 12, hours - 12,
                      am_pm == "AM", hours,
                      hours == 12, hours,
                      hours + 12)
| project dt = make_datetime(1970, 1, 1, hours, minutes, seconds) // just used 1970-01-01 for the example
</code>```

b. otherwise, if you just want to create a string value, you could do something somewhat similar:

```<code>datatable (TimeOfDay:string, Event:string)
[
    '07:00:01 AM', "Morning",
    '07:01:23 PM', "Evening"
]
| parse TimeOfDay with hours:int ":" minutes_seconds " " am_pm
| extend hours = case(am_pm == "AM" and hours == 12, tostring(hours),
                      am_pm == "AM", strcat("0", hours),
                      hours == 12, tostring(hours),
                      tostring(hours + 12))
| project str = strcat(hours, ":", minutes_seconds)
</code>```

Body:
I want to convert the following 12 hour time format to 24 time format using Azure Kusto language. I would expect the output to be converted from 07:00:00 AM to 07:00:00 and 07:00:00 PM to 19:00:00. Executing the below query is not resulting into correct output, sure i am missing something. Can anyone help please.

datatable (Date:string, Event:string)
    ['07:00:00 AM', "Morning",
     '07:00:00 PM', "Evening"]
     | extend val = todatetime(Date), val2 = format_datetime(todatetime(strcat('1900-01-01, ',Date)),'HH:mm:ss')

Body:
a. if you want to create a datetime value, you could try something like this:

parse the parts out of the string (hours, minutes, ...).

adjust the hours part to be in 24-hour format

create a datetime value out of those, using make_datetime(), or using datetime / timespan arithmetic.

for example:

datatable (TimeOfDay:string, Event:string)
[
    '07:00:01 AM', "Morning",
    '07:01:23 PM', "Evening"
]
| parse TimeOfDay with hours:int ":" minutes:int ":" seconds:int " " am_pm
| extend hours = case(am_pm == "AM" and hours == 12, hours - 12,
                      am_pm == "AM", hours,
                      hours == 12, hours,
                      hours + 12)
| project dt = make_datetime(1970, 1, 1, hours, minutes, seconds) // just used 1970-01-01 for the example

b. otherwise, if you just want to create a string value, you could do something somewhat similar:

datatable (TimeOfDay:string, Event:string)
[
    '07:00:01 AM', "Morning",
    '07:01:23 PM', "Evening"
]
| parse TimeOfDay with hours:int ":" minutes_seconds " " am_pm
| extend hours = case(am_pm == "AM" and hours == 12, tostring(hours),
                      am_pm == "AM", strcat("0", hours),
                      hours == 12, tostring(hours),
                      tostring(hours + 12))
| project str = strcat(hours, ":", minutes_seconds)


问:
overwriting react-native stylesheets styles
I have a custom react component that looks like this:

```<code>import { StyleSheet } from 'react-native';
import { Input, Item } from 'native-base';
import Icon from 'react-native-vector-icons/FontAwesome';
import { moderateScale, verticalScale } from 'react-native-size-matters';
import { styles as commonStyles } from '~/styles/RegistrationStyles';

type FieldInputProps = {
  handleChange: (e: string) => undefined;
  handleBlur: (e: string) => undefined;
  value: string;
  fieldType: string;
  placeholderText?: string;
  hidePasswordIcon?: string;
  hidePassword?: boolean;
  togglePassword?: () => void;
  icon: string;
};

export const FieldInput: React.FunctionComponent<FieldInputProps> = ({
  handleChange,
  handleBlur,
  fieldType,
  placeholderText,
  value,
  hidePassword,
  hidePasswordIcon,
  togglePassword,
  icon,
}) => {
  return (
    <Item rounded style={styles.personalListItem}>
      <Icon name={icon} size={moderateScale(20)} color="green" />
      <Input
        autoFocus={true}
        autoCapitalize="none"
        style={{ fontSize: moderateScale(15) }}
        placeholder={placeholderText}
        keyboardType="default"
        onChangeText={handleChange(fieldType)}
        onBlur={handleBlur(fieldType)}
        value={value}
        secureTextEntry={hidePassword}
      />
      {togglePassword ? (
        <Icon
          name={hidePasswordIcon}
          onPress={togglePassword}
          style={commonStyles.iconStyle}
          size={moderateScale(20)}
          color="green"
        />
      ) : null}
    </Item>
  );
};

const styles = StyleSheet.create({
  container: {
    alignItems: 'center',
    backgroundColor: '#2E3331',
    flex: 1,
  },
  personalListItem: {
    width: moderateScale(320),
    backgroundColor: 'white',
    borderBottomColor: 'grey',
    borderRadius: moderateScale(10),
    height: verticalScale(50),
    paddingRight: moderateScale(20),
    paddingLeft: moderateScale(10),
    marginVertical: moderateScale(20),
  },
  text: {
    fontFamily: 'Roboto',
    fontSize: moderateScale(20),
    fontWeight: '600',
    marginVertical: moderateScale(10),
    color: '#17D041',
  },
  subtext: {
    color: '#17D041',
    fontSize: moderateScale(14),
  },
  subtextBold: {
    textDecorationLine: 'underline',
    color: '#17D041',
    fontWeight: '600',
    fontSize: moderateScale(14),
  },
  button: {
    height: moderateScale(50),
    width: moderateScale(350),
    borderRadius: moderateScale(10),
    justifyContent: 'center',
    marginBottom: moderateScale(5),
  },
  buttonText: {
    fontSize: moderateScale(15),
  },
});
</code>```

Usually when I use this component, I want to keep using this style. However, in one particular case, I want to overwrite the styles. For example, change the width or the background color of the input field etc. However, if I try to overwrite the styles, there are no changes.

```<code><FieldInput style={styles.fieldInput}
                      handleChange={handleChange}
                      handleBlur={handleBlur}
                      value={values.phoneNumber}
                      fieldType="phoneNumber"
                      icon="phone"
                      placeholderText="49152901820"
                    />

 fieldInput: {
    width: moderateScale(320),
    backgroundColor: 'red',
  },
</code>```

答:
You're not using style prop in your component. Please fix it as shown below.

```<code>export const FieldInput: React.FunctionComponent<FieldInputProps> = ({
  handleChange,
  handleBlur,
  fieldType,
  placeholderText,
  value,
  hidePassword,
  hidePasswordIcon,
  togglePassword,
  icon,
  style,
  rounded,
}) => {
  return (
    <Item rounded={rounded} style={[styles.personalListItem, style]}>
      /* remaining code code */
    </Item>
  );
};
</code>```

Body:
I have a custom react component that looks like this:

import { StyleSheet } from 'react-native';
import { Input, Item } from 'native-base';
import Icon from 'react-native-vector-icons/FontAwesome';
import { moderateScale, verticalScale } from 'react-native-size-matters';
import { styles as commonStyles } from '~/styles/RegistrationStyles';

type FieldInputProps = {
  handleChange: (e: string) => undefined;
  handleBlur: (e: string) => undefined;
  value: string;
  fieldType: string;
  placeholderText?: string;
  hidePasswordIcon?: string;
  hidePassword?: boolean;
  togglePassword?: () => void;
  icon: string;
};

export const FieldInput: React.FunctionComponent<FieldInputProps> = ({
  handleChange,
  handleBlur,
  fieldType,
  placeholderText,
  value,
  hidePassword,
  hidePasswordIcon,
  togglePassword,
  icon,
}) => {
  return (
    <Item rounded style={styles.personalListItem}>
      <Icon name={icon} size={moderateScale(20)} color="green" />
      <Input
        autoFocus={true}
        autoCapitalize="none"
        style={{ fontSize: moderateScale(15) }}
        placeholder={placeholderText}
        keyboardType="default"
        onChangeText={handleChange(fieldType)}
        onBlur={handleBlur(fieldType)}
        value={value}
        secureTextEntry={hidePassword}
      />
      {togglePassword ? (
        <Icon
          name={hidePasswordIcon}
          onPress={togglePassword}
          style={commonStyles.iconStyle}
          size={moderateScale(20)}
          color="green"
        />
      ) : null}
    </Item>
  );
};

const styles = StyleSheet.create({
  container: {
    alignItems: 'center',
    backgroundColor: '#2E3331',
    flex: 1,
  },
  personalListItem: {
    width: moderateScale(320),
    backgroundColor: 'white',
    borderBottomColor: 'grey',
    borderRadius: moderateScale(10),
    height: verticalScale(50),
    paddingRight: moderateScale(20),
    paddingLeft: moderateScale(10),
    marginVertical: moderateScale(20),
  },
  text: {
    fontFamily: 'Roboto',
    fontSize: moderateScale(20),
    fontWeight: '600',
    marginVertical: moderateScale(10),
    color: '#17D041',
  },
  subtext: {
    color: '#17D041',
    fontSize: moderateScale(14),
  },
  subtextBold: {
    textDecorationLine: 'underline',
    color: '#17D041',
    fontWeight: '600',
    fontSize: moderateScale(14),
  },
  button: {
    height: moderateScale(50),
    width: moderateScale(350),
    borderRadius: moderateScale(10),
    justifyContent: 'center',
    marginBottom: moderateScale(5),
  },
  buttonText: {
    fontSize: moderateScale(15),
  },
});

Usually when I use this component, I want to keep using this style. However, in one particular case, I want to overwrite the styles. For example, change the width or the background color of the input field etc. However, if I try to overwrite the styles, there are no changes.

<FieldInput style={styles.fieldInput}
                      handleChange={handleChange}
                      handleBlur={handleBlur}
                      value={values.phoneNumber}
                      fieldType="phoneNumber"
                      icon="phone"
                      placeholderText="49152901820"
                    />

 fieldInput: {
    width: moderateScale(320),
    backgroundColor: 'red',
  },

Body:
You're not using style prop in your component. Please fix it as shown below.

export const FieldInput: React.FunctionComponent<FieldInputProps> = ({
  handleChange,
  handleBlur,
  fieldType,
  placeholderText,
  value,
  hidePassword,
  hidePasswordIcon,
  togglePassword,
  icon,
  style,
  rounded,
}) => {
  return (
    <Item rounded={rounded} style={[styles.personalListItem, style]}>
      /* remaining code code */
    </Item>
  );
};


问:
How do I create a list of all possible anagrams of a word in javascript?
How do I create a list of all possible anagrams of a word in javascript?If this question has already been asked please direct me to the answer?

Thank You

答:
Here you go: Anagrams finder in javascript

I'm not sure whether that's the exact same problem as yours, but there look to be a few good solutions in the answers.

EDIT: Actually, this is what you need: Is there any pre-built method for finding all permutations of a given string in JavaScript?


问:
How to install vue3 beta using vue/cli?
Right now vue3 is in beta and I want to try it.

Is there a way using @vue/cli to install the vue3 beta? if so, How?

答:
You need the latest version of @vue/cli and then run vue add vue-next in an existing Vue CLI project.

This will:

Add Vue 3 and the new Vue 3 Compiler to your project

Configure webpack to use the new vue compiler

Install Vuex 4 and vue-router 4 beta (or alpha dunno where they are rn) if the older versions are in your project

Codemods for compatibility

More Info here

However, not every package that works with Vue2 will work with this Vue3.
If all you want to try out is the new composition-api, there is a plugin which you can add which is still using Vue2 but with many of the composition-apis Features, probably all non-breaking changes? You install that by either running

npm install @vue/composition-api

or

yarn add @vue/composition-api

and then install it like this before using other APIs:

```<code>
import Vue from 'vue';
import VueCompositionApi from '@vue/composition-api';

Vue.use(VueCompositionApi);
</code>```

Title: How to install vue3 beta using vue/cli?

Body:
You need the latest version of @vue/cli and then run vue add vue-next in an existing Vue CLI project.

This will:

Add Vue 3 and the new Vue 3 Compiler to your project

Configure webpack to use the new vue compiler

Install Vuex 4 and vue-router 4 beta (or alpha dunno where they are rn) if the older versions are in your project

Codemods for compatibility

More Info here

However, not every package that works with Vue2 will work with this Vue3.
If all you want to try out is the new composition-api, there is a plugin which you can add which is still using Vue2 but with many of the composition-apis Features, probably all non-breaking changes? You install that by either running

npm install @vue/composition-api

or

yarn add @vue/composition-api

and then install it like this before using other APIs:

import Vue from 'vue';
import VueCompositionApi from '@vue/composition-api';

Vue.use(VueCompositionApi);


问:
How to emit only last request in subscribe method
I send a form using complex logic inside concatMap operator. And all works fine, but in my subscribe method I have additional http requests, which fires 2 times instead of 1. I tried to use takeLast operator, but it didn't help. I need to make requests in subscribe method only after all requests completed in concatMap.
For example, if I have two updateMember() events, after each request I get invoked function from subscribe method.

```<code>makeRequest(value) {
  const team = toFormData(this.form.controls.profile.value);

  this.teamService
  .sendTeam(team)
  .pipe(
    concatMap(() => {
      const tasks$ = [];

      for (const [index, m] of this.form.controls.members.value.entries()) {
        const member = toFormData(m);

        if (m.id) {
          tasks$.push(this.teamService.updateMember(member, m.id).pipe(take(1)));
        } else if (!member.entries().next().done) {
          if (member.has('name')) {
            tasks$.push(this.teamService.createMember(member).pipe(take(1)));
          } else {
            (this.form.controls.members as FormArray).controls[index].markAllAsTouched();
            this.scrollToFirstInvalidControl();
          }
        }
      }

      return tasks$.length ? concat(...tasks$) : EMPTY;
    }),
  )
  .subscribe(() => {

    this.teamService.getMembers().subscribe();

  });
}
</code>```

What should I use to make only necessary requests?

答: I think, the data structure you are looking for is the ReplySubject. It will act as a Subject and will store the last emitted value.</p>

Body:
I send a form using complex logic inside concatMap operator. And all works fine, but in my subscribe method I have additional http requests, which fires 2 times instead of 1. I tried to use takeLast operator, but it didn't help. I need to make requests in subscribe method only after all requests completed in concatMap.
For example, if I have two updateMember() events, after each request I get invoked function from subscribe method.

makeRequest(value) {
  const team = toFormData(this.form.controls.profile.value);

  this.teamService
  .sendTeam(team)
  .pipe(
    concatMap(() => {
      const tasks$ = [];

      for (const [index, m] of this.form.controls.members.value.entries()) {
        const member = toFormData(m);

        if (m.id) {
          tasks$.push(this.teamService.updateMember(member, m.id).pipe(take(1)));
        } else if (!member.entries().next().done) {
          if (member.has('name')) {
            tasks$.push(this.teamService.createMember(member).pipe(take(1)));
          } else {
            (this.form.controls.members as FormArray).controls[index].markAllAsTouched();
            this.scrollToFirstInvalidControl();
          }
        }
      }

      return tasks$.length ? concat(...tasks$) : EMPTY;
    }),
  )
  .subscribe(() => {

    this.teamService.getMembers().subscribe();

  });
}

What should I use to make only necessary requests?


问:
RxJS: Run asynchronous code before next or error
I have the following code:

```<code>of(true)
  .pipe(
    take(1)
  )
  .subscribe(async (_) =>  {
    await this.close();
    await Promise.all(...);
  }, _ => {
    this.close();
    console.error(_);
  });
</code>```

I want to only write once this.close(), however I can't use finalize since it has to be run before Promise.all. Is there something I could use to run a code (and wait for it to resolve) before next or error ?

答:
You could emit a value on error with catchError. This way your next callback will be executed when an error occurs.

const ERROR_TOKEN = 'my-error';

of(true).pipe(
  take(1),
  catchError(_ => {
    console.error(_);
    return of(ERROR_TOKEN); // emit some kind of error value
  })
)
.subscribe(async (value) =>  {
  // do on normal and error value
  await this.close();
  if (value !== ERROR_TOKEN) {
    // only do on normal values
    await Promise.all(...);
  }
});
```

<hr>

<p>Or write a custom operator that merges your async code into the stream.</p>

<pre class="lang-ts prettyprint-override"><code>function awaitOnNextAndError<T, R extends ObservableInput<any>>(
  asyncOnNextAndError: () => R,
  sideEffectOnError?: (e) => void
): MonoTypeOperatorFunction<T> {
  // only run your async code on 'subscribe' and ignore its output
  const pre = defer(() => asyncOnNextAndError()).pipe(ignoreElements())
  return (source: Observable<T>) => source.pipe(
    // do some side effect on errors immediately, e.g. logging
    tap({ error: sideEffectOnError }),
    // execute your async code before you continue with the value from the stream
    mergeMap(v => concat(pre, of(v))),
    // execute your async code on error
    catchError(e => pre)
  )
}

of(true).pipe(
  take(1),
  awaitOnNextAndError(() => this.close(), console.error)
)
.subscribe(async (_) => {
  await Promise.all(...);
});
</code>```

https://stackblitz.com/edit/rxjs-efscr8

Body:
I have the following code:

of(true)
  .pipe(
    take(1)
  )
  .subscribe(async (_) =>  {
    await this.close();
    await Promise.all(...);
  }, _ => {
    this.close();
    console.error(_);
  });

I want to only write once this.close(), however I can't use finalize since it has to be run before Promise.all. Is there something I could use to run a code (and wait for it to resolve) before next or error ?

Body:
You could emit a value on error with catchError. This way your next callback will be executed when an error occurs.

const ERROR_TOKEN = 'my-error';

of(true).pipe(
  take(1),
  catchError(_ => {
    console.error(_);
    return of(ERROR_TOKEN); // emit some kind of error value
  })
)
.subscribe(async (value) =>  {
  // do on normal and error value
  await this.close();
  if (value !== ERROR_TOKEN) {
    // only do on normal values
    await Promise.all(...);
  }
});

Or write a custom operator that merges your async code into the stream.

function awaitOnNextAndError<T, R extends ObservableInput<any>>(
  asyncOnNextAndError: () => R,
  sideEffectOnError?: (e) => void
): MonoTypeOperatorFunction<T> {
  // only run your async code on 'subscribe' and ignore its output
  const pre = defer(() => asyncOnNextAndError()).pipe(ignoreElements())
  return (source: Observable<T>) => source.pipe(
    // do some side effect on errors immediately, e.g. logging
    tap({ error: sideEffectOnError }),
    // execute your async code before you continue with the value from the stream
    mergeMap(v => concat(pre, of(v))),
    // execute your async code on error
    catchError(e => pre)
  )
}

of(true).pipe(
  take(1),
  awaitOnNextAndError(() => this.close(), console.error)
)
.subscribe(async (_) => {
  await Promise.all(...);
});

https://stackblitz.com/edit/rxjs-efscr8


问:
Navigating nested navigators in React Navigation 5.0
I am migrating my app from react navigation 4 to react navigation 5. The difference is that now one cannot jump from a deeply nested navigator to the root one, and I need to navigate up in the tree but I cannot find a way to do it.

The structure right now looks like this:

```<code>Root navigator
- Auth navigator
-- Login
-- Signup
-- ...
- App navigator
-- Home
--- ...
-- Settings
--- Settings page
--- Account page
</code>```

I need to be able to go from settings page to login but whatever i try i get the error

```<code>The action 'REPLACE' with payload '{"name":"AuthNav","params":{"screen":"Login"}}' was not handled by any navigator.
</code>```

I've tried to add a ref att the root navigator and use that but i get the same error.

Any help would be appreciated, wheather tips on best nesting practices or code samples that help me navigate.

答:
In this page https://reactnavigation.org/docs/nesting-navigators#navigating-to-a-screen-in-a-nested-navigator they show the way need for nested. So in your case should be something like that.</p>

```<code>navigation.replace('Auth', { screen: 'Login' });
</code>```

Body:
I am migrating my app from react navigation 4 to react navigation 5. The difference is that now one cannot jump from a deeply nested navigator to the root one, and I need to navigate up in the tree but I cannot find a way to do it.

The structure right now looks like this:

Root navigator
- Auth navigator
-- Login
-- Signup
-- ...
- App navigator
-- Home
--- ...
-- Settings
--- Settings page
--- Account page

I need to be able to go from settings page to login but whatever i try i get the error

The action 'REPLACE' with payload '{"name":"AuthNav","params":{"screen":"Login"}}' was not handled by any navigator.

I've tried to add a ref att the root navigator and use that but i get the same error.

Any help would be appreciated, wheather tips on best nesting practices or code samples that help me navigate.

Body:
In this page https://reactnavigation.org/docs/nesting-navigators#navigating-to-a-screen-in-a-nested-navigator they show the way need for nested. So in your case should be something like that.

navigation.replace('Auth', { screen: 'Login' });


问:
Functions in other files
How can I use functions that I have created before, in different python files and projects? for example functions that I have created in project A I want to use in project B.</p>

答:
You need to import like any other library you import in your python file. For example if you have a python script A.py and you are writing another python script B.py and you want to use some methods of A then you just need to import like this:

```<code>from A import *
</code>```

Will import all the methods of A.

you can import a specific method only like this:

from A import method1

Thanks hope it helps

Title: Functions in other files

Body:
You need to import like any other library you import in your python file. For example if you have a python script A.py and you are writing another python script B.py and you want to use some methods of A then you just need to import like this:

from A import *

Will import all the methods of A.

you can import a specific method only like this:

from A import method1

Thanks hope it helps