问:
Search complexity of Dictionary<TKey,TValue> vs List<T>
I've been doing some reading on the generic Dictionary class and the general advice is to use Dictionary if you need really fast access to an item matching a specific key. This is because a dictionary is using a type-safe Hashtable under the hood. When accessing items the search complexity is O(1) in dictionaries whereas in a List we would need to loop through EVERY SINGLE item until we find a match making the complexity O(n).

I wrote a little console app to see just how significant the difference between the two would be. The app stores 10 million items in each collection and attempts to access the second last item. The time difference between the List and Dictionary<TKey,TValue> is only one second, making the dictionary a winner but only just.

Question - can you provide an example(verbal is fine) where using a Dictionary vs a List would  yield significant performance improvements?

```<code>class Program
{
    static void Main(string[] args)
    {
        var iterations = 10000000;//10 million

        var sw = new Stopwatch();

        sw.Start();
        var value1 = GetSecondLastFromDictionary(iterations);
        sw.Stop();
        var t1 = sw.Elapsed.ToString();
        sw.Restart();

        var value2 = GetSecondLastFromList(iterations);

        sw.Stop();
        var t2 = sw.Elapsed.ToString();

        Console.WriteLine($"Dictionary - {t1}\nList - {t2}");
        Console.ReadKey();
    }

    private static string GetSecondLastFromList(int iterations)
    {
        var collection = new List<Test>();
        for (var i = 0; i < iterations; i++)
            collection.Add(new Test { Key = i, Value = $"#{i}" });
        return collection.Where(e => e.Key == iterations - 1).First().Value;
    }

    private static string GetSecondLastFromDictionary(int iterations)
    {
        var collection = new Dictionary<int, string>();
        for (var i = 0; i < iterations; i++)
            collection.Add(i, $"#{i}");
        return collection[iterations - 1];
    }
}
class Test
{
    public int Key { get; set; }
    public string Value { get; set; }
}
</code>```

答:
Your own example is fine to show where using a Dictionary yields significant performance improvements.  The problem is you're not looking at the right thing.  Your code spends a lot of time creating the dictionary or list and then does just one access of it.  You need to separate out the collection creation and time multiple accesses of the item.

The code below does this.  I get multiple accesses of the dictionary take 0.001s, whereas of the list the same number of accesses takes 2 minutes 32 seconds.  Assuming I've done that right I think it shows dictionaries are faster for access.

```<code>    static void Main(string[] args)
    {
        var iterations = 100000;

        var sw = new Stopwatch();
        var dict = CreateDict(iterations);
        var list = CreateList(iterations);
        sw.Start();
        GetSecondLastFromDictionary(iterations, dict);
        sw.Stop();
        var t1 = sw.Elapsed.ToString();
        sw.Restart();
        GetSecondLastFromList(iterations, list);
        sw.Stop();
        var t2 = sw.Elapsed.ToString();

        Console.WriteLine($"Dictionary - {t1}\nList - {t2}");
        Console.ReadKey();
    }

    private static Dictionary<int, string> CreateDict(int iterations)
    {
        var collection = new Dictionary<int, string>();
        for (var i = 0; i < iterations; i++)
            collection.Add(i, $"#{i}");
        return collection;
    }

    private static List<Test> CreateList(int iterations)
    {
        var collection = new List<Test>();
        for (var i = 0; i < iterations; i++)
            collection.Add(new Test { Key = i, Value = $"#{i}" });
        return collection;
    }

    private static void GetSecondLastFromList(int iterations, List<Test> collection)
    {
        string test;
        for (var i = 0; i < iterations; i++)
            test = collection.Where(e => e.Key == iterations - 1).First().Value;
    }

    private static void GetSecondLastFromDictionary(int iterations, Dictionary<int, string> collection)
    {
        string test;
        for (var i = 0; i < iterations; i++)
            test = collection[iterations - 1];
    }
}
</code>```

Body:
I've been doing some reading on the generic Dictionary class and the general advice is to use Dictionary if you need really fast access to an item matching a specific key. This is because a dictionary is using a type-safe Hashtable under the hood. When accessing items the search complexity is O(1) in dictionaries whereas in a List we would need to loop through EVERY SINGLE item until we find a match making the complexity O(n).

I wrote a little console app to see just how significant the difference between the two would be. The app stores 10 million items in each collection and attempts to access the second last item. The time difference between the List and Dictionary<TKey,TValue> is only one second, making the dictionary a winner but only just.

Question - can you provide an example(verbal is fine) where using a Dictionary vs a List would  yield significant performance improvements?

class Program
{
    static void Main(string[] args)
    {
        var iterations = 10000000;//10 million

        var sw = new Stopwatch();

        sw.Start();
        var value1 = GetSecondLastFromDictionary(iterations);
        sw.Stop();
        var t1 = sw.Elapsed.ToString();
        sw.Restart();

        var value2 = GetSecondLastFromList(iterations);

        sw.Stop();
        var t2 = sw.Elapsed.ToString();

        Console.WriteLine($"Dictionary - {t1}\nList - {t2}");
        Console.ReadKey();
    }

    private static string GetSecondLastFromList(int iterations)
    {
        var collection = new List<Test>();
        for (var i = 0; i < iterations; i++)
            collection.Add(new Test { Key = i, Value = $"#{i}" });
        return collection.Where(e => e.Key == iterations - 1).First().Value;
    }

    private static string GetSecondLastFromDictionary(int iterations)
    {
        var collection = new Dictionary<int, string>();
        for (var i = 0; i < iterations; i++)
            collection.Add(i, $"#{i}");
        return collection[iterations - 1];
    }
}
class Test
{
    public int Key { get; set; }
    public string Value { get; set; }
}

Body:
Your own example is fine to show where using a Dictionary yields significant performance improvements.  The problem is you're not looking at the right thing.  Your code spends a lot of time creating the dictionary or list and then does just one access of it.  You need to separate out the collection creation and time multiple accesses of the item.

The code below does this.  I get multiple accesses of the dictionary take 0.001s, whereas of the list the same number of accesses takes 2 minutes 32 seconds.  Assuming I've done that right I think it shows dictionaries are faster for access.

    static void Main(string[] args)
    {
        var iterations = 100000;

        var sw = new Stopwatch();
        var dict = CreateDict(iterations);
        var list = CreateList(iterations);
        sw.Start();
        GetSecondLastFromDictionary(iterations, dict);
        sw.Stop();
        var t1 = sw.Elapsed.ToString();
        sw.Restart();
        GetSecondLastFromList(iterations, list);
        sw.Stop();
        var t2 = sw.Elapsed.ToString();

        Console.WriteLine($"Dictionary - {t1}\nList - {t2}");
        Console.ReadKey();
    }

    private static Dictionary<int, string> CreateDict(int iterations)
    {
        var collection = new Dictionary<int, string>();
        for (var i = 0; i < iterations; i++)
            collection.Add(i, $"#{i}");
        return collection;
    }

    private static List<Test> CreateList(int iterations)
    {
        var collection = new List<Test>();
        for (var i = 0; i < iterations; i++)
            collection.Add(new Test { Key = i, Value = $"#{i}" });
        return collection;
    }

    private static void GetSecondLastFromList(int iterations, List<Test> collection)
    {
        string test;
        for (var i = 0; i < iterations; i++)
            test = collection.Where(e => e.Key == iterations - 1).First().Value;
    }

    private static void GetSecondLastFromDictionary(int iterations, Dictionary<int, string> collection)
    {
        string test;
        for (var i = 0; i < iterations; i++)
            test = collection[iterations - 1];
    }
}


来源: stackexchange

问:
How to access USDZ schema at runtime
From what I have read at https://developer.apple.com/documentation/arkit/usdz_schemas_for_ar it looks like you can do some great AR stuff like anchoring all from within the USDZ file itself.

I understand you can access this schema with python, but I would like to access the schema at runtime with Swift. Is that possible?

答:
At the moment (February 2022) – no way!

Let's wait for AR USD schemas API.

ContentLicense: CC BY-SA 4.0

Title: How to access USDZ schema at runtime


问:
replicate rows by n times in python
I have a dataframe that the first column are strings, the 2nd column are the numbers that I want to replicate each string.

```<code>df = pd.DataFrame({'String':['a','b', 'c', 'd', 'e', 'f', 'g'],
        'Times':[2, 3, 5, 3, 2, 4, 5]})
df
</code>```

String
Times

a
2

b
3

c
5

d
3

e
2

f
4

g
5

How can I create a data frame into this in python? (stopped at d but you know the pattern). Thanks!

String
Times

a
1

a
2

b
1

b
2

b
3

c
1

c
2

c
3

c
4

c
5

答:
Use df.explode. Make this work by converting your repetitions to list:

```<code>s = ['a','b', 'c', 'd', 'e', 'f', 'g']
t = [2, 3, 5, 3, 2, 4, 5]
</code>```

Then,

```<code>times = [list(range(i + 1)) for i in t]
df = pd.DataFrame({'string': s, 'times': times}).explode('times')
</code>```

```<code>>>> df.head(10)
  string times
0      a     0
0      a     1
0      a     2
1      b     0
1      b     1
1      b     2
1      b     3
2      c     0
2      c     1
2      c     2
</code>```

If you don't want the index repeated like that, df.reset_index(drop=True, inplace=True) (if in place, otherwise, reassign). If you want 1-indexing rather than 0-indexing, for list(range(i + 1)) substitute list(range(1, i + 2)). Alternatively, just add one to the times column at the end. The times column doesn't really matter for df.explode, it explodes based on repetitions anyway.

Title: replicate rows by n times in python

Body:
I have a dataframe that the first column are strings, the 2nd column are the numbers that I want to replicate each string.

df = pd.DataFrame({'String':['a','b', 'c', 'd', 'e', 'f', 'g'],
        'Times':[2, 3, 5, 3, 2, 4, 5]})
df

String
Times

a
2

b
3

c
5

d
3

e
2

f
4

g
5

How can I create a data frame into this in python? (stopped at d but you know the pattern). Thanks!

String
Times

a
1

a
2

b
1

b
2

b
3

c
1

c
2

c
3

c
4

c
5

Body:
Use df.explode. Make this work by converting your repetitions to list:

s = ['a','b', 'c', 'd', 'e', 'f', 'g']
t = [2, 3, 5, 3, 2, 4, 5]

Then,

times = [list(range(i + 1)) for i in t]
df = pd.DataFrame({'string': s, 'times': times}).explode('times')

>>> df.head(10)
  string times
0      a     0
0      a     1
0      a     2
1      b     0
1      b     1
1      b     2
1      b     3
2      c     0
2      c     1
2      c     2

If you don't want the index repeated like that, df.reset_index(drop=True, inplace=True) (if in place, otherwise, reassign). If you want 1-indexing rather than 0-indexing, for list(range(i + 1)) substitute list(range(1, i + 2)). Alternatively, just add one to the times column at the end. The times column doesn't really matter for df.explode, it explodes based on repetitions anyway.


问:
Javascript or jquery change fields value by name
I use these codes to change the value of a field. Only the first two lines run, I tried the rest of the code but it did not work and sometimes the message "Uncaught ReferenceError: $ is not defined" is displayed on the console.

```<code>document.getElementsByName('tmcp_textfield_6').value = Pak;
document.getElementById("tmcp_textfield_116202d52cbd078").value = Pak;
$("input[name='tmcp_textfield_6']").val(Pak);
document.getElementsByName("tmcp_textfield_6").value = 100;
document.getElementByname("tmcp_textfield_6").value = "100";
$("input[name='tmcp_textfield_6']").val(Pak);
</code>```

