问:
Failing to match number ranges with pattern declared in DEFINE block using PyPi regex package
I'm using https://github.com/mrabarnett/mrab-regex (via pip install regex, but experiencing a failure here:

pattern_string =  r'''
        (?&N)
        ^ \W*? ENTRY              \W* (?P<entries>    (?&Range)    )     (?&N)

        (?(DEFINE)
             (?P<Decimal>
                 [ ]*? \d+ (?:[.,] \d+)? [ ]*?
             )
             (?P<Range>
                 (?&Decimal) - (?&Decimal) | (?&Decimal)
                 #(?&d) (?: - (?&d))?
             )
             (?P<N>
                 [\s\S]*?
             )
        )
    '''

flags = regex.MULTILINE | regex.VERBOSE  #| regex.DOTALL  | regex.V1 #| regex.IGNORECASE | regex.UNICODE

pattern = regex.compile(pattern_string, flags=flags)

bk2 = f'''
ENTRY: 0.0975 - 0.101
'''.strip()
match = pattern.match('ENTRY: 0.0975 - 0.101')
match.groupdict()
```
<p>gives:</p>
```{'entries': '0.0975', 'Decimal': None, 'Range': None, 'N': None}
```
<p>It misses the second value.</p>
```> pip show regex
Name: regex
Version: 2022.1.18
Summary: Alternative regular expression module, to replace re.
Home-page: https://github.com/mrabarnett/mrab-regex
Author: Matthew Barnett
Author-email: regex@mrabarnett.plus.com
License: Apache Software License
Location: ...
Requires:
Required-by:

> python --version
Python 3.10.0
```

答:
The problem is that the spaces you defined in the Decimal group pattern are consumed, and the DEFINE patterns are atomic, so although the last [ ]*? part is lazy and can match zero times, once it matches, there is no going back. You can check this if you put the Decimal pattern into an atomic group and compare two patterns, cf. this regex demo and this regex demo. (?mx)^\W*?ENTRY\W*(?P<entries>(?>[ ]*? \d+ (?:[.,] \d+)? [ ]*?) - (?>[ ]*? \d+ (?:[.,] \d+)? [ ]*?) | (?>[ ]*? \d+ (?:[.,] \d+)? [ ]*?)) exposes the same behavior as your regex with DEFINE block, while (?mx)^\W*?ENTRY\W*(?P<entries>[ ]*? \d+ (?:[.,] \d+)? [ ]*? - [ ]*? \d+ (?:[.,] \d+)? [ ]*? | [ ]*? \d+ (?:[.,] \d+)? [ ]*?) finds the match correctly.

The easiest fix is to move the optional space patterns into the Range group pattern.

There are other minor enhancements you might want to introduce here:

As you are only interested in the captured substring, you do not need to use regex.match with the N group pattern ([\s\S]*?), you may use regex.search and remove the N pattern from the regex

You do not need to use a group for a a|a-b like patterns, you can use a more efficient optional non-capturing group approach, a(?:-b)?.

So, the regex can look like

```<code>^ \W* ENTRY              \W* (?P<entries>    (?&Range)    )
(?(DEFINE)
    (?P<Decimal>
        \d+ (?:[.,] \d+)?
    )
    (?P<Range>
        (?&Decimal)(?:\ *-\ *(?&Decimal))*
    )
)
</code>```

See the regex demo.

See the Python demo:

import regex
pattern_string =  r'''
        ^ \W* ENTRY              \W* (?P<entries>    (?&Range)    )

        (?(DEFINE)
             (?P<Decimal>
                 \d+ (?:[.,] \d+)?
             )
             (?P<Range>
                 (?&Decimal)(?:\ *-\ *(?&Decimal))?
             )
        )
    '''

flags = regex.MULTILINE | regex.VERBOSE
pattern = regex.compile(pattern_string, flags=flags)

bk2 = f'''
ENTRY: 0.0975 - 0.101
'''.strip()

match = pattern.search('ENTRY: 0.0975 - 0.101')

print(match.groupdict())
```
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>{'entries': '0.0975 - 0.101', 'Decimal': None, 'Range': None}
</code>```

Body:
I'm using https://github.com/mrabarnett/mrab-regex (via pip install regex, but experiencing a failure here:

pattern_string =  r'''
        (?&N)
        ^ \W*? ENTRY              \W* (?P<entries>    (?&Range)    )     (?&N)

        (?(DEFINE)
             (?P<Decimal>
                 [ ]*? \d+ (?:[.,] \d+)? [ ]*?
             )
             (?P<Range>
                 (?&Decimal) - (?&Decimal) | (?&Decimal)
                 #(?&d) (?: - (?&d))?
             )
             (?P<N>
                 [\s\S]*?
             )
        )
    '''

flags = regex.MULTILINE | regex.VERBOSE  #| regex.DOTALL  | regex.V1 #| regex.IGNORECASE | regex.UNICODE

pattern = regex.compile(pattern_string, flags=flags)

bk2 = f'''
ENTRY: 0.0975 - 0.101
'''.strip()
match = pattern.match('ENTRY: 0.0975 - 0.101')
match.groupdict()

gives:

{'entries': '0.0975', 'Decimal': None, 'Range': None, 'N': None}

It misses the second value.

> pip show regex
Name: regex
Version: 2022.1.18
Summary: Alternative regular expression module, to replace re.
Home-page: https://github.com/mrabarnett/mrab-regex
Author: Matthew Barnett
Author-email: regex@mrabarnett.plus.com
License: Apache Software License
Location: ...
Requires:
Required-by:

> python --version
Python 3.10.0

Body:
The problem is that the spaces you defined in the Decimal group pattern are consumed, and the DEFINE patterns are atomic, so although the last [ ]*? part is lazy and can match zero times, once it matches, there is no going back. You can check this if you put the Decimal pattern into an atomic group and compare two patterns, cf. this regex demo and this regex demo. (?mx)^\W*?ENTRY\W*(?P<entries>(?>[ ]*? \d+ (?:[.,] \d+)? [ ]*?) - (?>[ ]*? \d+ (?:[.,] \d+)? [ ]*?) | (?>[ ]*? \d+ (?:[.,] \d+)? [ ]*?)) exposes the same behavior as your regex with DEFINE block, while (?mx)^\W*?ENTRY\W*(?P<entries>[ ]*? \d+ (?:[.,] \d+)? [ ]*? - [ ]*? \d+ (?:[.,] \d+)? [ ]*? | [ ]*? \d+ (?:[.,] \d+)? [ ]*?) finds the match correctly.

The easiest fix is to move the optional space patterns into the Range group pattern.

There are other minor enhancements you might want to introduce here:

As you are only interested in the captured substring, you do not need to use regex.match with the N group pattern ([\s\S]*?), you may use regex.search and remove the N pattern from the regex

You do not need to use a group for a a|a-b like patterns, you can use a more efficient optional non-capturing group approach, a(?:-b)?.

So, the regex can look like

^ \W* ENTRY              \W* (?P<entries>    (?&Range)    )
(?(DEFINE)
    (?P<Decimal>
        \d+ (?:[.,] \d+)?
    )
    (?P<Range>
        (?&Decimal)(?:\ *-\ *(?&Decimal))*
    )
)

See the regex demo.

See the Python demo:

import regex
pattern_string =  r'''
        ^ \W* ENTRY              \W* (?P<entries>    (?&Range)    )

        (?(DEFINE)
             (?P<Decimal>
                 \d+ (?:[.,] \d+)?
             )
             (?P<Range>
                 (?&Decimal)(?:\ *-\ *(?&Decimal))?
             )
        )
    '''

flags = regex.MULTILINE | regex.VERBOSE
pattern = regex.compile(pattern_string, flags=flags)

bk2 = f'''
ENTRY: 0.0975 - 0.101
'''.strip()

match = pattern.search('ENTRY: 0.0975 - 0.101')

print(match.groupdict())

Output:

{'entries': '0.0975 - 0.101', 'Decimal': None, 'Range': None}


来源: stackexchange

问:
Check if a given time lies between two times regardless of date
I have timespans:

String time1 = 01:00:00

String time2 = 05:00:00

I want to check if time1 and time2 both lies between 20:11:13 and 14:49:00.

Actually, 01:00:00 is greater than 20:11:13 and less than 14:49:00 considering 20:11:13 is always less than 14:49:00. This is given prerequisite.

So what I want is, 20:11:13 < 01:00:00 < 14:49:00.

So I need something like that:

```<code> public void getTimeSpans()
{
    boolean firstTime = false, secondTime = false;

    if(time1 > "20:11:13" && time1 < "14:49:00")
    {
       firstTime = true;
    }

    if(time2 > "20:11:13" && time2 < "14:49:00")
    {
       secondTime = true;
    }
 }
