问:
PostAsync is not a member of HttpClient
I have used the following code before without any issues. Now I am getting :

```<code>PostAsync is not a member of HttpClient
</code>```

I have made sure that the relevant references are present, and that all Imports are in place (Imports System.Net.Http).

I am using .Net Framework 4.5, I have also tried 4.5.1 but to no avail.

```<code>Public Shared Async Function PostTrx(ByVal baseURI As String, ByVal code As String, ByVal account As String, ByVal serial As String, ByVal dest As String) As Task(Of String)
    Dim client As HttpClient = New HttpClient()

    Dim content = New FormUrlEncodedContent({New KeyValuePair(Of String, String)("response", code), New KeyValuePair(Of String, String)("account", account), New KeyValuePair(Of String, String)("sn", serial), New KeyValuePair(Of String, String)("mode", dest)})
    Dim response = Await client.PostAsync(baseURI, content)
    Dim stringContent = Await response.Content.ReadAsStringAsync()
    Return stringContent
End Function
</code>```

答:
I was able to solve this problem by appending "Http." before HttpClient, so your code would look like:

```<code>Public Shared Async Function PostTrx(ByVal baseURI As String, ByVal code As String, ByVal account As String, ByVal serial As String, ByVal dest As String) As Task(Of String)
    Dim client As Http.HttpClient = New Http.HttpClient()

    Dim content = New FormUrlEncodedContent({New KeyValuePair(Of String, String)("response", code), New KeyValuePair(Of String, String)("account", account), New KeyValuePair(Of String, String)("sn", serial), New KeyValuePair(Of String, String)("mode", dest)})
    Dim response = Await client.PostAsync(baseURI, content)
    Dim stringContent = Await response.Content.ReadAsStringAsync()
    Return stringContent
End Function
</code>```

Hope this helps!

Title: PostAsync is not a member of HttpClient

Body:
I have used the following code before without any issues. Now I am getting :

PostAsync is not a member of HttpClient

I have made sure that the relevant references are present, and that all Imports are in place (Imports System.Net.Http).

I am using .Net Framework 4.5, I have also tried 4.5.1 but to no avail.

Public Shared Async Function PostTrx(ByVal baseURI As String, ByVal code As String, ByVal account As String, ByVal serial As String, ByVal dest As String) As Task(Of String)
    Dim client As HttpClient = New HttpClient()

    Dim content = New FormUrlEncodedContent({New KeyValuePair(Of String, String)("response", code), New KeyValuePair(Of String, String)("account", account), New KeyValuePair(Of String, String)("sn", serial), New KeyValuePair(Of String, String)("mode", dest)})
    Dim response = Await client.PostAsync(baseURI, content)
    Dim stringContent = Await response.Content.ReadAsStringAsync()
    Return stringContent
End Function

Body:
I was able to solve this problem by appending "Http." before HttpClient, so your code would look like:

Public Shared Async Function PostTrx(ByVal baseURI As String, ByVal code As String, ByVal account As String, ByVal serial As String, ByVal dest As String) As Task(Of String)
    Dim client As Http.HttpClient = New Http.HttpClient()

    Dim content = New FormUrlEncodedContent({New KeyValuePair(Of String, String)("response", code), New KeyValuePair(Of String, String)("account", account), New KeyValuePair(Of String, String)("sn", serial), New KeyValuePair(Of String, String)("mode", dest)})
    Dim response = Await client.PostAsync(baseURI, content)
    Dim stringContent = Await response.Content.ReadAsStringAsync()
    Return stringContent
End Function

Hope this helps!


来源: stackexchange

问:
What is the difference between src/main/java and src in Springsource Tool
I'm learning to use Springsource Tool Suite (STS) and the Spring framework for development. I am trying out the Amazon AWS SDK for eclipse and decided to install it into STS. When I follow create a new AWS project, it puts the .java file under src instead of src/main/java and when I try to build that, it says

"There is no main"
or something like that.

But, when I move the AwsConsoleApp.java and the AwsCredentials.properties to src/main/java then (default package), I can run the file as a Java application.

My question is, what is the difference between src/main/java -> default package and src -> main. I've attached an image to clarify things:

答:
Answer:

Each Java project in Eclipse (and STS as well), has associated build path, where it is specified, which folders in the project contains java classes. Thus, the difference between src/ and src/main/java is that src/main/java is configured as a folder, containing java classes (or source folder in Eclipse terminology), while src/ folder just contains the source folder.

More information can be found in Eclipse Help.

I'm not sure what has caused that your Java classes end up in the wrong folder, but this means that they are not in the classpath of the project. So, when you run your application as Java application, it complains that it cannot find main() method (which is the default entry point for any Java application).

Everything comes into place, when you move your classes under the default package in src/main/java: Eclipse finds your Java classes and the main() method.

ContentLicense: CC BY-SA 3.0


问:
Categorize Traffic with Specific (non-UTM) Parameter as Email Traffic
I have traffic coming from Salesloft emails sent by sales reps that gets bounced off a subdomain and then has a sbrc parameter appended to the URL. I'd like to ensure that this traffic gets counted by Google Analytics as coming from Email, whereas it's currently falling under the "Direct" bucket. Ideally, users would also be appending utm parameters to their links, but this isn't happening consistently.

I tried creating a filter to search and replace the following regex (?:^|\?|&)(sbrc=[^&]*&?) with ?utm_medium=email&utm_source=salesloft in the Request URI. This changed the displayed URL when looking at my realtime traffic, but did not change how GA categorized the channel of the traffic (still direct).

I then tried editing the default channel groupings for Email to be the system categorized OR Landing Page URL contains "sbrc" and dragged Email to the first channel grouping at the top. This doesn't seem to have done anything at all.

How can I make GA recognize this custom parameter as being attributable to the Email channel?

答:
Ideally, users would also be appending utm parameters to their links,
  but this isn't happening consistently.

If they add their own and use a utm_medium other then utm_medium=Email, then it will not be defined as being in the default Email channel.

Filters are not retroactive.

Filters also run after data has already been processed by Google, to only change how it displays in the reports as it gets sent back into the GA reports.

A Search and Replace Filter applied to the RequestURI for

?utm_medium=email&utm_source=salesloft is not going to have the result you want.

It will change the appearance of the RequestURI in reports, not actually change how that traffic is attributed.

Changes to the default Channel grouping are not retroactive, it should have affect going forward though.

To see the changes in historical data for the Channels, you would do best to create a custom Channel grouping at the View level, this can then be applied retroactively to the historic data.

ContentLicense: CC BY-SA 4.0


问:
How to write types / or use use types for flatten object key in typescript?
Consider this scenario

interface abc {
  a: { b: string }
}

const test: abc = { a: { b: 'string'} }

test['a.b'] = 'new string' // error type a.b doesnt exists
```

https://codesandbox.io/s/delicate-night-9u5ps?file=/src/index.ts

How to solve this error? How can I utilize the already defined type and still use the flatten key?

PS: I cannot use it like test.a.b

答:
What we'd like to see Typescript do here is convert one set of keys to another. There are ways it can do that, for instance with Pick:

interface IA {
    a: number;
    b: number;
    c: boolean;
}

const x: Pick<IA, 'a' | 'b'> = {
    a: 1,
    b: 2,
    c: 3, // type error here as we're not picking that property
}
```

<p>In this example, Typescript is able to convert between the set of keys <code>['a', 'b', 'c']</code> and <code>['a', 'b']</code> based on selecting certain specified keys. We can also extend an object's keys:</p>

<pre class="lang-js prettyprint-override"><code>type TestExtentionType = IA & { d: number };

const y: TestExtentionType = {
    a: 1,
    b: 2,
    c: true,
    d: 4,
}
</code>```

What we'd need the type system to do though, in order to have typescript determine automatically the return types you're looking for, is to be able to go from key, key to 'key.key', or more generically, we need Typescript's type system to be able to concatenate string literals. At the point at which I'm writing this, it doesn't seem to be possible to have typescript do that.

The only option I can see to get close to what you need would be to define a specific type with your flattened key:

interface abc {
  a: { b: string }
}

interface abcFlattened {
    'a.b': string;
}

const flattenAbc = (x: abc): abcFlattened =>
    // do the flattening
```

Other options involve complete rewrites of what you're doing; if you want to get at that key as 'a.b' then I don't know as there's any other way of doing this.

Body:
Consider this scenario

interface abc {
  a: { b: string }
}

const test: abc = { a: { b: 'string'} }

test['a.b'] = 'new string' // error type a.b doesnt exists

https://codesandbox.io/s/delicate-night-9u5ps?file=/src/index.ts

How to solve this error? How can I utilize the already defined type and still use the flatten key?

PS: I cannot use it like test.a.b