答:
Find the Working Script here, I think you should switch quotes, where double quotes use single, and where single quotes, use double.

var Pak = "Test"
$('input[name="tmcp_textfield_6"]').val(Pak)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="tmcp_textfield_6"></code>```

Be sure you've also included the jquery file to whatever page you need it to work on

Body:
I use these codes to change the value of a field. Only the first two lines run, I tried the rest of the code but it did not work and sometimes the message "Uncaught ReferenceError: $ is not defined" is displayed on the console.

document.getElementsByName('tmcp_textfield_6').value = Pak;
document.getElementById("tmcp_textfield_116202d52cbd078").value = Pak;
$("input[name='tmcp_textfield_6']").val(Pak);
document.getElementsByName("tmcp_textfield_6").value = 100;
document.getElementByname("tmcp_textfield_6").value = "100";
$("input[name='tmcp_textfield_6']").val(Pak);

Body:
Find the Working Script here, I think you should switch quotes, where double quotes use single, and where single quotes, use double.

var Pak = "Test"
$('input[name="tmcp_textfield_6"]').val(Pak)

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="tmcp_textfield_6">

Be sure you've also included the jquery file to whatever page you need it to work on


问:
redis: delete oldest keys when memory limited
I have keys I want to keep indefinitely in redis provided I have enough memory.  However, if redis runs low on memory, then I'd like it to remove the oldest keys first.  I looked at the "eviction policy" options and it appears redis doesn't support this out of the box.  https://support.redislabs.com/hc/en-us/articles/203290657-What-eviction-policies-do-you-support-

How could I implement this myself using commands available as part of the redis-client api?

Here's some pseudocode that might work to give a flavor for what I need:

```<code>1.  Get the first N keys from a list sorted by key date asc.
2.  Delete the oldest keys.
3.  Repeat until memory is no longer constrained.
</code>```

答:
The eviction policy determines what happens when a database reaches its memory limit. To make room for new data, older data is evicted (removed) according to the selected policy.

You can select the policies from the reference link below based on your requirement. The one I am using in the example below is "allkeys-lru"

reference link

Example -

```<code>127.0.0.1:6379> CONFIG SET maxmemory-policy allkeys-lru

OK
</code>```

Example in Python -

```<code>import redis
client = redis.Redis(host='localhost', port=6379, db=0)
client.config_set('maxmemory-policy', "allkeys-lru")
</code>```

Body:
I have keys I want to keep indefinitely in redis provided I have enough memory.  However, if redis runs low on memory, then I'd like it to remove the oldest keys first.  I looked at the "eviction policy" options and it appears redis doesn't support this out of the box.  https://support.redislabs.com/hc/en-us/articles/203290657-What-eviction-policies-do-you-support-

How could I implement this myself using commands available as part of the redis-client api?

Here's some pseudocode that might work to give a flavor for what I need:

1.  Get the first N keys from a list sorted by key date asc.
2.  Delete the oldest keys.
3.  Repeat until memory is no longer constrained.

Body:
The eviction policy determines what happens when a database reaches its memory limit. To make room for new data, older data is evicted (removed) according to the selected policy.

You can select the policies from the reference link below based on your requirement. The one I am using in the example below is "allkeys-lru"

reference link

Example -

127.0.0.1:6379> CONFIG SET maxmemory-policy allkeys-lru

OK

Example in Python -

import redis
client = redis.Redis(host='localhost', port=6379, db=0)
client.config_set('maxmemory-policy', "allkeys-lru")


问:
dplyr solution: absolute difference of two values in one column matched by other column
I have a dataframe that looks like this, but there will be many more IDs:

```<code># Groups:   ID [1]
      ID   ARS stim
   <int> <int> <chr>
 1     3     0 1
 2     3     4 2
 3     3     2 3
 4     3     3 4
 5     3     1 5
 6     3     0 6
 7     3     2 10
 8     3     4 11
 9     3     0 12
10     3     3 13
11     3     2 14
12     3     2 15
</code>```

I would like to calculate the sum of the absolute difference abs() between the values in ARS, e.g. for stim=1 and stim=10 plus for stim=2 and stim=11 and so on.
Any good solutions are appreciated!

The desired output calculation is:

```<code>abs(0-2) + abs(4-4) + abs(2-0) + abs(3-3) + abs(1-2) + abs(0-2)
</code>```

Hence, 2+0+2+0+1+2
Output for ID==3: 7

Body:
I have a dataframe that looks like this, but there will be many more IDs:

# Groups:   ID [1]
      ID   ARS stim
   <int> <int> <chr>
 1     3     0 1
 2     3     4 2
 3     3     2 3
 4     3     3 4
 5     3     1 5
 6     3     0 6
 7     3     2 10
 8     3     4 11
 9     3     0 12
10     3     3 13
11     3     2 14
12     3     2 15

I would like to calculate the sum of the absolute difference abs() between the values in ARS, e.g. for stim=1 and stim=10 plus for stim=2 and stim=11 and so on.
Any good solutions are appreciated!

The desired output calculation is:

abs(0-2) + abs(4-4) + abs(2-0) + abs(3-3) + abs(1-2) + abs(0-2)

Hence, 2+0+2+0+1+2
Output for ID==3: 7

Body:
A possible solution:

library(dplyr)

df <- structure(list(ID = c(3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3), ARS = c(0, 4, 2, 3, 1, 0, 2, 4, 0, 3, 2, 2), stim = c(1, 2, 3, 4, 5, 6,
                                                                                10, 11, 12, 13, 14, 15)), row.names = c(NA, -12L), class = "data.frame")

df %>%
  group_by(ID) %>%
  summarise(value = abs(ARS[which(stim == 1:6)] - ARS[which(stim == 9+1:6)]),
            .groups = "drop") %>%
  pull(value) %>% sum

#> [1] 7


问:
Dependency injection for generic interface with some parameters
I want to give parameters when injecting generic types. Is this possible?

My generic type definition:

```<code>public interface IApiClient<T> where T : class
{

}

public class ApiClient<T> : IApiClient<T> where T : class
{
    public ApiClient(string baseAddress = "", string endpoint = "")
    {
        //some codes
    }
}
</code>```

My implementation is:

```<code>services.AddSingleton(typeof(IApiClient<>), typeof(ApiClient<>));
</code>```

How do I give baseAddress and endpoint in this usage?

Thanks.

答:
You can make separate class for the constructor parameters.

For example based on your code:

```<code>public class ApiClientSettings
{
    public string BaseAddress { get; set; }
    public string Endpoint { get; set; }
}
</code>```

Create an instance of the ApiClientSettings (or even you can simply get values from appsettings.json file). Then register ApiClientSettings in the container.

```<code>var apiClientSettings = new ApiClientSettings
{
    BaseAddress = "address",
    Endpoint = "endpoint"
};
services.AddSingleton(apiClientSettings);
</code>```

Inject settings class to your ApiClient

```<code>public class ApiClient<T> : IApiClient<T> where T : class
{
    public ApiClient(ApiClientSettings settings)
    {
        //some codes
    }
}
</code>```

Body:
I want to give parameters when injecting generic types. Is this possible?

My generic type definition:

public interface IApiClient<T> where T : class
{

}

public class ApiClient<T> : IApiClient<T> where T : class
{
    public ApiClient(string baseAddress = "", string endpoint = "")
    {
        //some codes
    }
}

My implementation is:

services.AddSingleton(typeof(IApiClient<>), typeof(ApiClient<>));

How do I give baseAddress and endpoint in this usage?

Thanks.

Body:
You can make separate class for the constructor parameters.

For example based on your code:

public class ApiClientSettings
{
    public string BaseAddress { get; set; }
    public string Endpoint { get; set; }
}

Create an instance of the ApiClientSettings (or even you can simply get values from appsettings.json file). Then register ApiClientSettings in the container.

var apiClientSettings = new ApiClientSettings
{
    BaseAddress = "address",
    Endpoint = "endpoint"
};
services.AddSingleton(apiClientSettings);

Inject settings class to your ApiClient

public class ApiClient<T> : IApiClient<T> where T : class
{
    public ApiClient(ApiClientSettings settings)
    {
        //some codes
    }
}


问:
Android - No Activity found to handle HTTPS CustomTabsIntent
I have an app in production and some users get a weird ActivityNotFoundException about a VIEW https intent. I cannot reproduce it locally on my physical device or emulator. I also assume that every Android has a browser to open URLs by default, am I wrong? (None of the devices that encounter the bug is rooted). Could the problem be because the phone doesn't have chrome?

I use CustomTabsIntent to open the URLs:

```<code>public static void openUrl(final Uri url, final Activity activity) {
        CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
        builder.setToolbarColor(ContextCompat.getColor(activity, R.color.denis_red));
        builder.setCloseButtonIcon(
                BitmapFactory.decodeResource(activity.getResources(),
                        R.drawable.ic_arrow_back_white_24dp));
        builder.setStartAnimations(activity, R.anim.activity_slide_in_right,
                R.anim.activity_slide_out_left);
        builder.setExitAnimations(activity, R.anim.activity_slide_in_left,
                R.anim.activity_slide_out_right);
        builder.build().launchUrl(activity, url);
    }
</code>```

I add some of the stack traces if it can help. Thanks!

1:

```<code>android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=https://redirect.denis.de/... (has extras) }
    at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:2031)
    at android.app.Instrumentation.execStartActivity(Instrumentation.java:1686)
    at android.app.Activity.startActivityForResult(Activity.java:4506)
    at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:767)
    at android.app.Activity.startActivity(Activity.java:4825)
    at android.support.v4.content.ContextCompat.startActivity(ContextCompat.java:248)
    at android.support.customtabs.CustomTabsIntent.launchUrl(CustomTabsIntent.java:263)
    at de.boxine.denisapp.util.web.ChromeTabUtil.openUrl(ChromeTabUtil.java:26)
    at de.boxine.denisapp.denis.list.DenisListActivity.onOptionsItemSelected(DenisListActivity.java:82)
    at android.app.Activity.onMenuItemSelected(Activity.java:3469)
    at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:436)
    at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:196)
    at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:109)
    at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:109)
    at android.support.v7.app.ToolbarActionBar$2.onMenuItemClick(ToolbarActionBar.java:64)
    at android.support.v7.widget.Toolbar$1.onMenuItemClick(Toolbar.java:204)
    at android.support.v7.widget.ActionMenuView$MenuBuilderCallback.onMenuItemSelected(ActionMenuView.java:781)
    at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:840)
    at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:158)
    at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:991)
    at android.support.v7.view.menu.MenuPopup.onItemClick(MenuPopup.java:128)
    at android.widget.AdapterView.performItemClick(AdapterView.java:318)
    at android.widget.AbsListView.performItemClick(AbsListView.java:1158)
    at android.widget.AbsListView$PerformClick.run(AbsListView.java:3153)
    at android.widget.AbsListView$3.run(AbsListView.java:4068)
    at android.os.Handler.handleCallback(Handler.java:790)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6626)
    at java.lang.reflect.Method.invoke(Method.java)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:811)