</code>```

I know that this code does not give correct result as I am comparing the string objects.

How to do that as they are the timespans but not the strings to compare?

答:
In my situation, I'm not interested at all in date times.
So this is my solution which works solely on hours as integers:</p>
```<code>boolean isInTimeRange(int startingHour, int endingHour, int hourOfDayToCheck) {
    if (endingHour > startingHour) {
        return hourOfDayToCheck >= startingHour && hourOfDayToCheck < endingHour;
    } else {
        return hourOfDayToCheck >= startingHour || hourOfDayToCheck < endingHour;
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have timespans:

String time1 = 01:00:00

String time2 = 05:00:00

I want to check if time1 and time2 both lies between 20:11:13 and 14:49:00.

Actually, 01:00:00 is greater than 20:11:13 and less than 14:49:00 considering 20:11:13 is always less than 14:49:00. This is given prerequisite.

So what I want is, 20:11:13 < 01:00:00 < 14:49:00.

So I need something like that:

 public void getTimeSpans()
{
    boolean firstTime = false, secondTime = false;

    if(time1 > "20:11:13" && time1 < "14:49:00")
    {
       firstTime = true;
    }

    if(time2 > "20:11:13" && time2 < "14:49:00")
    {
       secondTime = true;
    }
 }

I know that this code does not give correct result as I am comparing the string objects.

How to do that as they are the timespans but not the strings to compare?

Body:
In my situation, I'm not interested at all in date times.
So this is my solution which works solely on hours as integers:

boolean isInTimeRange(int startingHour, int endingHour, int hourOfDayToCheck) {
    if (endingHour > startingHour) {
        return hourOfDayToCheck >= startingHour && hourOfDayToCheck < endingHour;
    } else {
        return hourOfDayToCheck >= startingHour || hourOfDayToCheck < endingHour;
    }
}

ContentLicense: CC BY-SA 4.0


问:
How to make middle ellipsis in Text with Jetpack Compose
I need to make Middle Ellipsis in Jetpack Compose Text. As far as I see there is only Clip, Ellipsis and Visible options for TextOverflow.
Something like this:  4gh45g43h...bh4bh6b64

答:
Since TextView already supports ellipsize in the middle you can just wrap it in compose using AndroidView

```<code>AndroidView(
  factory = { context ->
    TextView(context).apply {
      maxLines = 1
      ellipsize = MIDDLE
    }
  },
  update = { it.text = "A looooooooooong text" }
)
</code>```

Body:
Since TextView already supports ellipsize in the middle you can just wrap it in compose using AndroidView

AndroidView(
  factory = { context ->
    TextView(context).apply {
      maxLines = 1
      ellipsize = MIDDLE
    }
  },
  update = { it.text = "A looooooooooong text" }
)


问:
Rails: Reset a model attribute at specific time each day
I have a rails app with a Location model, which has a rating, and a rating_count field. Now, I need to reset every Location's rating and rating_countattributes to 0 at a specific time everyday, lets say 12:00:00 UTC.

How would I accomplish this? I'm using the default sqlite3 databases.

答:
The easiest thing is to write a rake task that does that job, and then use whatever scheduling system your host uses (cron).

An alternative is to use delayed_job which allows to push work to a background process. While delayed-job is not exactly suited for something like this, it is perfectably capable of doing this. If your rails process starts, you add a new job, to run at 12:00. And the running of the job reschedules the job.

The nice thing of delayed-job is that your code runs in the context of a rails-process, so you can use methods you already have. Also nice: jobs are stored in the database, so you can have an overview.


问:
How can I make a textbox readonly using spring security role?
I'm just a new to Spring security.

Today I just wonder how can I make a textbox as readonly depends on account's role?

For example, If account's role is not Admin I want to make textbox as readonly.

I tried this code for it, but It didn't work.

```<code><sec:authorize access="hasAnyRole('ROLE_ADMIN')">
    <input type="text" id="userID">
</sec:authorize>
</code>```

Thanks for your help.

答:
If you mean client side, I think you're looking for

```<code> <input type="text" id="userID" readonly="readonly">
</code>```

If you mean server-side ("don't trust the user input"), well... That depends how your server side works.

Body:
I'm just a new to Spring security.

Today I just wonder how can I make a textbox as readonly depends on account's role?

For example, If account's role is not Admin I want to make textbox as readonly.

I tried this code for it, but It didn't work.

<sec:authorize access="hasAnyRole('ROLE_ADMIN')">
    <input type="text" id="userID">
</sec:authorize>

Thanks for your help.

Body:
If you mean client side, I think you're looking for

 <input type="text" id="userID" readonly="readonly">

If you mean server-side ("don't trust the user input"), well... That depends how your server side works.


问:
NavigationView embedded in a UIHostingController has additional safe area insets
Anyone know how to deal with this? Seems as though when you have a UIHostingController with a NavigationView the following happens:

Notice the big grey tab bar safe area.

This is primarily a UIKit application. Were replacing on of our tabs in the tab bar with A swiftUI view.

here is my code:

```<code>var body: some View {
    NavigationView {
        ZStack {
            MapKitMapView(
                mapView: mapView,
                annotations: $annotations,
                polylines: $polylines,
                centerCoordinate: $centerCoordinate,
                newMapRegion: $newMapRegion,
                userTrackingMode: $userTrackingMode
            )
            .edgesIgnoringSafeArea(.all)
            .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .center)

            ButtonLayer(mapView: mapView, userTrackingMode: $userTrackingMode, showSheet: $showSheet)
                .frame(maxWidth: .infinity, maxHeight: .infinity)
                .padding(.margin)
        }
        .edgesIgnoringSafeArea(.all)
        .navigationBarHidden(true)
        .sheet(isPresented: $showSheet) {
            SettingsView()
        }
    }
}
</code>```

pardon the censorship. I want the app to remain anonymous.

But essentially my UITabBar is built as follows:

there is a global UINavigationViewController

the first and only item in the UINavigationController is this UITabBar

The UITabBar tabs are all created programatically.

The tab in question is just a UIHostingController with the code you see above as the rootView.

I have tried manually setting additional safe area insets to the UIHostingController to make it expand outside of the safe area.

If I remove the NavigationView everything looks and functions as intended.

答:
This situation happens when you embed UIHostingController in UITabBar. To remove this gray line, just set the translucency of the UITabBar.

tabBar.isTranslucent = true
```

Body:
Anyone know how to deal with this? Seems as though when you have a UIHostingController with a NavigationView the following happens:

Notice the big grey tab bar safe area.

This is primarily a UIKit application. Were replacing on of our tabs in the tab bar with A swiftUI view.

here is my code:

var body: some View {
    NavigationView {
        ZStack {
            MapKitMapView(
                mapView: mapView,
                annotations: $annotations,
                polylines: $polylines,
                centerCoordinate: $centerCoordinate,
                newMapRegion: $newMapRegion,
                userTrackingMode: $userTrackingMode
            )
            .edgesIgnoringSafeArea(.all)
            .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .center)

            ButtonLayer(mapView: mapView, userTrackingMode: $userTrackingMode, showSheet: $showSheet)
                .frame(maxWidth: .infinity, maxHeight: .infinity)
                .padding(.margin)
        }
        .edgesIgnoringSafeArea(.all)
        .navigationBarHidden(true)
        .sheet(isPresented: $showSheet) {
            SettingsView()
        }
    }
}

pardon the censorship. I want the app to remain anonymous.

But essentially my UITabBar is built as follows:

there is a global UINavigationViewController

the first and only item in the UINavigationController is this UITabBar

The UITabBar tabs are all created programatically.

The tab in question is just a UIHostingController with the code you see above as the rootView.

I have tried manually setting additional safe area insets to the UIHostingController to make it expand outside of the safe area.

If I remove the NavigationView everything looks and functions as intended.


问:
Left join pandas if column value is within a certain range?
I was wondering if it were possible to merge two datasets if the values were in a certain range of each other.

For example, If I want to join on zip codes, then an exact match isn't required and the join takes place if the left table zip code is within a range of 15 from the right table zip code.

Here is some example data and a diagram to make this clear.

```<code># Create sample dataframe

data1 = [[10001, 'NY'], [10007, 'NY'], [10013, 'NY'], [90011, 'CA'], [91331, 'CA'], [90650, 'CA']]

data2 = [[10003, 'NY', 1200], [10008, 'NY', 1460], [10010, 'NY', 1900], [90011, 'CA', 850], [91315, 'CA', 1700], [90645, 'CA',2300]]

df_left = pd.DataFrame(data1, columns = ['Zip', 'State'])
df_right = pd.DataFrame(data2, columns = ['Zip', 'State', 'Average_Rent'])

print(df_left.head())
print(df_right.head())

# Merge
df_merge = df_left.merge(df_right, left_on='Zip', right_on = 'Zip', how='left')
print(df_merge)

# Want to merge if within a 5 zipcode radius. If two zips nearby, then choose the first observation.
data3 = [[10001, 'NY', 10003, 12000], [10007, 'NY', 10008, 1460], [10007, 'NY', 10010, 1900], [10013, 'NY', 'NaN', 'NaN'],
         [90011, 'CA', 90011, 850], [91331, 'CA', 'NaN', 'NaN'], [90650, 'CA', 90645, 2300]]

df_want = pd.DataFrame(data3, columns = ['Zip_left', 'State', 'Zip_right', 'Rent'])
df_want.head(6)
</code>```

The result of this is shown below:

A traditional left join will leave me with the top result, whereas the result I am after is shown in the bottom (not concerned about what columns are output, I just input them on the spot).

The main rule I want to enforce is the interval merge. For the tie-breaker this example chooses the first one, but even if the zip code 10010 from the right table gets matched twice: once to 10007 and once to 10013, that's not an issue. Quite frankly the tie-breaker rule doesn't bother me, as long as at least one merge is made.

答:
One option is conditional_join from pyjanitor, which tries to avoid a cartesian join, and improve memory performance.

I also borrow from enke's solution (He grasped your question way better than I could):

# install latest from dev
# pip install git+https://github.com/pyjanitor-devs/pyjanitor.git
import pandas as pd
import janitor
```
<p>Create boundaries for start and end, for df_right</p>
<pre class="lang-py prettyprint-override"><code>df_right = (df_right
            .assign(
                start = df_right.Zip - 15,
                end = df_right.Zip + 15)
            .rename(columns = {'Zip':'Zip_right',
                               'State':'State_right'})
            )
</code>```

Compute conditional_join:

out = (df_left
      .conditional_join(
          df_right,
          ('State', 'State_right', '=='),
          ('Zip', 'start', '>='),
          ('Zip', 'end', '<='),
          how = 'left')
      .assign(diff_ = lambda df: df.Zip.sub(df.Zip_right).abs())
       )
```
<p>Get the rows with the minimum <code>diff_</code>:</p>
<pre class="lang-py prettyprint-override"><code>(
out
# you can get better performance
# if you skip the sort
# and just grab the fist match
.sort_values(['Zip', 'diff_'])
.groupby('Zip', sort = False)
.nth(0)
.loc[:, ['State', 'Zip_right', 'Average_Rent']]
.reset_index()
)

     Zip State  Zip_right  Average_Rent
0  10001    NY    10003.0        1200.0
1  10007    NY    10008.0        1460.0
2  10013    NY    10010.0        1900.0
3  90011    CA    90011.0         850.0
4  90650    CA    90645.0        2300.0
5  91331    CA        NaN           NaN
</code>```

Body:
I was wondering if it were possible to merge two datasets if the values were in a certain range of each other.

For example, If I want to join on zip codes, then an exact match isn't required and the join takes place if the left table zip code is within a range of 15 from the right table zip code.

Here is some example data and a diagram to make this clear.

# Create sample dataframe

data1 = [[10001, 'NY'], [10007, 'NY'], [10013, 'NY'], [90011, 'CA'], [91331, 'CA'], [90650, 'CA']]

data2 = [[10003, 'NY', 1200], [10008, 'NY', 1460], [10010, 'NY', 1900], [90011, 'CA', 850], [91315, 'CA', 1700], [90645, 'CA',2300]]

df_left = pd.DataFrame(data1, columns = ['Zip', 'State'])
df_right = pd.DataFrame(data2, columns = ['Zip', 'State', 'Average_Rent'])

print(df_left.head())
print(df_right.head())

# Merge
df_merge = df_left.merge(df_right, left_on='Zip', right_on = 'Zip', how='left')
print(df_merge)

# Want to merge if within a 5 zipcode radius. If two zips nearby, then choose the first observation.
data3 = [[10001, 'NY', 10003, 12000], [10007, 'NY', 10008, 1460], [10007, 'NY', 10010, 1900], [10013, 'NY', 'NaN', 'NaN'],
         [90011, 'CA', 90011, 850], [91331, 'CA', 'NaN', 'NaN'], [90650, 'CA', 90645, 2300]]

df_want = pd.DataFrame(data3, columns = ['Zip_left', 'State', 'Zip_right', 'Rent'])
df_want.head(6)

The result of this is shown below:

A traditional left join will leave me with the top result, whereas the result I am after is shown in the bottom (not concerned about what columns are output, I just input them on the spot).

The main rule I want to enforce is the interval merge. For the tie-breaker this example chooses the first one, but even if the zip code 10010 from the right table gets matched twice: once to 10007 and once to 10013, that's not an issue. Quite frankly the tie-breaker rule doesn't bother me, as long as at least one merge is made.

Body:
One option is conditional_join from pyjanitor, which tries to avoid a cartesian join, and improve memory performance.

I also borrow from enke's solution (He grasped your question way better than I could):

# install latest from dev
# pip install git+https://github.com/pyjanitor-devs/pyjanitor.git
import pandas as pd
import janitor

Create boundaries for start and end, for df_right

df_right = (df_right
            .assign(
                start = df_right.Zip - 15,
                end = df_right.Zip + 15)
            .rename(columns = {'Zip':'Zip_right',
                               'State':'State_right'})
            )

Compute conditional_join:

out = (df_left
      .conditional_join(
          df_right,
          ('State', 'State_right', '=='),
          ('Zip', 'start', '>='),
          ('Zip', 'end', '<='),
          how = 'left')
      .assign(diff_ = lambda df: df.Zip.sub(df.Zip_right).abs())
       )

Get the rows with the minimum diff_:

(
out
# you can get better performance
# if you skip the sort
# and just grab the fist match
.sort_values(['Zip', 'diff_'])
.groupby('Zip', sort = False)
.nth(0)
.loc[:, ['State', 'Zip_right', 'Average_Rent']]
.reset_index()
)

     Zip State  Zip_right  Average_Rent
0  10001    NY    10003.0        1200.0
1  10007    NY    10008.0        1460.0
2  10013    NY    10010.0        1900.0
3  90011    CA    90011.0         850.0
4  90650    CA    90645.0        2300.0
5  91331    CA        NaN           NaN


问:
Listview is showing only after I hot reload or refresh in flutter
I almost tried everything. My functions async, my snapshots async. I'm using future builders, My carousel slider works fine. I don't need to hot reload or refresh for carousel slider. But for my listview builder i need to refresh every time to fetch data. I tried connection state status for if statment but connection state getting done quickly (before data completely loaded). So my pictures and my datas not coming without refresh or hot reload.

```<code>import 'package:cached_network_image/cached_network_image.dart';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

import 'package:video_games/model.dart';
import 'package:flutter/material.dart';
import 'package:video_games/send_models.dart';
import 'package:video_games/views/details_view.dart';
import 'package:get/get.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';

class HomePage extends StatefulWidget {
  HomePage({
    Key? key,
  }) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  Future<Autogenerated> apiCall() async {
    final response = await http.get(Uri.parse(
        'https://api.rawg.io/api/games?key=5ac29048d12d45d0949c77038115cb56&page=1'));

    return Autogenerated.fromJson(jsonDecode(response.body));
  }

  int slideractiveindex = 0;
  var urlImages = [];
  var uniqueImages = [];
  var growableList = [];
  var listId = [];

  @override
  Widget build(BuildContext context) {
    clearCache();

    return SingleChildScrollView(
      child: Column(
        children: [
          FutureBuilder<Autogenerated>(
            future: apiCall(),
            builder: (BuildContext context, AsyncSnapshot snapshot) {
              List<Results>? data = snapshot.data!.results;
              return Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  CarouselSlider.builder(
                    itemCount: 20,
                    itemBuilder: (context, index, realIndex) {
                      urlImages.add(data![index].backgroundImage);
                      uniqueImages = urlImages.toSet().toList();

                      final urlImage = uniqueImages[index];
                      return buildImage(urlImage, index);
                    },
                    options: CarouselOptions(
                        autoPlay: true,
                        enlargeCenterPage: true,
                        onPageChanged: (index, reason) {}),
                  ),
                  const SizedBox(height: 32),
                ],
              );
            },
          ),
          FutureBuilder<Autogenerated>(
            future: apiCall(),
            builder: (BuildContext context, AsyncSnapshot snapshot) {
              if (snapshot.hasData) {
                print(snapshot.connectionState);
                print(urlImages.length);
                List<Results>? data = snapshot.data!.results;

                return ListView.builder(
                  physics: NeverScrollableScrollPhysics(),
                  shrinkWrap: true,
                  itemBuilder: (BuildContext context, index) {
                    growableList.add(data![index].name);
                    listId.assign(data[index].id);

                    // String? id = data[index].id.toString();
                    // urlImages.add(data[index].backgroundImage);
                    uniqueImages = urlImages.toSet().toList();
                    final urlImage = uniqueImages[index + 1];
                    return Padding(
                      padding: const EdgeInsets.all(10.0),
                      child: ListTile(
                        tileColor: Colors.black12,
                        leading: InkWell(
                            onTap: () {
                              Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                    builder: (context) => DetailsPage(
                                      id: '${data[index].id}',
                                    ),
                                  ));
                            },
                            child: buildImage2(urlImage, index)),
                        title: Column(
                          children: [
                            Text(
                              '${data[index].name}',
                            ),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Text('Rating : ${data[index].rating}'),
                                SizedBox(
                                  width: 20,
                                ),
                                Text('Release : ${data[index].released}'),
                              ],
                            )
                          ],
                        ),
                      ),
                    );
                  },
                  itemCount: 19,
                );
              } else {
                return CircularProgressIndicator();
              }
            },
          ),
        ],
      ),
    );
  }

  Widget buildImage(String? urlImage, int index) {
    return Container(
        margin: EdgeInsets.symmetric(horizontal: 12),
        color: Colors.grey,
        child: CachedNetworkImage(
          imageUrl: urlImage!,
          fit: BoxFit.cover,
          key: UniqueKey(),
          errorWidget: (context, url, error) => Icon(Icons.error),
          placeholder: (context, url) => Container(
            child: Center(
              child: CircularProgressIndicator(),
            ),
          ),
        ));
  }

  Widget buildImage2(String? urlImage, int index) {
    return Container(
        height: 100,
        width: 100,
        child: CachedNetworkImage(
          imageUrl: urlImage!,
          key: UniqueKey(),
          fit: BoxFit.cover,
          errorWidget: (context, url, error) => Icon(Icons.error),
          placeholder: (context, url) => Container(
            child: Center(
              child: CircularProgressIndicator(),
            ),
          ),
        ));
  }

  void clearCache() {
    DefaultCacheManager().emptyCache();
    imageCache!.clear();
    imageCache!.clearLiveImages();
    setState(() {});
  }
}

