问:
Promise.all vs await Promise.all example wrong
I'm trying to see myself the different between Promise.all and await Promise.all. I have learnt that the first one ends earlier if one of the promises fail but in the same case with await we have to wait to the completion of all promises.

In my example, in both cases, they finish at the same time. What I'm doing wrong?

/**
 * Create a promise
 * @param ok true -> resolve, false -> reject
 */
function create_promise(ok) {
  return new Promise((resolve, reject) => {
    setTimeout(() => ok ? resolve() : reject(), 2e3)
  })
}

// Finish as soon as I get a reject
Promise.all([create_promise(true), create_promise(false), create_promise(true)])
  .catch(() => console.log('rejected'))

// Finish after waiting all
const my_async_function = async () =>
  await Promise.all([create_promise(true), create_promise(false), create_promise(true)])

my_async_function().catch(() => console.log('rejected'))```

答:
await Promise.all will ensure that all the promises will be resolved before executing the line after the await.

/**
 * Create a promise
 * @param ok true -> resolve, false -> reject
 */
function create_promise(ok) {
  return new Promise((resolve, reject) => {
    setTimeout(() => ok ? resolve() : reject(), 2e3)
  })
}

console.log("async/await version...")
const my_async_function = async () => {
  console.log("before await promise.all");
  const res = await Promise.all([create_promise(true), create_promise(false), create_promise(true)]);
  console.log("after await  promise.all"); // This line will be executed only after all promises are successfully resolved
  return res;
  }
my_async_function().catch(() => console.log('rejected'))

console.log("without async/await version...")
const my_SYNC_function = () => {
  console.log("before promise.all");
  const res = Promise.all([create_promise(true), create_promise(false), create_promise(true)]);
  console.log("after promise.all"); // This line will always be immediately executed after the Promise.all line, and not waiting for the promise completion  at all.
  return res; // So this line returns the return value of Promise.all, which will be an unresolved promise because the 2 seconds have not been elapsed yet.
  }

my_SYNC_function().catch(() => console.log('rejected'))```

This has nothing to do with a Promise itself being somehow "executed faster".

However, the function that calls Promise.all without await returns earlier, it just returns some Promise that has not been resolved yet.

Body:
await Promise.all will ensure that all the promises will be resolved before executing the line after the await.

/**
 * Create a promise
 * @param ok true -> resolve, false -> reject
 */
function create_promise(ok) {
  return new Promise((resolve, reject) => {
    setTimeout(() => ok ? resolve() : reject(), 2e3)
  })
}

console.log("async/await version...")
const my_async_function = async () => {
  console.log("before await promise.all");
  const res = await Promise.all([create_promise(true), create_promise(false), create_promise(true)]);
  console.log("after await  promise.all"); // This line will be executed only after all promises are successfully resolved
  return res;
  }
my_async_function().catch(() => console.log('rejected'))

console.log("without async/await version...")
const my_SYNC_function = () => {
  console.log("before promise.all");
  const res = Promise.all([create_promise(true), create_promise(false), create_promise(true)]);
  console.log("after promise.all"); // This line will always be immediately executed after the Promise.all line, and not waiting for the promise completion  at all.
  return res; // So this line returns the return value of Promise.all, which will be an unresolved promise because the 2 seconds have not been elapsed yet.
  }

my_SYNC_function().catch(() => console.log('rejected'))

This has nothing to do with a Promise itself being somehow "executed faster".

However, the function that calls Promise.all without await returns earlier, it just returns some Promise that has not been resolved yet.


来源: stackexchange

问:
Pine Script beginner question work with arrays --> create a new out of exisiting overwrite some values
don't know, why i cannot find an answer in the internet for my easy problem.
Just new in PineScript and the only I want to do is to create build an own array based with some specified values plus the input as source and get an sma out of it:

```<code>src = input(close, title="Source")
length = 10
lastBar = 1234 //overwrite the last bar of the input source

newSource[0]=lastBar

for i = 1 to length-2
     newSource[i] = src[i]

newSMA= sma(foreCastSourceFull, length)
plot(newSMA, color=orange)
</code>```

Thank you very much in advance.

答:
There are no arrays in Pine, there are series and they are immutable. You can use barstate.islast to override the last bar:

```<code>//@version=4
study("My Script")
newSource = barstate.islast ? 1234 : close
newSMA = sma(newSource, 10)
plot(newSMA)
</code>```

UPDATE

Use the following script if you want to duplicate the last bar (works on active markets only):

```<code>//@version=4
study("My Script")

plot(close)

LastClose = barstate.islast and not barstate.isconfirmed ? close : na
plot(LastClose, offset=1)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
don't know, why i cannot find an answer in the internet for my easy problem.
Just new in PineScript and the only I want to do is to create build an own array based with some specified values plus the input as source and get an sma out of it:

src = input(close, title="Source")
length = 10
lastBar = 1234 //overwrite the last bar of the input source

newSource[0]=lastBar

for i = 1 to length-2
     newSource[i] = src[i]

newSMA= sma(foreCastSourceFull, length)
plot(newSMA, color=orange)

Thank you very much in advance.

Body:
There are no arrays in Pine, there are series and they are immutable. You can use barstate.islast to override the last bar:

//@version=4
study("My Script")
newSource = barstate.islast ? 1234 : close
newSMA = sma(newSource, 10)
plot(newSMA)

UPDATE

Use the following script if you want to duplicate the last bar (works on active markets only):

//@version=4
study("My Script")

plot(close)

LastClose = barstate.islast and not barstate.isconfirmed ? close : na
plot(LastClose, offset=1)


问:
Help needed for developing iPhone application
I have following system configuration:

```<code>MAC OS X (10.5.8)
XCode (3.1.4)
iOS (3.0)
</code>```

1) Can i develop application for iPhone 4 with this configuration?

2) If not then what are the basic system requirement for developing application for both iPhone 3 and iPhone 4.

Thanks.

答:
as per apple -

To install Xcode 4, you must have an Intel-based Mac running Mac OS X v10.6 Snow Leopard.

ContentLicense: CC BY-SA 3.0

Body:
I have following system configuration:

MAC OS X (10.5.8)
XCode (3.1.4)
iOS (3.0)

1) Can i develop application for iPhone 4 with this configuration?

2) If not then what are the basic system requirement for developing application for both iPhone 3 and iPhone 4.

Thanks.


问:
Does std::move invalidates the raw pointer points to something owned by unique_ptr?
If I have a unique pointer and I took a pointer to the something owned by unique_ptr:

```<code>auto t = std::make_unique<int>(67);
auto m = t.get();
auto d = std::move(t);
std::cout << *m;

</code>```

I know m will be valid until t is modified or destroyed.
But when I move ownership from t, m is still valid.
Could someone make me understand what happens here or what standard says about this.

答:
Transferring the ownership of the integer between std::unique<int> objects, from t to d, does not affect m because m doesn't own the integer. m is a raw pointer (i.e., int *), it never participates in the ownership of the integer.

If m doesn't outlive the object that owns the integer – which is d by the end of your snippet – there can't be any issue.

Body:
If I have a unique pointer and I took a pointer to the something owned by unique_ptr:

auto t = std::make_unique<int>(67);
auto m = t.get();
auto d = std::move(t);
std::cout << *m;

I know m will be valid until t is modified or destroyed.
But when I move ownership from t, m is still valid.
Could someone make me understand what happens here or what standard says about this.


问:
how can i look for dynamic string with find elements by xpath?
I use this line of code in order to get links that contain '6z_04n'. However, this string changes according to the month. How can I put dynamically changing string value?

```<code>flag = '6z_' + month + 'n' // 6z_04n
links = driver.find_elements_by_xpath("//a[contains(@href, '6z_04n')]")
</code>```

I want something like:

```<code>flag = '6z_' + month + 'n' // 6z_04n
links = driver.find_elements_by_xpath("//a[contains(@href, flag )]")
</code>```

Unfortunately this is not working

答:
Consider f-strings if you are on Python 3.6+:

```<code>links = driver.find_elements_by_xpath(f"//a[contains(@href, '{flag}')]")
</code>```

Alternatively, str.format does the same thing:

```<code>links = driver.find_elements_by_xpath("//a[contains(@href, '{flag}')]".format(flag=flag))
</code>```

Body:
I use this line of code in order to get links that contain '6z_04n'. However, this string changes according to the month. How can I put dynamically changing string value?

flag = '6z_' + month + 'n' // 6z_04n
links = driver.find_elements_by_xpath("//a[contains(@href, '6z_04n')]")

I want something like:

flag = '6z_' + month + 'n' // 6z_04n
links = driver.find_elements_by_xpath("//a[contains(@href, flag )]")

Unfortunately this is not working

Body:
Consider f-strings if you are on Python 3.6+:

links = driver.find_elements_by_xpath(f"//a[contains(@href, '{flag}')]")

Alternatively, str.format does the same thing:

links = driver.find_elements_by_xpath("//a[contains(@href, '{flag}')]".format(flag=flag))


问:
how to assign color to helperText material ui to highlight error in TextField
How to assign a color to helperText material-UI to highlight the error in TextField.I am unable to set the color to helperText in material-UI.

I tried to use MuiFormHelperText-root-406 to apply CSS
but it does not work

```<code><Grid item xs={3}>
   <TextField
       label="EmailId"
       name="emailId"
       value={editItem.emailId}
       onChange={this.editInputValue}
       helperText={this.state.emailerror}  />
</Grid>

.MuiFormHelperText-root-406{
   color:rgba(255,0,0,0.5);
 }