</code>```

2:

```<code>android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=https://redirect.denis.de/... (has extras) }
    at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1981)
    at android.app.Instrumentation.execStartActivity(Instrumentation.java:1636)
    at android.app.Activity.startActivityForResult(Activity.java:4762)
    at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:767)
    at android.app.Activity.startActivity(Activity.java:5119)
    at android.support.v4.content.ContextCompat.startActivity(ContextCompat.java:248)
    at android.support.customtabs.CustomTabsIntent.launchUrl(CustomTabsIntent.java:263)
    at de.boxine.denisapp.util.web.ChromeTabUtil.openUrl(ChromeTabUtil.java:26)
    at de.boxine.denisapp.login.LoginActivity.openUrl(LoginActivity.java:205)
    at de.boxine.denisapp.login.LoginPresenter.onPasswordForgetLinkClicked(LoginPresenter.java:93)
    at de.boxine.denisapp.login.LoginActivity.lambda$onCreate$2$LoginActivity(LoginActivity.java:153)
    at de.boxine.denisapp.login.-$$Lambda$LoginActivity$HDjhvwi_2M2aWu9LndZHRP-ar9Q.onClick
    at android.view.View.performClick(View.java:6291)
    at android.view.View$PerformClick.run(View.java:24931)
    at android.os.Handler.handleCallback(Handler.java:808)
    at android.os.Handler.dispatchMessage(Handler.java:101)
    at android.os.Looper.loop(Looper.java:166)
    at android.app.ActivityThread.main(ActivityThread.java:7529)
    at java.lang.reflect.Method.invoke(Method.java)
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921)
</code>```

答:
It seems that feature is NOT supported by all browsers on Android. Perhaps this is what is causing the issue.

From the Chrome developer docs (https://developer.chrome.com/docs/android/custom-tabs/): Custom Tabs is a browser feature, introduced by Chrome, that is now supported by most major browsers on Android.

So you need to first check if there is a browser app available to you that supports CustomTabsIntent. This question has several answers that show you how to do that. How can I check whether Chrome supports Chrome custom tabs?

Body:
I have an app in production and some users get a weird ActivityNotFoundException about a VIEW https intent. I cannot reproduce it locally on my physical device or emulator. I also assume that every Android has a browser to open URLs by default, am I wrong? (None of the devices that encounter the bug is rooted). Could the problem be because the phone doesn't have chrome?

I use CustomTabsIntent to open the URLs:

public static void openUrl(final Uri url, final Activity activity) {
        CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
        builder.setToolbarColor(ContextCompat.getColor(activity, R.color.denis_red));
        builder.setCloseButtonIcon(
                BitmapFactory.decodeResource(activity.getResources(),
                        R.drawable.ic_arrow_back_white_24dp));
        builder.setStartAnimations(activity, R.anim.activity_slide_in_right,
                R.anim.activity_slide_out_left);
        builder.setExitAnimations(activity, R.anim.activity_slide_in_left,
                R.anim.activity_slide_out_right);
        builder.build().launchUrl(activity, url);
    }

I add some of the stack traces if it can help. Thanks!

1:

android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=https://redirect.denis.de/... (has extras) }
    at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:2031)
    at android.app.Instrumentation.execStartActivity(Instrumentation.java:1686)
    at android.app.Activity.startActivityForResult(Activity.java:4506)
    at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:767)
    at android.app.Activity.startActivity(Activity.java:4825)
    at android.support.v4.content.ContextCompat.startActivity(ContextCompat.java:248)
    at android.support.customtabs.CustomTabsIntent.launchUrl(CustomTabsIntent.java:263)
    at de.boxine.denisapp.util.web.ChromeTabUtil.openUrl(ChromeTabUtil.java:26)
    at de.boxine.denisapp.denis.list.DenisListActivity.onOptionsItemSelected(DenisListActivity.java:82)
    at android.app.Activity.onMenuItemSelected(Activity.java:3469)
    at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:436)
    at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:196)
    at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:109)
    at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:109)
    at android.support.v7.app.ToolbarActionBar$2.onMenuItemClick(ToolbarActionBar.java:64)
    at android.support.v7.widget.Toolbar$1.onMenuItemClick(Toolbar.java:204)
    at android.support.v7.widget.ActionMenuView$MenuBuilderCallback.onMenuItemSelected(ActionMenuView.java:781)
    at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:840)
    at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:158)
    at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:991)
    at android.support.v7.view.menu.MenuPopup.onItemClick(MenuPopup.java:128)
    at android.widget.AdapterView.performItemClick(AdapterView.java:318)
    at android.widget.AbsListView.performItemClick(AbsListView.java:1158)
    at android.widget.AbsListView$PerformClick.run(AbsListView.java:3153)
    at android.widget.AbsListView$3.run(AbsListView.java:4068)
    at android.os.Handler.handleCallback(Handler.java:790)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6626)
    at java.lang.reflect.Method.invoke(Method.java)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:811)

2:

android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=https://redirect.denis.de/... (has extras) }
    at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1981)
    at android.app.Instrumentation.execStartActivity(Instrumentation.java:1636)
    at android.app.Activity.startActivityForResult(Activity.java:4762)
    at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:767)
    at android.app.Activity.startActivity(Activity.java:5119)
    at android.support.v4.content.ContextCompat.startActivity(ContextCompat.java:248)
    at android.support.customtabs.CustomTabsIntent.launchUrl(CustomTabsIntent.java:263)
    at de.boxine.denisapp.util.web.ChromeTabUtil.openUrl(ChromeTabUtil.java:26)
    at de.boxine.denisapp.login.LoginActivity.openUrl(LoginActivity.java:205)
    at de.boxine.denisapp.login.LoginPresenter.onPasswordForgetLinkClicked(LoginPresenter.java:93)
    at de.boxine.denisapp.login.LoginActivity.lambda$onCreate$2$LoginActivity(LoginActivity.java:153)
    at de.boxine.denisapp.login.-$$Lambda$LoginActivity$HDjhvwi_2M2aWu9LndZHRP-ar9Q.onClick
    at android.view.View.performClick(View.java:6291)
    at android.view.View$PerformClick.run(View.java:24931)
    at android.os.Handler.handleCallback(Handler.java:808)
    at android.os.Handler.dispatchMessage(Handler.java:101)
    at android.os.Looper.loop(Looper.java:166)
    at android.app.ActivityThread.main(ActivityThread.java:7529)
    at java.lang.reflect.Method.invoke(Method.java)
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921)


问:
VBA Merging two strings excluding overlap part
Is it possible to merge two strings but when end of s1 is the same as beginning of s2 do not repeat that part of the string? For example:

```<code>s1 = "The quick "          s2 = "brown fox"       -> "The quick brown fox"
s1 = "The quick brown fox" s2 = "quick brown fox" -> "The quick brown fox"
s1 = "The quick brown "    s2 = "quick brown fox" -> "The quick brown fox"
s1 = "The quick brown fox" s2 = ""                -> "The quick brown fox"
s1 = ""                    s2 = "fox"             -> "fox"
</code>```

答:
If you are using O365, then you may apply any one of the approaches as well,

FORMULA APPROACH ONE: In Cell C1

```<code>=TEXTJOIN(" ",,UNIQUE(FILTERXML("<a><b>"&SUBSTITUTE(TEXTJOIN(" ",,TRIM(A1:B1))," ","</b><b>")&"</b></a>","//b")))
</code>```

FORMULA APPROACH TWO: In Cell D1

```<code>=TEXTJOIN(" ",,UNIQUE(TRIM(MID(SUBSTITUTE(A1&" "&B1," ",REPT(" ",100)),COLUMN(A1:Z1)*99-98,100)),1))
</code>```

Body:
Is it possible to merge two strings but when end of s1 is the same as beginning of s2 do not repeat that part of the string? For example:

s1 = "The quick "          s2 = "brown fox"       -> "The quick brown fox"
s1 = "The quick brown fox" s2 = "quick brown fox" -> "The quick brown fox"
s1 = "The quick brown "    s2 = "quick brown fox" -> "The quick brown fox"
s1 = "The quick brown fox" s2 = ""                -> "The quick brown fox"
s1 = ""                    s2 = "fox"             -> "fox"

Body:
If you are using O365, then you may apply any one of the approaches as well,

FORMULA APPROACH ONE: In Cell C1

=TEXTJOIN(" ",,UNIQUE(FILTERXML("<a><b>"&SUBSTITUTE(TEXTJOIN(" ",,TRIM(A1:B1))," ","</b><b>")&"</b></a>","//b")))

FORMULA APPROACH TWO: In Cell D1

=TEXTJOIN(" ",,UNIQUE(TRIM(MID(SUBSTITUTE(A1&" "&B1," ",REPT(" ",100)),COLUMN(A1:Z1)*99-98,100)),1))


问:
Formatting Emails from Sheets in Google App Script
I'm trying to format emails from a Google Sheet into a string that I can use as email recipients. I've gotten the emails, and I'm using a for loop to try to remove empty values, but it's not catching ("true" never triggers). Can someone tell me what I'm doing wrong?

Here's my sample sheet: https://docs.google.com/spreadsheets/d/1RPw_sNHF3JTlMYBD_Mk1BTOHDLaXya8IaeuU3YkxHUQ/edit?usp=sharing

Here's my code:

```<code>function affiliateReportReminder() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName('Sheet1');
  var lastRow = sheet.getRange("A1:A").getLastRow();
  var emails = sheet.getRange("A1:A" + lastRow).getValues();
  for (i = 0; i > lastRow; i++) {
    if (emails[i]='') {
      console.log(true)
      emails.splice(i,1);
    }
  }
  console.log(emails);
};
</code>```

答:
comma separated list of email recipients

```<code>function affiliateReportReminder() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName('Sheet1');
  const emails = sh.getRange(1,1,sh.getLastRow()).getValues().flat().join(",");
  console.log(emails);
}
</code>```

Body:
I'm trying to format emails from a Google Sheet into a string that I can use as email recipients. I've gotten the emails, and I'm using a for loop to try to remove empty values, but it's not catching ("true" never triggers). Can someone tell me what I'm doing wrong?

Here's my sample sheet: https://docs.google.com/spreadsheets/d/1RPw_sNHF3JTlMYBD_Mk1BTOHDLaXya8IaeuU3YkxHUQ/edit?usp=sharing

Here's my code:

function affiliateReportReminder() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName('Sheet1');
  var lastRow = sheet.getRange("A1:A").getLastRow();
  var emails = sheet.getRange("A1:A" + lastRow).getValues();
  for (i = 0; i > lastRow; i++) {
    if (emails[i]='') {
      console.log(true)
      emails.splice(i,1);
    }
  }
  console.log(emails);
};

Body:
comma separated list of email recipients

function affiliateReportReminder() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName('Sheet1');
  const emails = sh.getRange(1,1,sh.getLastRow()).getValues().flat().join(",");
  console.log(emails);
}


问:
nodejs filtering an array of objects where the filtering is partially done in an async function
I've read many similar questions and have tried a bunch of code. Unfortunately, I'm not getting my code to run :-(

So, the situation is as follows: In a route of a node.js server, I have to respond with a filtered array of Objects. Unfortunately, whatever I do, I always get an empty array [] back. The filter is a bit tricky in my opinion, as it consists of a string comparison AND an async call to a library function. With the console output, I can clearly see that the correct element is found, but at the same time I see that I've already received the object...

Here is some code that exemplifies my challenge:

```<code>let testArray = [
  {
    id: 'stringId1',
    data: {
      someDoc: {
        moreContent: 'Some random content',
        type: 'noInterest'
      }
    }
  },
  {
    id: 'stringId2',
    data: {
      someDoc: {
        moreContent: 'Some random content',
        type: 'ofInterest'
      }
    }
  },
  {
    id: 'stringId3',
    data: {
      someDoc: {
        moreContent: 'Some random content',
        type: 'ofInterest'
      }
    }
  }
]

// code from a library. Can't take an influence in it.
async function booleanWhenGood(id) {
  if (id in some Object) {
    return { myBoolean: true };
  } else {
    return { myBoolean: false };
  }
}