</code>```

This is my error part

```<code>════════ Exception caught by widgets library ═══════════════════════════════════
RangeError (index): Invalid value: Valid value range is empty: 17
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by widgets library ═══════════════════════════════════
RangeError (index): Invalid value: Valid value range is empty: 18
════════════════════════════════════════════════════════════════════════════════

</code>```

答:
FutureBuilder removes boilerplate code. see

Let's say you want to fetch some data from the backend on page launch and show a loader until data comes.

Tasks for ListBuilder:

Have two state variables, dataFromBackend and isLoadingFlag On

launch, set isLoadingFlag = true, and based on this, show loader.

Once data arrives, set data with what you get from backend and set

isLoadingFlag = false (inside setState obviously)

We need to have a if-else in widget creation. If isLoadingFlag is
true,show the loader else show the data. On failure, show error
message.

Tasks for FutureBuilder:

Give the async task in future of Future Builder

Based on connectionState, show message (loading, active(streams),
done)

Based on data(snapshot.hasError), show view

Pros of FutureBuilder

Does not use the two state variables and setState

Reactive programming (FutureBuilder will take care of updating the
view on data arrival)

Example:

```<code>FutureBuilder<String>(
future: _fetchNetworkCall, // async work
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
   switch (snapshot.connectionState) {
     case ConnectionState.waiting: return Text('Loading....');
     default:
       if (snapshot.hasError)
          return Text('Error: ${snapshot.error}');
       else
      return Text('Result: ${snapshot.data}');
    }
  },
)
</code>```

Body:
I almost tried everything. My functions async, my snapshots async. I'm using future builders, My carousel slider works fine. I don't need to hot reload or refresh for carousel slider. But for my listview builder i need to refresh every time to fetch data. I tried connection state status for if statment but connection state getting done quickly (before data completely loaded). So my pictures and my datas not coming without refresh or hot reload.

import 'package:cached_network_image/cached_network_image.dart';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

import 'package:video_games/model.dart';
import 'package:flutter/material.dart';
import 'package:video_games/send_models.dart';
import 'package:video_games/views/details_view.dart';
import 'package:get/get.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';

class HomePage extends StatefulWidget {
  HomePage({
    Key? key,
  }) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  Future<Autogenerated> apiCall() async {
    final response = await http.get(Uri.parse(
        'https://api.rawg.io/api/games?key=5ac29048d12d45d0949c77038115cb56&page=1'));

    return Autogenerated.fromJson(jsonDecode(response.body));
  }

  int slideractiveindex = 0;
  var urlImages = [];
  var uniqueImages = [];
  var growableList = [];
  var listId = [];

  @override
  Widget build(BuildContext context) {
    clearCache();

    return SingleChildScrollView(
      child: Column(
        children: [
          FutureBuilder<Autogenerated>(
            future: apiCall(),
            builder: (BuildContext context, AsyncSnapshot snapshot) {
              List<Results>? data = snapshot.data!.results;
              return Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  CarouselSlider.builder(
                    itemCount: 20,
                    itemBuilder: (context, index, realIndex) {
                      urlImages.add(data![index].backgroundImage);
                      uniqueImages = urlImages.toSet().toList();

                      final urlImage = uniqueImages[index];
                      return buildImage(urlImage, index);
                    },
                    options: CarouselOptions(
                        autoPlay: true,
                        enlargeCenterPage: true,
                        onPageChanged: (index, reason) {}),
                  ),
                  const SizedBox(height: 32),
                ],
              );
            },
          ),
          FutureBuilder<Autogenerated>(
            future: apiCall(),
            builder: (BuildContext context, AsyncSnapshot snapshot) {
              if (snapshot.hasData) {
                print(snapshot.connectionState);
                print(urlImages.length);
                List<Results>? data = snapshot.data!.results;

                return ListView.builder(
                  physics: NeverScrollableScrollPhysics(),
                  shrinkWrap: true,
                  itemBuilder: (BuildContext context, index) {
                    growableList.add(data![index].name);
                    listId.assign(data[index].id);

                    // String? id = data[index].id.toString();
                    // urlImages.add(data[index].backgroundImage);
                    uniqueImages = urlImages.toSet().toList();
                    final urlImage = uniqueImages[index + 1];
                    return Padding(
                      padding: const EdgeInsets.all(10.0),
                      child: ListTile(
                        tileColor: Colors.black12,
                        leading: InkWell(
                            onTap: () {
                              Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                    builder: (context) => DetailsPage(
                                      id: '${data[index].id}',
                                    ),
                                  ));
                            },
                            child: buildImage2(urlImage, index)),
                        title: Column(
                          children: [
                            Text(
                              '${data[index].name}',
                            ),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Text('Rating : ${data[index].rating}'),
                                SizedBox(
                                  width: 20,
                                ),
                                Text('Release : ${data[index].released}'),
                              ],
                            )
                          ],
                        ),
                      ),
                    );
                  },
                  itemCount: 19,
                );
              } else {
                return CircularProgressIndicator();
              }
            },
          ),
        ],
      ),
    );
  }

  Widget buildImage(String? urlImage, int index) {
    return Container(
        margin: EdgeInsets.symmetric(horizontal: 12),
        color: Colors.grey,
        child: CachedNetworkImage(
          imageUrl: urlImage!,
          fit: BoxFit.cover,
          key: UniqueKey(),
          errorWidget: (context, url, error) => Icon(Icons.error),
          placeholder: (context, url) => Container(
            child: Center(
              child: CircularProgressIndicator(),
            ),
          ),
        ));
  }

  Widget buildImage2(String? urlImage, int index) {
    return Container(
        height: 100,
        width: 100,
        child: CachedNetworkImage(
          imageUrl: urlImage!,
          key: UniqueKey(),
          fit: BoxFit.cover,
          errorWidget: (context, url, error) => Icon(Icons.error),
          placeholder: (context, url) => Container(
            child: Center(
              child: CircularProgressIndicator(),
            ),
          ),
        ));
  }

  void clearCache() {
    DefaultCacheManager().emptyCache();
    imageCache!.clear();
    imageCache!.clearLiveImages();
    setState(() {});
  }
}

This is my error part

════════ Exception caught by widgets library ═══════════════════════════════════
RangeError (index): Invalid value: Valid value range is empty: 17
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by widgets library ═══════════════════════════════════
RangeError (index): Invalid value: Valid value range is empty: 18
════════════════════════════════════════════════════════════════════════════════

Body:
FutureBuilder removes boilerplate code. see

Let's say you want to fetch some data from the backend on page launch and show a loader until data comes.

Tasks for ListBuilder:

Have two state variables, dataFromBackend and isLoadingFlag On

launch, set isLoadingFlag = true, and based on this, show loader.

Once data arrives, set data with what you get from backend and set

isLoadingFlag = false (inside setState obviously)

We need to have a if-else in widget creation. If isLoadingFlag is
true,show the loader else show the data. On failure, show error
message.

Tasks for FutureBuilder:

Give the async task in future of Future Builder

Based on connectionState, show message (loading, active(streams),
done)

Based on data(snapshot.hasError), show view

Pros of FutureBuilder

Does not use the two state variables and setState

Reactive programming (FutureBuilder will take care of updating the
view on data arrival)

Example:

FutureBuilder<String>(
future: _fetchNetworkCall, // async work
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
   switch (snapshot.connectionState) {
     case ConnectionState.waiting: return Text('Loading....');
     default:
       if (snapshot.hasError)
          return Text('Error: ${snapshot.error}');
       else
      return Text('Result: ${snapshot.data}');
    }
  },
)


问:
equivalent java library required for curl- to submit forms to remote web sites
I have a php web application that asks the user for all fields' values (all fields for a web form) and then shows only captcha and multiple choice values of that form on screen, the end user has to fill in these values and then the form is submitted to its action. The operative part of the php code uses curl for this operation. That php code is given below-

```<code>    $page = $curl->post($submit_url, array(
    'TITLE'   => $urltitle,
    'URL' => $urlurl,
    'OWNER_NAME' => $urlname,
    'OWNER_EMAIL' => $urlemail,
    'CATEGORY_ID' =>  $CATEGORY_ID,
    'RECPR_URL' => '',
    'IMAGEHASH' => $hash,
    'LINK_TYPE' => $dfln,
    'CAPTCHA' => $captcha,
    'AGREERULES' => 'on',
    'submit'    => 'Continue'
));
</code>```

My question is, is there a library in Java that can do the same thing? I plan to submit same/similar data to many web forms, if this can be done in java...

答:
java.net.HttpURLConnection - see this answer

apache http components

Body:
I have a php web application that asks the user for all fields' values (all fields for a web form) and then shows only captcha and multiple choice values of that form on screen, the end user has to fill in these values and then the form is submitted to its action. The operative part of the php code uses curl for this operation. That php code is given below-

    $page = $curl->post($submit_url, array(
    'TITLE'   => $urltitle,
    'URL' => $urlurl,
    'OWNER_NAME' => $urlname,
    'OWNER_EMAIL' => $urlemail,
    'CATEGORY_ID' =>  $CATEGORY_ID,
    'RECPR_URL' => '',
    'IMAGEHASH' => $hash,
    'LINK_TYPE' => $dfln,
    'CAPTCHA' => $captcha,
    'AGREERULES' => 'on',
    'submit'    => 'Continue'
));

My question is, is there a library in Java that can do the same thing? I plan to submit same/similar data to many web forms, if this can be done in java...


问:
Properly linking to a javascript library installed with npm?
When I install a JS library with npm, say:

```<code>npm install chartjs
</code>```

It places the required JS file in ./node_modules/chartjs/chart.js.

Since I want the file to be located in, say, ./public/js/chart.js, I could just copy and paste it there. But is there a proper way to do that, like linking directly to the file installed by npm ?

Thanks in advance for your help. (Yes I'm kind of new to JS...)

答:
In general, if you are using npm to manage your dependencies then you would use a bundler (such as Rollup, Webpack, or Parcel) to combine them into a browser-friendly file in your distribution directory.

MDN has a tutorial which walks through setting up a basic project in Parcel.

Body:
When I install a JS library with npm, say:

npm install chartjs

It places the required JS file in ./node_modules/chartjs/chart.js.

Since I want the file to be located in, say, ./public/js/chart.js, I could just copy and paste it there. But is there a proper way to do that, like linking directly to the file installed by npm ?

Thanks in advance for your help. (Yes I'm kind of new to JS...)


问:
converting a string to lowercase/uppercase depending upon the count of upper/lower case characters in it
i have to output a string in all uppercase if count of uppercase characters in it is more otherwise lowercase string will be shown if lowercase characters are more in the string,in case both characters are equal i will print the string in lowercase only
this the code i have written , but , it's not giving desired output,like it is returning the same string back to me , please help me with the errors

here's the code,i am using c++.

```<code>string s;
cin>>s;
int uc=0,lc=0;
for (int i = 0; i < s.size(); i++)
{
    if(isupper(s[i])){
        uc++;
    }
    else{
        lc++;
    }
}
if(uc>lc){
    for (int j = 0; j < s.size(); j++)
    {
        toupper(s[j]);

    }
    cout<<s<<endl;
}
else{
    for (int k = 0; k < s.size(); k++)
    {
        tolower(s[k]);
    }
    cout<<s<<endl;
}
</code>```

答:
After your first loop, do this:</p>
```<code>string result = (uc>lc) ? toupper(s) : tolower(s);
</code>```

Body:
i have to output a string in all uppercase if count of uppercase characters in it is more otherwise lowercase string will be shown if lowercase characters are more in the string,in case both characters are equal i will print the string in lowercase only
this the code i have written , but , it's not giving desired output,like it is returning the same string back to me , please help me with the errors

here's the code,i am using c++.

string s;
cin>>s;
int uc=0,lc=0;
for (int i = 0; i < s.size(); i++)
{
    if(isupper(s[i])){
        uc++;
    }
    else{
        lc++;
    }
}
if(uc>lc){
    for (int j = 0; j < s.size(); j++)
    {
        toupper(s[j]);

    }
    cout<<s<<endl;
}
else{
    for (int k = 0; k < s.size(); k++)
    {
        tolower(s[k]);
    }
    cout<<s<<endl;
}

Body:
After your first loop, do this:

string result = (uc>lc) ? toupper(s) : tolower(s);


问:
Aggregation data design
I am new to MongoDB and I have data in the table name doctors

```<code>[
  {
    _id: "610d0f36a793342c08b49b0a",
    hospitals: [
      {
        _id: "6166c2ea807d823f20722d52",
        hospital: "6166c2ea807d823f20722d4f"
      },
      {
        _id: "61cd446d20c97e302c667e89",
        hospital: "61cd446d20c97e302c667e87"
      }
    ]
  }
]
</code>```

2nd table name weekdays

```<code> [
  {
    _id: "6166c2ea807d823f20722d4f",
    hospitalId: "615442355273d22b90b92491",
    fee: "800"
  },
  {
    _id: "61cd446d20c97e302c667e87",
    hospitalId: "615d4ebc5521472af0aae53d",
    fee: "1000"
  }
]
</code>```

3rd table name hospitals

```<code>  [
  {
    _id: "615442355273d22b90b92491",
    hospitalName: "ABC"
  },
  {
    _id: "615d4ebc5521472af0aae53d",
    hospitalName: "ABC"
  }
]
</code>```

If I use

```<code>db.doctors.find().populate({
          path: "hospitals.hospital",
          populate: {
            path: "hospitalId",
            select: "hospitalName",
          },
        })