</code>```

答:
If @ange-loron's answer didn't work, try to add !important :

```<code>.MuiFormHelperText-root {
    color: rgba(255,0,0,0.5) !important;
}
</code>```

Body:
How to assign a color to helperText material-UI to highlight the error in TextField.I am unable to set the color to helperText in material-UI.

I tried to use MuiFormHelperText-root-406 to apply CSS
but it does not work

<Grid item xs={3}>
   <TextField
       label="EmailId"
       name="emailId"
       value={editItem.emailId}
       onChange={this.editInputValue}
       helperText={this.state.emailerror}  />
</Grid>

.MuiFormHelperText-root-406{
   color:rgba(255,0,0,0.5);
 }

Body:
If @ange-loron's answer didn't work, try to add !important :

.MuiFormHelperText-root {
    color: rgba(255,0,0,0.5) !important;
}


问:
System.NullReferenceException: Object reference not set to an instance of an object

Possible Duplicate:

  System.NullReferenceException: Object reference not set to an instance of an object

look at my code

```<code>if (ViewState["Edit"].ToString() == "new") {
}
else {
      row = _section.GetBannerEntry(ViewState["Edit"].ToString());
}
</code>```

I was getting the error on this line if (ViewState["Edit"].ToString() == "new") I replaced with if (ViewState["Edit"] != null && ViewState["Edit"].ToString() == "new") it works.

Now I am getting the same error here in else row = _section.GetBannerEntry(ViewState["Edit"].ToString());

please help

答:
```<code>if (ViewState["Edit"] != null && ViewState["Edit"].ToString() == "new") {
</code>```

or if whats supposed to be in the viewstate is a string, this should work:

```<code>if ((string)ViewState["Edit"] == "new") {
</code>```

Body:
Possible Duplicate:

  System.NullReferenceException: Object reference not set to an instance of an object

look at my code

if (ViewState["Edit"].ToString() == "new") {
}
else {
      row = _section.GetBannerEntry(ViewState["Edit"].ToString());
}

I was getting the error on this line if (ViewState["Edit"].ToString() == "new") I replaced with if (ViewState["Edit"] != null && ViewState["Edit"].ToString() == "new") it works.

Now I am getting the same error here in else row = _section.GetBannerEntry(ViewState["Edit"].ToString());

please help

Body:
if (ViewState["Edit"] != null && ViewState["Edit"].ToString() == "new") {

or if whats supposed to be in the viewstate is a string, this should work:

if ((string)ViewState["Edit"] == "new") {


问:
Generating Lehmar code in linear time - bitset algorithm
To generate the lexicographic index of a permutation, we generate first its Lehmar code - basically representation in the factorial number system. To do this, we take each element of the permutation and subtract the number of elements to the left that are less than it. How do you find the number of elements on the left that are lesser than a particular digit of the permutation? You can do it in linear time if you simply scan all of them. You can do it in logarithmic time if you store them in a Binary search tree. But there is also a way to do it in constant time. In the blog here, this is covered in the section "a linear algorithm". Quoting:

Let’s work through this algorithm by way of example, again using the permutation (2 0 1).

Start with a bitset of length 3, initialized to zero (000b).

The first element of the permutation is 2, so flip bit 2 of the bitset: 001b. As mentioned above, the first digit of the Lehmer code is always the same as the first digit of the permutation, 2 in this case.

The second element of the permutation is 0, so set bit 0 of the bitset: 101b. Right-shift the bitset by n - k, where n is 3, the number of elements in the permutation, and k is 0, the second element of the permutation. 101b >> (3-0) = 000b. Count the number of ones in the result (countOnes(000b) = 0), and subtract that from the element to get the Lehmer digit: 0 - 0 = 0.

The third element of the permutation is 1, so set bit 1 of the bitset: 111b. Right-shift: 111b >> (3-1) = 001b. Subtract the number of ones in the result from the element to get the Lehmer digit: 1 - countOnes(001b) = 1-1 = 0.
As expected, the Lehmer code is 200.

I can see this works for that specific permutation, but I'm completely lost as to why it works.

答: Let's see it this way: say we're in the position t of the permutation. until now, bit i in the bitset is 1 iff i is on the left of the current element. When you shift it n-k times to the right, what is left is the first k bits of the string (consider shifting all the way n times, then undoing it k times) so now we have some 0s and some 1s that each corresponds to a number less than the current element. Thus, all we need to do is to count 1s in the resulting string.</p>


问:
How to stop centered changing text from moving
Recently I have downloaded a text rotator plugin. Works great but there is a small issue with it. Every time it changes text the whole heading moves becuse it's centered.

A simple example here: (Don't mind the js code, It's just a simplified example of the plugin)

HTML

```<code><h1>
Heading <span class="change">Change</span>
</h1>
</code>```

CSS

```<code>h1 {
  text-align: center;
}
</code>```

JS

```<code>var itr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var  interval = 1000; //one second
itr.forEach((itr, index) => {
setTimeout(() => {
    $('.change').text('Car');
            setTimeout(() => {
            $('.change').text('Boat');
                    setTimeout(() => {
                    $('.change').text('Helicopter');
                    }, index * interval
                   );
          }, index * interval
         );
  }, index * interval
 );
})
</code>```

You can try it here: https://jsfiddle.net/teku3a0w/1/

Is there a way to stop the heading from moving when it changes?

Permanent margin would definitely be an answer but i want it to be responsive.

答:
I found a good solution to this myself.

```<code>.change{
  display: inline-block;
    width: 150px;
    text-align: left;
}
</code>```

I added a fixed width to the part thats changing.

Note that the width has to be big enough to contain the longest word in the list.

 You can try it here: https://jsfiddle.net/0Lqpj2zc/

Body:
Recently I have downloaded a text rotator plugin. Works great but there is a small issue with it. Every time it changes text the whole heading moves becuse it's centered.

A simple example here: (Don't mind the js code, It's just a simplified example of the plugin)

HTML

Heading Change

CSS

h1 {
  text-align: center;
}

JS

var itr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var  interval = 1000; //one second
itr.forEach((itr, index) => {
setTimeout(() => {
    $('.change').text('Car');
            setTimeout(() => {
            $('.change').text('Boat');
                    setTimeout(() => {
                    $('.change').text('Helicopter');
                    }, index * interval
                   );
          }, index * interval
         );
  }, index * interval
 );
})

You can try it here: https://jsfiddle.net/teku3a0w/1/

Is there a way to stop the heading from moving when it changes?

Permanent margin would definitely be an answer but i want it to be responsive.

Body:
I found a good solution to this myself.

.change{
  display: inline-block;
    width: 150px;
    text-align: left;
}

I added a fixed width to the part thats changing.

Note that the width has to be big enough to contain the longest word in the list.

 You can try it here: https://jsfiddle.net/0Lqpj2zc/


问:
ASP.NET MVC: Controlling serialization of property names with JsonResult
Is there a way to control the JSON output of JsonResult with attributes, similar to how you can use XmlElementAttribute and its bretheren to control the output of XML serialization?

For example, given the following class:

```<code>public class Foo
{
    [SomeJsonSerializationAttribute("bar")]
    public String Bar { get; set; }

    [SomeJsonSerializationAttribute("oygevalt")]
    public String Oygevalt { get; set; }
}
</code>```

I'd like to then get the following output:

```<code>{ bar: '', oygevalt: '' }
</code>```

As opposed to:

```<code>{ Bar: '', Oygevalt: '' }
</code>```

答:
These answers were helpful to me, but coming to this problem a few years later than everyone else I found that this code didn't work with the current framework version.  This version works with Newtonsoft.Json and ASP NET Core 3.1:</p>

```<code>/*
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
*/
public class JsonDataContractActionResult : IActionResult
{
    public JsonDataContractActionResult(object data)
    {
        this.Data = data;
    }

    public object Data { get; private set; }

    public async Task ExecuteResultAsync(ActionContext context)
    {
        context.HttpContext.Response.ContentType = "application/json";
        JsonSerializer serializer = new JsonSerializer();
        serializer.NullValueHandling = NullValueHandling.Ignore;
        using (MemoryStream ms = new MemoryStream()) {
            using (StreamWriter sw = new StreamWriter(ms))
            {
                using (JsonWriter writer = new JsonTextWriter(sw))
                {
                    serializer.Serialize(writer, Data);
                }
            }
            byte[] b = ms.ToArray();
            await context.HttpContext.Response.Body.WriteAsync(b);
        }
    }
}
</code>```

Body:
Is there a way to control the JSON output of JsonResult with attributes, similar to how you can use XmlElementAttribute and its bretheren to control the output of XML serialization?

For example, given the following class:

public class Foo
{
    [SomeJsonSerializationAttribute("bar")]
    public String Bar { get; set; }

    [SomeJsonSerializationAttribute("oygevalt")]
    public String Oygevalt { get; set; }
}

I'd like to then get the following output:

{ bar: '', oygevalt: '' }

As opposed to:

{ Bar: '', Oygevalt: '' }

Body:
These answers were helpful to me, but coming to this problem a few years later than everyone else I found that this code didn't work with the current framework version.  This version works with Newtonsoft.Json and ASP NET Core 3.1:

/*
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
*/
public class JsonDataContractActionResult : IActionResult
{
    public JsonDataContractActionResult(object data)
    {
        this.Data = data;
    }

    public object Data { get; private set; }

    public async Task ExecuteResultAsync(ActionContext context)
    {
        context.HttpContext.Response.ContentType = "application/json";
        JsonSerializer serializer = new JsonSerializer();
        serializer.NullValueHandling = NullValueHandling.Ignore;
        using (MemoryStream ms = new MemoryStream()) {
            using (StreamWriter sw = new StreamWriter(ms))
            {
                using (JsonWriter writer = new JsonTextWriter(sw))
                {
                    serializer.Serialize(writer, Data);
                }
            }
            byte[] b = ms.ToArray();
            await context.HttpContext.Response.Body.WriteAsync(b);
        }
    }
}


问:
Conditional Statement inside Lambda Expression c#
I'm trying to remove strings from List by given command.
The command is to remove all strings that starts or ends with given string.

List input = new List() {"Pesho", "Misho", "Stefan"};

string command = "Remove StartsWith P"; or "Remove EndsWith P"

I'm trying to do it with lambda. Smth like this:

```<code>input.RemoveAll(x =>
{
if (command[1] == "StartsWith")
    x.StartsWith(command[2]);

else if (command[1] == "EndsWith")
    x.EndsWith(command[2]);
});
</code>```

The compiler says:
Not all code paths return a value in lambda expression of type Predicate

I'm asking is it possible to do it inside one lambda,
or I have to write it for both cases.

答:
The lambda syntax is a function.  Without the {} braces the single line present implicitly returns its result, but with the braces you need an explicit return:

```<code>input.RemoveAll(x =>
{
    if (command[1] == "StartsWith")
        return x.StartsWith(command[2]);
    else if (command[1] == "EndsWith")
        return x.EndsWith(command[2]);
    else
        return false; // You'll need a default too
});
</code>```

Body:
I'm trying to remove strings from List by given command.
The command is to remove all strings that starts or ends with given string.

List input = new List() {"Pesho", "Misho", "Stefan"};

string command = "Remove StartsWith P"; or "Remove EndsWith P"

I'm trying to do it with lambda. Smth like this:

input.RemoveAll(x =>
{
if (command[1] == "StartsWith")
    x.StartsWith(command[2]);

else if (command[1] == "EndsWith")
    x.EndsWith(command[2]);
});

The compiler says:
Not all code paths return a value in lambda expression of type Predicate

I'm asking is it possible to do it inside one lambda,
or I have to write it for both cases.

Body:
The lambda syntax is a function.  Without the {} braces the single line present implicitly returns its result, but with the braces you need an explicit return:

input.RemoveAll(x =>
{
    if (command[1] == "StartsWith")
        return x.StartsWith(command[2]);
    else if (command[1] == "EndsWith")
        return x.EndsWith(command[2]);
    else
        return false; // You'll need a default too
});


问:
Django view and separate processes
I would like to do something similar:

f(n) calculates n! , this obviously takes a long time to do, so the calculations need to run in a separate process from the django view. Additionally I would like the view to return a response immediately (ex.  progress 0% ) and subsequent polling needs to update progress, so the view needs to communicate with the above process.

What would be the best way to achieve this?

答:
Andrey Fedoseev gave a great suggestion, but let me come up with a more general solution. You can create some WaitingTasks model into which where your view puts new tasks. Then, there can use any method to process those waiting tasks - cronjob, upstart daemon, whatever - writing back progress and result.

(In fact celery uses a similar approach, only with RabbitMQ)

Title: Django view and separate processes


问:
Android Dynamic Feature INSTALL_FAILED_INVALID_APK
I am trying to add some functionality to an existing application. The app's build.gradle contains several productFlavors and a couple of buildTypes. I have tried to replicate that as best I can in my dynamic-feature module, but I cannot seem to get it to install properly from Android Studio.

I followed the example from: https://github.com/googlearchive/android-dynamic-features to set up my feature module, so my project is structured like

```<code>app
features/module/build.gradle
build.gradle
</code>```

I added a buildType and flavor to  the app build.gradle

```<code>defaultConfig {
    minSdkVersion 24
    targetSdkVersion 28
 }
dynamicFeatures = [":features:module"]
buildTypes{
    myBuildType {
        debuggable true
        multiDexEnabled true
    }
}

flavorDimensions "blah"
productFlavors{
        arm64 {
            ndk {
                abiFilters "arm64-v8a"
            }
            ext {
                abiVersionCode = 5
            }
            matchingFallbacks = ['defaultFlavor']
        }
}
</code>```

and in the module build.gradle, I have attempted to match that with:

```<code>defaultConfig {
    minSdkVersion 24
    targetSdkVersion 28
    }
buildTypes {

    dynamic {
        multiDexEnabled true
        debuggable true
    }
}

flavorDimensions "blah"
productFlavors {
    arm64 {
        ext {
            abiVersionCode = 5
        }
    }
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation project(':app')
}
</code>```

In my Run->Edit Configuration screen, I have put a checkbox next to both the base app and the module under the dynamic features to deploy section. I am trying to test this on a Nokia 6, with Android 9.0 running on it. The only output I get from the build is:

```<code>01/12 22:39:25: Launching 'app' on HMD Global TA-1025.
Installation did not succeed.
The application could not be installed: INSTALL_FAILED_INVALID_APK
The APKs are invalid.
</code>```

答:
I found a solution that resolved my problem. Make sure your libraries and class paths are up to date. I had a class for firebase plugins that were out of date. This problem occurred when using the new graddle. After updating the classpath, everything looks fine.

In my case. I changed this

classpath 'com.google.firebase:firebase-plugins:1.1.0'

to this

classpath 'com.google.firebase:perf-plugin:1.3.1'

Body:
I am trying to add some functionality to an existing application. The app's build.gradle contains several productFlavors and a couple of buildTypes. I have tried to replicate that as best I can in my dynamic-feature module, but I cannot seem to get it to install properly from Android Studio.

I followed the example from: https://github.com/googlearchive/android-dynamic-features to set up my feature module, so my project is structured like

app
features/module/build.gradle
build.gradle

I added a buildType and flavor to  the app build.gradle

defaultConfig {
    minSdkVersion 24
    targetSdkVersion 28
 }
dynamicFeatures = [":features:module"]
buildTypes{
    myBuildType {
        debuggable true
        multiDexEnabled true
    }
}

flavorDimensions "blah"
productFlavors{
        arm64 {
            ndk {
                abiFilters "arm64-v8a"
            }
            ext {
                abiVersionCode = 5
            }
            matchingFallbacks = ['defaultFlavor']
        }
}

and in the module build.gradle, I have attempted to match that with:

defaultConfig {
    minSdkVersion 24
    targetSdkVersion 28
    }
buildTypes {

    dynamic {
        multiDexEnabled true
        debuggable true
    }
}

flavorDimensions "blah"
productFlavors {
    arm64 {
        ext {
            abiVersionCode = 5
        }
    }
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation project(':app')
}

In my Run->Edit Configuration screen, I have put a checkbox next to both the base app and the module under the dynamic features to deploy section. I am trying to test this on a Nokia 6, with Android 9.0 running on it. The only output I get from the build is:

01/12 22:39:25: Launching 'app' on HMD Global TA-1025.
Installation did not succeed.
The application could not be installed: INSTALL_FAILED_INVALID_APK
The APKs are invalid.


答: m is a raw pointer to the integer owned by t. auto d = std::move(t); transfers ownership to a new smart pointer d. The internal raw pointer of d gets set to the adress of your ressource and the raw pointer of t get's set to nullptr. The integer that is now owned by d is still at the exact same location as before. That is why your raw pointer m that you got from t to that adress is still valid after the move to d. At this point t has nothing to do with your integer anymore, its just a std::unique_ptr<int> that is currently not assigned. Your raw pointer m will remain valid until the currently owning unique_ptr actually deletes it, for example because it goes out of scope.

Title: Does std::move invalidates the raw pointer points to something owned by unique_ptr?


问:
android data binding: how to get useful error messages
In android studio 2.1, the compile time error messages from xml mistakes are entirely non-helpful:

```<code>Error:(11, 41) error: package mypackage.databinding does not exist
Error:(15, 13) error: cannot find symbol class MyActivityBinding
</code>```

The real error would usually be something like "there's no such attribute android:adapter", or "variable foo doesn't contain property bar" or something like that. But instead of actually showing such errors, it shows the above unhelpful ones, which only tell you that the bindings weren't generated because of some unknown error.

答:
The way I use in Android Studio 4.0:

Select the top level Build: failed item on the Build Output panel

On the right part click Run with --stacktrace. When build is finished select the top Build: failed item again on the left panel. You'll get a databinding error description on the right panel:

In my case it's:

[databinding] {"msg":"Cannot find a getter for \u003ccom.google.android.material.slider.Slider app:value\u003e that accepts parameter type \u0027java.lang.Float\u0027\n\nIf a binding adapter provides the getter, check that the adapter is annotated correctly and that the parameter type matches.","file":"SliderDatabinding\src\main\res\layout\activity_main.xml","pos":[{"line0":14,"col0":8,"line1":21,"col1":41}]}

Body:
In android studio 2.1, the compile time error messages from xml mistakes are entirely non-helpful:

Error:(11, 41) error: package mypackage.databinding does not exist
Error:(15, 13) error: cannot find symbol class MyActivityBinding

The real error would usually be something like "there's no such attribute android:adapter", or "variable foo doesn't contain property bar" or something like that. But instead of actually showing such errors, it shows the above unhelpful ones, which only tell you that the bindings weren't generated because of some unknown error.


问:
Join table with null in all group
im new in stack. I cant found problem like this.

I have two tables.

One table x with transactions

```<code>Hour (approximation to full hour)   id_seler     expenses
1:00                                    1             3,04
2:00                                    2             4,04
3:00                                    3             5,03
4:00                                    4             6,04
3:00                                    4             7,04
</code>```

Second table y with limit seler id:

```<code>seler_id
   1
   2
   4
   5
</code>```

I try to join table y to table x to get score like this

```<code>id_seler      hour            sum expensex
   1        1:00              3,04
   1        2:00              null
   1        3:00              null
   1        4:00              null
   2        1:00              null
   2        2:00              4,04
   2        3:00              null
   2        4:00              null
   4        1:00              null
   4        2:00              null
   4       3:00               7,04
   4        4:00              6,04
   5        1:00              null
   5        2:00              null
   5       3:00               null
   5       4:00               null
</code>```

I want that query back me all id_seler for all hours with expenses.

I tried to use left join

```<code>from y left join x on x.id_seller=y.id_seller
group by hour
</code>```

but it back me null only for this id_seler which is dosent exist in table x next of last hour - In this exaple for id_seler=5

答:
you don't get results for times that aren't set in table x because you don't ask for them. SQL doesn't know what an hour is or how it works.

use a temp table for every time slot you always want to see like

```<code>CREATE TABLE #TIMES ([TIMES] nvarchar(5))
INSERT INTO #TIMES([TIMES]) VALUES(<insert the hours here>)
</code>```

then join y on the times table (on 1 = 1) so you get every time slot for every SELER_ID. left join those on table x (on id_seler = id_seler and x.hour = times.times)

Title: Join table with null in all group

Body:
im new in stack. I cant found problem like this.

I have two tables.

One table x with transactions

Hour (approximation to full hour)   id_seler     expenses
1:00                                    1             3,04
2:00                                    2             4,04
3:00                                    3             5,03
4:00                                    4             6,04
3:00                                    4             7,04

Second table y with limit seler id:

seler_id
   1
   2
   4
   5

I try to join table y to table x to get score like this

id_seler      hour            sum expensex
   1        1:00              3,04
   1        2:00              null
   1        3:00              null
   1        4:00              null
   2        1:00              null
   2        2:00              4,04
   2        3:00              null
   2        4:00              null
   4        1:00              null
   4        2:00              null
   4       3:00               7,04
   4        4:00              6,04
   5        1:00              null
   5        2:00              null
   5       3:00               null
   5       4:00               null

I want that query back me all id_seler for all hours with expenses.

I tried to use left join

from y left join x on x.id_seller=y.id_seller
group by hour

but it back me null only for this id_seler which is dosent exist in table x next of last hour - In this exaple for id_seler=5

Body:
you don't get results for times that aren't set in table x because you don't ask for them. SQL doesn't know what an hour is or how it works.

use a temp table for every time slot you always want to see like

CREATE TABLE #TIMES ([TIMES] nvarchar(5))
INSERT INTO #TIMES([TIMES]) VALUES(<insert the hours here>)

then join y on the times table (on 1 = 1) so you get every time slot for every SELER_ID. left join those on table x (on id_seler = id_seler and x.hour = times.times)


问:
OpenXml pivot table: how do you read the total and subtotals in order to display them?
I'm trying to create an Excel pivot table entirely from scratch, using OpenXml.

I've successfully created the pivot table itself (created a PivotTable definition, a cache definition, all the cache  records, pivotFields, RowItems, etc. etc.).

But how do I display any of the data?  How do I read the PivotTable calculations in order to write these values to cells?

For example:

The "grand total" is $86,631.62.

Two subtotals are $61,631,12 and $25,000.50

When I look at the XML in xl\worksheets\sheet2.xml, these values are all "hard coded" into the cell.

If I'm creating the cell myself (using OpenXml), then how do I "query" these values, letting the Pivot Table calculate them for me?

PS:
I've been using the OpenXml Productivity Tool extensively  ... but it, too, just "hard codes" the totals and subtotals ... without giving any clue how/where the values were actually calculated.

答:
You can use cell formula if you do not want to use EPPlus:

```<code>cell.DataType = new EnumValue<CellValue.Number);
cell.CellFormula = new CellFormula($"=SUBTOTAL{"109"}{rowName}");

//force full recalculation of the cells
workbookPart.workbook.CalculationProperties.ForceFullCalculation = true;
workbookPart.workbook.CalculationProperties.FullCalculationLoad = true;
</code>```

This way you can use every formula through OpenXml to calculate whatever yoe need.

In order to load into DataTable:

```<code>DataTable dt = new DataTable();

using (SpreadsheetDocument spreadSheetDocument = SpreadsheetDocument.Open(@"..\..\example.xlsx", false))
{

    WorkbookPart workbookPart = spreadSheetDocument.WorkbookPart;
    IEnumerable<Sheet> sheets = spreadSheetDocument.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>();
    string relationshipId = sheets.First().Id.Value;
    WorksheetPart worksheetPart = (WorksheetPart)spreadSheetDocument.WorkbookPart.GetPartById(relationshipId);
    Worksheet workSheet = worksheetPart.Worksheet;
    SheetData sheetData = workSheet.GetFirstChild<SheetData>();
    IEnumerable<Row> rows = sheetData.Descendants<Row>();

    foreach (Cell cell in rows.ElementAt(0))
    {
        dt.Columns.Add(GetCellValue(spreadSheetDocument, cell));
    }

    foreach (Row row in rows) //this will also include your header row...
    {
        DataRow tempRow = dt.NewRow();

        for (int i = 0; i < row.Descendants<Cell>().Count(); i++)
        {
            tempRow[i] = GetCellValue(spreadSheetDocument, row.Descendants<Cell>().ElementAt(i-1));
        }

        dt.Rows.Add(tempRow);
    }
</code>```

}

Body:
You can use cell formula if you do not want to use EPPlus:

cell.DataType = new EnumValue<CellValue.Number);
cell.CellFormula = new CellFormula($"=SUBTOTAL{"109"}{rowName}");

//force full recalculation of the cells
workbookPart.workbook.CalculationProperties.ForceFullCalculation = true;
workbookPart.workbook.CalculationProperties.FullCalculationLoad = true;

This way you can use every formula through OpenXml to calculate whatever yoe need.

In order to load into DataTable:

DataTable dt = new DataTable();

using (SpreadsheetDocument spreadSheetDocument = SpreadsheetDocument.Open(@"..\..\example.xlsx", false))
{

    WorkbookPart workbookPart = spreadSheetDocument.WorkbookPart;
    IEnumerable<Sheet> sheets = spreadSheetDocument.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>();
    string relationshipId = sheets.First().Id.Value;
    WorksheetPart worksheetPart = (WorksheetPart)spreadSheetDocument.WorkbookPart.GetPartById(relationshipId);
    Worksheet workSheet = worksheetPart.Worksheet;
    SheetData sheetData = workSheet.GetFirstChild<SheetData>();
    IEnumerable<Row> rows = sheetData.Descendants<Row>();

    foreach (Cell cell in rows.ElementAt(0))
    {
        dt.Columns.Add(GetCellValue(spreadSheetDocument, cell));
    }

    foreach (Row row in rows) //this will also include your header row...
    {
        DataRow tempRow = dt.NewRow();

        for (int i = 0; i < row.Descendants<Cell>().Count(); i++)
        {
            tempRow[i] = GetCellValue(spreadSheetDocument, row.Descendants<Cell>().ElementAt(i-1));
        }

        dt.Rows.Add(tempRow);
    }

}


问:
New user cannot login to SQL Azure
I am creating a new read/write user on SQL Azure as follows:

```<code>-- Connected to master
create login [fred] with password = 'xxx';

-- Connected to my DB
create user [fred] from login fred;
EXEC sp_addrolemember 'db_datareader', 'fred';
EXEC sp_addrolemember 'db_datawriter', 'fred';
</code>```

When I login using SSMS I get an error saying Cannot open database "master" requested by the login. The login failed.

What am I doing wrong or missing?

答:
Two other reasons that can trip you up:

The Server Login and the Database User must be the same. You cannot have APILogin link to APIUser, Azure just doesn't like it

Hyphens aren't allowed in usernames on Azure, so you can't have API-User

Title: New user cannot login to SQL Azure

Body:
I am creating a new read/write user on SQL Azure as follows:

-- Connected to master
create login [fred] with password = 'xxx';

-- Connected to my DB
create user [fred] from login fred;
EXEC sp_addrolemember 'db_datareader', 'fred';
EXEC sp_addrolemember 'db_datawriter', 'fred';

When I login using SSMS I get an error saying Cannot open database "master" requested by the login. The login failed.

What am I doing wrong or missing?


答:
Your View state is null
Check for </p>

```<code>if(ViewState["Edit"]!= null)
{
 if (ViewState["Edit"].ToString() == "new")
}
</code>```

Title: System.NullReferenceException: Object reference not set to an instance of an object

Body:
Your View state is null
Check for

if(ViewState["Edit"]!= null)
{
 if (ViewState["Edit"].ToString() == "new")
}


问:
finding semantic similarity between 2 statements
I am currently working with small application in python and my application has search functionality (currently using difflib) but I want to create Semantic Search which can give top 5 or 10 results from my database, based on user inputted text. It is same as google search engine works. I found some solutions Here.

But the problem is, below two statements from one of solution are semantically incorrect. And I don't care about this. because they are making things too hard which I don't want And also solution will be some pretrained neural network model or library from which I can implement easily.

Pete and Rob have found a dog near the station.

Pete and Rob have never found a dog near the station

And also I found some solutions which are showing using gensim and Glove embeddings and finding similarity between words and not sentences.

What I wanted ?

Suppose my db has statement display classes and user inputs show, showed, displayed, displayed class, show types etc are same. And if above 2 statements are given as same then also I don't care. displayed and displayed class already showing in difflib.

Points to be noted

Find from fixed set of statements but user inputted statements can differ

Must work for statements

答:
I think it is not gensim embedding. It is word2vec embedding. Whatever it is.

You need tensorflow_hub

The Universal Sentence Encoder encodes text into high-dimensional vectors that can be used for text classification, semantic similarity, clustering and other natural language tasks.

I believe you need here is Text Classification or Semantic Similarity because you want to find nearest top 5 or 10 statements given statement from user.

It is easy to use. But size of model is ≈ 1GB. It works with words, sentences, phrases or short paragraphs. The input is variable length English text and the output is a 512 dimensional vector. You can find more information about it Here

Code

import tensorflow_hub as hub
import numpy as np

# Load model. It will download first time.
module_url = "https://tfhub.dev/google/universal-sentence-encoder-large/5"
model = hub.load(module_url)

# first data[0] is your actual value
data = ["display classes", "show", "showed" ,"displayed class", "show types"]

# find high-dimensional vectors.
vecs = model(data)

# find distance between statements using inner product
dists = np.inner(vecs[0], vecs)

# print dists
print(dists)
```
<h2>Output</h2>
<pre class="lang-sh prettyprint-override"><code>array([0.9999999 , 0.5633253 , 0.46475542, 0.85303843, 0.61701006],dtype=float32)
</code>```

Conclusion

First value 0.999999 is distance between display classes and display classes itself. second 0.5633253 is distance between display classes and show and last 0.61701006 is distance between display classes and show types.

Using this, you can find distance between given input and statements in db. then rank them according to distance.

Body:
I think it is not gensim embedding. It is word2vec embedding. Whatever it is.

You need tensorflow_hub

The Universal Sentence Encoder encodes text into high-dimensional vectors that can be used for text classification, semantic similarity, clustering and other natural language tasks.

I believe you need here is Text Classification or Semantic Similarity because you want to find nearest top 5 or 10 statements given statement from user.

It is easy to use. But size of model is ≈ 1GB. It works with words, sentences, phrases or short paragraphs. The input is variable length English text and the output is a 512 dimensional vector. You can find more information about it Here

Code

import tensorflow_hub as hub
import numpy as np

# Load model. It will download first time.
module_url = "https://tfhub.dev/google/universal-sentence-encoder-large/5"
model = hub.load(module_url)

# first data[0] is your actual value
data = ["display classes", "show", "showed" ,"displayed class", "show types"]

# find high-dimensional vectors.
vecs = model(data)

# find distance between statements using inner product
dists = np.inner(vecs[0], vecs)

# print dists
print(dists)

Output

array([0.9999999 , 0.5633253 , 0.46475542, 0.85303843, 0.61701006],dtype=float32)

Conclusion

First value 0.999999 is distance between display classes and display classes itself. second 0.5633253 is distance between display classes and show and last 0.61701006 is distance between display classes and show types.

Using this, you can find distance between given input and statements in db. then rank them according to distance.


问:
Normalizing JSON with Pandas appends path to columns
I am trying to parse a JSON file and export that into CSV that is going to be processed separately.

I have JSON that looks like this:

```<code> "data": [
{
  "id": "fHF6fFQrZ8Qxwrw1ALiMC5_a2920fb2-e91b-11e9-9b3f-2fe890320230",
  "type": "leads",
  "attributes": {
    "facebook_url": "someurl",
    "status": "new",
    "twitter_handle": "somehandle",
    "first_visit_date": "2020-06-01",
    "last_visit_date": "2020-06-01",
    "linkedin_url": "linkedinlink",
    "name": "name",
    "website_url": "website",
    "industry": "Computer Software",
    "phone": "123123123",
    "crm_lead_id": null,
    "crm_organization_id": null,
    "employee_count": 10001,
    "tags": [],
    "logo_url": "logo"
  },
  "relationships": {
    "location": {
      "data": {
        "id": "a2920fb2-e91b-11e9-9b3f-2fe890320230",
        "type": "locations"
      }
    }
  }
}
</code>```

I use pandas to normalize the data:

```<code>with open('leads.json') as data_file:
    d= json.load(data_file)

df = json_normalize(d['data'])
</code>```

This results in the column names being named like this:

id  type    attributes.facebook_url attributes.status   attributes.twitter_handle attributes.first_visit_date

How am I supposed to get only the column names without the whole attribute path being attached to it?

edit: I will not parse the relationships node.

Example output would be:

id  type    facebook_url
 1  sometype http://myurl

答:
You can do it this way:</p>

```<code>df = pd.json_normalize(data['data'])[['id', 'type', 'attributes.facebook_url']]
df.columns = df.columns.str.replace('attributes.', '')
print(df)

                                                  id   type facebook_url
0  fHF6fFQrZ8Qxwrw1ALiMC5_a2920fb2-e91b-11e9-9b3f...  leads      someurl
</code>```

Body:
I am trying to parse a JSON file and export that into CSV that is going to be processed separately.

I have JSON that looks like this:

 "data": [
{
  "id": "fHF6fFQrZ8Qxwrw1ALiMC5_a2920fb2-e91b-11e9-9b3f-2fe890320230",
  "type": "leads",
  "attributes": {
    "facebook_url": "someurl",
    "status": "new",
    "twitter_handle": "somehandle",
    "first_visit_date": "2020-06-01",
    "last_visit_date": "2020-06-01",
    "linkedin_url": "linkedinlink",
    "name": "name",
    "website_url": "website",
    "industry": "Computer Software",
    "phone": "123123123",
    "crm_lead_id": null,
    "crm_organization_id": null,
    "employee_count": 10001,
    "tags": [],
    "logo_url": "logo"
  },
  "relationships": {
    "location": {
      "data": {
        "id": "a2920fb2-e91b-11e9-9b3f-2fe890320230",
        "type": "locations"
      }
    }
  }
}

I use pandas to normalize the data:

with open('leads.json') as data_file:
    d= json.load(data_file)

df = json_normalize(d['data'])

This results in the column names being named like this:

id  type    attributes.facebook_url attributes.status   attributes.twitter_handle attributes.first_visit_date

How am I supposed to get only the column names without the whole attribute path being attached to it?

edit: I will not parse the relationships node.

Example output would be:

id  type    facebook_url
 1  sometype http://myurl

Body:
You can do it this way:

df = pd.json_normalize(data['data'])[['id', 'type', 'attributes.facebook_url']]
df.columns = df.columns.str.replace('attributes.', '')
print(df)

                                                  id   type facebook_url
0  fHF6fFQrZ8Qxwrw1ALiMC5_a2920fb2-e91b-11e9-9b3f...  leads      someurl


问:
Autodesk Forge Viewer - Click Events on models created through SceneBuilder
I am working on adding geometry to the viewer using the new SceneBuilder extension (using this guide). I have been able to show the geometry in the viewer and also been able to add TextGeometry to the same dbId as some of the models.

The viewer is allowing me to click and isolate the geometry, but when I use viewer.getSelection(), it returns an empty array. I even added a click event listener to the Geometry itself, but no luck there as well.

Would any one know of a way to add a listener to this newly created fragment or geometry.

答:
Did you set dbid to the mesh appended to the scene? Otherwise the selector wouldn't be able to pick up their dbids as it would for the document(original model)'s bubble:

```<code>
    sceneBuilder.addNewModel({conserveMemory: false,
    modelNameOverride: 'My Model Name233'})
        .then(modelBuilder => {
            //...
            mesh = new THREE.Mesh(geom, phongMaterial);
            mesh.dbId=23333;
            modelBuilder.addMesh(mesh);

        })
</code>```

Then you would be able to call the selector on the custom model to get the current selection - since we are getting selection status from the custom model as opposed to the one loaded by Viewer (exposed via viewer.model):

```<code>modelBuilder.model.selector.getSelection() //[23333]
</code>```

EDIT

Forgot to mention you may also subscribe to the AGGREGATE_SELECTION_CHANGED_EVEN since we are dealing with multiple models here:

```<code>NOP_VIEWER.addEventListener(Autodesk.Viewing.AGGREGATE_SELECTION_CHANGED_EVENT,e=>{
//...
})
</code>```

Body:
Did you set dbid to the mesh appended to the scene? Otherwise the selector wouldn't be able to pick up their dbids as it would for the document(original model)'s bubble:

    sceneBuilder.addNewModel({conserveMemory: false,
    modelNameOverride: 'My Model Name233'})
        .then(modelBuilder => {
            //...
            mesh = new THREE.Mesh(geom, phongMaterial);
            mesh.dbId=23333;
            modelBuilder.addMesh(mesh);

        })

Then you would be able to call the selector on the custom model to get the current selection - since we are getting selection status from the custom model as opposed to the one loaded by Viewer (exposed via viewer.model):

modelBuilder.model.selector.getSelection() //[23333]

EDIT

Forgot to mention you may also subscribe to the AGGREGATE_SELECTION_CHANGED_EVEN since we are dealing with multiple models here:

NOP_VIEWER.addEventListener(Autodesk.Viewing.AGGREGATE_SELECTION_CHANGED_EVENT,e=>{
//...
})


问:
How do you check the amount of options in a selector class using javascript?
I need to write a function to check the number of options in a selector tag using javascript. The only thing is I cannot use jQuery (My script is based on puppeteer and web scraping). If you have any suggestions please leave them down below.
Example:

I need the function to return 2 in this example.

Thanks.

答:
For this you can use the following code snippet:

```<code>var x = document.getElementById("size").length;
</code>```

x will hold the number of options here.

source: https://www.w3schools.com/JSREF/prop_select_length.asp

Body:
For this you can use the following code snippet:

var x = document.getElementById("size").length;

x will hold the number of options here.

source: https://www.w3schools.com/JSREF/prop_select_length.asp


问:
how to type extended class?
I have a set of classes extending a base class. And there is a function which might be called with an argument as any of the classes above. How do I type the function here?

For example:

```<code>class BaseClass {}

class A extends BaseClass {
// ...
}

class B extends BaseClass{
}
</code>```

and here is the function I want to type:

```<code>function myfunc(arg){
 // do something
}
</code>```

here the arg will be A or B or anything which is extended from BaseClass.
(I don't prefer giving It as A | B, because there is a lot of classes and it is a generic function)

答:
As you wrote "it is a generic function". So give it a generic type argument with a constraint to extend BaseClass

```<code>function myfunc<T extends BaseClass>(arg: T){
 // do something
}
</code>```

Title: how to type extended class?

Body:
I have a set of classes extending a base class. And there is a function which might be called with an argument as any of the classes above. How do I type the function here?

For example:

class BaseClass {}

class A extends BaseClass {
// ...
}

class B extends BaseClass{
}

and here is the function I want to type:

function myfunc(arg){
 // do something
}

here the arg will be A or B or anything which is extended from BaseClass.
(I don't prefer giving It as A | B, because there is a lot of classes and it is a generic function)

Body:
As you wrote "it is a generic function". So give it a generic type argument with a constraint to extend BaseClass

function myfunc<T extends BaseClass>(arg: T){
 // do something
}


问:
['type aliases' can only be used in a .ts file]
I use command react-native init "name project" then open vscode appear to have error message code. (image)

答:
Helped me to resolve

To disable the [js] parser (connected to Typescript),

In VSCode menu: File -> Preferences -> User settings, (or ctrl+,) and add the following line

"javascript.validate.enable": false,


问:
trying to clone a branch using git, but it doesn't work
```<code>$ git clone gitosis@tony:stylingGit2.git
Cloning into stylingGit2...
ERROR:gitosis.serve.main:Repository read access denied
fatal: The remote end hung up unexpectedly
</code>```

I'm trying to connect to a server, this happens and I wouldn't know what to do...

...does anybody knows how to solve this issue?

答: By the looks of the error message you don't have permission to read that directory. Do you have access to the server? then you can try chmoding och chowning it so that your user can access it.

Body:
$ git clone gitosis@tony:stylingGit2.git
Cloning into stylingGit2...
ERROR:gitosis.serve.main:Repository read access denied
fatal: The remote end hung up unexpectedly

I'm trying to connect to a server, this happens and I wouldn't know what to do...

...does anybody knows how to solve this issue?


问:
Can DataGrip iterate through CSV files?
I'm using DataGrip and need to do multiple queries of the following format:

```<code>SELECT * FROM table WHERE id = '01345' AND date = '01-01-2020'
</code>```

For each query, the id and date are different. I have a CSV file with many rows, each row containing a different id and date. Is there a way to get DataGrip to iterate through the CSV file and execute all required queries, and save each output as a CSV file (all outputs combined as a single CSV file would also suffice)?

答:
There is no one step solution.
But here what I would do:

Import CSV file into a table in a temporary in-memory database, e.g. H2

Write your custom extractor, see examples by @moscas

Additionally, see DataGrip blog posts about export and extractors:

Export data in any way with intellij based ides

Data extractors

What objects functions are available for custom data extractors

Title: Can DataGrip iterate through CSV files?

Body:
I'm using DataGrip and need to do multiple queries of the following format:

SELECT * FROM table WHERE id = '01345' AND date = '01-01-2020'

For each query, the id and date are different. I have a CSV file with many rows, each row containing a different id and date. Is there a way to get DataGrip to iterate through the CSV file and execute all required queries, and save each output as a CSV file (all outputs combined as a single CSV file would also suffice)?


问:
Assigning best grid searched hyperparameters into final model in Python Bagging Classifier
I am training a Logistic Regression and using bagging. I want to use gridsearch CV to find the best hyperparameters. I used the '__' to denote a hyperparameter of the base estimator:

```<code>from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import BaggingClassifier

param_grid = {
    'base_estimator__C': [1e-15, 1e-10, 1e-8, 1e-4, 1e-3, 1e-2, 1, 5, 10, 20, 50, 100, 1000], # lambdas for regularization
    'max_samples': [0.05, 0.1, 0.2, 0.5], # for bootstrap sampling
    'max_features': [0.3,0.5,0.7,0.9]}

clf = GridSearchCV(BaggingClassifier(LogisticRegression(penalty='l2'),
                                            n_estimators = 100),
                        param_grid, cv=cv, scoring='f1', return_train_score=True)
clf.fit(x,y)
best_hyperparams = clf.best_params_
best_hyperparams

Results:
{'base_estimator__C': 10, 'max_features': 0.3, 'max_samples': 0.1}
</code>```

Now that I have got the best parameters, how do I put it into the bagging classifier again? Using **best_hyperparams does not work as the Bagging classifier does not recognize that the base_estimator__C should go into the base estimator, Logistic Regression

```<code>best_clf = BaggingClassifier(LogisticRegression(penalty='l2'), n_estimators = 100, **best_hyperparams) # train model with best hyperparams
</code>```

答:
You can use set_params() after initializing the bagging classifier.

```<code>best_clf = BaggingClassifier(LogisticRegression(penalty='l2'), n_estimators = 100)
best_clf.set_params(**best_hyperparams)
</code>```

Body:
I am training a Logistic Regression and using bagging. I want to use gridsearch CV to find the best hyperparameters. I used the '__' to denote a hyperparameter of the base estimator:

from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import BaggingClassifier

param_grid = {
    'base_estimator__C': [1e-15, 1e-10, 1e-8, 1e-4, 1e-3, 1e-2, 1, 5, 10, 20, 50, 100, 1000], # lambdas for regularization
    'max_samples': [0.05, 0.1, 0.2, 0.5], # for bootstrap sampling
    'max_features': [0.3,0.5,0.7,0.9]}

clf = GridSearchCV(BaggingClassifier(LogisticRegression(penalty='l2'),
                                            n_estimators = 100),
                        param_grid, cv=cv, scoring='f1', return_train_score=True)
clf.fit(x,y)
best_hyperparams = clf.best_params_
best_hyperparams

Results:
{'base_estimator__C': 10, 'max_features': 0.3, 'max_samples': 0.1}

Now that I have got the best parameters, how do I put it into the bagging classifier again? Using **best_hyperparams does not work as the Bagging classifier does not recognize that the base_estimator__C should go into the base estimator, Logistic Regression

best_clf = BaggingClassifier(LogisticRegression(penalty='l2'), n_estimators = 100, **best_hyperparams) # train model with best hyperparams

Body:
You can use set_params() after initializing the bagging classifier.

best_clf = BaggingClassifier(LogisticRegression(penalty='l2'), n_estimators = 100)
best_clf.set_params(**best_hyperparams)


问:
How to run two methods in parallel in Groovy?
Example :

```<code>def mylist = ['item1','item2']
mylist.each {
     fun1()
     fun2()
}

def fun1() {
    println "function-1"
}

def fun2() {
    println "function-2"
}
</code>```

Actual result :

```<code>function-1
function-2
function-1
function-2
</code>```

Expected result :

same as above, however I want fun1() and fun2() to be called in parallel for each item in the list. It does not matter the sequence of output as in my actual code, both methods are independent of each other.

答:
As cfrick says, you can use GPars which is now part of groovy:</p>

```<code>import static groovyx.gpars.GParsPool.*

def mylist = ['item1','item2']

withPool {
    mylist.eachParallel {
       fun1()
       fun2()
    }
}

def fun1() {
    println "function-1"
}

def fun2() {
    println "function-2"
}
</code>```

Body:
Example :

def mylist = ['item1','item2']
mylist.each {
     fun1()
     fun2()
}

def fun1() {
    println "function-1"
}

def fun2() {
    println "function-2"
}

Actual result :

function-1
function-2
function-1
function-2

Expected result :

same as above, however I want fun1() and fun2() to be called in parallel for each item in the list. It does not matter the sequence of output as in my actual code, both methods are independent of each other.

Body:
As cfrick says, you can use GPars which is now part of groovy:

import static groovyx.gpars.GParsPool.*

def mylist = ['item1','item2']

withPool {
    mylist.eachParallel {
       fun1()
       fun2()
    }
}

def fun1() {
    println "function-1"
}

def fun2() {
    println "function-2"
}


问:
How does this pointer-based strcat work in C?
I have some basic experience with C, but it usually takes me a little while to figure out how to implement something; using pointers and such is still a bit of a mystery to me.

Then I see an example like strcat implementation and I can't follow along. Would someone mind kindly explaining this to a C newcomer?

```<code>char *
my_strcat(char *dest, const char *src)
{
    char *rdest = dest;

    while (*dest)
      dest++;
    while (*dest++ = *src++)
      ;
    return rdest;
}
</code>```

When I read that, I think "rdest = ?, maybe real destination". So set a pointer to the original destination. Then "while (*dest) dest++;", what is that doing? Same with the next line. I don't follow.

Is it using any additional memory to the original two parts (src and dest)? Like in JS, if you concatenate 2 strings, it creates memory for a third string that combines the two, so you have double the memory. How is this avoided in this C implementation (if it is)?

答:
If you change a bit the role of the rdest will be more clearer

```<code>char * my_strcat(char *dest, const char *src)
{
    char *workdest = dest;

    while (*workdest) workdest++;
    while (*workdest++ = *src++);
    return dest;
}
</code>```

Now we use a work pointer just to iterate and return the original dest

Is it using any additional memory to the original two parts (src and
  dest)? Like in JS, if you concatenate 2 strings, it creates memory for
  a third string that combines the two, so you have double the memory.
  How is this avoided in this C implementation (if it is)?

This version (and the standard library strcat as well) does not allocate any memory and the caller has to make sure that the dest is writeable and and large enough to accommodate the connected strings

You need to write another version the function:

```<code>char * my_strcat_s(char *dest, const char *src)
{
    size_t destlen = strlen(dest);
    char *workdest = malloc(destlen + strlen(src) + 1);

    if(workdest)
    {
        strcpy(workdest, dest);
        strcpy(workdest + destlen, src);
    }
    return workdest;
}
</code>```

But freeing the allocated memory is the programmers responsibility

Body:
I have some basic experience with C, but it usually takes me a little while to figure out how to implement something; using pointers and such is still a bit of a mystery to me.

Then I see an example like strcat implementation and I can't follow along. Would someone mind kindly explaining this to a C newcomer?

char *
my_strcat(char *dest, const char *src)
{
    char *rdest = dest;

    while (*dest)
      dest++;
    while (*dest++ = *src++)
      ;
    return rdest;
}

When I read that, I think "rdest = ?, maybe real destination". So set a pointer to the original destination. Then "while (*dest) dest++;", what is that doing? Same with the next line. I don't follow.

Is it using any additional memory to the original two parts (src and dest)? Like in JS, if you concatenate 2 strings, it creates memory for a third string that combines the two, so you have double the memory. How is this avoided in this C implementation (if it is)?

Body:
If you change a bit the role of the rdest will be more clearer

char * my_strcat(char *dest, const char *src)
{
    char *workdest = dest;

    while (*workdest) workdest++;
    while (*workdest++ = *src++);
    return dest;
}

Now we use a work pointer just to iterate and return the original dest

Is it using any additional memory to the original two parts (src and
  dest)? Like in JS, if you concatenate 2 strings, it creates memory for
  a third string that combines the two, so you have double the memory.
  How is this avoided in this C implementation (if it is)?

This version (and the standard library strcat as well) does not allocate any memory and the caller has to make sure that the dest is writeable and and large enough to accommodate the connected strings

You need to write another version the function:

char * my_strcat_s(char *dest, const char *src)
{
    size_t destlen = strlen(dest);
    char *workdest = malloc(destlen + strlen(src) + 1);

    if(workdest)
    {
        strcpy(workdest, dest);
        strcpy(workdest + destlen, src);
    }
    return workdest;
}

But freeing the allocated memory is the programmers responsibility


问:
How can I make the letters stop moving when I hover over them?
What happens when I hover over the numbers:

https://gyazo.com/20b6426d435551c5ee238241d3f96b4d

Basically when I hover over the pagination numbers they move to the right and I don't know what I have done wrong in my code for them to do that. At the very bottom of the post I'll add an HTML that is basically only pagination but doesn't have this problem.

The Code:

```<code><!-- Scripts -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script>
      // Collapsible
            var coll = document.getElementsByClassName("collapsible");
            var i;

            for (i = 0; i < coll.length; i++) {
                coll[i].addEventListener("click", function() {
                    this.classList.toggle("active");
                    var content = this.nextElementSibling;
                    if (content.style.maxHeight){
                        content.style.maxHeight = null;
                    } else {
                        content.style.maxHeight = content.scrollHeight + "px";
                    }
                });
            }
        </script>
    <script>
      // Pagination
      pageSize = 20;

      var pageCount =  $(".line-content").length / pageSize;

         for(var i = 0 ; i<pageCount;i++){

           $("#pagin").append('<li><a href="#">'+(i+1)+'</a></li> ');
         }
            $("#pagin li").first().find("a").addClass("current")
        showPage = function(page) {
          $(".line-content").hide();
          $(".line-content").each(function(n) {
              if (n >= pageSize * (page - 1) && n < pageSize * page)
                  $(this).show();
          });
      }

      showPage(1);

      $("#pagin li a").click(function() {
          $("#pagin li a").removeClass("current");
          $(this).addClass("current");
          showPage(parseInt($(this).text()))
      });
    </script>
</code>```

```<code>/* main.css */
body {
    background-color: #333;
    color: #999;
    font-family: Arial, Helvetica, sans-serif;
    font-size: 16px;
    line-height: 1.6em;
    margin: 0;
}
::-webkit-scrollbar {
    width: 10px;
}
::-webkit-scrollbar-track {
    box-shadow: inset 0 0 2px #000;
    border-radius: 5px;
    background: #999999;
}
::-webkit-scrollbar-thumb {
    border-radius: 5px;
    background: #686868;
}
::-webkit-scrollbar-thumb:hover {
    background: #4a4a4a;
}
.container {
    width: 80%;
    margin: auto;
    overflow: hidden;
}
#main-header {
    background-color: #444;
    color: #fff;
}
#navbar {
    background-color: #333;
    color: #fff;
}
#navbar ul {
    padding: 0;
    list-style: none;
}
#navbar li {
    display: inline;
}
#navbar a {
    color: #fff;
    text-decoration: none;
    font-size: 18px;
    padding-right: 15px;
}
#showcase {
    background-image: url('../images/background.jpg');
    background-position: center right;
    min-height: 300px;
    margin-bottom: 30px;
    text-align: center;
}
#showcase h1 {
    color: #fff;
    font-size: 50px;
    line-height: 1.6em;
    padding-top: 30px;
}
#main {
    float: left;
    width: 70%;
    padding: 0 30px;
    box-sizing: border-box;
}
#sidebar {
    border-radius: 10px;
    float: right;
    width: 30%;
    background: #444;
    color: #999;
    padding: 0px 15px;
  padding-bottom: 15px;
    box-sizing: border-box;
}
#main-footer {
    background: #222;
    color: #fff;
    text-align: center;
    padding: 20px;
    margin-top: 40px;
}
@media(max-width:600px) {
    #main {
        width: 100%;
        float: none;
    }
    #sidebar {
        width: 100%;
        float: none;
    }
}
</code>```

```<code>/* songscollapsible.css */
.current {
  color: inherit;
}
#pagin li {
  display: inline-block;
}
.collapsible {
  background-color: #444;
  color: #999;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  border: none;
  text-align: left;
  outline: none;
  font-size: 17px;
}
.active, .collapsible:hover {
  background-color: #555;
}
.content {
  max-height: 0;
  padding: 0px 15px 0px 15px;
  overflow: hidden;
  background-color: #666;
  color: #999;
  border-radius: 15px;
  transition: max-height 0.7s ease-out;
}
.button {
  box-shadow: 0px 2px 4px #555;
  border-radius: 15px;
}
/* .limg -> left image */
.limg {
  float: left;
  padding-right: 5px;
  max-width: 20px;
  max-height: 20px;
}
/* .fimg -> front image */
.fimg {
  float: left;
  padding-bottom: 15px;
  max-width: 20%;
}
.pl5 {
  padding-left: 5px;
}
.pl40 {
  padding-left: 40%;
}
.lh1-4 {
  line-height: 1.4;
}
.dli {
  max-width: 17px;
  max-height: 17px;
  padding-right: 5px;
}
a:link {
  text-decoration: none;
  color: #999;
}
a:visited {
  text-decoration: none;
  color: #999;
}
a:hover {
  text-decoration: none;
  color: #999;
}
a:active {
  text-decoration: none;
  color: #999;
}
</code>```

```<code><html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>test</title>
    <style>
      .current {
        color: inherit;
      }
      #pagin li {
        display: inline-block;
      }
    </style>
  </head>
  <body>
    <div class="line-content">test1</div>
    <div class="line-content">test2</div>
    <div class="line-content">test3</div>
    <div class="line-content">test4</div>
    <div class="line-content">test5</div>
    <div class="line-content">test6</div>
    <ul id="pagin"></ul>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
    </script>
    <script>
      // Pagination
      pageSize = 2;

      var pageCount =  $(".line-content").length / pageSize;

         for(var i = 0 ; i<pageCount;i++){

           $("#pagin").append('<li><a href="#">'+(i+1)+'</a></li> ');
         }
            $("#pagin li").first().find("a").addClass("current")
        showPage = function(page) {
          $(".line-content").hide();
          $(".line-content").each(function(n) {
              if (n >= pageSize * (page - 1) && n < pageSize * page)
                  $(this).show();
          });
      }

      showPage(1);

      $("#pagin li a").click(function() {
          $("#pagin li a").removeClass("current");
          $(this).addClass("current");
          showPage(parseInt($(this).text()))
      });
    </script>
  </body>