// Should return only elements with type 'ofInterest' and that the function booleanWhenGood is true
router.get('/', function(res,req) {
  tryOne(testArray).then(tryOneResult =>{
    console.log('tryOneResult', tryOneResult);
  });
  tryTwo(testArray).then(tryTwoResult => {
    console.log("tryTwoResult ", tryTwoResult);
  });

  result = [];
  for (const [idx, item] of testArray.entries() ) {
    console.log(idx);
    if (item.data.someDoc.type === "ofInterest") {
      smt.find(item.id).then(element => {
        if(element.found) {
          result.push(item.id);
          console.log("ID is true: ", item.id);
        }
      });
    }

    if (idx === testArray.length-1) {
      // Always returns []
      console.log(result);
      res.send(result);
    }
  }
})

// A helper function I wrote that I use in the things I've tried
async function myComputeBoolean(inputId, inputBoolean) {
  let result = await booleanWhenGood(inputId)

  if (result.myBoolean) {
    console.log("ID is true: ", inputId);
  }

  return (result.myBoolean && inputBoolean);
}

// A few things I've tried so far:
async function tryOne(myArray) {
  let myTmpArray = []

  Promise.all(myArray.filter(item => {
    console.log("item ", item.id);
    myComputeBoolean(item.id, item.data.someDoc.type === "ofInterest")
    .then(myBResult => {
      console.log("boolean result", myBResult)
      if (myBResult) {
        tmpjsdlf.push(item.id);
        return true;
      }
    })
  })).then(returnOfPromise => {
    // Always returns [];
    console.log("returnOfPromise", myTmpArray);
  });

  // Always returns []
  return(myTmpArray);
}

async function tryTwo(myArray) {
  let myTmpArray = [];
  myArray.forEach(item => {
    console.log("item ", item.id);
    myCompuBoolean(item.id, item.data.someDoc.type === "ofInterest")
    .then(myBResult => {
      console.log("boolean result", myBResult)
      if (myBResult) {
        myTmpArray.push(item.did);
      }
    })
  });

  Promise.all(myTmpArray).then(promiseResult => {
    return myTmpArray;
  });
}
</code>```

Asynchronous programming is really tough for me in this situation... Can you help me get it running?

答:
I didn't inspect your attempts that closely, but I believe you are experiencing some race conditions (you print return and print the array before the promises resolve).

However you can alwayd use a regular for loop to filter iterables. Like this:

```<code>let testArray = [
    {
        id: 'stringId1',
        data: {
            someDoc: {
                moreContent: 'Some random content',
                type: 'noInterest'
            }
        }
    },
    {
        id: 'stringId2',
        data: {
            someDoc: {
                moreContent: 'Some random content',
                type: 'ofInterest'
            }
        }
    },
    {
        id: 'stringId3',
        data: {
            someDoc: {
                moreContent: 'Some random content',
                type: 'ofInterest'
            }
        }
    }
]

async function booleanWhenGood(id) {
    if (id in { 'stringId1': 1, 'stringId2': 1 }) { // mock object
        return { myBoolean: true };
    } else {
        return { myBoolean: false };
    }
}

async function main() {
    let filtered = []
    for (item of testArray)
        if ((await booleanWhenGood(item.id)).myBoolean && item.data.someDoc.type === 'ofInterest')
            filtered.push(item)
    console.log('filtered :>> ', filtered);
}

main()
</code>```

Body:
I've read many similar questions and have tried a bunch of code. Unfortunately, I'm not getting my code to run :-(

So, the situation is as follows: In a route of a node.js server, I have to respond with a filtered array of Objects. Unfortunately, whatever I do, I always get an empty array [] back. The filter is a bit tricky in my opinion, as it consists of a string comparison AND an async call to a library function. With the console output, I can clearly see that the correct element is found, but at the same time I see that I've already received the object...

Here is some code that exemplifies my challenge:

let testArray = [
  {
    id: 'stringId1',
    data: {
      someDoc: {
        moreContent: 'Some random content',
        type: 'noInterest'
      }
    }
  },
  {
    id: 'stringId2',
    data: {
      someDoc: {
        moreContent: 'Some random content',
        type: 'ofInterest'
      }
    }
  },
  {
    id: 'stringId3',
    data: {
      someDoc: {
        moreContent: 'Some random content',
        type: 'ofInterest'
      }
    }
  }
]

// code from a library. Can't take an influence in it.
async function booleanWhenGood(id) {
  if (id in some Object) {
    return { myBoolean: true };
  } else {
    return { myBoolean: false };
  }
}

// Should return only elements with type 'ofInterest' and that the function booleanWhenGood is true
router.get('/', function(res,req) {
  tryOne(testArray).then(tryOneResult =>{
    console.log('tryOneResult', tryOneResult);
  });
  tryTwo(testArray).then(tryTwoResult => {
    console.log("tryTwoResult ", tryTwoResult);
  });

  result = [];
  for (const [idx, item] of testArray.entries() ) {
    console.log(idx);
    if (item.data.someDoc.type === "ofInterest") {
      smt.find(item.id).then(element => {
        if(element.found) {
          result.push(item.id);
          console.log("ID is true: ", item.id);
        }
      });
    }

    if (idx === testArray.length-1) {
      // Always returns []
      console.log(result);
      res.send(result);
    }
  }
})

// A helper function I wrote that I use in the things I've tried
async function myComputeBoolean(inputId, inputBoolean) {
  let result = await booleanWhenGood(inputId)

  if (result.myBoolean) {
    console.log("ID is true: ", inputId);
  }

  return (result.myBoolean && inputBoolean);
}

// A few things I've tried so far:
async function tryOne(myArray) {
  let myTmpArray = []

  Promise.all(myArray.filter(item => {
    console.log("item ", item.id);
    myComputeBoolean(item.id, item.data.someDoc.type === "ofInterest")
    .then(myBResult => {
      console.log("boolean result", myBResult)
      if (myBResult) {
        tmpjsdlf.push(item.id);
        return true;
      }
    })
  })).then(returnOfPromise => {
    // Always returns [];
    console.log("returnOfPromise", myTmpArray);
  });

  // Always returns []
  return(myTmpArray);
}

async function tryTwo(myArray) {
  let myTmpArray = [];
  myArray.forEach(item => {
    console.log("item ", item.id);
    myCompuBoolean(item.id, item.data.someDoc.type === "ofInterest")
    .then(myBResult => {
      console.log("boolean result", myBResult)
      if (myBResult) {
        myTmpArray.push(item.did);
      }
    })
  });

  Promise.all(myTmpArray).then(promiseResult => {
    return myTmpArray;
  });
}

Asynchronous programming is really tough for me in this situation... Can you help me get it running?

Body:
I didn't inspect your attempts that closely, but I believe you are experiencing some race conditions (you print return and print the array before the promises resolve).

However you can alwayd use a regular for loop to filter iterables. Like this:

let testArray = [
    {
        id: 'stringId1',
        data: {
            someDoc: {
                moreContent: 'Some random content',
                type: 'noInterest'
            }
        }
    },
    {
        id: 'stringId2',
        data: {
            someDoc: {
                moreContent: 'Some random content',
                type: 'ofInterest'
            }
        }
    },
    {
        id: 'stringId3',
        data: {
            someDoc: {
                moreContent: 'Some random content',
                type: 'ofInterest'
            }
        }
    }
]

async function booleanWhenGood(id) {
    if (id in { 'stringId1': 1, 'stringId2': 1 }) { // mock object
        return { myBoolean: true };
    } else {
        return { myBoolean: false };
    }
}

async function main() {
    let filtered = []
    for (item of testArray)
        if ((await booleanWhenGood(item.id)).myBoolean && item.data.someDoc.type === 'ofInterest')
            filtered.push(item)
    console.log('filtered :>> ', filtered);
}

main()


问:
Laravel vue return 401 error in api routes
so i have a route group in my api.php file like:

```<code>Route::group(['middleware' => 'auth:api'], function(){
//routes
});
</code>```

The problem with this group is that is returning 401 error.

Why?

I guess my cookies/session whatever it is, is expired and it return 401 error (while user is not aware of it).

Issue

The problem here is laravel keeps my user logged in for SESSION_LIFETIME=120 but my api is sett to 60 (not sure about this yet)

```<code>'api' => [
  'throttle:60,1',
  'bindings',
],
</code>```

Question

What should I do in order to logout user after session has expired
so the next time user visits my site not get into 401 error and
know he/she is already logged out and need to login again?

Update

I've made a middleware in order to check session lifetime and logout user if it's expire, but i can't get lifetime value out of it.

```<code>public function handle($request, Closure $next)
    {
        $bag = Session::all();
        $max = config('session.lifetime') * 60; // min to hours conversion
        if (($bag && $max < (time() - $bag->getLastUsed()))) {
            $request->session()->flush(); // remove all the session data
            Auth::logout(); // logout user
        }
        return $next($request);
    }
</code>```

答:
Make sure to add this line in the Kernel.php file :

```<code>'web' => [
    // Other middleware...
    \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
],
</code>```

Source : https://laravel.com/docs/5.8/passport#consuming-your-api-with-javascript

Body:
so i have a route group in my api.php file like:

Route::group(['middleware' => 'auth:api'], function(){
//routes
});

The problem with this group is that is returning 401 error.

Why?

I guess my cookies/session whatever it is, is expired and it return 401 error (while user is not aware of it).

Issue

The problem here is laravel keeps my user logged in for SESSION_LIFETIME=120 but my api is sett to 60 (not sure about this yet)

'api' => [
  'throttle:60,1',
  'bindings',
],

Question

What should I do in order to logout user after session has expired
so the next time user visits my site not get into 401 error and
know he/she is already logged out and need to login again?

Update

I've made a middleware in order to check session lifetime and logout user if it's expire, but i can't get lifetime value out of it.

public function handle($request, Closure $next)
    {
        $bag = Session::all();
        $max = config('session.lifetime') * 60; // min to hours conversion
        if (($bag && $max < (time() - $bag->getLastUsed()))) {
            $request->session()->flush(); // remove all the session data
            Auth::logout(); // logout user
        }
        return $next($request);
    }

Body:
Make sure to add this line in the Kernel.php file :

'web' => [
    // Other middleware...
    \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
],

Source : https://laravel.com/docs/5.8/passport#consuming-your-api-with-javascript


问:
Selenium: how to define css if webpage has mutiple elements with same name
I have the following HTML code:

```<code><table id="userPlaylistTable" cellspacing="0" cellpadding="0">
<div class="numCellWrapper">
<div class="listArrow up" onclick="moveRowUp($(this))"></div>
<div class="numCell"> 1 </div>
<div class="listArrow down" onclick="moveRowDown($(this))"></div>
</div>
<div class="numCellWrapper">
<div class="listArrow up" onclick="moveRowUp($(this))"></div>
<div class="numCell"> 2 </div>
<div class="listArrow down" onclick="moveRowDown($(this))"></div>
</div>
<div class="numCellWrapper">
<div class="listArrow up" onclick="moveRowUp($(this))"></div>
<div class="numCell"> 3 </div>
<div class="listArrow down" onclick="moveRowDown($(this))"></div>
</div>
</code>```

Basically, now if I define my css as:

```<code>css=table#userPlaylistTable div[class='listArrow up']
</code>```

It picks the first such element it finds. But, how would I have to define my css, so that it picks second element of this type?
So, basically how would I define my css to pick a particular element, if multiple elements of the same kind exist on the page?

Could someone please help me with this query?

Thanks.

答:
You need to do something like:

```<code>css=table#userPlaylistTable>div[class='listArrow up']:nth(1)