</code>```

I get result in this format

```<code>[
  {
    _id: "610d0f36a793342c08b49b0a",
    hospitals: [
      {
        _id: "6166c2ea807d823f20722d52",
        hospital: {
          _id: "6166c2ea807d823f20722d4f",
          fee: "800",
          hospitalId: {
            _id: "615442355273d22b90b92491",
            hosptialName: "ABC"
          }
        }
      },
      {
        _id: "61cd446d20c97e302c667e89",
        hospital: {
          _id: "61cd446d20c97e302c667e87",
          fee: "1000",
          hospitalId: {
            _id: "615d4ebc5521472af0aae53d",
            hosptialName: "ABC"
          }
        }
      }
    ]
  }
]
</code>```

Now I am achieving this kind of result using the aggregation
When I `

```<code>db.doctors.aggregate([{$lookup:{from:"weekdays", localField:"hospitals.hospital", foreignField:"_id", as:"hospitals"}}])
</code>```

it returns

```<code>[
  {
    _id: "610d0f36a793342c08b49b0a",
    hospitals: [
      {
        _id: "6166c2ea807d823f20722d52",
        hospitalId: "615442355273d22b90b92491",
        fee: "800"
      },
      {
        _id: 61cd446d20c97e302c667e89,
        hospitalId: "615d4ebc5521472af0aae53d",
        fee: 800
      }
    ]
  }
]
</code>```