</html>
</code>```

答:
The problem is that on hover they resize and push the other divs aside. You may try this convenient approach to resize them absolute:

```<code>a:hover {
    transform: scale(1.1);
}
</code>```

or keep them as is:

```<code>a:hover {
    transform: scale(1.0);
}
</code>```

(not sure which effect you want to achieve using on:hover

Body:
What happens when I hover over the numbers:

https://gyazo.com/20b6426d435551c5ee238241d3f96b4d

Basically when I hover over the pagination numbers they move to the right and I don't know what I have done wrong in my code for them to do that. At the very bottom of the post I'll add an HTML that is basically only pagination but doesn't have this problem.

The Code:

/* main.css */
body {
    background-color: #333;
    color: #999;
    font-family: Arial, Helvetica, sans-serif;
    font-size: 16px;
    line-height: 1.6em;
    margin: 0;
}
::-webkit-scrollbar {
    width: 10px;
}
::-webkit-scrollbar-track {
    box-shadow: inset 0 0 2px #000;
    border-radius: 5px;
    background: #999999;
}
::-webkit-scrollbar-thumb {
    border-radius: 5px;
    background: #686868;
}
::-webkit-scrollbar-thumb:hover {
    background: #4a4a4a;
}
.container {
    width: 80%;
    margin: auto;
    overflow: hidden;
}
#main-header {
    background-color: #444;
    color: #fff;
}
#navbar {
    background-color: #333;
    color: #fff;
}
#navbar ul {
    padding: 0;
    list-style: none;
}
#navbar li {
    display: inline;
}
#navbar a {
    color: #fff;
    text-decoration: none;
    font-size: 18px;
    padding-right: 15px;
}
#showcase {
    background-image: url('../images/background.jpg');
    background-position: center right;
    min-height: 300px;
    margin-bottom: 30px;
    text-align: center;
}
#showcase h1 {
    color: #fff;
    font-size: 50px;
    line-height: 1.6em;
    padding-top: 30px;
}
#main {
    float: left;
    width: 70%;
    padding: 0 30px;
    box-sizing: border-box;
}
#sidebar {
    border-radius: 10px;
    float: right;
    width: 30%;
    background: #444;
    color: #999;
    padding: 0px 15px;
  padding-bottom: 15px;
    box-sizing: border-box;
}
#main-footer {
    background: #222;
    color: #fff;
    text-align: center;
    padding: 20px;
    margin-top: 40px;
}
@media(max-width:600px) {
    #main {
        width: 100%;
        float: none;
    }
    #sidebar {
        width: 100%;
        float: none;
    }
}

/* songscollapsible.css */
.current {
  color: inherit;
}
#pagin li {
  display: inline-block;
}
.collapsible {
  background-color: #444;
  color: #999;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  border: none;
  text-align: left;
  outline: none;
  font-size: 17px;
}
.active, .collapsible:hover {
  background-color: #555;
}
.content {
  max-height: 0;
  padding: 0px 15px 0px 15px;
  overflow: hidden;
  background-color: #666;
  color: #999;
  border-radius: 15px;
  transition: max-height 0.7s ease-out;
}
.button {
  box-shadow: 0px 2px 4px #555;
  border-radius: 15px;
}
/* .limg -> left image */
.limg {
  float: left;
  padding-right: 5px;
  max-width: 20px;
  max-height: 20px;
}
/* .fimg -> front image */
.fimg {
  float: left;
  padding-bottom: 15px;
  max-width: 20%;
}
.pl5 {
  padding-left: 5px;
}
.pl40 {
  padding-left: 40%;
}
.lh1-4 {
  line-height: 1.4;
}
.dli {
  max-width: 17px;
  max-height: 17px;
  padding-right: 5px;
}
a:link {
  text-decoration: none;
  color: #999;
}
a:visited {
  text-decoration: none;
  color: #999;
}
a:hover {
  text-decoration: none;
  color: #999;
}
a:active {
  text-decoration: none;
  color: #999;
}

    <meta charset="utf-8">
    <title>test</title>

test1

test2

test3

test4

test5

test6

Body:
The problem is that on hover they resize and push the other divs aside. You may try this convenient approach to resize them absolute:

a:hover {
    transform: scale(1.1);
}

or keep them as is:

a:hover {
    transform: scale(1.0);
}

(not sure which effect you want to achieve using on:hover


问:
Download multiple files from S3 bucket in the form of Zip file
I am working on an Angular / JavaScript App:

Is there a way to compress (zip) and download multiple files from  a S3 bucket.

OR

Copy the selected files to a dynamic folder and download the folder in the as a zip file from a S3 bucket.

答: Since S3 is just a file storage service, so it won't zip your "folders" on the fly. You can either use the sync command of AWS CLI to download all files whose object keys start with a given prefix, or you need some other AWS service such as Lambda, EC2, Fargate to zip those "folders" before downloading.</p>


问:
Htaccess redirections depending on OS
1- I need the .htaccess code for this condition If the user clicked on:
website1.download
OR
website2.download
It redirects the user depending on his OS for example:

If on PC, redirect to http://google.com/

If on Android, redirect to https://play.google.com/store

If on iOS, redirect to https://www.apple.com/ios/app-store/

2- I've more than one website in my host and I need to create a one .htaccess to all websites in the host, where I can create the .htaccess file?

That is the htaccess codes and it's not working:

```<code><If "req('Host') = 'website1.download' && = 'website2.download'">
    # turn on rewrite engine
    RewriteEngine on

    # only detect smart phone devices if we are not on mobile site
    # to prevent redirect looping
    RewriteCond %{HTTP_HOST} !^https://google.com/$

    # Android
    RewriteCond %{HTTP_USER_AGENT} "android" [NC]
    # redirect to google play
    RewriteRule .? https://play.google.com/store%{REQUEST_URI}  [L,R=302]

    # iOS
    RewriteCond %{HTTP_USER_AGENT} "android" [NC]
    # redirect to app store
    RewriteRule .? https://www.apple.com/ios/app-store/%{REQUEST_URI}  [L,R=302]