css=table#userPlaylistTable>div[class='listArrow up']:nth(2)
</code>```

This will give you the 2nd and the 3rd instance

ContentLicense: CC BY-SA 3.0

Body:
I have the following HTML code:

 1

 2

 3

Basically, now if I define my css as:

css=table#userPlaylistTable div[class='listArrow up']

It picks the first such element it finds. But, how would I have to define my css, so that it picks second element of this type?
So, basically how would I define my css to pick a particular element, if multiple elements of the same kind exist on the page?

Could someone please help me with this query?

Thanks.

Body:
You need to do something like:

css=table#userPlaylistTable>div[class='listArrow up']:nth(1)

css=table#userPlaylistTable>div[class='listArrow up']:nth(2)

This will give you the 2nd and the 3rd instance


问:
CMake nested OBJECT library dependencies
I created a project with some nested library dependencies using the OBJECT library type. The motivation for this is to avoid link order issues with static libraries.

I have a simple directory structure as follows:

```<code>├── bar
│   ├── bar.c
│   └── bar.h
├── foo
│   ├── foo.c
│   └── foo.h
├── main.c
└── CMakeLists.txt
</code>```

foo depends on bar, and main depends on foo. For example,

bar.c

#include "bar.h"

#include <stdio.h>

void bar(void) {
  printf("woot woot\n");
}
```
<p>foo.c</p>
<pre class="lang-c prettyprint-override"><code>#include "foo.h"

#include "bar.h"

void foo(void) {
  bar();
}
</code>```

main.c

#include "foo.h"

int main() {
  foo();
  return 0;
}
```
<p>The CMakeLists.txt</p>
<pre class="lang-sh prettyprint-override"><code>cmake_minimum_required(VERSION 3.18)

project(myproj)

enable_language(C ASM)
set(CMAKE_C_STANDARD 11)
set(CMAKE_C_STANDARD_REQUIRED ON)
set(CMAKE_C_EXTENSIONS OFF)

# build bar
add_library(bar OBJECT ${PROJECT_SOURCE_DIR}/bar/bar.c)
target_include_directories(bar PUBLIC ${PROJECT_SOURCE_DIR}/bar)

# build foo, depends on bar
add_library(foo OBJECT ${PROJECT_SOURCE_DIR}/foo/foo.c)
target_include_directories(foo PUBLIC ${PROJECT_SOURCE_DIR}/foo)
target_link_libraries(foo PUBLIC bar)

# build executable, depends on foo
add_executable(myexe ${PROJECT_SOURCE_DIR}/main.c)
target_link_libraries(myexe PUBLIC foo)
</code>```

My expectation is that myexe would inherit the bar dependency from foo when it links to it. However, this is not the case it seems. When the code is compiled, main.o only links to foo.o, and thus there is an undefined reference to bar. However, if I change the library types from OBJECT to STATIC everything works fine. Why does this happen?

答:
Object libraries cannot be chained this way. You must link directly (not transitively) to an object library to acquire its object files. As it says in the documentation,

Object Libraries may "link" to other object libraries to get usage requirements, but since they do not have a link step nothing is done with their object files. [...] In other words, when Object Libraries appear in a target's INTERFACE_LINK_LIBRARIES property they will be treated as Interface Libraries, but when they appear in a target's LINK_LIBRARIES property their object files will be included in the link too.

I agree it defies all reason, though.

However, you can manually propagate the object files via target_link_libraries(INTERFACE) and the $<TARGET_OBJECTS> generator expression as of 3.21 (doing so was buggy in earlier versions, and the even-hacker target_sources may be used in earlier versions, too).

Do note that this is a bit of a hack, since there are some cases that will break. Notably, if a library target links to such a target publicly, then the object files will propagate again. So... be careful.

Still, here's a corrected version of your example build:

```<code>cmake_minimum_required(VERSION 3.21)
project(myproj LANGUAGES C ASM)

set(CMAKE_C_STANDARD 11 CACHE STRING "The C standard to use")
option(CMAKE_C_STANDARD_REQUIRED "Enforce strict C standard selection" ON)
option(CMAKE_C_EXTENSIONS "Allow compiler-specific C extensions" OFF)

# build bar
add_library(bar OBJECT bar/bar.c)
target_include_directories(
  bar PUBLIC "$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/bar>"
)

# build foo, depends on bar
add_library(foo OBJECT foo/foo.c)
target_include_directories(
  foo PUBLIC "$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/foo>"
)
target_link_libraries(foo PUBLIC bar "$<TARGET_OBJECTS:bar>")

# build executable, depends on foo
add_executable(myexe main.c)
target_link_libraries(myexe PRIVATE foo)
</code>```

At the command line:

```<code>$ cmake -G Ninja -S . -B build
...
$ cmake --build build -- -nv
[1/4] /usr/bin/cc  -I/path/to/bar -std=c11 -MD -MT CMakeFiles/bar.dir/bar/bar.c.o -MF CMakeFiles/bar.dir/bar/bar.c.o.d -o CMakeFiles/bar.dir/bar/bar.c.o -c /path/to/bar/bar.c
[2/4] /usr/bin/cc  -I/path/to/foo -I/path/to/bar -std=c11 -MD -MT CMakeFiles/foo.dir/foo/foo.c.o -MF CMakeFiles/foo.dir/foo/foo.c.o.d -o CMakeFiles/foo.dir/foo/foo.c.o -c /path/to/foo/foo.c
[3/4] /usr/bin/cc  -I/path/to/foo -I/path/to/bar -std=c11 -MD -MT CMakeFiles/myexe.dir/main.c.o -MF CMakeFiles/myexe.dir/main.c.o.d -o CMakeFiles/myexe.dir/main.c.o -c /path/to/main.c
[4/4] : && /usr/bin/cc   CMakeFiles/foo.dir/foo/foo.c.o CMakeFiles/myexe.dir/main.c.o -o myexe  CMakeFiles/bar.dir/./bar/bar.c.o && :
</code>```

Body:
I created a project with some nested library dependencies using the OBJECT library type. The motivation for this is to avoid link order issues with static libraries.

I have a simple directory structure as follows:

├── bar
│   ├── bar.c
│   └── bar.h
├── foo
│   ├── foo.c
│   └── foo.h
├── main.c
└── CMakeLists.txt

foo depends on bar, and main depends on foo. For example,

bar.c

#include "bar.h"

#include <stdio.h>

void bar(void) {
  printf("woot woot\n");
}

foo.c

#include "foo.h"

#include "bar.h"

void foo(void) {
  bar();
}

main.c

#include "foo.h"

int main() {
  foo();
  return 0;
}

The CMakeLists.txt

cmake_minimum_required(VERSION 3.18)

project(myproj)

enable_language(C ASM)
set(CMAKE_C_STANDARD 11)
set(CMAKE_C_STANDARD_REQUIRED ON)
set(CMAKE_C_EXTENSIONS OFF)

# build bar
add_library(bar OBJECT ${PROJECT_SOURCE_DIR}/bar/bar.c)
target_include_directories(bar PUBLIC ${PROJECT_SOURCE_DIR}/bar)

# build foo, depends on bar
add_library(foo OBJECT ${PROJECT_SOURCE_DIR}/foo/foo.c)
target_include_directories(foo PUBLIC ${PROJECT_SOURCE_DIR}/foo)
target_link_libraries(foo PUBLIC bar)

# build executable, depends on foo
add_executable(myexe ${PROJECT_SOURCE_DIR}/main.c)
target_link_libraries(myexe PUBLIC foo)

My expectation is that myexe would inherit the bar dependency from foo when it links to it. However, this is not the case it seems. When the code is compiled, main.o only links to foo.o, and thus there is an undefined reference to bar. However, if I change the library types from OBJECT to STATIC everything works fine. Why does this happen?

Body:
Object libraries cannot be chained this way. You must link directly (not transitively) to an object library to acquire its object files. As it says in the documentation,

Object Libraries may "link" to other object libraries to get usage requirements, but since they do not have a link step nothing is done with their object files. [...] In other words, when Object Libraries appear in a target's INTERFACE_LINK_LIBRARIES property they will be treated as Interface Libraries, but when they appear in a target's LINK_LIBRARIES property their object files will be included in the link too.

I agree it defies all reason, though.

However, you can manually propagate the object files via target_link_libraries(INTERFACE) and the $<TARGET_OBJECTS> generator expression as of 3.21 (doing so was buggy in earlier versions, and the even-hacker target_sources may be used in earlier versions, too).

Do note that this is a bit of a hack, since there are some cases that will break. Notably, if a library target links to such a target publicly, then the object files will propagate again. So... be careful.

Still, here's a corrected version of your example build:

cmake_minimum_required(VERSION 3.21)
project(myproj LANGUAGES C ASM)

set(CMAKE_C_STANDARD 11 CACHE STRING "The C standard to use")
option(CMAKE_C_STANDARD_REQUIRED "Enforce strict C standard selection" ON)
option(CMAKE_C_EXTENSIONS "Allow compiler-specific C extensions" OFF)

# build bar
add_library(bar OBJECT bar/bar.c)
target_include_directories(
  bar PUBLIC "$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/bar>"
)

# build foo, depends on bar
add_library(foo OBJECT foo/foo.c)
target_include_directories(
  foo PUBLIC "$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/foo>"
)
target_link_libraries(foo PUBLIC bar "$<TARGET_OBJECTS:bar>")

# build executable, depends on foo
add_executable(myexe main.c)
target_link_libraries(myexe PRIVATE foo)

At the command line:

$ cmake -G Ninja -S . -B build
...
$ cmake --build build -- -nv
[1/4] /usr/bin/cc  -I/path/to/bar -std=c11 -MD -MT CMakeFiles/bar.dir/bar/bar.c.o -MF CMakeFiles/bar.dir/bar/bar.c.o.d -o CMakeFiles/bar.dir/bar/bar.c.o -c /path/to/bar/bar.c
[2/4] /usr/bin/cc  -I/path/to/foo -I/path/to/bar -std=c11 -MD -MT CMakeFiles/foo.dir/foo/foo.c.o -MF CMakeFiles/foo.dir/foo/foo.c.o.d -o CMakeFiles/foo.dir/foo/foo.c.o -c /path/to/foo/foo.c
[3/4] /usr/bin/cc  -I/path/to/foo -I/path/to/bar -std=c11 -MD -MT CMakeFiles/myexe.dir/main.c.o -MF CMakeFiles/myexe.dir/main.c.o.d -o CMakeFiles/myexe.dir/main.c.o -c /path/to/main.c
[4/4] : && /usr/bin/cc   CMakeFiles/foo.dir/foo/foo.c.o CMakeFiles/myexe.dir/main.c.o -o myexe  CMakeFiles/bar.dir/./bar/bar.c.o && :


问:
Device manager does not work (open) after updating Android Studio to 2021.1.1
Android studio's device manager AVD manager works fine in old versions, but in 2021.1.1 version does not open!
Windows 10 and 11 tested
last version flutter
Intel
Sdk manager everything updated
could anyone help?</p>

答:
I had the same problem, found the solution to return the icon to the toolbar, where it's easy to use it.

I guess it happans to anyone who upgrades from prvious version.

The idea is just to replace the "old" device manager with the new device manager created in 2021.1.1.

Right click the right side of the top toolbar and click the "Customize Menues and toolbars.

In the "Menus and Toolbar" window expand "Main Toolbar"

Expand "Android.MainToolBarActionGroup"

Press the "+" button in the top and select "Add Action..."

In the "Choose Action To Add" windows , search for "Virtual Device manager", select it and press OK.

You will see the the new icon is added.

To make sure it's working you can press OK to close this window and return to Android Studio main screen.

Now, you should have 2 similar icons in the toolbar, only the bubbles will be different.

The old is called "Device manager"

The new one is called "Virtual Device Manager"

Make sure it really works and opens the new Device Manager.

Once it is working , you can go back to the toolbar manger and delete the old icon.

Folow setps 1-3 above

Locate the "Android.RunAndroidAvdManager" item, select it and delete it by pressing the "-" button in the top of the screen.

Close this window and return to main screen.


问:
How to sort an array based on the second value with javascript?
I have an array:

```<code>[
    [0, 'Please select a Customer'],
    [2072, 'S-Customer'],
    [834, '01-Customer'],
    [709, 'C-Customer'],
    [4217, 'Test'],
    [2074, 'A-Customer']
]
</code>```

but how can I sort it numeric and alphabetically and still have the same ID which is the first value?? It would be like this:

obs: the first value should not be changed.

```<code>[
    [0, 'Please select a Customer'],
    [834, '01-Customer'],
    [2074, 'A-Customer'],
    [709, 'C-Customer'],
    [2072, 'S-Customer'],
    [4217, 'Test']
]
</code>```

答:
You could keep the first array in place by looking to index 0 and sort the rest by the value of index 1

const
    array = [[0, 'Please select a Customer'], [2072, 'S-Customer'], [834, '01-Customer'], [709, 'C-Customer'], [4217, 'Test'], [2074, 'A-Customer']];

array.sort((a, b) => !b[0] - !a[0] || a[1].localeCompare(b[1]));

console.log(array);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I have an array:

[
    [0, 'Please select a Customer'],
    [2072, 'S-Customer'],
    [834, '01-Customer'],
    [709, 'C-Customer'],
    [4217, 'Test'],
    [2074, 'A-Customer']
]

but how can I sort it numeric and alphabetically and still have the same ID which is the first value?? It would be like this:

obs: the first value should not be changed.

[
    [0, 'Please select a Customer'],
    [834, '01-Customer'],
    [2074, 'A-Customer'],
    [709, 'C-Customer'],
    [2072, 'S-Customer'],
    [4217, 'Test']
]

Body:
You could keep the first array in place by looking to index 0 and sort the rest by the value of index 1

const
    array = [[0, 'Please select a Customer'], [2072, 'S-Customer'], [834, '01-Customer'], [709, 'C-Customer'], [4217, 'Test'], [2074, 'A-Customer']];

array.sort((a, b) => !b[0] - !a[0] || a[1].localeCompare(b[1]));

console.log(array);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Pandas multi index partial selection using list of tuples
Consider the following dataframe

```<code>import pandas as pd
import numpy as np