how to achieve the result like I am getting from find query using the aggregate.

答:
Alright, so basically .populate is a method by mongoose. Populate

I am assuming you wanted the result from the aggregation to be like this shown below.

```<code>[
  {
    "_id": "111",
    "hospitals": [
      {
        "_id": "331",
        "fee": "800",
        "hospital": {
          "_id": "441",
          "hospitalName": "ABC"
        },
        "hospitalId": "441"
      },
      {
        "_id": "332",
        "fee": "1000",
        "hospital": {
          "_id": "442",
          "hospitalName": "ABC"
        },
        "hospitalId": "442"
      }
    ]
  }
]
</code>```

So to achieve this you will need to $unwind arrays and do a $lookup again with the 3rd collection hospitals and $unwind again before grouping them up.

Here is the MongoDB Playground link

```<code>db.doctors.aggregate([
  {
    $lookup: {
      from: "weekdays",
      localField: "hospitals.hospital",
      foreignField: "_id",
      as: "hospitals"
    }
  },
  {
    "$unwind": "$hospitals"
  },
  {
    $lookup: {
      from: "hospitals",
      localField: "hospitals.hospitalId",
      foreignField: "_id",
      as: "hospitals.hospital"
    }
  },
  {
    "$unwind": "$hospitals.hospital"
  },
  {
    "$group": {
      "_id": "$_id",
      "hospitals": {
        "$push": "$hospitals"
      }
    }
  }
])
</code>```

Title: Aggregation data design

Body:
I am new to MongoDB and I have data in the table name doctors

[
  {
    _id: "610d0f36a793342c08b49b0a",
    hospitals: [
      {
        _id: "6166c2ea807d823f20722d52",
        hospital: "6166c2ea807d823f20722d4f"
      },
      {
        _id: "61cd446d20c97e302c667e89",
        hospital: "61cd446d20c97e302c667e87"
      }
    ]
  }
]

2nd table name weekdays

 [
  {
    _id: "6166c2ea807d823f20722d4f",
    hospitalId: "615442355273d22b90b92491",
    fee: "800"
  },
  {
    _id: "61cd446d20c97e302c667e87",
    hospitalId: "615d4ebc5521472af0aae53d",
    fee: "1000"
  }
]

3rd table name hospitals

  [
  {
    _id: "615442355273d22b90b92491",
    hospitalName: "ABC"
  },
  {
    _id: "615d4ebc5521472af0aae53d",
    hospitalName: "ABC"
  }
]

If I use

db.doctors.find().populate({
          path: "hospitals.hospital",
          populate: {
            path: "hospitalId",
            select: "hospitalName",
          },
        })

I get result in this format

[
  {
    _id: "610d0f36a793342c08b49b0a",
    hospitals: [
      {
        _id: "6166c2ea807d823f20722d52",
        hospital: {
          _id: "6166c2ea807d823f20722d4f",
          fee: "800",
          hospitalId: {
            _id: "615442355273d22b90b92491",
            hosptialName: "ABC"
          }
        }
      },
      {
        _id: "61cd446d20c97e302c667e89",
        hospital: {
          _id: "61cd446d20c97e302c667e87",
          fee: "1000",
          hospitalId: {
            _id: "615d4ebc5521472af0aae53d",
            hosptialName: "ABC"
          }
        }
      }
    ]
  }
]

Now I am achieving this kind of result using the aggregation
When I `

db.doctors.aggregate([{$lookup:{from:"weekdays", localField:"hospitals.hospital", foreignField:"_id", as:"hospitals"}}])

it returns

[
  {
    _id: "610d0f36a793342c08b49b0a",
    hospitals: [
      {
        _id: "6166c2ea807d823f20722d52",
        hospitalId: "615442355273d22b90b92491",
        fee: "800"
      },
      {
        _id: 61cd446d20c97e302c667e89,
        hospitalId: "615d4ebc5521472af0aae53d",
        fee: 800
      }
    ]
  }
]

how to achieve the result like I am getting from find query using the aggregate.

Body:
Alright, so basically .populate is a method by mongoose. Populate

I am assuming you wanted the result from the aggregation to be like this shown below.

[
  {
    "_id": "111",
    "hospitals": [
      {
        "_id": "331",
        "fee": "800",
        "hospital": {
          "_id": "441",
          "hospitalName": "ABC"
        },
        "hospitalId": "441"
      },
      {
        "_id": "332",
        "fee": "1000",
        "hospital": {
          "_id": "442",
          "hospitalName": "ABC"
        },
        "hospitalId": "442"
      }
    ]
  }
]

So to achieve this you will need to $unwind arrays and do a $lookup again with the 3rd collection hospitals and $unwind again before grouping them up.

Here is the MongoDB Playground link

db.doctors.aggregate([
  {
    $lookup: {
      from: "weekdays",
      localField: "hospitals.hospital",
      foreignField: "_id",
      as: "hospitals"
    }
  },
  {
    "$unwind": "$hospitals"
  },
  {
    $lookup: {
      from: "hospitals",
      localField: "hospitals.hospitalId",
      foreignField: "_id",
      as: "hospitals.hospital"
    }
  },
  {
    "$unwind": "$hospitals.hospital"
  },
  {
    "$group": {
      "_id": "$_id",
      "hospitals": {
        "$push": "$hospitals"
      }
    }
  }
])


问:
Twitter:image meta tag not showing image for its Twitter card
```<code><meta name="twitter:card" content="summary">
<meta property="twitter:title" content="Website's title">
<meta property="twitter:description" content="Lorem ipsum dol sor em convectur">
<meta property="twitter:image" content="styles/assetsOptimized/ourStory/StoreFront.jpeg">
<meta property="twitter:url" content="https://website.com/">
</code>```

Twitter card validation shows as follows:

Everything shows in the card except the image.

I have tried:

```<code><meta property="twitter:image" content="https://styles/assetsOptimized/ourStory/StoreFront.jpeg">
</code>```

These are the Open Graph Meta tags that work for Facebook, placed above the twitter tags(referencing the 11 meta tags found in the twitter validation - viewport, http-equiv:

```<code><meta property="og:title" content="Website's title">
<meta property="og:description" content="Lorem ipsum dol sor em convectur">
<meta property="og:image" content="styles/assetsOptimized/ourStory/ourStoryStoreFront.jpeg">
<meta property="og:url" content="https://website.com/">
</code>```

答:
I see the issue is solved but just FYI: An additional issue here is probably the fact twitter's meta tags do not use the property attribute but the name attribute, as shown in their documentation here.

So your code would look like:

<meta name="twitter:image" content="https://styles/assetsOptimized/ourStory/StoreFront.jpeg">```

Body:
<meta name="twitter:card" content="summary">
<meta property="twitter:title" content="Website's title">
<meta property="twitter:description" content="Lorem ipsum dol sor em convectur">
<meta property="twitter:image" content="styles/assetsOptimized/ourStory/StoreFront.jpeg">
<meta property="twitter:url" content="https://website.com/">

Twitter card validation shows as follows:

Everything shows in the card except the image.

I have tried:

<meta property="twitter:image" content="https://styles/assetsOptimized/ourStory/StoreFront.jpeg">