Body:
What we'd like to see Typescript do here is convert one set of keys to another. There are ways it can do that, for instance with Pick:

interface IA {
    a: number;
    b: number;
    c: boolean;
}

const x: Pick<IA, 'a' | 'b'> = {
    a: 1,
    b: 2,
    c: 3, // type error here as we're not picking that property
}

In this example, Typescript is able to convert between the set of keys ['a', 'b', 'c'] and ['a', 'b'] based on selecting certain specified keys. We can also extend an object's keys:

type TestExtentionType = IA & { d: number };

const y: TestExtentionType = {
    a: 1,
    b: 2,
    c: true,
    d: 4,
}

What we'd need the type system to do though, in order to have typescript determine automatically the return types you're looking for, is to be able to go from key, key to 'key.key', or more generically, we need Typescript's type system to be able to concatenate string literals. At the point at which I'm writing this, it doesn't seem to be possible to have typescript do that.

The only option I can see to get close to what you need would be to define a specific type with your flattened key:

interface abc {
  a: { b: string }
}

interface abcFlattened {
    'a.b': string;
}

const flattenAbc = (x: abc): abcFlattened =>
    // do the flattening

Other options involve complete rewrites of what you're doing; if you want to get at that key as 'a.b' then I don't know as there's any other way of doing this.


问:
Pine script error when applying colors to volume bars
I'm trying to highlight volume bars that are 200% or greater than the previous bar but keep receiving the following error Error: Undeclared identifier volColor , however, it is declared so I don't understand the error.

```<code>study("200% Volume Highlight", shorttitle="Vol_200%")

v = volume
v0=volume[0]
v1=volume[1]

pct = (v0-v1)/v1*100

volColor = iff(pct>200, #DC143C)
plot(series=volume, style=histogram, color=volColor)
</code>```

答:
The volColor error is not the problem.

That's the last error the compiler encountered, because a previous statement did not compile.

Your full error is this:

```<code>Error: Cannot call `iff` with arguments (series__bool, literal__color); available overloads: iff(bool, integer, integer) => integer; iff(bool, float, float) => float; iff(bool, series, series) => series; iff(bool, series__color, series__color) => series__color; iff(bool, bool, bool) => bool; iff(bool, string, string) => string; iff(series__bool, integer, integer) => series__integer; iff(series__bool, float, float) => series; iff(series__bool, series, series) => series; iff(series__bool, series__color, series__color) => series__color; iff(series__bool, bool, bool) => series__bool; iff(float, integer, integer) => integer; iff(float, float, float) => float; iff(float, series, series) => series; iff(float, series__color, series__color) => series__color; iff(float, bool, bool) => bool; iff(float, string, string) => string; iff(series, integer, integer) => series__integer; iff(series, float, float) => series; iff(series, series, series) => series; iff(series, series__color, series__color) => series__color; iff(series, bool, bool) => series__bool;
Error: Undeclared identifier `volColor`
</code>```

The real problem is that iif takes 3 inputs instead of 2.

This will work.

```<code>//@version=4
study("200% Volume Highlight", shorttitle="Vol_200%")

signalThreshold = input(defval=200, title="Threshold (%)", type=input.float, minval=0)

v  = volume
v0 = volume[0] // volume[0] is the volume on the current bar. So it's the same as just using 'volume'. Or in your case, variable 'v'.
v1 = volume[1]

color volColor = na
color defaultColor = color.blue
color signalColor = #DC143C

pct = (v0-v1)/v1*100

volColor := iff(pct>signalThreshold, signalColor, defaultColor)

// This code will be faster. It does the same thing, but doesn't call a function.
//volColor := pct > signalThreshold ? signalColor : defaultColor

plot(series=volume, style=plot.style_histogram, color=volColor)
</code>```

Note: You must always use the //@version=x as the first line of your scripts.

Body:
I'm trying to highlight volume bars that are 200% or greater than the previous bar but keep receiving the following error Error: Undeclared identifier volColor , however, it is declared so I don't understand the error.

study("200% Volume Highlight", shorttitle="Vol_200%")

v = volume
v0=volume[0]
v1=volume[1]

pct = (v0-v1)/v1*100