arr = np.random.random((2, 4))
mdf = pd.DataFrame({'cid': ['c1', 'c2']})
pdf = pd.DataFrame({'doc_id': ['d1', 'd1', 'd2', 'd2'], 'passage_id': ['p1', 'p2', 'p1', 'p2']})
index = pd.MultiIndex.from_frame(mdf.join(pdf, how='cross'))
df = pd.DataFrame({'score': arr.flatten()}, index=index)
</code>```

df is

```<code>                             score
cid     doc_id  passage_id
c1      d1       p1          0.708722
                 p2          0.975350
        d2       p1          0.326029
                 p2          0.979832
c2      d1       p1          0.147153
                 p2          0.381807
        d2       p1          0.525054
                 p2          0.245478
</code>```

Now If i try to index using a list of tuples using only two levels

df.loc[[('c1', 'd1'), ('c2', 'd2')]]

I get the following error:

ValueError: operands could not be broadcast together with shapes (2,2) (3,) (2,2)

Why is this error happening ?

I expected the answer to be:

```<code>                             score
cid     doc_id  passage_id
c1      d1       p1          0.708722
                 p2          0.975350
c2      d2       p1          0.525054
                 p2          0.245478
</code>```

答:
To add to the solutions that have been provided:

df.reset_index(level=2).loc[[('c1', 'd1'), ('c2', 'd2')]].set_index('passage_id', append=True)
```

I wish I could think of a more elegant solution. Here's the breakdown of what this is doing:

.reset_index(level=2) moves the third index from the left into the "body" of the DataFrame (as a regular column).

Now that there's only two levels of indexing left, .loc[[('c1', 'd1'), ('c2', 'd2')]] gets the rows that you wanted.

.set_index('passage_id', append=True) moves the passage_id column back into the index.

Body:
Consider the following dataframe

import pandas as pd
import numpy as np

arr = np.random.random((2, 4))
mdf = pd.DataFrame({'cid': ['c1', 'c2']})
pdf = pd.DataFrame({'doc_id': ['d1', 'd1', 'd2', 'd2'], 'passage_id': ['p1', 'p2', 'p1', 'p2']})
index = pd.MultiIndex.from_frame(mdf.join(pdf, how='cross'))
df = pd.DataFrame({'score': arr.flatten()}, index=index)

df is

                             score
cid     doc_id  passage_id
c1      d1       p1          0.708722
                 p2          0.975350
        d2       p1          0.326029
                 p2          0.979832
c2      d1       p1          0.147153
                 p2          0.381807
        d2       p1          0.525054
                 p2          0.245478

Now If i try to index using a list of tuples using only two levels

df.loc[[('c1', 'd1'), ('c2', 'd2')]]

I get the following error:

ValueError: operands could not be broadcast together with shapes (2,2) (3,) (2,2)

Why is this error happening ?

I expected the answer to be:

                             score
cid     doc_id  passage_id
c1      d1       p1          0.708722
                 p2          0.975350
c2      d2       p1          0.525054
                 p2          0.245478

Body:
To add to the solutions that have been provided:

df.reset_index(level=2).loc[[('c1', 'd1'), ('c2', 'd2')]].set_index('passage_id', append=True)

I wish I could think of a more elegant solution. Here's the breakdown of what this is doing:

.reset_index(level=2) moves the third index from the left into the "body" of the DataFrame (as a regular column).

Now that there's only two levels of indexing left, .loc[[('c1', 'd1'), ('c2', 'd2')]] gets the rows that you wanted.

.set_index('passage_id', append=True) moves the passage_id column back into the index.


问:
Error on fetch data, function instead of value
Hi guys I am trying to fetch data using get, and I want the data to be displayed after  I click on the button, as a normal crud
I am new in programming if there is someone that can help me. I APPRECIATE THANKS
everything in my backend is ok, I try in postman and console.log is everything good. My problem is only in this part thanks</p>
```<code>
import { useState, useEffect } from "react";
import axios from "axios";

 function Usuarios() {
    const [users, setUsers] = useState([]);

     useEffect(()=> {
        const todosUsers = async () => {
            const res= await axios.get("/users");
            console.log(res)
            setUsers(res.data);
        }
        todosUsers()
    },[])

    return (
        <>
        <button onClick=
        {users.map((users) => (
            <h1>{users.username}</h1>
            ))}></button>
        </>

        )
}

export default Usuarios;

</code>```

答:
Move

```<code> {users.map((users) => (
        <h1>{users.username}</h1>
        ))
 }
</code>```

from onClick definition and place it in an a markup where you want it to render. Define onClick hendler, which will be setting data from an API to a state

```<code> import { useState, useEffect } from "react";
 import axios from "axios";

  function Usuarios() {
      const [users, setUsers] = useState([]);

      const fetchOnClick = async () => {
          await axios.get("/users");
          console.log(res)
          setUsers(res.data);
      }

      return (
          <>
              <button onClick={fetchOnClick}>
                  Fetch
              </button>
              <div>
                  {users.map((users) => (
                      <h1>{users.username}</h1>
                  ))}
              </div>
         </>

    )
 }
</code>```

OR

If you want to fetch the data inside useEffect hook, like you did in your example

```<code> import React, { useState, useEffect } from "react";

     function Usuarios() {
         const [users, setUsers] = useState([]);
         const [isContainerShowed, setIsContainerShowed] = useState(false)

         useEffect(() => {
             const res= await axios.get("/users");
             console.log(res)
             setUsers(res.data);
         }, [])

         const displayContainer = () => setIsContainerShowed(true);

         return (
             <>
                 <button onClick={displayContainer}>
                     Fetch
                 </button>
                 <div style={{display: isContainerShowed ? "block" : "none"}}>
                     {users.map(users => <h1>{users.username}</h1>)}
                 </div>
             </>

        )
     }
</code>```

Body:
Hi guys I am trying to fetch data using get, and I want the data to be displayed after  I click on the button, as a normal crud
I am new in programming if there is someone that can help me. I APPRECIATE THANKS
everything in my backend is ok, I try in postman and console.log is everything good. My problem is only in this part thanks

import { useState, useEffect } from "react";
import axios from "axios";

 function Usuarios() {
    const [users, setUsers] = useState([]);

     useEffect(()=> {
        const todosUsers = async () => {
            const res= await axios.get("/users");
            console.log(res)
            setUsers(res.data);
        }
        todosUsers()
    },[])

    return (
        <>
        <button onClick=
        {users.map((users) => (

{users.username}

            ))}></button>
        </>

        )
}

export default Usuarios;

Body:
Move

 {users.map((users) => (
        <h1>{users.username}</h1>
        ))
 }

from onClick definition and place it in an a markup where you want it to render. Define onClick hendler, which will be setting data from an API to a state

 import { useState, useEffect } from "react";
 import axios from "axios";

  function Usuarios() {
      const [users, setUsers] = useState([]);

      const fetchOnClick = async () => {
          await axios.get("/users");
          console.log(res)
          setUsers(res.data);
      }

      return (
          <>
              <button onClick={fetchOnClick}>
                  Fetch
              </button>
              <div>
                  {users.map((users) => (
                      <h1>{users.username}</h1>
                  ))}
              </div>
         </>

    )
 }

OR

If you want to fetch the data inside useEffect hook, like you did in your example

 import React, { useState, useEffect } from "react";

     function Usuarios() {
         const [users, setUsers] = useState([]);
         const [isContainerShowed, setIsContainerShowed] = useState(false)

         useEffect(() => {
             const res= await axios.get("/users");
             console.log(res)
             setUsers(res.data);
         }, [])

         const displayContainer = () => setIsContainerShowed(true);

         return (
             <>
                 <button onClick={displayContainer}>
                     Fetch
                 </button>
                 <div style={{display: isContainerShowed ? "block" : "none"}}>
                     {users.map(users => <h1>{users.username}</h1>)}
                 </div>
             </>

        )
     }


问:
TypeORM: QueryFailedError: relation does not exist
I need a little help with migration. I'm trying to seed DB using migration. But I get an error "QueryFailedError: relation "account" does not exist". I think it's just typical newbie mistake. So please check my code:

account.entity.ts

import { BeforeInsert, Column, Entity, OneToMany } from 'typeorm';
import { AbstractEntity } from '../../common/abstract.entity';
import { SourceEntity } from '../source/source.entity';
import { UtilsService } from '../../shared/services/utils.service';

@Entity({ name: 'account' })
export class AccountEntity extends AbstractEntity {
  @Column({ unique: true })
  username: string;

  @Column({ nullable: true })
  password: string;

  @OneToMany(() => SourceEntity, (source) => source.account, {
    cascade: true,
  })
  sources: SourceEntity[];