These are the Open Graph Meta tags that work for Facebook, placed above the twitter tags(referencing the 11 meta tags found in the twitter validation - viewport, http-equiv:

<meta property="og:title" content="Website's title">
<meta property="og:description" content="Lorem ipsum dol sor em convectur">
<meta property="og:image" content="styles/assetsOptimized/ourStory/ourStoryStoreFront.jpeg">
<meta property="og:url" content="https://website.com/">


问:
xcode build to iPhone device it has an invalid code signature
I wanted to build my project in my iPhone, I got this error message

```<code>The operation couldn’t be completed.
Unable to launch com.xxxx.test because it has an invalid code signature,
inadequate entitlements or its profile has not been explicitly trusted by the user.
</code>```

I tried to go to settings> general> VPN and device management but I have nothing inside it I only have the possibility to log in with a work or school account and nothing else. My app does not appear in the VPN and device management section therefore I cannot authorize anything.How can I fix it? Thanks.

Xcode 13.0
iPhone X iOS 15

答:
This solved my case.

```<code>iPhone Settings -> General -> VPN and device management -> From "Developer App" section found "Apple Development: APPLE_ID" -> Trust
</code>```

See the screenshots:

Body:
I wanted to build my project in my iPhone, I got this error message

The operation couldn’t be completed.
Unable to launch com.xxxx.test because it has an invalid code signature,
inadequate entitlements or its profile has not been explicitly trusted by the user.

I tried to go to settings> general> VPN and device management but I have nothing inside it I only have the possibility to log in with a work or school account and nothing else. My app does not appear in the VPN and device management section therefore I cannot authorize anything.How can I fix it? Thanks.

Xcode 13.0
iPhone X iOS 15

Body:
This solved my case.

iPhone Settings -> General -> VPN and device management -> From "Developer App" section found "Apple Development: APPLE_ID" -> Trust

See the screenshots:


问:
Divide number into digits and save them in list (array) using python
I want to divide number into digits and save them in list (or array) in python. So firstly I should create list like

```<code>dig = [0 for i in range(10)]
</code>```

and then

```<code>i = 0
while num > 9:
    dig[i] = num % 10
    i += 1
    num /= 10
dig[i] = num
</code>```

But I don't really like just creating list for 10 spaces, is it possible to get length of number without repeating loop

```<code>i = 0
num2 = num
while num2 > 9:
    num2 /= 10
    i += 1
i += 1
</code>```

and then repeat first part of code? Or just make as I made in first place? I don't know exact length of number but it won't be very long

So any advices? Maybe you know better way to divide numbers into digits, or maybe something else.

答:
Since you're just adding the digits from smallest to greatest in order, just use an empty list:

```<code>dig = []
i = 0
while num > 9:
    dig.append(num % 10)
    i += 1
    num /= 10
dig.append(num)
</code>```

Alternatively, just do

```<code>dig = list(int(d) for d in str(num))
</code>```

Which will turn i.e. 123 into '123' then turn each digit back into a number and put them into a list, resulting in [1, 2, 3].

If you want it in the same order as your version, use

```<code>dig = reversed(int(d) for d in str(num))
</code>```

If you really just want to get the length of a number, it's easiest to do len(str(num)) which turns it into a string then gets the length.

Body:
I want to divide number into digits and save them in list (or array) in python. So firstly I should create list like

dig = [0 for i in range(10)]

and then

i = 0
while num > 9:
    dig[i] = num % 10
    i += 1
    num /= 10
dig[i] = num

But I don't really like just creating list for 10 spaces, is it possible to get length of number without repeating loop

i = 0
num2 = num
while num2 > 9:
    num2 /= 10
    i += 1
i += 1

and then repeat first part of code? Or just make as I made in first place? I don't know exact length of number but it won't be very long

So any advices? Maybe you know better way to divide numbers into digits, or maybe something else.

Body:
Since you're just adding the digits from smallest to greatest in order, just use an empty list:

dig = []
i = 0
while num > 9:
    dig.append(num % 10)
    i += 1
    num /= 10
dig.append(num)

Alternatively, just do

dig = list(int(d) for d in str(num))

Which will turn i.e. 123 into '123' then turn each digit back into a number and put them into a list, resulting in [1, 2, 3].

If you want it in the same order as your version, use

dig = reversed(int(d) for d in str(num))

If you really just want to get the length of a number, it's easiest to do len(str(num)) which turns it into a string then gets the length.


问:
Move S3 objects to another folder in same bucket but with same permissions using C#
I am able to move an object in an S3 bucket from one directory to another directory using C# but unable to copy all current permissions with that object.

For example, my current object has public access permissions but after moving it to another directory it lost the public read permissions.

Here is the code I'm using to move objects:

```<code>public void MoveFile(string sourceBucket, string destinationFolder, string file) {
        AmazonS3Client s3Client = new AmazonS3Client(ConfigurationHelper.AmazonS3AccessKey, ConfigurationHelper.AmazonS3SecretAccessKey, Amazon.RegionEndpoint.USEast1);

        S3FileInfo currentObject = new S3FileInfo(s3Client, sourceBucket, file);
        currentObject.MoveTo(sourceBucket + "/" + destinationFolder, file);
    }
</code>```

Here is the output after moving file to another directory:

It lost public "Read" permission.

答:
I've figure out issue myself, by using CopyObject() and DeleteObject() instead of using moveTo inbuild method and that solves my issue,

here is the code which really helped me:

```<code>CopyObjectRequest copyObjectRequest = new CopyObjectRequest
        {
            SourceBucket = sourceBucket,
            DestinationBucket = sourceBucket + "/" + destinationFolder,
            SourceKey = file,
            DestinationKey = file,
            CannedACL = S3CannedACL.PublicRead,
            StorageClass = S3StorageClass.StandardInfrequentAccess,
        };

        CopyObjectResponse response1 = s3Client.CopyObject(copyObjectRequest);

        var deleteObjectRequest = new DeleteObjectRequest
        {
            BucketName = sourceBucket,
            Key = file
        };

        s3Client.DeleteObject(deleteObjectRequest);
</code>```

I'm posting answer so it can be helpful for someone!!!

Body:
I am able to move an object in an S3 bucket from one directory to another directory using C# but unable to copy all current permissions with that object.

For example, my current object has public access permissions but after moving it to another directory it lost the public read permissions.

Here is the code I'm using to move objects:

public void MoveFile(string sourceBucket, string destinationFolder, string file) {
        AmazonS3Client s3Client = new AmazonS3Client(ConfigurationHelper.AmazonS3AccessKey, ConfigurationHelper.AmazonS3SecretAccessKey, Amazon.RegionEndpoint.USEast1);

        S3FileInfo currentObject = new S3FileInfo(s3Client, sourceBucket, file);
        currentObject.MoveTo(sourceBucket + "/" + destinationFolder, file);
    }

Here is the output after moving file to another directory:

It lost public "Read" permission.

Body:
I've figure out issue myself, by using CopyObject() and DeleteObject() instead of using moveTo inbuild method and that solves my issue,

here is the code which really helped me:

CopyObjectRequest copyObjectRequest = new CopyObjectRequest
        {
            SourceBucket = sourceBucket,
            DestinationBucket = sourceBucket + "/" + destinationFolder,
            SourceKey = file,
            DestinationKey = file,
            CannedACL = S3CannedACL.PublicRead,
            StorageClass = S3StorageClass.StandardInfrequentAccess,
        };

        CopyObjectResponse response1 = s3Client.CopyObject(copyObjectRequest);

        var deleteObjectRequest = new DeleteObjectRequest
        {
            BucketName = sourceBucket,
            Key = file
        };

        s3Client.DeleteObject(deleteObjectRequest);

I'm posting answer so it can be helpful for someone!!!


问:
Selecting all same html attributes with (different) values included in VSCode
I'm using VSCode for html editing. In VSCode it's very easy to select same occurences of a piece of code. What i need is selecting all ocuurances of an html attribute (like class, aria-label, etc.) with different values. Here's an example:

I want to select all "aria-label" occurences with the values included. So these will be selected:

```<code>aria-label="Apple"
aria-label="Oranges"
aria-label="Multiple Fruit Names"
aria-label=""
...
</code>```

Is there a way to do that in VSCode?

答:
You could use a regex for that:

^aria-label="[^"]*"

Explanation:

'^' ... matches newline

'aria-label=' ... that's your "search word"

'[^"]' ... any character

'*' ... zero or more occurrences of stuff within the group

Don't forget to enable regex search in search dialog (see below):

This is a good starting point to grasp the regex magic: https://en.wikipedia.org/wiki/Regular_expression#Basic_concepts .

Body:
I'm using VSCode for html editing. In VSCode it's very easy to select same occurences of a piece of code. What i need is selecting all ocuurances of an html attribute (like class, aria-label, etc.) with different values. Here's an example:

I want to select all "aria-label" occurences with the values included. So these will be selected:

aria-label="Apple"
aria-label="Oranges"
aria-label="Multiple Fruit Names"
aria-label=""
...

Is there a way to do that in VSCode?


问:
Reset role inheritance on a folder
I'm playing around with setting and resetting custom permissions on folders to get an idea of how this works for a script I'm planning to write to do this in bulk.  I am having trouble with ResetRoleInheritance.

I connect to the SharePoint site using Connect-PnPOnline and then do this:

```<code>$FolderURL = 'Shared Documents/General/Test Folder 2'
$Folder = Get-PnPFolder -Url $FolderURL -Includes ListItemAllFields.HasUniqueRoleAssignments
$Folder.ListItemAllFields.HasUniqueRoleAssignments
</code>```

This returns False as expected as I haven't broken inheritance yet.

Then I do:

```<code>$Folder.ListItemAllFields.BreakRoleInheritance($True,$True)
$Folder = Get-PnPFolder -Url $FolderURL -Includes ListItemAllFields.HasUniqueRoleAssignments
$Folder.ListItemAllFields.HasUniqueRoleAssignments
</code>```

This returns True as expected.

Then I do this:

```<code>$Folder.ResetRoleInheritance
$Folder = Get-PnPFolder -Url $FolderURL -Includes ListItemAllFields.HasUniqueRoleAssignments
$Folder.ListItemAllFields.HasUniqueRoleAssignments
</code>```

This still returns True so the inheritance hasn't been reset.  What am I doing wrong here?

答:
You could use the amd could be:</p>
```<code>$Folder.ListItemAllFields.ResetRoleInheritance()
$folder.Update()
$Folder = Get-PnPFolder -Url $FolderURL -Includes
ListItemAllFields.HasUniqueRoleAssignments
$Folder.ListItemAllFields.HasUniqueRoleAssignments
</code>```

Title: Reset role inheritance on a folder