volColor = iff(pct>200, #DC143C)
plot(series=volume, style=histogram, color=volColor)

Body:
The volColor error is not the problem.

That's the last error the compiler encountered, because a previous statement did not compile.

Your full error is this:

Error: Cannot call `iff` with arguments (series__bool, literal__color); available overloads: iff(bool, integer, integer) => integer; iff(bool, float, float) => float; iff(bool, series, series) => series; iff(bool, series__color, series__color) => series__color; iff(bool, bool, bool) => bool; iff(bool, string, string) => string; iff(series__bool, integer, integer) => series__integer; iff(series__bool, float, float) => series; iff(series__bool, series, series) => series; iff(series__bool, series__color, series__color) => series__color; iff(series__bool, bool, bool) => series__bool; iff(float, integer, integer) => integer; iff(float, float, float) => float; iff(float, series, series) => series; iff(float, series__color, series__color) => series__color; iff(float, bool, bool) => bool; iff(float, string, string) => string; iff(series, integer, integer) => series__integer; iff(series, float, float) => series; iff(series, series, series) => series; iff(series, series__color, series__color) => series__color; iff(series, bool, bool) => series__bool;
Error: Undeclared identifier `volColor`

The real problem is that iif takes 3 inputs instead of 2.

This will work.

//@version=4
study("200% Volume Highlight", shorttitle="Vol_200%")

signalThreshold = input(defval=200, title="Threshold (%)", type=input.float, minval=0)

v  = volume
v0 = volume[0] // volume[0] is the volume on the current bar. So it's the same as just using 'volume'. Or in your case, variable 'v'.
v1 = volume[1]

color volColor = na
color defaultColor = color.blue
color signalColor = #DC143C

pct = (v0-v1)/v1*100

volColor := iff(pct>signalThreshold, signalColor, defaultColor)

// This code will be faster. It does the same thing, but doesn't call a function.
//volColor := pct > signalThreshold ? signalColor : defaultColor

plot(series=volume, style=plot.style_histogram, color=volColor)

Note: You must always use the //@version=x as the first line of your scripts.


问:
Use the value of an ID to start a countdown
I have a circular progress bar where the user can select the time for a countdown, when the time is chosen the value is saved in an ID but I cannot get this countdown to start from that ID

```<code><script>
    $(document).ready(function() {
      $('.dial').knob({
        'min':0,
        'max':20,
        'width':250,
        'height':250,
        'displayInput':true,
        'fgColor':"#e74c3c",
        'pColor' :"FFA491",

        'release':function(v) {
            document.getElementById('v').innerHTML = v;
        },
   });
    });
  </script>
</code>```

The value is recorded at release and then converted to the ID "v"

I have uploaded the result on this page:https://juanmannnuel.neocities.org/

答:
In your case if you want it to countdown it would looks something like.

```<code>  $('.dial').knob({
    'min':0,
    'max':20,
    'width':250,
    'height':250,
    'displayInput':true,
    'fgColor':"#e74c3c",
    'pColor' :"FFA491",

    'release':function(v) {
        document.getElementById('v').innerHTML = v;
        $('.dial').val(v).trigger("blur");
    },
   });
</code>```

Could you give a try?

Here is an updated fiddle with countdown.
https://codepen.io/mitkodeli/pen/KKdjQyN

Body:
I have a circular progress bar where the user can select the time for a countdown, when the time is chosen the value is saved in an ID but I cannot get this countdown to start from that ID

The value is recorded at release and then converted to the ID "v"

I have uploaded the result on this page:https://juanmannnuel.neocities.org/

Body:
In your case if you want it to countdown it would looks something like.

  $('.dial').knob({
    'min':0,
    'max':20,
    'width':250,
    'height':250,
    'displayInput':true,
    'fgColor':"#e74c3c",
    'pColor' :"FFA491",

    'release':function(v) {
        document.getElementById('v').innerHTML = v;
        $('.dial').val(v).trigger("blur");
    },
   });

Could you give a try?

Here is an updated fiddle with countdown.
https://codepen.io/mitkodeli/pen/KKdjQyN


问:
Split a string with multiple delimiters in Ruby
Take for instance, I have a string like this:

```<code>options = "Cake or pie, ice cream, or pudding"
</code>```

I want to be able to split the string via or, ,, and , or.

The thing is, is that I have been able to do it, but only by parsing , and , or first, and then splitting each array item at or, flattening the resultant array afterwards as such:

```<code>options = options.split(/(?:\s?or\s)*([^,]+)(?:,\s*)*/).reject(&:empty?);
options.each_index {|index| options[index] = options[index].sub("?","").split(" or "); }
</code>```

The resultant array is as such: ["Cake", "pie", "ice cream", "pudding"]

Is there a more efficient (or easier) way to split my string on those three delimiters?

答:
First of all, your method could be simplified a bit with Array#flatten:

```<code>>> options.split(',').map{|x|x.split 'or'}.flatten.map(&:strip).reject(&:empty?)
=> ["Cake", "pie", "ice cream", "pudding"]
</code>```

I would prefer using a single regex:

```<code>>> options.split /\s*, or\s+|\s*,\s*|\s+or\s+/
=> ["Cake", "pie", "ice cream", "pudding"]
</code>```

You can use | in a regex to give alternatives, and putting , or first guarantees that it won’t produce an empty item. Capturing the whitespace with the regex is probably best for efficiency, since you don’t have to scan the array again.

As Zabba points out, you may still want to reject empty items, prompting this solution:

```<code>>> options.split(/,|\sor\s/).map(&:strip).reject(&:empty?)
=> ["Cake", "pie", "ice cream", "pudding"]
</code>```

Body:
Take for instance, I have a string like this:

options = "Cake or pie, ice cream, or pudding"

I want to be able to split the string via or, ,, and , or.

The thing is, is that I have been able to do it, but only by parsing , and , or first, and then splitting each array item at or, flattening the resultant array afterwards as such:

options = options.split(/(?:\s?or\s)*([^,]+)(?:,\s*)*/).reject(&:empty?);
options.each_index {|index| options[index] = options[index].sub("?","").split(" or "); }

The resultant array is as such: ["Cake", "pie", "ice cream", "pudding"]

Is there a more efficient (or easier) way to split my string on those three delimiters?

Body:
First of all, your method could be simplified a bit with Array#flatten:

>> options.split(',').map{|x|x.split 'or'}.flatten.map(&:strip).reject(&:empty?)
=> ["Cake", "pie", "ice cream", "pudding"]

I would prefer using a single regex:

>> options.split /\s*, or\s+|\s*,\s*|\s+or\s+/
=> ["Cake", "pie", "ice cream", "pudding"]

You can use | in a regex to give alternatives, and putting , or first guarantees that it won’t produce an empty item. Capturing the whitespace with the regex is probably best for efficiency, since you don’t have to scan the array again.

As Zabba points out, you may still want to reject empty items, prompting this solution:

>> options.split(/,|\sor\s/).map(&:strip).reject(&:empty?)
=> ["Cake", "pie", "ice cream", "pudding"]


问:
CodeWars Javascript Challenge: Are they the "same"?
The Kata: link

My solution:

```<code>function comp(array1, array2) {
    let result;
    if (Array.isArray(array1) && Array.isArray(array2) && array1.length && array2.length) {
        result = true;
        const squares = array2.map(e => Math.sqrt(e));
        squares.forEach((e) => {
            if (array1.includes(e)) return;
            result = false;
        });
    } else {
        result = false
    }
    return result;
}
</code>```

I don't want another solution. I want to figure out why mine doesn't pass in all of the tests. (Fails on two tests but I can't see which)

I suspect the test expects true if both arrays are []. But the Kata's description says otherwise:

If a or b are nil (or null or None), the problem doesn't make sense so return false.

Help would be appreciated.

Working Solution Based off of the answers:

```<code>function comp(array1, array2) {
    let result;
    if (Array.isArray(array1) && Array.isArray(array2)) {
        result = true;
        const sortedArray1 = array1.sort((a, b) => a - b);
        const squares = array2.map(e => Math.sqrt(e)).sort((a, b) => a - b);
        squares.forEach((e, i) => {
            if (sortedArray1[i] === e) return;
            result = false;
        });
    } else {
        result = false
    }
    return result;
}
</code>```

答:
if there is more then one number the same, but different count here and there, it will return true in your code, since it's includes in both arrays. you should sort it and iterate by index for compare, in order to make sure each item in the array used only once.

Here is what works for me:

```<code>function comp(array1, array2){
  if(!array1 || !array2) return false;
  array1 = array1.map(t => t**2).sort((a,b)=>a-b);
  array2 = array2.sort((a,b)=>a-b);

  for(let i=0;i<array1.length;i++){if(array1[i] !== array2[i])return false}
  return true;
}
</code>```

sure youcan understand the idea and just make some twick in your existing code

Body:
The Kata: link

My solution:

function comp(array1, array2) {
    let result;
    if (Array.isArray(array1) && Array.isArray(array2) && array1.length && array2.length) {
        result = true;
        const squares = array2.map(e => Math.sqrt(e));
        squares.forEach((e) => {
            if (array1.includes(e)) return;
            result = false;
        });
    } else {
        result = false
    }
    return result;
}

I don't want another solution. I want to figure out why mine doesn't pass in all of the tests. (Fails on two tests but I can't see which)

I suspect the test expects true if both arrays are []. But the Kata's description says otherwise:

If a or b are nil (or null or None), the problem doesn't make sense so return false.

Help would be appreciated.

Working Solution Based off of the answers:

function comp(array1, array2) {
    let result;
    if (Array.isArray(array1) && Array.isArray(array2)) {
        result = true;
        const sortedArray1 = array1.sort((a, b) => a - b);
        const squares = array2.map(e => Math.sqrt(e)).sort((a, b) => a - b);
        squares.forEach((e, i) => {
            if (sortedArray1[i] === e) return;
            result = false;
        });
    } else {
        result = false
    }
    return result;
}

Body:
if there is more then one number the same, but different count here and there, it will return true in your code, since it's includes in both arrays. you should sort it and iterate by index for compare, in order to make sure each item in the array used only once.

Here is what works for me:

function comp(array1, array2){
  if(!array1 || !array2) return false;
  array1 = array1.map(t => t**2).sort((a,b)=>a-b);
  array2 = array2.sort((a,b)=>a-b);

  for(let i=0;i<array1.length;i++){if(array1[i] !== array2[i])return false}
  return true;
}

sure youcan understand the idea and just make some twick in your existing code


问:
How does urllib.request differ from curl or httpx in behaviour? Getting a 401 in a request to the Google Container Registry
I am currently working on some code to interact with images on the Google Container Registry. I have working code both using plain curl and also httpx. I am trying to build a package without 3rd party dependencies. My curiosity is around a particular endpoint from which I get a successful response in curl and httpx but a 401 Unauthorized using urllib.request.

The bash script that demonstrates what I'm trying to achieve is the following. It retrieves an access token from the registry API, then uses that token to verify that the API indeed runs version 2 and tries to access a particular Docker image configuration. I'm afraid that in order to test this, you will need access to a private GCR image and a digest for one of the tags.

#!/usr/bin/env bash

set -eu

token=$(gcloud auth print-access-token)
image=...
digest=sha256:...

get_token() {
    curl -sSL \
        -G \
        --http1.1 \
        -H "Authorization: Bearer ${token}" \
        -H "Accept: application/vnd.docker.distribution.manifest.v2+json" \
        --data-urlencode "scope=repository:$1:pull" \
        --data-urlencode "service=gcr.io" \
        "https://gcr.io/v2/token" | jq -r '.token'
}

echo "---"
echo "Retrieving access token."
access_token=$(get_token ${image})

echo
echo "---"
echo "Testing version 2 capability with access token."
curl -sSL \
    --http1.1 \
    -o /dev/null \
    -w "%{http_code}" \
    -H "Authorization: Bearer ${access_token}" \
    -H "Accept: application/vnd.docker.distribution.manifest.v2+json" \
    https://gcr.io/v2/

echo
echo "---"
echo "Retrieving image configuration with access token."
curl -vL \
    --http1.1 \
    -o /dev/null \
    -w "%{http_code}" \
    -H "Authorization: Bearer ${access_token}" \
    -H "Accept: application/vnd.docker.distribution.manifest.v2+json" \
    "https://gcr.io/v2/${image}/blobs/${digest}"
```

I additionally created two Jupyter notebooks demonstrating my solutions in httpx and bare urllib.request. The httpx one works perfectly while somehow urllib fails on the image configuration request. I'm running out of ideas trying to spot the difference. If you run the notebook yourself, you will see that the called URL contains a token as a query parameter (is this a security issue?). When I open that link I can actually successfully download the data myself. Maybe urllib still passes along the Authorization header with the Bearer token making that last call fail with 401 Unauthorized?

Any insights are greatly appreciated.

答:
I did some investigation and I believe the difference is that the last call to "https://gcr.io/v2/${image}/blobs/${digest}" actually contains a redirect. Inspecting the curl and httpx calls showed me that both do not include the Authorization header in the second, redirected request, whereas in the way that I set up the urllib.request in the notebook, this header is always included. It's a bit odd that this leads to a 401 but now I know how to address it.

Edit: I can now confirm that by building a urllib.request.Request instance and unlike in the linked notebook, add the authorization header with the request's add_unredirected_header method, everything works as expected.

Body:
I am currently working on some code to interact with images on the Google Container Registry. I have working code both using plain curl and also httpx. I am trying to build a package without 3rd party dependencies. My curiosity is around a particular endpoint from which I get a successful response in curl and httpx but a 401 Unauthorized using urllib.request.

The bash script that demonstrates what I'm trying to achieve is the following. It retrieves an access token from the registry API, then uses that token to verify that the API indeed runs version 2 and tries to access a particular Docker image configuration. I'm afraid that in order to test this, you will need access to a private GCR image and a digest for one of the tags.

#!/usr/bin/env bash

set -eu

token=$(gcloud auth print-access-token)
image=...
digest=sha256:...

get_token() {
    curl -sSL \
        -G \
        --http1.1 \
        -H "Authorization: Bearer ${token}" \
        -H "Accept: application/vnd.docker.distribution.manifest.v2+json" \
        --data-urlencode "scope=repository:$1:pull" \
        --data-urlencode "service=gcr.io" \
        "https://gcr.io/v2/token" | jq -r '.token'
}

echo "---"
echo "Retrieving access token."
access_token=$(get_token ${image})

echo
echo "---"
echo "Testing version 2 capability with access token."
curl -sSL \
    --http1.1 \
    -o /dev/null \
    -w "%{http_code}" \
    -H "Authorization: Bearer ${access_token}" \
    -H "Accept: application/vnd.docker.distribution.manifest.v2+json" \
    https://gcr.io/v2/

echo
echo "---"
echo "Retrieving image configuration with access token."
curl -vL \
    --http1.1 \
    -o /dev/null \
    -w "%{http_code}" \
    -H "Authorization: Bearer ${access_token}" \
    -H "Accept: application/vnd.docker.distribution.manifest.v2+json" \
    "https://gcr.io/v2/${image}/blobs/${digest}"

I additionally created two Jupyter notebooks demonstrating my solutions in httpx and bare urllib.request. The httpx one works perfectly while somehow urllib fails on the image configuration request. I'm running out of ideas trying to spot the difference. If you run the notebook yourself, you will see that the called URL contains a token as a query parameter (is this a security issue?). When I open that link I can actually successfully download the data myself. Maybe urllib still passes along the Authorization header with the Bearer token making that last call fail with 401 Unauthorized?

Any insights are greatly appreciated.


问:
What's default password in docker container mysql-server when you don't set one?
I am try to run a mysql container and connect with mysql client then:

I've used following commands:

```<code>docker run --name=mysql -d mysql/mysql-server:latest
docker exec -it mysql mysql -uroot -p
</code>```

According to tutorial, the last command allow me configure database password but When I introduce the first password it fails...

The first password was root and I get an unusual error, then I try with admin, admin an even my linux user password but They don't work...

I would like to know what's the error?

答:
Following the documentation in: https://dev.mysql.com/doc/refman/8.0/en/docker-mysql-getting-started.html

You get the password with command:

```<code>docker logs mysql 2>&1 | grep GENERATED
</code>```

Example output:

```<code>GENERATED ROOT PASSWORD: Axegh3kAJyDLaRuBemecis&EShOs
</code>```

Body:
I am try to run a mysql container and connect with mysql client then:

I've used following commands:

docker run --name=mysql -d mysql/mysql-server:latest
docker exec -it mysql mysql -uroot -p

According to tutorial, the last command allow me configure database password but When I introduce the first password it fails...

The first password was root and I get an unusual error, then I try with admin, admin an even my linux user password but They don't work...

I would like to know what's the error?

Body:
Following the documentation in: https://dev.mysql.com/doc/refman/8.0/en/docker-mysql-getting-started.html

You get the password with command:

docker logs mysql 2>&1 | grep GENERATED

Example output:

GENERATED ROOT PASSWORD: Axegh3kAJyDLaRuBemecis&EShOs


问:
prop.test display the confidence interval in percentage terms instead of decimal in R?
I am wondering if there is a way to change the output settings of the prop.test function in R so that it displays the confidence interval already in percentage terms instead of a decimal? For example, I am trying to find the 95% confidence interval for the proportion of immigrants in the West with diabetes. Here is my code and the output: </p>

```<code>    sum(Immigrant_West$DIABETES)= 8, nrow(Immigrant_West)=144
prop.test(x=sum(Immigrant_West$DIABETES),n=nrow(Immigrant_West),conf.level = .95,correct=TRUE)

    > 1-sample proportions test with continuity correction
    data:  sum(Immigrant_West$DIABETES) out of nrow(Immigrant_West), null probability 0.5
   X-squared = 112, df = 1, p-value <2e-16
alternative hypothesis: true p is not equal to 0.5
95 percent confidence interval:
 0.02606 0.11017
sample estimates:
      p
0.05556
</code>```

<p>So is there a way to change the confidence interval output to show [2.606%, 11.017%] instead of as decimals? Thank you! </p>

答:
This will probably be simpler:</p>

```<code>prp.out <- prop.test(x=8, n=144, conf.level=.95, correct=TRUE)
prp.out$conf.int <- prp.out$conf.int * 100
prp.out
#
#   1-sample proportions test with continuity correction
#
# data:  8 out of 144, null probability 0.5
# X-squared = 112.01, df = 1, p-value < 2.2e-16
# alternative hypothesis: true p is not equal to 0.5
# 95 percent confidence interval:
#   2.606172 11.016593
# sample estimates:
#          p
# 0.05555556
</code>```

Body:
I am wondering if there is a way to change the output settings of the prop.test function in R so that it displays the confidence interval already in percentage terms instead of a decimal? For example, I am trying to find the 95% confidence interval for the proportion of immigrants in the West with diabetes. Here is my code and the output:

    sum(Immigrant_West$DIABETES)= 8, nrow(Immigrant_West)=144
prop.test(x=sum(Immigrant_West$DIABETES),n=nrow(Immigrant_West),conf.level = .95,correct=TRUE)

    > 1-sample proportions test with continuity correction
    data:  sum(Immigrant_West$DIABETES) out of nrow(Immigrant_West), null probability 0.5
   X-squared = 112, df = 1, p-value <2e-16
alternative hypothesis: true p is not equal to 0.5
95 percent confidence interval:
 0.02606 0.11017
sample estimates:
      p
0.05556

So is there a way to change the confidence interval output to show [2.606%, 11.017%] instead of as decimals? Thank you!

Body:
This will probably be simpler:

prp.out <- prop.test(x=8, n=144, conf.level=.95, correct=TRUE)
prp.out$conf.int <- prp.out$conf.int * 100
prp.out
#
#   1-sample proportions test with continuity correction
#
# data:  8 out of 144, null probability 0.5
# X-squared = 112.01, df = 1, p-value < 2.2e-16
# alternative hypothesis: true p is not equal to 0.5
# 95 percent confidence interval:
#   2.606172 11.016593
# sample estimates:
#          p
# 0.05555556


问:
Cannot find column name of a reactive dataframe in a shiny app
I have the shiny dashboard below in which I want to use a variable from my pickerInput() and create a plot. The issue is that my dataset is a reactive object and when I try to use table() I get object 'name' not found. If it would not be reactive it would work but it has to be in my real app.

```<code>library(shiny)
library(shinydashboard)
library(shinyWidgets)
library(ggplot2)
library(plotly)
ui <- dashboardPage(
    header = dashboardHeader(title = "My dashboard"),
    sidebar = dashboardSidebar(
        uiOutput("dbs")

    ),
    body = dashboardBody(
        plotlyOutput("fn")
    )
)

server <- function(input, output, session) {
    pe<-reactive({
        sts<-c("Rev","Rev")
        sID<-c("123","124")
        snID<-c("23","34")
        name<-c("s","d")
        data.frame(sts,sID,snID,name)
    })

    output$dbs<-renderUI({

            pickerInput("DB", "Select Database/s",
                        choices = c("name","snID"),
                        multiple = F,options = list(`actions-box` = TRUE),
                        selected = "name")

    })
    output$fn<-renderPlotly({

            #2.2 MAKING A TABLE for public.exists
        tbl<-table(pe()[[input$DB]], pe()$sts)
            ggplotly(
                ggplot(as.data.frame(tbl), aes(!!sym(input$DB), Freq, fill = sts))
            )

    })

}

shinyApp(ui, server)
</code>```

答:
The problem is your reactive df pe. In shiny logic, when the app runs renderPlotly your non-standard evaluation of !!sym(input$DB) is evaluated and it tries to get the object name, and then it searches for the dataframe, because ractive uses lazy loading in shiny. That means the reactive will only run when some other code requires it, but your !!sym(input$DB) has already run and I think there is a delay between finding non-standard evaluation required dataframe and run the reactive. So error happens.

You have two solutions, first, change your !! to string evaluation:

        ggplotly(
            ggplot(as.data.frame(tbl), aes_(input$DB, 'Freq', fill = 'sts'))
        )
```

<p>Second, since your <code>pe</code> is a fixed df, no need to use <code>reactive</code></p>

<pre class="lang-r prettyprint-override"><code>server <- function(input, output, session) {
    pe<-{
        sts<-c("Rev","Rev")
        sID<-c("123","124")
        snID<-c("23","34")
        name<-c("s","d")
        data.frame(sts,sID,snID,name)
    }

    output$dbs<-renderUI({

        pickerInput("DB", "Select Database/s",
                    choices = c("name","snID"),
                    multiple = F,options = list(`actions-box` = TRUE),
                    selected = "name")

    })
    output$fn<-renderPlotly({
        #2.2 MAKING A TABLE for public.exists
        tbl<-table(pe[[input$DB]], pe$sts)

        ggplotly(
            ggplot(as.data.frame(tbl), aes(!!sym(input$DB), Freq, fill = sts))
        )

    })

}
</code>```

Body:
I have the shiny dashboard below in which I want to use a variable from my pickerInput() and create a plot. The issue is that my dataset is a reactive object and when I try to use table() I get object 'name' not found. If it would not be reactive it would work but it has to be in my real app.

library(shiny)
library(shinydashboard)
library(shinyWidgets)
library(ggplot2)
library(plotly)
ui <- dashboardPage(
    header = dashboardHeader(title = "My dashboard"),
    sidebar = dashboardSidebar(
        uiOutput("dbs")

    ),
    body = dashboardBody(
        plotlyOutput("fn")
    )
)

server <- function(input, output, session) {
    pe<-reactive({
        sts<-c("Rev","Rev")
        sID<-c("123","124")
        snID<-c("23","34")
        name<-c("s","d")
        data.frame(sts,sID,snID,name)
    })

    output$dbs<-renderUI({

            pickerInput("DB", "Select Database/s",
                        choices = c("name","snID"),
                        multiple = F,options = list(`actions-box` = TRUE),
                        selected = "name")

    })
    output$fn<-renderPlotly({

            #2.2 MAKING A TABLE for public.exists
        tbl<-table(pe()[[input$DB]], pe()$sts)
            ggplotly(
                ggplot(as.data.frame(tbl), aes(!!sym(input$DB), Freq, fill = sts))
            )

    })

}

shinyApp(ui, server)

Body:
The problem is your reactive df pe. In shiny logic, when the app runs renderPlotly your non-standard evaluation of !!sym(input$DB) is evaluated and it tries to get the object name, and then it searches for the dataframe, because ractive uses lazy loading in shiny. That means the reactive will only run when some other code requires it, but your !!sym(input$DB) has already run and I think there is a delay between finding non-standard evaluation required dataframe and run the reactive. So error happens.

You have two solutions, first, change your !! to string evaluation:

        ggplotly(
            ggplot(as.data.frame(tbl), aes_(input$DB, 'Freq', fill = 'sts'))
        )

Second, since your pe is a fixed df, no need to use reactive

server <- function(input, output, session) {
    pe<-{
        sts<-c("Rev","Rev")
        sID<-c("123","124")
        snID<-c("23","34")
        name<-c("s","d")
        data.frame(sts,sID,snID,name)
    }

    output$dbs<-renderUI({

        pickerInput("DB", "Select Database/s",
                    choices = c("name","snID"),
                    multiple = F,options = list(`actions-box` = TRUE),
                    selected = "name")

    })
    output$fn<-renderPlotly({
        #2.2 MAKING A TABLE for public.exists
        tbl<-table(pe[[input$DB]], pe$sts)

        ggplotly(
            ggplot(as.data.frame(tbl), aes(!!sym(input$DB), Freq, fill = sts))
        )

    })

}


问:
How to sort data with descending order
I have String data like "1,2,3,4,5,1,2,1,5,6". I split with "," and count them one by one. After that I want to order them with descending. How can I do that with Swift.

I want to get a result like this. Key should be the above string number(converting to Int is fine). Value should be number of data. If some data have the same count number, smaller key should be first.

final result

["1" => 3, "2" => 2, "5" => 2, "3" => 1, "4" => 1, "6" => 1]
```

<p>or</p>

<pre class="lang-none prettyprint-override"><code>[1 => 3, 2 => 2, 5 => 2, 3 => 1, 4 => 1, 6 => 1]
</code>```

答:
First you would need to separate your components by the comma, map the components to integers, reduce the elements counting their frequency and then do a custom sort on the result:</p>

```<code>let string = "1,2,3,4,5,1,2,1,5,6"
let results = string.components(separatedBy: ",")
    .compactMap(Int.init)
    .reduce(into: [:]) { $0[$1, default: 0] += 1 }
    .sorted(by: { $1.value < $0.value ? true :
                  $0.key < $1.key })
print(results)
// "[(key: 1, value: 3), (key: 2, value: 2), (key: 5, value: 2), (key: 3, value: 1), (key: 4, value: 1), (key: 6, value: 1)]\n"
</code>```

Title: How to sort data with descending order

Body:
I have String data like "1,2,3,4,5,1,2,1,5,6". I split with "," and count them one by one. After that I want to order them with descending. How can I do that with Swift.

I want to get a result like this. Key should be the above string number(converting to Int is fine). Value should be number of data. If some data have the same count number, smaller key should be first.

final result

["1" => 3, "2" => 2, "5" => 2, "3" => 1, "4" => 1, "6" => 1]

or

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

Body:
First you would need to separate your components by the comma, map the components to integers, reduce the elements counting their frequency and then do a custom sort on the result:

let string = "1,2,3,4,5,1,2,1,5,6"
let results = string.components(separatedBy: ",")
    .compactMap(Int.init)
    .reduce(into: [:]) { $0[$1, default: 0] += 1 }
    .sorted(by: { $1.value < $0.value ? true :
                  $0.key < $1.key })
print(results)
// "[(key: 1, value: 3), (key: 2, value: 2), (key: 5, value: 2), (key: 3, value: 1), (key: 4, value: 1), (key: 6, value: 1)]\n"


问:
Python Requests Not Respecting verify=False
Python requests is giving me an ssl handshake failure even when verify=False (I know that not using SSL is inadvisable). Requests works as expected for me with other sites that have valid certs. I'm using 2.7.

```<code>from lxml import html
import requests
import csv

outputfile  = open('/Users/jim/Documents/FabFoundationURLs.csv', "wb")
writer = csv.writer(outputfile, delimiter=';', quotechar='"', quoting=csv.QUOTE_MINIMAL)

source = 'https://www.fablabs.io/labs'

page = requests.get(source, verify=False)
tree = html.fromstring(page.content)

#This will create a list of links:
links = tree.xpath('/html/body/div[@id="main"]/div[2]/div[1]/div[2]//span/a/text()')

targets = links

print links
</code>```

Here's the exception:

```<code>SSLError: [SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] sslv3 alert handshake failure (_ssl.c:590)
</code>```

答:
SSL handshake error can be a protocol error instead of a cert verification error.  In this case it happens before the cert verification: you can't establish the SSL connection and verify=False won't help.  Protocol error generally refers to an unknown/unistalled SSL cipher version.

You can try to reinstall extra ciphers in requests (worked for me on Ubuntu 18.04, but not on OS X)

```<code>pip install requests[security]
</code>```

Body:
Python requests is giving me an ssl handshake failure even when verify=False (I know that not using SSL is inadvisable). Requests works as expected for me with other sites that have valid certs. I'm using 2.7.

from lxml import html
import requests
import csv

outputfile  = open('/Users/jim/Documents/FabFoundationURLs.csv', "wb")
writer = csv.writer(outputfile, delimiter=';', quotechar='"', quoting=csv.QUOTE_MINIMAL)

source = 'https://www.fablabs.io/labs'

page = requests.get(source, verify=False)
tree = html.fromstring(page.content)

#This will create a list of links:
links = tree.xpath('/html/body/div[@id="main"]/div[2]/div[1]/div[2]//span/a/text()')

targets = links

print links

Here's the exception:

SSLError: [SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] sslv3 alert handshake failure (_ssl.c:590)

Body:
SSL handshake error can be a protocol error instead of a cert verification error.  In this case it happens before the cert verification: you can't establish the SSL connection and verify=False won't help.  Protocol error generally refers to an unknown/unistalled SSL cipher version.

You can try to reinstall extra ciphers in requests (worked for me on Ubuntu 18.04, but not on OS X)

pip install requests[security]


问:
Do static libraries, which depend on other slibs need the actual 'code' from them to work?
Sorry about the vague question title, I just want to ascertain some things.

Static libraries don't link with other static libraries, right?

So when I write a slib: A, that uses functionality of another: B, all I have to provide are the headers of B to A, and only those, even if A actually uses functionality from B?
Yes?

As long as exe: X, which uses A,has B.lib specified as linker input?

So that at link time, the linker takes A.lib, which basically only knows that a function of B was called somewhere inside its code, and somehow fills that information from B.lib, making A.lib 'whole', before X gets linked with the now working parts of it?

The motivation behind these questions is to get rid of some linker warnings 4006 and discarded double definitions, and I think that should do the trick, if this is actually a valid way of doing it.

答: Can't really add the Neils answer except to say that a static library is really just a whole bunch of object (.o) files collected into a single indexed file. So what works for a .o file will work for a static library.</p>


问:
Insert line break using SKLabelNode in SpriteKit
Simple question on how to insert a line break using SKLabelNode class in SpriteKit. I have the following code but it does not work -

```<code> SKLabelNode *nerdText = [SKLabelNode labelNodeWithFontNamed:@"Times"];
    NSString *st1 = @"Test break";
    NSString *st2 = @"I want it to break";
    NSString *test = [NSString stringWithFormat:@"%@,\r%@",st1,st2]; //Even tried \n
    nerdText.text = test;
    nerdText.fontSize = 11;
    nerdText.fontColor = [SKColor colorWithRed:0.15 green:0.15 blue:0.3 alpha:1.0];
    nerdText.position = CGPointMake(150.0, 250.0);
    [self addChild:nerdText];
</code>```

Please help me out!

答:
In the scene editor, change the SKLabelNode's text to attributed in the attributes inspector in the right pane, as shown below.

Doing so will give you very much freedom to customize the text that is displayed without having to create multiple SKLabelNode instances or a UIImage. For instance, you can create a paragraph as shown below.

For programmatic interaction, use the attributedString property of the label node to add custom attributes.

Body:
Simple question on how to insert a line break using SKLabelNode class in SpriteKit. I have the following code but it does not work -

 SKLabelNode *nerdText = [SKLabelNode labelNodeWithFontNamed:@"Times"];
    NSString *st1 = @"Test break";
    NSString *st2 = @"I want it to break";
    NSString *test = [NSString stringWithFormat:@"%@,\r%@",st1,st2]; //Even tried \n
    nerdText.text = test;
    nerdText.fontSize = 11;
    nerdText.fontColor = [SKColor colorWithRed:0.15 green:0.15 blue:0.3 alpha:1.0];
    nerdText.position = CGPointMake(150.0, 250.0);
    [self addChild:nerdText];

Please help me out!


问:
What's the procedure to re-download locally deleted files using SFTP Inbound
As per this doc couldn't find the right process to re-downloading a locally removed file from remote SFTP.

The requirement is, to delete local file which already been fetched from remote SFTP and use sftp-inbound-adapter (DSL configuration) to re-fetch that same file when required. In this implementation, MetadataStore haven't been persisted into any external system like PropertiesPersistingMetadataStore or Redis Metadata Store. So as per doc, MetadataStore stored in In-Memory.

Couldn't find any way to remove meta data of that remote file from MetadataStore to re-fetch the locally deleted file using file_name. And don't have any clue, how should this removeRemoteFileMetadata() callback needs to be implemented (according to this doc).

Configuration class contain followings:

```<code>    @Bean
    public IntegrationFlow fileFlow() {
        SftpInboundChannelAdapterSpec spec = Sftp.inboundAdapter(sftpConfig.getSftpSessionFactory())
                .preserveTimestamp(true)
                .patternFilter(Constants.FILE_NAME_CONVENTION)
                .remoteDirectory(sftpConfig.getSourceLocation())
                .autoCreateLocalDirectory(true)
                .deleteRemoteFiles(false)
                .localDirectory(new File(sftpConfig.getDestinationLocation()));

        return IntegrationFlows
                .from(spec, e -> e.id("sftpInboundAdapter").autoStartup(false)
                        .poller(Pollers.fixedDelay(5000).get()))
                .channel(MessageChannels.direct().get())
                .handle(message -> {
                    log.info("Fetching File : " + message.getHeaders().get("file_name").toString());
                })
                .get();
    }
</code>```

答:
Use a ChainFileListFilter, with a SftpSimplePatternFileListFilter and a SftpPersistentAcceptOnceFileListFilter.

Use a SimpleMetadataStore to store the state in memory (or some other MetadataStore).

new SftpPersistentAcceptOnceFileListFilter(store, "somePrefix");

Then, store.remove(key) where key is somePrefix + fileName.

Use a similar filter in the localFilter with FileSystemPersistentAcceptOnceFileListFilter.

Body:
As per this doc couldn't find the right process to re-downloading a locally removed file from remote SFTP.

The requirement is, to delete local file which already been fetched from remote SFTP and use sftp-inbound-adapter (DSL configuration) to re-fetch that same file when required. In this implementation, MetadataStore haven't been persisted into any external system like PropertiesPersistingMetadataStore or Redis Metadata Store. So as per doc, MetadataStore stored in In-Memory.

Couldn't find any way to remove meta data of that remote file from MetadataStore to re-fetch the locally deleted file using file_name. And don't have any clue, how should this removeRemoteFileMetadata() callback needs to be implemented (according to this doc).

Configuration class contain followings:

    @Bean
    public IntegrationFlow fileFlow() {
        SftpInboundChannelAdapterSpec spec = Sftp.inboundAdapter(sftpConfig.getSftpSessionFactory())
                .preserveTimestamp(true)
                .patternFilter(Constants.FILE_NAME_CONVENTION)
                .remoteDirectory(sftpConfig.getSourceLocation())
                .autoCreateLocalDirectory(true)
                .deleteRemoteFiles(false)
                .localDirectory(new File(sftpConfig.getDestinationLocation()));

        return IntegrationFlows
                .from(spec, e -> e.id("sftpInboundAdapter").autoStartup(false)
                        .poller(Pollers.fixedDelay(5000).get()))
                .channel(MessageChannels.direct().get())
                .handle(message -> {
                    log.info("Fetching File : " + message.getHeaders().get("file_name").toString());
                })
                .get();
    }


问:
ASP.NET Core -- Upload .json file and convert to List<T>
So I managed to export a .json file by serializing my List. Now i'm trying to upload a .json file and desearialize it and add it back to my list. The idea is to be able to click on import, choose a file, then convert it so i can add it to my list. Here is the function in my controller that doesn't work:

** Update **
So now I managed to convert the .json file back to my List but if the list is empty and I want to add the new list to it, then I get this error:

```<code>[HttpPost]
    public async Task<IActionResult> Import(IFormFile file)
    {
        if (file == null || file.Length == 0)
            return Content("file not selected");

        var path = Path.Combine(Directory.GetCurrentDirectory(), "Import", file.FileName);

        using (var stream = new FileStream(path, FileMode.Create))
        {
            await file.CopyToAsync(stream);
        }

        String jsonImport = System.IO.File.ReadAllText(path);
        Console.WriteLine(jsonImport);
        List<Booking> bookings;
        _cache.TryGetValue("key", out bookings);
        List<Booking> newList = new List<Booking>();

        newList = JsonConvert.DeserializeObject<List<Booking>>(jsonImport);

        foreach (var item in newList)
        {
            bookings.Add(item);
            _cache.Set<List<Booking>>("key", bookings);
        }
        return RedirectToAction("Index");
    }
</code>```

So I want to choose a file (user should only be allowed to upload .json format nothing else but idk how to do that yet) and then from that .json I want to add every entry to my bookings List.
Here is the Booking Model:

```<code>public class Booking
{
    [Required]
    [Display(Name = "Ladestand")]
    [Range(0, 100)]
    public double chargeState { get; set; }

    [Required]
    [Display(Name = "Benötigte Fahrstrecke")]
    [Range(1, 1000)]
    public double distance { get; set; }

    [Required]
    [Display(Name = "Beginn")]

    public DateTime startTime { get; set; }

    [Required]
    [Display(Name = "Ende")]

    public DateTime endTime { get; set; }

    [Required]
    [Display(Name = "Anschlusstyp")]
    [EnumDataType(typeof(ConnectorType))]
    public ConnectorType connectorType { get; set; }
}
</code>```

And here is the export function:

```<code>public ActionResult Export()
    {
        string fileName = "BookingsExport.json";
        List<Booking> bookingsList;
        _cache.TryGetValue("key", out bookingsList);

        string json = JsonConvert.SerializeObject(bookingsList);
        FileInfo file = new FileInfo(fileName);
        using (StreamWriter writer = file.CreateText())
        {
            writer.Write(json);
        }

        byte[] fileBytes = System.IO.File.ReadAllBytes(fileName);

        return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Json, fileName);
    }
</code>```

答:
You need to initialize the list, before you are trying to add new items to it.</p>

```<code>var bookings = new List<Booking>();
</code>```

Body:
So I managed to export a .json file by serializing my List. Now i'm trying to upload a .json file and desearialize it and add it back to my list. The idea is to be able to click on import, choose a file, then convert it so i can add it to my list. Here is the function in my controller that doesn't work:

** Update **
So now I managed to convert the .json file back to my List but if the list is empty and I want to add the new list to it, then I get this error:

[HttpPost]
    public async Task<IActionResult> Import(IFormFile file)
    {
        if (file == null || file.Length == 0)
            return Content("file not selected");

        var path = Path.Combine(Directory.GetCurrentDirectory(), "Import", file.FileName);

        using (var stream = new FileStream(path, FileMode.Create))
        {
            await file.CopyToAsync(stream);
        }

        String jsonImport = System.IO.File.ReadAllText(path);
        Console.WriteLine(jsonImport);
        List<Booking> bookings;
        _cache.TryGetValue("key", out bookings);
        List<Booking> newList = new List<Booking>();

        newList = JsonConvert.DeserializeObject<List<Booking>>(jsonImport);

        foreach (var item in newList)
        {
            bookings.Add(item);
            _cache.Set<List<Booking>>("key", bookings);
        }
        return RedirectToAction("Index");
    }

So I want to choose a file (user should only be allowed to upload .json format nothing else but idk how to do that yet) and then from that .json I want to add every entry to my bookings List.
Here is the Booking Model:

public class Booking
{
    [Required]
    [Display(Name = "Ladestand")]
    [Range(0, 100)]
    public double chargeState { get; set; }

    [Required]
    [Display(Name = "Benötigte Fahrstrecke")]
    [Range(1, 1000)]
    public double distance { get; set; }

    [Required]
    [Display(Name = "Beginn")]

    public DateTime startTime { get; set; }

    [Required]
    [Display(Name = "Ende")]

    public DateTime endTime { get; set; }

    [Required]
    [Display(Name = "Anschlusstyp")]
    [EnumDataType(typeof(ConnectorType))]
    public ConnectorType connectorType { get; set; }
}

And here is the export function:

public ActionResult Export()
    {
        string fileName = "BookingsExport.json";
        List<Booking> bookingsList;
        _cache.TryGetValue("key", out bookingsList);

        string json = JsonConvert.SerializeObject(bookingsList);
        FileInfo file = new FileInfo(fileName);
        using (StreamWriter writer = file.CreateText())
        {
            writer.Write(json);
        }

        byte[] fileBytes = System.IO.File.ReadAllBytes(fileName);

        return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Json, fileName);
    }

Body:
You need to initialize the list, before you are trying to add new items to it.

var bookings = new List<Booking>();


问:
Manually specifying styleColorBar limits in DT
I am trying to create side-by-side data tables in R using the DT package, and have cell backgrounds shaded using the styleColorBar function shown at the bottom of this page. However, I want the size of the bar to be proportional to an absolute value, not just values in the table. For example, if I made two tables out of the data below

```<code>data_1 <- data.frame("Team" = c("Alex", "Beth", "Charlie", "Diane"),
   "Spending_Q1" = c(1000, 500, 1500, 1000))

data_2 <- data.frame("Team" = c("Alex", "Beth", "Charlie", "Diane"),
   "Spending_Q2" = c(3000, 500, 500, 500))
</code>```

I would want the cell showing 3000 to have the longest background bar, and the one with 1500 to have a bar half as long.

Is this possible, or are the bars always proportional to the largest value only in the same data table?

答:
You can specify it in absolute values like this:

```<code>library(DT)
data_1 <- data.frame("Team" = c("Alex", "Beth", "Charlie", "Diane"),
                     "Spending_Q1" = c(1000, 500, 1500, 1000))

data_2 <- data.frame("Team" = c("Alex", "Beth", "Charlie", "Diane"),
                     "Spending_Q2" = c(3000, 500, 500, 500))

datatable(data_1) %>% formatStyle(names(data_1),
                              background = styleColorBar(1:3000, 'lightblue'),
                              backgroundSize = '98% 88%',
                              backgroundRepeat = 'no-repeat',
                              backgroundPosition = 'center')
datatable(data_2) %>% formatStyle(names(data_2),
                                  background = styleColorBar(1:3000, 'lightblue'),
                                  backgroundSize = '98% 88%',
                                  backgroundRepeat = 'no-repeat',
                                  backgroundPosition = 'center')
</code>```

Is this what you were looking for?

Body:
I am trying to create side-by-side data tables in R using the DT package, and have cell backgrounds shaded using the styleColorBar function shown at the bottom of this page. However, I want the size of the bar to be proportional to an absolute value, not just values in the table. For example, if I made two tables out of the data below

data_1 <- data.frame("Team" = c("Alex", "Beth", "Charlie", "Diane"),
   "Spending_Q1" = c(1000, 500, 1500, 1000))

data_2 <- data.frame("Team" = c("Alex", "Beth", "Charlie", "Diane"),
   "Spending_Q2" = c(3000, 500, 500, 500))

I would want the cell showing 3000 to have the longest background bar, and the one with 1500 to have a bar half as long.

Is this possible, or are the bars always proportional to the largest value only in the same data table?

Body:
You can specify it in absolute values like this:

library(DT)
data_1 <- data.frame("Team" = c("Alex", "Beth", "Charlie", "Diane"),
                     "Spending_Q1" = c(1000, 500, 1500, 1000))

data_2 <- data.frame("Team" = c("Alex", "Beth", "Charlie", "Diane"),
                     "Spending_Q2" = c(3000, 500, 500, 500))

datatable(data_1) %>% formatStyle(names(data_1),
                              background = styleColorBar(1:3000, 'lightblue'),
                              backgroundSize = '98% 88%',
                              backgroundRepeat = 'no-repeat',
                              backgroundPosition = 'center')
datatable(data_2) %>% formatStyle(names(data_2),
                                  background = styleColorBar(1:3000, 'lightblue'),
                                  backgroundSize = '98% 88%',
                                  backgroundRepeat = 'no-repeat',
                                  backgroundPosition = 'center')

Is this what you were looking for?


问:
Dom-If not refreshing after variable changes
I have this problem where, in a page from the polymer starter kit I set a variable to true, but a Dom-if created in the main app isn't re-rendered, though if I display the variable in plain, it changes.

Here's the code of the dom-if:

```<code><app-location route="{{route}}" url-space-regex="^[[rootPath]]">
   </app-location>

   <app-route route="{{route}}" pattern="[[rootPath]]:page" data="{{routeData}}" tail="{{subroute}}">
   </app-route>

   <app-drawer-layout fullbleed="" narrow="{{narrow}}">
     <!-- Drawer content -->
     <template is=dom-if if='{{isLoggedIn}}'>
     <app-drawer id="drawer" slot="drawer" swipe-open="[[narrow]]">
       <app-toolbar class="menu">Menu</app-toolbar>
       <iron-selector selected="[[page]]" attr-for-selected="name" class="drawer-list" role="navigation">
         <a class="textMenu" name="view1" href="[[rootPath]]view1">3Deseos</a>
         <a class="textMenu" name="login" href="[[rootPath]]login">Regalar</a>
         <a class="textMenu" name="view3" href="[[rootPath]]view3">Mi Perfil</a>
       </iron-selector>
       <img class="fondoDeTres" src="./images/background.png">
     </app-drawer>
     </template>

     <template is=dom-if if='{{!isLoggedIn}}'>
     <app-drawer id="drawer" slot="drawer" swipe-open="[[narrow]]">
       <app-toolbar class="menu">Menu</app-toolbar>
       <iron-selector selected="[[page]]" attr-for-selected="name" class="drawer-list" role="navigation">
         <a class="textMenu" name="view1" href="[[rootPath]]view1">3Deseos</a>
         <a class="textMenu" name="login" href="[[rootPath]]login">Ingresar</a>
       </iron-selector>
       <img class="fondoDeTres" src="./images/background.png">
     </app-drawer>
     </template>
</code>```

and here it's the code of the boolean (I even tried adding an observer, but it doesn't work):

```<code>   isLoggedIn: {
     type: Boolean,
     value: false,
     notify: true,
     observer: '_loginStatusChanged'
   }
</code>```

here it's the observer:

```<code>   _loginStatusChanged(status){
     this.isLoggedIn=status;
     console.log("Cambio el Login a "+status);
   }
</code>```

and the script that modifies it:

```<code>  submit(){
      console.log("requestSent");
      var xhr = new XMLHttpRequest();
      var url = "http://localhost:3000/api/login";
      var request = {
        username : this.username,
        password : this.password
      }
      var that=this;
      xhr.open("POST", url, true);
      xhr.setRequestHeader("Content-Type", "application/json");
      xhr.onreadystatechange = function () {
          if (xhr.readyState === 4 && xhr.status === 200) {
              var reply = JSON.parse(xhr.responseText);
              console.log(reply);
              that.set('isLoggedIn', reply);
              console.log(that.isLoggedIn);
          }
      };
      var data = JSON.stringify({request});
      xhr.send(data);
  }
</code>```

Any tips? Thanks in advance!

答: I solve this with iron-localstorage. I don't know if it's the best way, but ITS WORKING! :D</p>

Body:
I have this problem where, in a page from the polymer starter kit I set a variable to true, but a Dom-if created in the main app isn't re-rendered, though if I display the variable in plain, it changes.

Here's the code of the dom-if:

<app-location route="{{route}}" url-space-regex="^[[rootPath]]">
   </app-location>

   <app-route route="{{route}}" pattern="[[rootPath]]:page" data="{{routeData}}" tail="{{subroute}}">
   </app-route>

   <app-drawer-layout fullbleed="" narrow="{{narrow}}">

     <template is=dom-if if='{{isLoggedIn}}'>
     <app-drawer id="drawer" slot="drawer" swipe-open="[[narrow]]">
       <app-toolbar class="menu">Menu</app-toolbar>
       <iron-selector selected="[[page]]" attr-for-selected="name" class="drawer-list" role="navigation">
         3Deseos
         Regalar
         Mi Perfil
       </iron-selector>

     </app-drawer>
     </template>

     <template is=dom-if if='{{!isLoggedIn}}'>
     <app-drawer id="drawer" slot="drawer" swipe-open="[[narrow]]">
       <app-toolbar class="menu">Menu</app-toolbar>
       <iron-selector selected="[[page]]" attr-for-selected="name" class="drawer-list" role="navigation">
         3Deseos
         Ingresar
       </iron-selector>

     </app-drawer>
     </template>

and here it's the code of the boolean (I even tried adding an observer, but it doesn't work):

   isLoggedIn: {
     type: Boolean,
     value: false,
     notify: true,
     observer: '_loginStatusChanged'
   }

here it's the observer:

   _loginStatusChanged(status){
     this.isLoggedIn=status;
     console.log("Cambio el Login a "+status);
   }

and the script that modifies it:

  submit(){
      console.log("requestSent");
      var xhr = new XMLHttpRequest();
      var url = "http://localhost:3000/api/login";
      var request = {
        username : this.username,
        password : this.password
      }
      var that=this;
      xhr.open("POST", url, true);
      xhr.setRequestHeader("Content-Type", "application/json");
      xhr.onreadystatechange = function () {
          if (xhr.readyState === 4 && xhr.status === 200) {
              var reply = JSON.parse(xhr.responseText);
              console.log(reply);
              that.set('isLoggedIn', reply);
              console.log(that.isLoggedIn);
          }
      };
      var data = JSON.stringify({request});
      xhr.send(data);
  }

Any tips? Thanks in advance!


问:
Rails : rake db:create mysql error
I am trying to setup a mysql database, but I am getting this error message:

```
rake db:create
(in /Users/yookd/Desktop/rails/blog)
WARNING: Global access to Rake DSL methods is deprecated.  Please Include
    ...  Rake::DSL into classes and modules which use the Rake DSL methods.
WARNING: DSL method Blog::Application#task called at /Library/Ruby/Gems/1.8/gems/railties-3.0.7/lib/rails/application.rb:215:in `initialize_tasks'
db/test.sqlite3 already exists
rake aborted!
uninitialized constant Mysql2

Tasks: TOP => db:create
(See full trace by running task with --trace)
```

Any assistance with this?
(following directions on http://guides.rubyonrails.org/getting_started.html)

EDIT:::

How can I use mysql as my database as opposed to sqlite?  In the gemfile, it explicitly states: gem 'sqlite'... do I need to replace that line with something like gem mysql?

答:
For your edit, yes, to use mysql you have to first have mysql installed and configured on your system. Then in your gemfile, remove 'gem sqlite' and replace it with:

```<code>gem 'mysql'
</code>```

Then, in your config/database.yml, set it up something similar to:

```<code>development:
  adapter: mysql
  database: name_of_database
  pool: 5
  timeout: 5000
  host: localhost
  password: mysql_password
</code>```

Do the same for test and production.

Title: Rails : rake db:create mysql error

Body:
I am trying to setup a mysql database, but I am getting this error message:

rake db:create
(in /Users/yookd/Desktop/rails/blog)
WARNING: Global access to Rake DSL methods is deprecated.  Please Include
    ...  Rake::DSL into classes and modules which use the Rake DSL methods.
WARNING: DSL method Blog::Application#task called at /Library/Ruby/Gems/1.8/gems/railties-3.0.7/lib/rails/application.rb:215:in `initialize_tasks'
db/test.sqlite3 already exists
rake aborted!
uninitialized constant Mysql2

Tasks: TOP => db:create
(See full trace by running task with --trace)

Any assistance with this?
(following directions on http://guides.rubyonrails.org/getting_started.html)

EDIT:::

How can I use mysql as my database as opposed to sqlite?  In the gemfile, it explicitly states: gem 'sqlite'... do I need to replace that line with something like gem mysql?

Body:
For your edit, yes, to use mysql you have to first have mysql installed and configured on your system. Then in your gemfile, remove 'gem sqlite' and replace it with:

gem 'mysql'

Then, in your config/database.yml, set it up something similar to:

development:
  adapter: mysql
  database: name_of_database
  pool: 5
  timeout: 5000
  host: localhost
  password: mysql_password

Do the same for test and production.


问:
How to make responsive React bootstrap cards that are vertically aligned?
I have a card component:

   <Card className="m-5 border-0 shadow" style={styles.card}>
      <Row>
        <Col>
          <Card.Img src={props.image} style={styles.cardImage}/>
        </Col>
        <Col>
          <Card.Body>
            <Card.Title as="h1">
              {props.title}
            </Card.Title>
            <Card.Text as="h4" style={styles.cardText}>
              {props.description}
            </Card.Text>
          </Card.Body>
          {
            props.link &&
            <Button style={styles.button} href={props.url}>Read More</Button>
          }
        </Col>
      </Row>
    </Card>```
</div>
</div>
</p>

<p>The card is wrapped in a fluid <code><Container></code> and <code><CardGroup></code> component from <code>react-bootstrap</code>:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code><Container fluid className="text-center">
  <CardGroup className="m-5 d-block">
    <Card />
  </CardGroup>
</Container></code>```

On desktop device it looks like this:

But it looks like this on mobile device:

Here are the styles:

const styles = {
  card: {
    backgroundColor: '#B7E0F2',
    borderRadius: 55,
    padding: '3rem'
  },
  cardImage: {
    height: '100%',
    objectFit: 'cover',
    borderRadius: 55
  }
};```

Does anyone know how to fix this? Thanks.

答:
Try this. For the <Row> component class with className row in css file assign property as follows:

```<code>.row {
 display: flex,
 flex-wrap:wrap
 }
</code>```

Body:
I have a card component:

   <Card className="m-5 border-0 shadow" style={styles.card}>
      <Row>
        <Col>
          <Card.Img src={props.image} style={styles.cardImage}/>
        </Col>
        <Col>
          <Card.Body>
            <Card.Title as="h1">
              {props.title}
            </Card.Title>
            <Card.Text as="h4" style={styles.cardText}>
              {props.description}
            </Card.Text>
          </Card.Body>
          {
            props.link &&
            <Button style={styles.button} href={props.url}>Read More</Button>
          }
        </Col>
      </Row>
    </Card>

The card is wrapped in a fluid <Container> and <CardGroup> component from react-bootstrap:

<Container fluid className="text-center">
  <CardGroup className="m-5 d-block">
    <Card />
  </CardGroup>
</Container>

On desktop device it looks like this:

But it looks like this on mobile device:

Here are the styles:

const styles = {
  card: {
    backgroundColor: '#B7E0F2',
    borderRadius: 55,
    padding: '3rem'
  },
  cardImage: {
    height: '100%',
    objectFit: 'cover',
    borderRadius: 55
  }
};

Does anyone know how to fix this? Thanks.

Body:
Try this. For the <Row> component class with className row in css file assign property as follows:

.row {
 display: flex,
 flex-wrap:wrap
 }