  @BeforeInsert()
  async setPassword() {
    this.password = UtilsService.generateHash(this.password);
  }
}
```
<p><strong>seed-data.migration.ts</strong></p>
<pre class="lang-ts prettyprint-override"><code>import { getCustomRepository, MigrationInterface, QueryRunner } from 'typeorm';
import { AccountRepository } from '../modules/account/account.repository';
import { SourceRepository } from '../modules/source/source.repository';

type DataType = {
  username: string;
  password: string;
  sources: { username: string }[];
};

export class SeedData1617243952346 implements MigrationInterface {
  private data: DataType[] = [
    {
      username: 'test',
      password: 'password',
      sources: [
        { username: 'some_test' },
        { username: 'okey_test' },
        { username: 'super_test' },
      ],
    },
    {
      username: 'account',
      password: 'password',
      sources: [
        { username: 'some_account' },
        { username: 'okey_account' },
        { username: 'super_account' },
      ],
    },
  ];

  public async up(): Promise<void> {
    await Promise.all(
      this.data.map(async (item) => {
        const accountRepository = getCustomRepository(AccountRepository);
        const accountEntity = accountRepository.create();
        accountEntity.username = item.username;
        accountEntity.password = item.password;

        const sourceRepository = getCustomRepository(SourceRepository);
        const sources = [];

        await Promise.all(
          item.sources.map(async (sourceItem) => {
            const sourceEntity = sourceRepository.create();
            sourceEntity.username = sourceItem.username;

            sources.push(sourceEntity);
          }),
        );

        accountEntity.sources = sources;
        const account = await accountRepository.save(accountEntity);
        console.log('Account created:', account.id);
      }),
    );
  }

  public async down(): Promise<void> {
    await Promise.all(
      this.data.map(async (item) => {
        const sourceRepository = getCustomRepository(SourceRepository);
        const accountRepository = getCustomRepository(AccountRepository);

        const account = await accountRepository.findOne({
          where: { username: item.username },
        });
        if (account) {
          await Promise.all(
            item.sources.map(async (src) => {
              const source = await sourceRepository.findOne({
                where: { username: src.username },
              });
              if (source) {
                await sourceRepository.delete(source);
              }
            }),
          );

          await accountRepository.delete(account);
        }
      }),
    );
  }
}
</code>```

source.entity.ts

import { Column, Entity, ManyToOne } from 'typeorm';
import { AbstractEntity } from '../../common/abstract.entity';
import { AccountEntity } from '../account/account.entity';

@Entity({ name: 'source' })
export class SourceEntity extends AbstractEntity {
  @Column({ unique: true })
  username: string;

  @Column({ default: true })
  overrideCaption: boolean;

  @ManyToOne(() => AccountEntity, (account) => account.sources)
  account: AccountEntity;
}
```
<p><strong>Error:</strong></p>
<pre class="lang-sh prettyprint-override"><code>Error during migration run:
QueryFailedError: relation "account" does not exist
    at new QueryFailedError (/home/wiha/dev/own/instahub/src/error/QueryFailedError.ts:9:9)
    at PostgresQueryRunner.<anonymous> (/home/wiha/dev/own/instahub/src/driver/postgres/PostgresQueryRunner.ts:228:19)
    at step (/home/wiha/dev/own/instahub/node_modules/tslib/tslib.js:143:27)
    at Object.throw (/home/wiha/dev/own/instahub/node_modules/tslib/tslib.js:124:57)
    at rejected (/home/wiha/dev/own/instahub/node_modules/tslib/tslib.js:115:69)
    at processTicksAndRejections (internal/process/task_queues.js:97:5) {
  length: 106,
  severity: 'ERROR',
  code: '42P01',
  detail: undefined,
  hint: undefined,
  position: '13',
  internalPosition: undefined,
  internalQuery: undefined,
  where: undefined,
  schema: undefined,
  table: undefined,
  column: undefined,
  dataType: undefined,
  constraint: undefined,
  file: 'parse_relation.c',
  line: '1191',
  routine: 'parserOpenTable',
  query: 'INSERT INTO "account"("id", "created_at", "updated_at", "username", "password") VALUES (DEFAULT, DEFAULT, DEFAULT, $1, $2) RETURNING "id", "created_at", "updated_at"',
  parameters: [
    'test',
    '$2b$10$iB6yb3D8e6iGmKoVAJ7eYeYfoItclw5lcVXqauPf9VH94DlDrbuSa'
  ]
}
</code>```

Tables are created in another migration

DB: PostgreSQL 12.6

Node: 14.0.0

TypeORM: 0.2.32

@nestjs/typeorm: 7.1.5

答:
I got this error because I used double-quotes around my value instead of single quotes. For example:

WRONG:

```<code>private static async getProducts(): Promise<Product[]> {
  return await getRepository(Product)
    .createQueryBuilder('product')
    .where('product.source = "noobie"') // <---- DOUBLE QUOTES = BAD!!!
    .getMany();
}
</code>```

RIGHT:

```<code>private static async getProducts(): Promise<Product[]> {
  return await getRepository(Product)
    .createQueryBuilder('product')
    .where("product.source = 'noobie'") // <---- SINGLE QUOTES!!!
    .getMany();
}
</code>```

Body:
I need a little help with migration. I'm trying to seed DB using migration. But I get an error "QueryFailedError: relation "account" does not exist". I think it's just typical newbie mistake. So please check my code:

account.entity.ts

import { BeforeInsert, Column, Entity, OneToMany } from 'typeorm';
import { AbstractEntity } from '../../common/abstract.entity';
import { SourceEntity } from '../source/source.entity';
import { UtilsService } from '../../shared/services/utils.service';

@Entity({ name: 'account' })
export class AccountEntity extends AbstractEntity {
  @Column({ unique: true })
  username: string;

  @Column({ nullable: true })
  password: string;

  @OneToMany(() => SourceEntity, (source) => source.account, {
    cascade: true,
  })
  sources: SourceEntity[];

  @BeforeInsert()
  async setPassword() {
    this.password = UtilsService.generateHash(this.password);
  }
}

seed-data.migration.ts

import { getCustomRepository, MigrationInterface, QueryRunner } from 'typeorm';
import { AccountRepository } from '../modules/account/account.repository';
import { SourceRepository } from '../modules/source/source.repository';

type DataType = {
  username: string;
  password: string;
  sources: { username: string }[];
};

export class SeedData1617243952346 implements MigrationInterface {
  private data: DataType[] = [
    {
      username: 'test',
      password: 'password',
      sources: [
        { username: 'some_test' },
        { username: 'okey_test' },
        { username: 'super_test' },
      ],
    },
    {
      username: 'account',
      password: 'password',
      sources: [
        { username: 'some_account' },
        { username: 'okey_account' },
        { username: 'super_account' },
      ],
    },
  ];

  public async up(): Promise<void> {
    await Promise.all(
      this.data.map(async (item) => {
        const accountRepository = getCustomRepository(AccountRepository);
        const accountEntity = accountRepository.create();
        accountEntity.username = item.username;
        accountEntity.password = item.password;

        const sourceRepository = getCustomRepository(SourceRepository);
        const sources = [];

        await Promise.all(
          item.sources.map(async (sourceItem) => {
            const sourceEntity = sourceRepository.create();
            sourceEntity.username = sourceItem.username;

            sources.push(sourceEntity);
          }),
        );

        accountEntity.sources = sources;
        const account = await accountRepository.save(accountEntity);
        console.log('Account created:', account.id);
      }),
    );
  }

  public async down(): Promise<void> {
    await Promise.all(
      this.data.map(async (item) => {
        const sourceRepository = getCustomRepository(SourceRepository);
        const accountRepository = getCustomRepository(AccountRepository);

        const account = await accountRepository.findOne({
          where: { username: item.username },
        });
        if (account) {
          await Promise.all(
            item.sources.map(async (src) => {
              const source = await sourceRepository.findOne({
                where: { username: src.username },
              });
              if (source) {
                await sourceRepository.delete(source);
              }
            }),
          );

          await accountRepository.delete(account);
        }
      }),
    );
  }
}

source.entity.ts

import { Column, Entity, ManyToOne } from 'typeorm';
import { AbstractEntity } from '../../common/abstract.entity';
import { AccountEntity } from '../account/account.entity';

@Entity({ name: 'source' })
export class SourceEntity extends AbstractEntity {
  @Column({ unique: true })
  username: string;

  @Column({ default: true })
  overrideCaption: boolean;

  @ManyToOne(() => AccountEntity, (account) => account.sources)
  account: AccountEntity;
}

Error:

Error during migration run:
QueryFailedError: relation "account" does not exist
    at new QueryFailedError (/home/wiha/dev/own/instahub/src/error/QueryFailedError.ts:9:9)
    at PostgresQueryRunner.<anonymous> (/home/wiha/dev/own/instahub/src/driver/postgres/PostgresQueryRunner.ts:228:19)
    at step (/home/wiha/dev/own/instahub/node_modules/tslib/tslib.js:143:27)
    at Object.throw (/home/wiha/dev/own/instahub/node_modules/tslib/tslib.js:124:57)
    at rejected (/home/wiha/dev/own/instahub/node_modules/tslib/tslib.js:115:69)
    at processTicksAndRejections (internal/process/task_queues.js:97:5) {
  length: 106,
  severity: 'ERROR',
  code: '42P01',
  detail: undefined,
  hint: undefined,
  position: '13',
  internalPosition: undefined,
  internalQuery: undefined,
  where: undefined,
  schema: undefined,
  table: undefined,
  column: undefined,
  dataType: undefined,
  constraint: undefined,
  file: 'parse_relation.c',
  line: '1191',
  routine: 'parserOpenTable',
  query: 'INSERT INTO "account"("id", "created_at", "updated_at", "username", "password") VALUES (DEFAULT, DEFAULT, DEFAULT, $1, $2) RETURNING "id", "created_at", "updated_at"',
  parameters: [
    'test',
    '$2b$10$iB6yb3D8e6iGmKoVAJ7eYeYfoItclw5lcVXqauPf9VH94DlDrbuSa'
  ]
}

Tables are created in another migration

DB: PostgreSQL 12.6

Node: 14.0.0

TypeORM: 0.2.32

@nestjs/typeorm: 7.1.5

Body:
I got this error because I used double-quotes around my value instead of single quotes. For example:

WRONG:

private static async getProducts(): Promise<Product[]> {
  return await getRepository(Product)
    .createQueryBuilder('product')
    .where('product.source = "noobie"') // <---- DOUBLE QUOTES = BAD!!!
    .getMany();
}

RIGHT:

private static async getProducts(): Promise<Product[]> {
  return await getRepository(Product)
    .createQueryBuilder('product')
    .where("product.source = 'noobie'") // <---- SINGLE QUOTES!!!
    .getMany();
}


问:
In Node.js, If i am writing a long running function should I be using setTimeout
or something else to queue up the rest of my function? and use callbacks or does node handle that automatically?

I imagine that I would need to start my code and if there are other things that  need to occur I should be giving up my functions control to give other events control. Is this the case? Or can i be stingy and node will cut off my function when I have used enough time?

Thanks.

答:
If your long-running function does a lot of I/O just make sure that you do this in a non-blocking way. This is how node.js achieves concurrency even though it only has a single thread: As soon as any task needs to wait for something, another task gets the CPU.

If your long-running function needs uninterrupted CPU time (or the I/O cannot be made asynchronously) , then you probably need to fork out a separate process, because otherwise every one else will have to wait until you are done.

Or can i be stingy and node will cut off my function when I have used enough time?

No. This is totally cooperative multi-tasking. Node cannot preempt you.


问:
How to Find exact Match then Paste Similar Value to adjacent Cell
I am trying to create a function which match the exact value in the raw string if macthes then paste the value but here Lookup function is giving an wrong answer.