</If>
</code>```

答:
Okay, I'm going with example.com and example.net since that's what they are for. Also, I'm assuming these domains point to your server and they have all been bound to it, too. Lastly, I'm assuming you have a pattern already for device detection? It isn't super clear in your question. (If you don't you can probably just base this off Google and this thread.)

You can just stack RewriteCond and join them with an OR

```<code>RewriteCond %{HTTP_HOST} example.com [NC,OR]
RewriteCond %{HTTP_HOST} example.net [NC]
RewriteCond %{HTTP_USER_AGENT} "android" [NC]
RewriteRule .? https://play.google.com/store%{REQUEST_URI}  [L,R=302]
</code>```

Technically that is a regex, too, so some care should be taken for special characters as well as being more specific, adding subdomain support and just merging everything into a single condition.

```<code>RewriteCond %{HTTP_HOST} ^(www\.)?example\.(com|net)$ [NC]
RewriteCond %{HTTP_USER_AGENT} "android" [NC]
RewriteRule .? https://play.google.com/store%{REQUEST_URI}  [L,R=302]
</code>```

There's HTTP_HOST vs SERVER_NAME that you should be aware of, too.

All that said, I can't think of a good reason to do this. From an SEO-perspective, you are going to wind up hiding 2 out of 3 redirects because spiders store information they find at a given URL, and if that changes, the most recent change wins. From a user-perspective,   people are mostly trained to click the badges from the stores, I wouldn't introduce something new and weird. If you are trying to track a click, I'd just use JS.

Title: Htaccess redirections depending on OS

Body:
1- I need the .htaccess code for this condition If the user clicked on:
website1.download
OR
website2.download
It redirects the user depending on his OS for example:

If on PC, redirect to http://google.com/

If on Android, redirect to https://play.google.com/store

If on iOS, redirect to https://www.apple.com/ios/app-store/

2- I've more than one website in my host and I need to create a one .htaccess to all websites in the host, where I can create the .htaccess file?

That is the htaccess codes and it's not working:

<If "req('Host') = 'website1.download' && = 'website2.download'">
    # turn on rewrite engine
    RewriteEngine on

    # only detect smart phone devices if we are not on mobile site
    # to prevent redirect looping
    RewriteCond %{HTTP_HOST} !^https://google.com/$

    # Android
    RewriteCond %{HTTP_USER_AGENT} "android" [NC]
    # redirect to google play
    RewriteRule .? https://play.google.com/store%{REQUEST_URI}  [L,R=302]

    # iOS
    RewriteCond %{HTTP_USER_AGENT} "android" [NC]
    # redirect to app store
    RewriteRule .? https://www.apple.com/ios/app-store/%{REQUEST_URI}  [L,R=302]
</If>

Body:
Okay, I'm going with example.com and example.net since that's what they are for. Also, I'm assuming these domains point to your server and they have all been bound to it, too. Lastly, I'm assuming you have a pattern already for device detection? It isn't super clear in your question. (If you don't you can probably just base this off Google and this thread.)

You can just stack RewriteCond and join them with an OR

RewriteCond %{HTTP_HOST} example.com [NC,OR]
RewriteCond %{HTTP_HOST} example.net [NC]
RewriteCond %{HTTP_USER_AGENT} "android" [NC]
RewriteRule .? https://play.google.com/store%{REQUEST_URI}  [L,R=302]

Technically that is a regex, too, so some care should be taken for special characters as well as being more specific, adding subdomain support and just merging everything into a single condition.

RewriteCond %{HTTP_HOST} ^(www\.)?example\.(com|net)$ [NC]
RewriteCond %{HTTP_USER_AGENT} "android" [NC]
RewriteRule .? https://play.google.com/store%{REQUEST_URI}  [L,R=302]

There's HTTP_HOST vs SERVER_NAME that you should be aware of, too.

All that said, I can't think of a good reason to do this. From an SEO-perspective, you are going to wind up hiding 2 out of 3 redirects because spiders store information they find at a given URL, and if that changes, the most recent change wins. From a user-perspective,   people are mostly trained to click the badges from the stores, I wouldn't introduce something new and weird. If you are trying to track a click, I'd just use JS.


问:
Check if stdin has a white spaces

How to check if in stdin it has a white spaces ?
In this example I want to count all white spaces in av[1].
But I don't know how to represent white spaces begin with a '\' in av[1].

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

int main(int ac, char **av)
{
    int count;

    count = 0;
    if (ac == 2)
    {
        while (*av[1])
        {
            if (*av[1] == ' '|| *av[1] == '\t'||*av[1] == '\r'|| *av[1] == '\v'||*av[1] == '\n'||*av[1] == '\f')
            {
                count++;
            }
            av[1]++;
        }
        printf("%d\n",count);
    }
    else
        printf("Error\n");

    return(0);
}
</code>```