Body:
I'm playing around with setting and resetting custom permissions on folders to get an idea of how this works for a script I'm planning to write to do this in bulk.  I am having trouble with ResetRoleInheritance.

I connect to the SharePoint site using Connect-PnPOnline and then do this:

$FolderURL = 'Shared Documents/General/Test Folder 2'
$Folder = Get-PnPFolder -Url $FolderURL -Includes ListItemAllFields.HasUniqueRoleAssignments
$Folder.ListItemAllFields.HasUniqueRoleAssignments

This returns False as expected as I haven't broken inheritance yet.

Then I do:

$Folder.ListItemAllFields.BreakRoleInheritance($True,$True)
$Folder = Get-PnPFolder -Url $FolderURL -Includes ListItemAllFields.HasUniqueRoleAssignments
$Folder.ListItemAllFields.HasUniqueRoleAssignments

This returns True as expected.

Then I do this:

$Folder.ResetRoleInheritance
$Folder = Get-PnPFolder -Url $FolderURL -Includes ListItemAllFields.HasUniqueRoleAssignments
$Folder.ListItemAllFields.HasUniqueRoleAssignments

This still returns True so the inheritance hasn't been reset.  What am I doing wrong here?

Body:
You could use the amd could be:

$Folder.ListItemAllFields.ResetRoleInheritance()
$folder.Update()
$Folder = Get-PnPFolder -Url $FolderURL -Includes
ListItemAllFields.HasUniqueRoleAssignments
$Folder.ListItemAllFields.HasUniqueRoleAssignments


问:
Android Huawei maps agconnect-services.json can't be located
I have the issue with Huawei maps after introducing product flavours and issue is referenced to the fact that agconnect-services.json can't be located

```<code>E/HMSSDK_AGCUtils: Get client/cp_id failed: java.io.FileNotFoundException: agconnect-services.json
</code>```

So everything was working fine until product flavours are introduced.

The configuration of product flavours are following:

```<code>flavorDimensions "provider"
productFlavors {
    huawei {
        dimension "provider"
    }
    google {
        dimension "provider"
    }
}
 sourceSets {
    huawei {
        java {
            srcDirs 'src/huawei/java'
        }
        res {
            srcDirs 'src/huawei/res'
        }
    }
    google {
        java {
            srcDirs 'src/google/java'
        }
        res {
            srcDirs 'src/google/res'
        }
    }
}
if (getGradle().getStartParameter().getTaskRequests().toString().contains("Huawei"))
{
    apply plugin: 'com.huawei.agconnect'
}

classpath 'com.huawei.agconnect:agcp:1.6.3.300'
</code>```

So the package name keeps the same nothing is changing for flavour. I tried positioning .json file to app/src/huawei but nothing helped.

 This is my current setup.

I tried positioning .json file to app/src/huawei, app/src/debugHuawei, app/src/debugHuawei, app/, app/src/huaweiDebug, app/src/debug/huawei but didn't help.

Thanks in advance

答:
you have to put this agconnect-services file outside the src folder:
just app/agconnect-services.json

also in your screenshot there are 2 agconnect-services.json files, delete them and put only 1 file in the path I indicated above

Body:
I have the issue with Huawei maps after introducing product flavours and issue is referenced to the fact that agconnect-services.json can't be located

E/HMSSDK_AGCUtils: Get client/cp_id failed: java.io.FileNotFoundException: agconnect-services.json

So everything was working fine until product flavours are introduced.

The configuration of product flavours are following:

flavorDimensions "provider"
productFlavors {
    huawei {
        dimension "provider"
    }
    google {
        dimension "provider"
    }
}
 sourceSets {
    huawei {
        java {
            srcDirs 'src/huawei/java'
        }
        res {
            srcDirs 'src/huawei/res'
        }
    }
    google {
        java {
            srcDirs 'src/google/java'
        }
        res {
            srcDirs 'src/google/res'
        }
    }
}
if (getGradle().getStartParameter().getTaskRequests().toString().contains("Huawei"))
{
    apply plugin: 'com.huawei.agconnect'
}

classpath 'com.huawei.agconnect:agcp:1.6.3.300'

So the package name keeps the same nothing is changing for flavour. I tried positioning .json file to app/src/huawei but nothing helped.

 This is my current setup.

I tried positioning .json file to app/src/huawei, app/src/debugHuawei, app/src/debugHuawei, app/, app/src/huaweiDebug, app/src/debug/huawei but didn't help.

Thanks in advance


问:
How to use github nuget packages on Visual Studio 2019
I try to learn Github action and packages. So, I create a sample nuget package and successfully created. However I could not use it.

I follow this step;

Options > Nuget Package Manager > Package Sources

Click add button write organization name and add package source address like that:

After that Visual Studio doesn't ask me any credential for this address.

If there is no credential, I will expect to an error. And I got it.

[github] Failed to retrieve metadata from source 'https://nuget.pkg.github.com/[OrganizationName]/query?q=&skip=0&take=26&prerelease=false&semVerLevel=2.0.0'.
  Response status code does not indicate success: 401 (Unauthorized).

Then, I decide to some credential like explained in github documentation.

My nuget.config file:

However still I get Unauthorized error. And also when I click the error link gettin a message like that:

{"errors":[{"code":"Your token has not been granted the required
  scopes to execute this query. The 'id' field requires one of the
  following scopes","message":" ['read:packages'], but your token has
  only been granted the: [''] scopes. Please modify your token's scopes
  at: https://github.com/settings/tokens."}]}

but I already have a token with read/write package credential.

All that fails and I try to another way. I add credential information to Windows Credential Manager. Eveything still same.

So, how I add and use my private nuget packages?

答:
It is not an easy task, but here is the solution (after 2 days of struggling)

First generate PAT (Personal Access Token) in Github

Follow these steps to generate a PAT

Very important to select the read:packages options

Github will show you the PAT for ONLY ONE TIME, So make sure to copy it to save place, otherwise, you have to generate it again

Now with PAT in your hand, Add Nuget.Config file to your project

The content of the file should be like following

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
    <packageSources>
        <clear />
        <add key="github" value="https://nuget.pkg.github.com/OWNER/index.json" />
    </packageSources>
    <packageSourceCredentials>
        <github>
            <add key="Username" value="USERNAME" />
            <add key="ClearTextPassword" value="TOKEN" />
        </github>
    </packageSourceCredentials>
</configuration>
</code>```

You must replace:

USERNAME with the name of your user account on GitHub.

TOKEN with your personal access token (the token you generated in Step 1).

OWNER with the name of the user or organization account that owns the repository containing your project.

You must restart Visual Studio or even Restart the PC This is important

After that open the Terminal and copy and paste (maybe with some modifications) the statement that Github give to you to install the package

Now you are ready to get the Package.

UPDATE

How to configure github nuget packages for teams?

Configure the nuget.config using environment variables:

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <add key="NuGet official package source" value="https://api.nuget.org/v3/index.json" />
    <add key="Github" value="https://nuget.pkg.github.com/OWNER/index.json" />
  </packageSources>
  <packageSourceCredentials>
    <Github>
      <add key="Username" value="%GITHUB_PACKAGE_USER_NAME%" />
      <add key="ClearTextPassword" value="%GITHUB_PACKAGE_TOKEN%" />
    </Github>
  </packageSourceCredentials>
</configuration>
</code>```

The GITHUB_PACKAGE_USER_NAME and GITHUB_PACKAGE_TOKEN can be anything you want.

Now, each team member should configure their user environment variables:

GITHUB_PACKAGE_USER_NAME: team member github user name

GITHUB_PACKAGE_TOKEN: team member Personal Access Token (PAT)

With those configurations, Visual Studio will be able to query and download packages, assuming the team member has access to the OWNER package repository.

How to restore github nuget packages in github actions workflows?

With the previous NuGet.config configured, you need to change your workflow passing the required environment variables, like so:

```<code>- name: Restore dependencies
  env:
    GITHUB_PACKAGE_USER_NAME: ${{ github.actor }}
    GITHUB_PACKAGE_TOKEN: ${{ secrets.RESTORE_ORGANIZATION_PACKAGES }}
  run: dotnet restore ./src
</code>```

Since you can't pass your PAT, you need to configure a github secret (either for the repository or the organization). In the above example, I created a secret named RESTORE_ORGANIZATION_PACKAGES with read:packages permission at the repository level.

Body:
It is not an easy task, but here is the solution (after 2 days of struggling)

First generate PAT (Personal Access Token) in Github

Follow these steps to generate a PAT

Very important to select the read:packages options

Github will show you the PAT for ONLY ONE TIME, So make sure to copy it to save place, otherwise, you have to generate it again

Now with PAT in your hand, Add Nuget.Config file to your project

The content of the file should be like following

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <packageSources>
        <clear />
        <add key="github" value="https://nuget.pkg.github.com/OWNER/index.json" />
    </packageSources>
    <packageSourceCredentials>
        <github>
            <add key="Username" value="USERNAME" />
            <add key="ClearTextPassword" value="TOKEN" />
        </github>
    </packageSourceCredentials>
</configuration>

You must replace:

USERNAME with the name of your user account on GitHub.

TOKEN with your personal access token (the token you generated in Step 1).

OWNER with the name of the user or organization account that owns the repository containing your project.

You must restart Visual Studio or even Restart the PC This is important

After that open the Terminal and copy and paste (maybe with some modifications) the statement that Github give to you to install the package

Now you are ready to get the Package.

UPDATE

How to configure github nuget packages for teams?

Configure the nuget.config using environment variables:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <add key="NuGet official package source" value="https://api.nuget.org/v3/index.json" />
    <add key="Github" value="https://nuget.pkg.github.com/OWNER/index.json" />
  </packageSources>
  <packageSourceCredentials>
    <Github>
      <add key="Username" value="%GITHUB_PACKAGE_USER_NAME%" />
      <add key="ClearTextPassword" value="%GITHUB_PACKAGE_TOKEN%" />
    </Github>
  </packageSourceCredentials>
</configuration>

The GITHUB_PACKAGE_USER_NAME and GITHUB_PACKAGE_TOKEN can be anything you want.

Now, each team member should configure their user environment variables:

GITHUB_PACKAGE_USER_NAME: team member github user name

GITHUB_PACKAGE_TOKEN: team member Personal Access Token (PAT)

With those configurations, Visual Studio will be able to query and download packages, assuming the team member has access to the OWNER package repository.

How to restore github nuget packages in github actions workflows?

With the previous NuGet.config configured, you need to change your workflow passing the required environment variables, like so:

- name: Restore dependencies
  env:
    GITHUB_PACKAGE_USER_NAME: ${{ github.actor }}
    GITHUB_PACKAGE_TOKEN: ${{ secrets.RESTORE_ORGANIZATION_PACKAGES }}
  run: dotnet restore ./src

Since you can't pass your PAT, you need to configure a github secret (either for the repository or the organization). In the above example, I created a secret named RESTORE_ORGANIZATION_PACKAGES with read:packages permission at the repository level.


问:
In R how would you replace values in a matrix that have a certain condition with values from another vector?
I have a matrix and a vector like this:

```<code>Matrix<-cbind(c(3,3,5,1),c(2,5,2,1))
Vector<-c(2,3,3,3)
</code>```

I want to replace the Matrix elements that are >= the corresponding Vector value with the values in the Vector so that the Matrix would now look like this:

```<code>MatrixNew<-cbind(c(2,3,3,1),c(2,3,2,1))
</code>```

What logic would achieve this?

答:
It is also possible to do it with dplyr::mutate.
It is interesting when you have to select a subset of variables.

```<code>library(dplyr)
dd = structure(list(V1 = c(3, 3, 5, 1), ` V2` = c(2, 5, 2, 1), Condition = c(2,
                3, 3, 3)), class = "data.frame", row.names = c(NA, -4L))
dd %>% mutate(across(contains('V'), ~ifelse(.>=Condition, Condition,. )))
      V1  V2 Condition
    # 1  2   2         2
    # 2  3   3         3
    # 3  3   2         3
    # 4  1   1         3
</code>```

Body:
I have a matrix and a vector like this:

Matrix<-cbind(c(3,3,5,1),c(2,5,2,1))
Vector<-c(2,3,3,3)

I want to replace the Matrix elements that are >= the corresponding Vector value with the values in the Vector so that the Matrix would now look like this:

MatrixNew<-cbind(c(2,3,3,1),c(2,3,2,1))

What logic would achieve this?

Body:
It is also possible to do it with dplyr::mutate.
It is interesting when you have to select a subset of variables.

library(dplyr)
dd = structure(list(V1 = c(3, 3, 5, 1), ` V2` = c(2, 5, 2, 1), Condition = c(2,
                3, 3, 3)), class = "data.frame", row.names = c(NA, -4L))
dd %>% mutate(across(contains('V'), ~ifelse(.>=Condition, Condition,. )))
      V1  V2 Condition
    # 1  2   2         2
    # 2  3   3         3
    # 3  3   2         3
    # 4  1   1         3


问:
How to encrypt SQLite DB using SQLiteCrypt
I wanted to ecrypt the db file that i am storing on the sdcard. I have looked into SqliteCrypt library for serving my purpose but its using C libraries to perform the encryption/decryption.

I would like to know if anyone has successfully included the library in their project? If yes, please guide me through the process.  Any guidance or any samples will be of great help.

Edit :  Anyway, it's much more simpler to implement encryption yourself based on plain Java. It's not difficult – @barmaley

I want to encrypt the whole db file as single unit. Not individual data fields. Please let me know if there is any alnerate mechanism to achieve this.

答: Try using SQLCipher for Android.</p>

Body: Try using SQLCipher for Android.


问:
How to call specific array values in v-for in Vuejs?
User.vue

<template>

      {{ item }}

</template>

```

Working code:- https://codesandbox.io/s/hardcore-cartwright-vi6qg?file=/src/components/User.vue

How to call specific value from an array in Vuejs.

At present, It is calling all values, from an array. But want to call only {{name}} and {{age}} values.

If i remove the v-for and write directly like this  {{ user.name }} {{ user.age }} --> It is printing the array values, But getting error as

[Vue warn]: Error in render: "TypeError: Cannot read properties of undefined (reading 'name')"
TypeError: Cannot read properties of undefined (reading 'name')

答:
In User.vue you have this comparison:

```<code>return this.lists.find((item) => item.id === this.$route.params.id);
</code>```

but the data you use from datalisttwo.js does not have the property id but instead cmd_id

So that find result will always be undefined which is the error you see in the javascript console:

```<code>[Vue warn]: Error in render: "TypeError: Cannot read properties of undefined (reading 'name')"
</code>```

so you'll need to update your find to be the following:

```<code>return this.lists.find((item) => item.cmd_id === this.$route.params.id);
</code>```

Body:
User.vue

<template>

      {{ item }}

</template>

Working code:- https://codesandbox.io/s/hardcore-cartwright-vi6qg?file=/src/components/User.vue

How to call specific value from an array in Vuejs.

At present, It is calling all values, from an array. But want to call only {{name}} and {{age}} values.

If i remove the v-for and write directly like this  {{ user.name }} {{ user.age }} --> It is printing the array values, But getting error as

[Vue warn]: Error in render: "TypeError: Cannot read properties of undefined (reading 'name')"
TypeError: Cannot read properties of undefined (reading 'name')

Body:
In User.vue you have this comparison:

return this.lists.find((item) => item.id === this.$route.params.id);

but the data you use from datalisttwo.js does not have the property id but instead cmd_id

So that find result will always be undefined which is the error you see in the javascript console:

[Vue warn]: Error in render: "TypeError: Cannot read properties of undefined (reading 'name')"

so you'll need to update your find to be the following:

return this.lists.find((item) => item.cmd_id === this.$route.params.id);


问:
boost:math:factorial2 throws an error while computing double factorial of -1?
The official documentation of boost library in C++ confirms that -1!! is defined. However, when I try to compute the double factorial of -1, it throws the following error
"Error in function boost::math::tgamma result of gamma is too large to represent". I can implement a code based on iteration to compute the same (if it comes to that), but would like to use optimized libraries wherever possible. Any suggestions on rectifying this issue?

```<code>#include <iostream>
#include  <boost/math/special_functions/factorials.hpp>

int main(int argc, char const *argv[]) {
  double t  = boost::math::double_factorial<double>(-1);
  std::cout << t <<"\n";
  return 0;
}
</code>```

This is the minimal working example.

答:
This is how boost::math::double_factorial is declared:

```<code>namespace boost{ namespace math{

template <class T>
T double_factorial(unsigned i);

template <class T, class Policy>
T double_factorial(unsigned i, const Policy&);

}} // namespaces
</code>```

According to the documentation for boost::math::double_factorial

The argument to double_factorial is type unsigned even though
technically -1!! is defined.

This means that, although mathematically -1!! is well defined, the function does not support negative inputs.
In fact, -1 will be silently converted to an unsigned, which will result in a large number-- hence the overflow.

As a workaround, you could declare an additional double_factorial function inside the namespace boost::math

Example, where for simplicity I have allowed for just -1!!.

```<code>#include <iostream>
#include <exception>
#include  <boost/math/special_functions/factorials.hpp>

namespace boost { namespace math {
    template <class T>
    T double_factorial(int i) { if (i == -1) return T{1}; else throw(std::runtime_error("Unknown double factorial")); }
} }

int main(int argc, char const *argv[]) {
  double t  = boost::math::double_factorial<double>(-1);
  std::cout << t <<"\n";
  return 0;
}
</code>```

See it live on Coliru

Warning

This solution will work, because the compiler will choose your new overload, inside the same namespace, when you call double_factorial with a negative argument.
It is however potentially dangerous: if a future version of boost allows for negative values, the code may not compile anymore, or ignore the new boost version.

A better solution is to wrap around double_gamma to a function you define, like as follows

```<code>template <class T>
T my_double_factorial(int i) {
    if (i > 0)
       return boost::math::double_factorial<T>(i);
    else if (i == -1)
       return T{1};
    else
       throw(std::runtime_error("Unknown double factorial"));
}
</code>```

Body:
The official documentation of boost library in C++ confirms that -1!! is defined. However, when I try to compute the double factorial of -1, it throws the following error
"Error in function boost::math::tgamma result of gamma is too large to represent". I can implement a code based on iteration to compute the same (if it comes to that), but would like to use optimized libraries wherever possible. Any suggestions on rectifying this issue?

#include <iostream>
#include  <boost/math/special_functions/factorials.hpp>

int main(int argc, char const *argv[]) {
  double t  = boost::math::double_factorial<double>(-1);
  std::cout << t <<"\n";
  return 0;
}

This is the minimal working example.

Body:
This is how boost::math::double_factorial is declared:

namespace boost{ namespace math{

template <class T>
T double_factorial(unsigned i);

template <class T, class Policy>
T double_factorial(unsigned i, const Policy&);

}} // namespaces

According to the documentation for boost::math::double_factorial

The argument to double_factorial is type unsigned even though
technically -1!! is defined.

This means that, although mathematically -1!! is well defined, the function does not support negative inputs.
In fact, -1 will be silently converted to an unsigned, which will result in a large number-- hence the overflow.

As a workaround, you could declare an additional double_factorial function inside the namespace boost::math

Example, where for simplicity I have allowed for just -1!!.

#include <iostream>
#include <exception>
#include  <boost/math/special_functions/factorials.hpp>

namespace boost { namespace math {
    template <class T>
    T double_factorial(int i) { if (i == -1) return T{1}; else throw(std::runtime_error("Unknown double factorial")); }
} }

int main(int argc, char const *argv[]) {
  double t  = boost::math::double_factorial<double>(-1);
  std::cout << t <<"\n";
  return 0;
}

See it live on Coliru

Warning

This solution will work, because the compiler will choose your new overload, inside the same namespace, when you call double_factorial with a negative argument.
It is however potentially dangerous: if a future version of boost allows for negative values, the code may not compile anymore, or ignore the new boost version.

A better solution is to wrap around double_gamma to a function you define, like as follows

template <class T>
T my_double_factorial(int i) {
    if (i > 0)
       return boost::math::double_factorial<T>(i);
    else if (i == -1)
       return T{1};
    else
       throw(std::runtime_error("Unknown double factorial"));
}