I know how to extract it using Left function but how to macth exact string like in VBA we use Criteria: "" & CellValue & "".

```<code>=LOOKUP(99^99,SEARCH($K$3:$K$97,A3),$K$3:$K$97)
</code>```

This function is not matching exact string as you can see in attached picture.

Sheet Link

```<code>=IF(RegExMatch(B2,'Match Criteria'!B:B),"YES","NO")
</code>```

答:
EDIT

Paste this in cell C3 of your Sample Spreadsheet:

```<code>=ARRAYFORMULA(IFERROR(VLOOKUP(IFNA(REGEXEXTRACT(B3:B, "\b([A-Za-z]{2})\b(?:\s[\d{5}.]|$)"), REGEXEXTRACT(B3:B, "\b([A-Za-z]{4})\b(?:\s\d{5})")), 'Match Criteria'!B2:B, 1, FALSE)))
</code>```

and for D3:

```<code>=ARRAYFORMULA(IFERROR(VLOOKUP(REGEXEXTRACT(TO_TEXT(B3:B), "([\d]{5}\-[\d]{4}|[\d]{5})"),'Match Criteria'!A2:A,1,FALSE),))
</code>```

Note: Make sure to change the format of Columns A & B of Sheet Match Criteria to Plain Text.

Example output:

REFERENCES:

REGEXEXTRACT

VLOOKUP

IFERROR

ARRAYFORMULA

IFNA

TO_TEXT

Body:
I am trying to create a function which match the exact value in the raw string if macthes then paste the value but here Lookup function is giving an wrong answer.

I know how to extract it using Left function but how to macth exact string like in VBA we use Criteria: "" & CellValue & "".

=LOOKUP(99^99,SEARCH($K$3:$K$97,A3),$K$3:$K$97)

This function is not matching exact string as you can see in attached picture.

Sheet Link

=IF(RegExMatch(B2,'Match Criteria'!B:B),"YES","NO")

Body:
EDIT

Paste this in cell C3 of your Sample Spreadsheet:

=ARRAYFORMULA(IFERROR(VLOOKUP(IFNA(REGEXEXTRACT(B3:B, "\b([A-Za-z]{2})\b(?:\s[\d{5}.]|$)"), REGEXEXTRACT(B3:B, "\b([A-Za-z]{4})\b(?:\s\d{5})")), 'Match Criteria'!B2:B, 1, FALSE)))

and for D3:

=ARRAYFORMULA(IFERROR(VLOOKUP(REGEXEXTRACT(TO_TEXT(B3:B), "([\d]{5}\-[\d]{4}|[\d]{5})"),'Match Criteria'!A2:A,1,FALSE),))

Note: Make sure to change the format of Columns A & B of Sheet Match Criteria to Plain Text.

Example output:

REFERENCES:

REGEXEXTRACT

VLOOKUP

IFERROR

ARRAYFORMULA

IFNA

TO_TEXT


问:
How to stop textchangedlistener being executed infinitely after changing text once?
I have been working on a stock keeping application as a demo to learn kotlin and android studio, I have added textchangedlistener in a recycler view item, which everytime it text is changed, gets information from Api and displays new item on textview. This works good for only one time, After that it keeps infinitely changing. please check video for better understanding : ScreenRecording .

Here is my rcv adapter :

```<code>class RecyclerViewAdapterU (val dataList:ArrayList<ModelClass>): RecyclerView.Adapter<RecyclerViewAdapterU.ViewHolder>() {
var _binding: UploadItemViewBinding? = null
val binding get() = _binding!!
override fun onCreateViewHolder(
    parent: ViewGroup,
    viewType: Int
): RecyclerViewAdapterU.ViewHolder {

    val v =
        LayoutInflater.from(parent.context).inflate(R.layout.upload_item_view, parent, false)
    _binding = UploadItemViewBinding.bind(v)
    return ViewHolder(binding.root)
}

override fun onBindViewHolder(holder: ViewHolder, @SuppressLint("RecyclerView") position: Int) {

    bindItems(dataList[position])
    holder.getStock()
    holder.updateStockDetail()
}
fun bindItems(data: ModelClass) {

    binding.apply {
        itemquant.text=data.item_quant
        uploadItemName.text = data.item_name
        uploadMfg.text = data.mfg
        skuStock.setText(data.item_stock.toString())
        skuCode.setText(data.sku_code)
    }

}

fun getUpdatedDetails(skucode:String,pos:Int){
    val call: Call<List<ModelClass>>? =
        ApiClient.instance?.myApi?.getfromsku(skucode)!!
    call!!.enqueue(object : Callback<List<ModelClass>?> {
        override fun onResponse(
            call: Call<List<ModelClass>?>,
            response: Response<List<ModelClass>?>
        ) {
            val skuDetails=response.body()

            if (skuDetails != null) {
                dataList.removeAt(pos)
                for (i in skuDetails){
                    println(i.item_name)
                    dataList.add(pos,i)
                }
                notifyItemChanged(pos)
            }

        }

        override fun onFailure(call: Call<List<ModelClass>?>, t: Throwable) {
        }
    })
}

override fun getItemCount(): Int {
    return dataList.size
}

inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

    fun getStock() {

        binding.skuStock.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
            override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
            override fun afterTextChanged(editable: Editable) {
                for (i in 0 until RecyclerViewAdapter.ob.dataSelected.size){
                    if (editable.toString().trim()!=""){
                        var x= editable.toString().trim().toInt()
                        RecyclerViewAdapter.ob.dataSelected[adapterPosition].item_stock=x
                        //getting current itemstock before pushing update.
                        //assigning latest itemstock to the data for the update
                    }
                }
            }

        })
    }

    fun updateStockDetail(){
        binding.skuCode.addTextChangedListener(object : TextWatcher{
            override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
            override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {

            }
            override fun afterTextChanged(editable: Editable) {
                var x:String=""
                var pos:Int=adapterPosition
                    for (i in 0 until RecyclerViewAdapter.ob.dataSelected.size){

                        if (editable.toString().trim()!=""){
                            x=editable.toString().trim()
                            //RecyclerViewAdapter.ob.dataSelected[adapterPosition].sku_code=x
                            println("$x in if")
                        }
                    }
                    //println(RecyclerViewAdapter.ob.dataSelected[adapterPosition].sku_code)
                    //getting edited text and calling the function to get updated details.
                    getUpdatedDetails(x,pos)
    binding.skuStock.removeTextChangedListener(this)

                }
        })
    }

}
</code>```

}

If possible please review my code and let me know what are things i need to work on.
Note: ob.dataselected is a global variable from another recyclerview adapter.
Textchangedlistener i am talking about is in the fun updateStockDetail()

答:
In the documentation for afterTextChanged we see the following:

This method is called to notify you that, somewhere within s, the text has been changed. It is legitimate to make further changes to s from this callback, but be careful not to get yourself into an infinite loop, because any changes you make will cause this method to be called again recursively.

(The emphasis is mine.) I don't see where you remove the text watcher before changing the text, so you may be in an infinite loop.

To remove the text watcher use removeTextChangedListener. You can replace the text watcher after making changes.

Body:
I have been working on a stock keeping application as a demo to learn kotlin and android studio, I have added textchangedlistener in a recycler view item, which everytime it text is changed, gets information from Api and displays new item on textview. This works good for only one time, After that it keeps infinitely changing. please check video for better understanding : ScreenRecording .

Here is my rcv adapter :

class RecyclerViewAdapterU (val dataList:ArrayList<ModelClass>): RecyclerView.Adapter<RecyclerViewAdapterU.ViewHolder>() {
var _binding: UploadItemViewBinding? = null
val binding get() = _binding!!
override fun onCreateViewHolder(
    parent: ViewGroup,
    viewType: Int
): RecyclerViewAdapterU.ViewHolder {

    val v =
        LayoutInflater.from(parent.context).inflate(R.layout.upload_item_view, parent, false)
    _binding = UploadItemViewBinding.bind(v)
    return ViewHolder(binding.root)
}

override fun onBindViewHolder(holder: ViewHolder, @SuppressLint("RecyclerView") position: Int) {

    bindItems(dataList[position])
    holder.getStock()
    holder.updateStockDetail()
}
fun bindItems(data: ModelClass) {

    binding.apply {
        itemquant.text=data.item_quant
        uploadItemName.text = data.item_name
        uploadMfg.text = data.mfg
        skuStock.setText(data.item_stock.toString())
        skuCode.setText(data.sku_code)
    }

}

fun getUpdatedDetails(skucode:String,pos:Int){
    val call: Call<List<ModelClass>>? =
        ApiClient.instance?.myApi?.getfromsku(skucode)!!
    call!!.enqueue(object : Callback<List<ModelClass>?> {
        override fun onResponse(
            call: Call<List<ModelClass>?>,
            response: Response<List<ModelClass>?>
        ) {
            val skuDetails=response.body()

            if (skuDetails != null) {
                dataList.removeAt(pos)
                for (i in skuDetails){
                    println(i.item_name)
                    dataList.add(pos,i)
                }
                notifyItemChanged(pos)
            }

        }

        override fun onFailure(call: Call<List<ModelClass>?>, t: Throwable) {
        }
    })
}

override fun getItemCount(): Int {
    return dataList.size
}

inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

    fun getStock() {

        binding.skuStock.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
            override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
            override fun afterTextChanged(editable: Editable) {
                for (i in 0 until RecyclerViewAdapter.ob.dataSelected.size){
                    if (editable.toString().trim()!=""){
                        var x= editable.toString().trim().toInt()
                        RecyclerViewAdapter.ob.dataSelected[adapterPosition].item_stock=x
                        //getting current itemstock before pushing update.
                        //assigning latest itemstock to the data for the update
                    }
                }
            }

        })
    }

    fun updateStockDetail(){
        binding.skuCode.addTextChangedListener(object : TextWatcher{
            override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
            override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {

            }
            override fun afterTextChanged(editable: Editable) {
                var x:String=""
                var pos:Int=adapterPosition
                    for (i in 0 until RecyclerViewAdapter.ob.dataSelected.size){

                        if (editable.toString().trim()!=""){
                            x=editable.toString().trim()
                            //RecyclerViewAdapter.ob.dataSelected[adapterPosition].sku_code=x
                            println("$x in if")
                        }
                    }
                    //println(RecyclerViewAdapter.ob.dataSelected[adapterPosition].sku_code)
                    //getting edited text and calling the function to get updated details.
                    getUpdatedDetails(x,pos)
    binding.skuStock.removeTextChangedListener(this)

                }
        })
    }

}

}

If possible please review my code and let me know what are things i need to work on.
Note: ob.dataselected is a global variable from another recyclerview adapter.
Textchangedlistener i am talking about is in the fun updateStockDetail()


问:
how can test my API in different PC which is in same wifi network using my IPv4 address?
how can I test my API in different PC which is in same WIFI network using my IPv4 address ?
like if i have if 192.168.2.222 then I got the error URL image plz tell me how can I solve.The API is working fine in local host. but in IPv4 I got this error so plz guide me. I have tried all the configuration from different sources but still getting this error.</p>

答:
serve the application on your host IP address

command

```<code>php artisan serve --host=192.168.2.222
</code>```

Now you can access the app on another computer on the same network using the ip address

If connection to the app is frozen, try and check your firewall settings.

But on default, this command should do the magic without any extra steps.

Body:
serve the application on your host IP address

command

php artisan serve --host=192.168.2.222

Now you can access the app on another computer on the same network using the ip address

If connection to the app is frozen, try and check your firewall settings.

But on default, this command should do the magic without any extra steps.