Intput

```<code>./a.out "\n"
</code>```

Output

```<code>0
</code>```

答:
Your problem is that the shell does some magic before passing the arguments. If you send the arguments quoted it will work:

```<code>$ ./a.out "this string has four spaces"
4
</code>```

At least it will work for spaces. How whitespaces are escaped is shell dependent.

Title: Check if stdin has a white spaces

Body:
How to check if in stdin it has a white spaces ?
In this example I want to count all white spaces in av[1].
But I don't know how to represent white spaces begin with a '\' in av[1].

#include <stdio.h>

int main(int ac, char **av)
{
    int count;

    count = 0;
    if (ac == 2)
    {
        while (*av[1])
        {
            if (*av[1] == ' '|| *av[1] == '\t'||*av[1] == '\r'|| *av[1] == '\v'||*av[1] == '\n'||*av[1] == '\f')
            {
                count++;
            }
            av[1]++;
        }
        printf("%d\n",count);
    }
    else
        printf("Error\n");

    return(0);
}

Intput

./a.out "\n"

Output

0

Body:
Your problem is that the shell does some magic before passing the arguments. If you send the arguments quoted it will work:

$ ./a.out "this string has four spaces"
4

At least it will work for spaces. How whitespaces are escaped is shell dependent.


问:
P5.js ellipse not following mouseX and Y
I am not sure why but the "invisible circle" is not align with the mouseX and Y and i ended up hard coding it. Anyone know why this happens?

If i just wrote (mouseX,mouseY) the ellipse will be around 300 units away from the cusor.

Is there any way fix it/ improve it?
Without setting exact value such as mouseX-300?

Thanks

*not much details i can think of for now.not much details i can think of for now.not much details i can think of for now.

let cubes = [];

function setup() {
  createCanvas(windowWidth, windowHeight, WEBGL);
  backCol = color(243, 243, 243);
  //background(backCol);

  for (let i = 0; i < 10; i++) {
    for (let j = 0; j < 10; j++) {
      let xPos = map(i, 0, 9, 50, width - 50);
      let yPos = map(j, 0, 9, 50, height - 50);

      cubes.push(new Cubes(xPos, yPos));

    }
  }

}

function draw() {
  background(backCol);
  noFill();

  for (let a = 0; a < cubes.length; a++) {
    cubes[a].update();
  }
}

class Cubes {

  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.size = 30;
    this.stroke = 70;
    this.shift1 = color(96);
    this.shift2 = color(244);
  }

  update() {
    this.shape();
    this.shift_Color();
    this.Invisible_Circle();
  }

  Invisible_Circle () {
    push();
    stroke(10);
    //noFill();
    // translate(mouseX,mouseY);
    ellipse(mouseX - 280,mouseY - 280,200);
    pop();
  }

  shape() {
    push();
    stroke(this.stroke);
    translate(this.x - width / 2, this.y - height / 2, 0);
    this.magnetic()
    box(this.size);
    pop();
  }

  shift_Color() {
    let distance = dist(mouseX, mouseY, this.x, this.y);
    let shiftX = map(mouseX, 0, this.a, 0, 1.0);
    let change = lerpColor(this.shift1, this.shift2, shiftX);

    if (distance < this.a) {
      fill(change);
    } else {
      noFill();
    }
  }

  magnetic() {
    let distance = dist(mouseX, mouseY, this.x, this.y);

    if (distance < this.size * 3) {
      this.a = atan2(mouseY - this.y, mouseX - this.x);
      rotateX(this.a);
      rotateY(this.a);
    } else {
      rotateX(millis() / 1000);
      rotateY(millis() / 1000);
    }
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script></code>```

答:
In WEBGL mode (createCanvas()) the center of the screen is by default (0, 0). Anyway, the top left coordinate of the window is still (0, 0). Hence you have to translate the mouse position, by (-width/2, -height/2):

ellipse(mouseX - width/2, mouseY - height/2, 200);
```

<p>Furthermore <code>Invisible_Circle</code> should not a method of <code>Cubes</code>:</p>

<pre class="lang-js prettyprint-override"><code>function Invisible_Circle () {
    stroke(10);
    //noFill();
    ellipse(mouseX - width/2, mouseY - height/2, 200);
}

class Cubes {

  constructor(x, y) {
    // [...]
</code>```

And has to be called  after drawing the boxes:

function draw() {
  background(backCol);
  Invisible_Circle();
  noFill();

  for (let a = 0; a < cubes.length; a++) {
    cubes[a].update();
  }
  Invisible_Circle();
}
```

<p>See the example:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let cubes = [];

function setup() {
  createCanvas(windowWidth, windowHeight, WEBGL);
  backCol = color(243, 243, 243);
  //background(backCol);

  for (let i = 0; i < 10; i++) {
    for (let j = 0; j < 10; j++) {
      let xPos = map(i, 0, 9, 50, width - 50);
      let yPos = map(j, 0, 9, 50, height - 50);

      cubes.push(new Cubes(xPos, yPos));
    }
  }
}

function draw() {
  background(backCol);
  Invisible_Circle();
  noFill();

  for (let a = 0; a < cubes.length; a++) {
    cubes[a].update();
  }
  Invisible_Circle();
}

function Invisible_Circle () {
    stroke(10);
    //noFill();
    ellipse(mouseX - width/2, mouseY - height/2, 200);
}

class Cubes {

  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.size = 30;
    this.stroke = 70;
    this.shift1 = color(96);
    this.shift2 = color(244);
  }

  update() {
    this.shape();
    this.shift_Color();
  }

  shape() {
    push();
    stroke(this.stroke);
    translate(this.x - width / 2, this.y - height / 2, 0);
    this.magnetic()
    box(this.size);
    pop();
  }

  shift_Color() {
    let distance = dist(mouseX, mouseY, this.x, this.y);
    let shiftX = map(mouseX, 0, this.a, 0, 1.0);
    let change = lerpColor(this.shift1, this.shift2, shiftX);

    if (distance < this.a) {
      fill(change);
    } else {
      noFill();
    }
  }

  magnetic() {
    let distance = dist(mouseX, mouseY, this.x, this.y);

    if (distance < this.size * 3) {
      this.a = atan2(mouseY - this.y, mouseX - this.x);
      rotateX(this.a);
      rotateY(this.a);
    } else {
      rotateX(millis() / 1000);
      rotateY(millis() / 1000);
    }
  }
}</code>```

```

Body:
In WEBGL mode (createCanvas()) the center of the screen is by default (0, 0). Anyway, the top left coordinate of the window is still (0, 0). Hence you have to translate the mouse position, by (-width/2, -height/2):

ellipse(mouseX - width/2, mouseY - height/2, 200);

Furthermore Invisible_Circle should not a method of Cubes:

function Invisible_Circle () {
    stroke(10);
    //noFill();
    ellipse(mouseX - width/2, mouseY - height/2, 200);
}

class Cubes {

  constructor(x, y) {
    // [...]

And has to be called  after drawing the boxes:

function draw() {
  background(backCol);
  Invisible_Circle();
  noFill();

  for (let a = 0; a < cubes.length; a++) {
    cubes[a].update();
  }
  Invisible_Circle();
}

See the example:

let cubes = [];

function setup() {
  createCanvas(windowWidth, windowHeight, WEBGL);
  backCol = color(243, 243, 243);
  //background(backCol);

  for (let i = 0; i < 10; i++) {
    for (let j = 0; j < 10; j++) {
      let xPos = map(i, 0, 9, 50, width - 50);
      let yPos = map(j, 0, 9, 50, height - 50);

      cubes.push(new Cubes(xPos, yPos));
    }
  }
}

function draw() {
  background(backCol);
  Invisible_Circle();
  noFill();

  for (let a = 0; a < cubes.length; a++) {
    cubes[a].update();
  }
  Invisible_Circle();
}

function Invisible_Circle () {
    stroke(10);
    //noFill();
    ellipse(mouseX - width/2, mouseY - height/2, 200);
}

class Cubes {

  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.size = 30;
    this.stroke = 70;
    this.shift1 = color(96);
    this.shift2 = color(244);
  }

  update() {
    this.shape();
    this.shift_Color();
  }

  shape() {
    push();
    stroke(this.stroke);
    translate(this.x - width / 2, this.y - height / 2, 0);
    this.magnetic()
    box(this.size);
    pop();
  }

  shift_Color() {
    let distance = dist(mouseX, mouseY, this.x, this.y);
    let shiftX = map(mouseX, 0, this.a, 0, 1.0);
    let change = lerpColor(this.shift1, this.shift2, shiftX);

    if (distance < this.a) {
      fill(change);
    } else {
      noFill();
    }
  }

  magnetic() {
    let distance = dist(mouseX, mouseY, this.x, this.y);

    if (distance < this.size * 3) {
      this.a = atan2(mouseY - this.y, mouseX - this.x);
      rotateX(this.a);
      rotateY(this.a);
    } else {
      rotateX(millis() / 1000);
      rotateY(millis() / 1000);
    }
  }
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>


问:
UnoPlatform -The application called an interface that was marshalled for a different thread
i am using Uno prism template for my Uno platform App. After making an async call in UWP app. i.e.

var content = await GetHttpContentWithTokenAsync(graphAPIEndpoint,authResult.AccessToken).ConfigureAwait(false);
```

whenever RaisePropertyChanged() method hits I am getting following error=>

{"The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))"}

Git repo=> https://github.com/avikeid2007/Repayabl

File=> https://github.com/avikeid2007/Repayabl/blob/dev/RepayablClient/RepayablClient.Shared/ViewModels/LoginViewModel.cs#L131

答:
As mentioned in the comment, the problem here is the use of .ConfigureAwait(false).

With ConfigureAwait(false) you're telling the compiler, 'after this awaited method executes, don't bother coming back to the current context, I'm good.' In some cases this can be an appropriate optimization, or even a guard against deadlocking, particularly when you're writing a class library.

However you normally shouldn't use it in callbacks from the UI thread, like this case. In UWP and indeed most UI frameworks, you can only modify the UI from the main UI thread, otherwise you will get exactly the error you mention. So you need to be returned to the same context after the awaited method completes.

TLDR: Remove ConfigureAwait(false), don't use it in async methods invoked from the UI thread.

Body:
i am using Uno prism template for my Uno platform App. After making an async call in UWP app. i.e.

var content = await GetHttpContentWithTokenAsync(graphAPIEndpoint,authResult.AccessToken).ConfigureAwait(false);

whenever RaisePropertyChanged() method hits I am getting following error=>

{"The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))"}

Git repo=> https://github.com/avikeid2007/Repayabl

File=> https://github.com/avikeid2007/Repayabl/blob/dev/RepayablClient/RepayablClient.Shared/ViewModels/LoginViewModel.cs#L131


问:
Diff function Flex
I am looking for a way to compare two XML files (old and new) and copy to an array all the nodes that are present in the new version but not the old version. I think it should be relatively straight forward to, for each node in the new XML file, iterate through the old XML file and see if it's found ... however, I do not think this is an efficient solution for large XML files (<10k nodes). I am wondering if there is a better solution - either algorithmic or function in Flex - to accomplish this task.

Thanks for all the assistance!

答: I'd look into algorithms which SVN merge tools use and use one those on the raw text, create an XML out of the diff and only parse that.</p>

Title: Diff function Flex