问:
Not able to show multiple timer in flutter
I am creating a Chat Polling feature and in chat polling I am showing timer for every new poll. Everything is working fine for the first poll but when I create a 2nd poll form backend new poll is creatine good with new question but the first poll timer is also reflecting in 2nd poll.

This is PollWidget to show Question with Timer.

```<code>class PollWidget extends StatefulWidget {

  final Poll poll;
  final disabled;
  final PollCallbacks callbacks;

  PollWidget({required this.poll, required this.callbacks, this.disabled = false});

  @override
  State<StatefulWidget> createState() => PollWidgetState();
}
</code>```
```<code>class PollWidgetState extends State<PollWidget> {

  @override
  Widget build(BuildContext context) {
    return Container(
        child: AbsorbPointer(
          absorbing: widget.disabled,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            mainAxisAlignment: MainAxisAlignment.center,
            children: _getChildren(widget.poll.question!),
          ),
        ),
    );
  }

  List<Widget> _getChildren(Question question) {
    List<Widget> children = List.empty(growable: true);

      children.add(_getSpace());
      children.add(
        TimerWidget(maxSeconds: widget.poll.maxSeconds, onFinish: () {
          widget.callbacks.onTimeFinished(widget.poll);
          setState(() {
            isPollEnded = true;
          });
          },
        ),
      );
    return children;
  }
}
</code>```

Here is TimerWidget class to show timere in poll.

```<code>class TimerWidget extends StatefulWidget {

  final int maxSeconds;
  final Function onFinish;

  TimerWidget({required this.maxSeconds, required this.onFinish});

  @override
  State<StatefulWidget> createState() => _TimerWidgetState();
}
</code>```
```<code>class _TimerWidgetState extends State<TimerWidget> {
  int currentSeconds = 0;

  Timer? timer;

  @override
  void initState() {
    super.initState();
    currentSeconds = widget.maxSeconds > 0 ? widget.maxSeconds : 0;

    if (currentSeconds > 0) {
      timer = Timer.periodic(Duration(seconds: 1), (timer) {

        setState(() {
          currentSeconds -= 1;
        });
        if (currentSeconds <= 0) {
          timer.cancel();
          widget.onFinish();
        }

      });
    }

  }

  @override
  void dispose() {
    super.dispose();
    timer?.cancel();
    timer = null;
  }

  String getTime() {

    if (currentSeconds >= 86400) {
      int days = currentSeconds~/(24 * 3600);
      int n = currentSeconds % (24 * 3600);
      int hour = n ~/ 3600;
      return "${days.prefixZero()} Days ${hour.prefixZero()} ${Strings.hours}";

    } else if (currentSeconds >= 3600) {
      int hours = currentSeconds~/3600;
      int minutes = (currentSeconds % 3600) ~/ 60;
      int seconds = (currentSeconds% 3600) % 60;
      return "${hours.prefixZero()}:${minutes.prefixZero()}:${seconds.prefixZero()} ${Strings.hours}";

    } else {
      int minutes = currentSeconds ~/60;
      int seconds = currentSeconds % 60;
      return "${minutes.prefixZero()}:${seconds.prefixZero()} ${(currentSeconds >= 60) ? Strings.minutes : Strings.seconds}";
    }
  }

  @override
  Widget build(BuildContext context) =>
      Text("${getTime()}" , style: TextStyle(color: Color(AppColors.alert)),);

}
</code>```

Please see the output here i have created 2nd poll of 2 min but it is showing above poll time

答:
Can you please try to add Key in Timer Widget?

```<code>    class TimerWidget extends StatefulWidget {
          final int maxSeconds;
          final Function onFinish;
          Key key;

          TimerWidget({required this.maxSeconds, required this.onFinish, Key key});

          @override
          State<StatefulWidget> createState() => _TimerWidgetState();
        }
</code>```

Use Timer Widget Like This

```<code>List<Widget> _getChildren(Question question) {
    List<Widget> children = List.empty(growable: true);

      children.add(_getSpace());
      children.add(
        TimerWidget(
      key:UniqueKey(),
       maxSeconds: widget.poll.maxSeconds, onFinish: () {
          widget.callbacks.onTimeFinished(widget.poll);
          setState(() {
            isPollEnded = true;
          });
          },
        ),
      );
    return children;
  }
</code>```

Body:
I am creating a Chat Polling feature and in chat polling I am showing timer for every new poll. Everything is working fine for the first poll but when I create a 2nd poll form backend new poll is creatine good with new question but the first poll timer is also reflecting in 2nd poll.

This is PollWidget to show Question with Timer.

class PollWidget extends StatefulWidget {

  final Poll poll;
  final disabled;
  final PollCallbacks callbacks;

  PollWidget({required this.poll, required this.callbacks, this.disabled = false});

  @override
  State<StatefulWidget> createState() => PollWidgetState();
}

class PollWidgetState extends State<PollWidget> {

  @override
  Widget build(BuildContext context) {
    return Container(
        child: AbsorbPointer(
          absorbing: widget.disabled,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            mainAxisAlignment: MainAxisAlignment.center,
            children: _getChildren(widget.poll.question!),
          ),
        ),
    );
  }

  List<Widget> _getChildren(Question question) {
    List<Widget> children = List.empty(growable: true);

      children.add(_getSpace());
      children.add(
        TimerWidget(maxSeconds: widget.poll.maxSeconds, onFinish: () {
          widget.callbacks.onTimeFinished(widget.poll);
          setState(() {
            isPollEnded = true;
          });
          },
        ),
      );
    return children;
  }
}

Here is TimerWidget class to show timere in poll.

class TimerWidget extends StatefulWidget {

  final int maxSeconds;
  final Function onFinish;

  TimerWidget({required this.maxSeconds, required this.onFinish});

  @override
  State<StatefulWidget> createState() => _TimerWidgetState();
}

class _TimerWidgetState extends State<TimerWidget> {
  int currentSeconds = 0;

  Timer? timer;

  @override
  void initState() {
    super.initState();
    currentSeconds = widget.maxSeconds > 0 ? widget.maxSeconds : 0;

    if (currentSeconds > 0) {
      timer = Timer.periodic(Duration(seconds: 1), (timer) {

        setState(() {
          currentSeconds -= 1;
        });
        if (currentSeconds <= 0) {
          timer.cancel();
          widget.onFinish();
        }

      });
    }

  }

  @override
  void dispose() {
    super.dispose();
    timer?.cancel();
    timer = null;
  }

  String getTime() {

    if (currentSeconds >= 86400) {
      int days = currentSeconds~/(24 * 3600);
      int n = currentSeconds % (24 * 3600);
      int hour = n ~/ 3600;
      return "${days.prefixZero()} Days ${hour.prefixZero()} ${Strings.hours}";

    } else if (currentSeconds >= 3600) {
      int hours = currentSeconds~/3600;
      int minutes = (currentSeconds % 3600) ~/ 60;
      int seconds = (currentSeconds% 3600) % 60;
      return "${hours.prefixZero()}:${minutes.prefixZero()}:${seconds.prefixZero()} ${Strings.hours}";

    } else {
      int minutes = currentSeconds ~/60;
      int seconds = currentSeconds % 60;
      return "${minutes.prefixZero()}:${seconds.prefixZero()} ${(currentSeconds >= 60) ? Strings.minutes : Strings.seconds}";
    }
  }

  @override
  Widget build(BuildContext context) =>
      Text("${getTime()}" , style: TextStyle(color: Color(AppColors.alert)),);

}

Please see the output here i have created 2nd poll of 2 min but it is showing above poll time

Body:
Can you please try to add Key in Timer Widget?

    class TimerWidget extends StatefulWidget {
          final int maxSeconds;
          final Function onFinish;
          Key key;

          TimerWidget({required this.maxSeconds, required this.onFinish, Key key});

          @override
          State<StatefulWidget> createState() => _TimerWidgetState();
        }

Use Timer Widget Like This

List<Widget> _getChildren(Question question) {
    List<Widget> children = List.empty(growable: true);

      children.add(_getSpace());
      children.add(
        TimerWidget(
      key:UniqueKey(),
       maxSeconds: widget.poll.maxSeconds, onFinish: () {
          widget.callbacks.onTimeFinished(widget.poll);
          setState(() {
            isPollEnded = true;
          });
          },
        ),
      );
    return children;
  }


来源: stackexchange

问:
Stopping updation of CALayer's contents  in iPhone
I am working on a pdf Reader application.I am making use of CALayer to render the pdf contents.i employed swipe gesture to navigate across the pages.The issue is, if the user attempts to go to next or previous page once the rendering of layer has started,the 'going to next page' action is being performed after completion of rendering of the current pdf page on to the layer.I want the rendering of the current page to be stopped immediately as soon as the swipe occurred and next page should start rendering on the layer.any idea please help.

UPDate:
here is my code

```<code>-(void)loadSinglePageWithWidth:(float)width andHeight:(float)height{
    draw=0;
    NSLog(@"before draw");
    [markupView.layer insertSublayer:renderingLayer1 above:tiledLayer1];
    loadingThread=[[NSThread alloc] initWithTarget:self selector:@selector(loadSinglePage) object:nil];
    [loadingThread start];
}
-(void)loadSinglePage{
    [renderingLayer1 setNeedsDisplay];
}
</code>```

as soon as i swipe, in my action method, the code is written like

```<code>[loadingThread cancel];
[loadingThread release];
loadingThread=nil;
</code>```

even i cancel the "loadingThread" the execution of the drawLayer: method seems to be running.am i correct with this thread approach?will drawLayer: code be executed by the thread which i am using to call setNeedsDisplay method?

答: I think that the best solution is to do the rendering in a separate thread. Once it's done, you simply display the rendered image on the screen. If not, you can always cancel the operation.</p>

ContentLicense: CC BY-SA 3.0

Body:
I am working on a pdf Reader application.I am making use of CALayer to render the pdf contents.i employed swipe gesture to navigate across the pages.The issue is, if the user attempts to go to next or previous page once the rendering of layer has started,the 'going to next page' action is being performed after completion of rendering of the current pdf page on to the layer.I want the rendering of the current page to be stopped immediately as soon as the swipe occurred and next page should start rendering on the layer.any idea please help.

UPDate:
here is my code

-(void)loadSinglePageWithWidth:(float)width andHeight:(float)height{
    draw=0;
    NSLog(@"before draw");
    [markupView.layer insertSublayer:renderingLayer1 above:tiledLayer1];
    loadingThread=[[NSThread alloc] initWithTarget:self selector:@selector(loadSinglePage) object:nil];
    [loadingThread start];
}
-(void)loadSinglePage{
    [renderingLayer1 setNeedsDisplay];
}

as soon as i swipe, in my action method, the code is written like

[loadingThread cancel];
[loadingThread release];
loadingThread=nil;

even i cancel the "loadingThread" the execution of the drawLayer: method seems to be running.am i correct with this thread approach?will drawLayer: code be executed by the thread which i am using to call setNeedsDisplay method?


问:
ORA 01722 : Dealing with invalid number
I am dealing with some data quality issues. I would like to remove all the dots and replace dot with comma in the end and replace negative in the end to front.
Below are the examples:

70.693.271.273,20- convert to -70693271273,20
1.312.871.286.870- convert to -1312871286,870

For the first case 70.693.271.273,20- I am using the below syntax which gives me results -70693271273,20

```<code>CASE WHEN REGEXP_COUNT("/BIC/ISMVALUE", '\.') >= 1
AND REGEXP_COUNT("/BIC/ISMVALUE", ',') = 1 THEN
to_number(REPLACE(TRIM(BOTH '-' FROM TRIM("/BIC/ISMVALUE")), '.', '') * (-1))
ELSE TO_NUMBER(TRIM("/BIC/ISMVALUE")) END oprl_value
</code>```

Similarly I would like to get same format results for case 2.
Can you please help on how to deal with second case 1.312.871.286.870- ?
Thanks

答:
You can specify the group and decimal separators as part of the to_number() call. If the numbers are always negative then you can include that too:

```<code>to_number(
    "/BIC/ISMVALUE",
    '999G999G999G999G999D99MI',
    'NLS_NUMERIC_CHARACTERS=,.'
  )
</code>```

If you have a mix of positive and negative numbers then the MI element will cause an error; if the positive numbers have a trailing + then you could use S instead of MI, but that seems unlikely. So instead you can handle negativity separately via a case expression, and strip the minus sign during conversion:

```<code>case when substr("/BIC/ISMVALUE", -1) = '-' then -1 else 1 end
*
to_number(
    rtrim("/BIC/ISMVALUE", '-'),
    '999G999G999G999G999D99',
    'NLS_NUMERIC_CHARACTERS=,.'
  )
</code>```

db<>fiddle

It's then up to your client or application to decide how to format that number for display - including which character to use as a decimal separator.

ContentLicense: CC BY-SA 4.0

Title: ORA 01722 : Dealing with invalid number

Body:
I am dealing with some data quality issues. I would like to remove all the dots and replace dot with comma in the end and replace negative in the end to front.
Below are the examples:

70.693.271.273,20- convert to -70693271273,20
1.312.871.286.870- convert to -1312871286,870

For the first case 70.693.271.273,20- I am using the below syntax which gives me results -70693271273,20

CASE WHEN REGEXP_COUNT("/BIC/ISMVALUE", '\.') >= 1
AND REGEXP_COUNT("/BIC/ISMVALUE", ',') = 1 THEN
to_number(REPLACE(TRIM(BOTH '-' FROM TRIM("/BIC/ISMVALUE")), '.', '') * (-1))
ELSE TO_NUMBER(TRIM("/BIC/ISMVALUE")) END oprl_value

Similarly I would like to get same format results for case 2.
Can you please help on how to deal with second case 1.312.871.286.870- ?
Thanks

Body:
You can specify the group and decimal separators as part of the to_number() call. If the numbers are always negative then you can include that too:

to_number(
    "/BIC/ISMVALUE",
    '999G999G999G999G999D99MI',
    'NLS_NUMERIC_CHARACTERS=,.'
  )

If you have a mix of positive and negative numbers then the MI element will cause an error; if the positive numbers have a trailing + then you could use S instead of MI, but that seems unlikely. So instead you can handle negativity separately via a case expression, and strip the minus sign during conversion:

case when substr("/BIC/ISMVALUE", -1) = '-' then -1 else 1 end
*
to_number(
    rtrim("/BIC/ISMVALUE", '-'),
    '999G999G999G999G999D99',
    'NLS_NUMERIC_CHARACTERS=,.'
  )

db<>fiddle

It's then up to your client or application to decide how to format that number for display - including which character to use as a decimal separator.


问:
How to stay logged in between multiple tests in Appium?
I'm testing a website in Chrome using Python, Appium, Android Emulator and trying to figure out how to stay logged in between multiple tests. The most common answer to similar questions I found is to add --user-data-dir option so I wrote the following:

```<code>options.add_argument('--user-data-dir=/data/data/com.android.chrome/app_chrome/Profile')
</code>```

According to chrome://version it changed profile path to /data/data/com.android.chrome/app_chrome/Profile/Default but still each time a driver instance is created that directory is restored to its default state.

Answering Appium - running browser tests without clearing browser data one person states that "Chromedriver always starts totally fresh, nothing is keeping" while another person from Using selenium: How to keep logged in after closing Driver in Python confirms that in case of OSX "it worked perfectly fine, I don't need to login again".

I also encountered Appium Reset Strategies and tried to add the following to desired capabilities with no luck:

```<code>desired_caps['noReset'] = 'true'
desired_caps['fullReset'] = 'false'
</code>```

答:
Just to add to the above, around 4 months ago a flag was added to chromedriver which allows you to prevent the clearing of the app data directory called "androidKeepAppDataDir".

When setting up your desired caps this worked for me and it stops chromedriver from running the adb shell pm clear command:

```<code>    DesiredCapabilities appCapabilities = new DesiredCapabilities();
    appCapabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, "Android");
    appCapabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, "UiAutomator2");
    appCapabilities.setCapability(MobileCapabilityType.NO_RESET, true);
    appCapabilities.setCapability(MobileCapabilityType.BROWSER_NAME, "chrome");
    ChromeOptions options = new ChromeOptions();
    options.setExperimentalOption("androidKeepAppDataDir", true);
    appCapabilities.setCapability(ChromeOptions.CAPABILITY, options);
</code>```

Body:
I'm testing a website in Chrome using Python, Appium, Android Emulator and trying to figure out how to stay logged in between multiple tests. The most common answer to similar questions I found is to add --user-data-dir option so I wrote the following:

options.add_argument('--user-data-dir=/data/data/com.android.chrome/app_chrome/Profile')

According to chrome://version it changed profile path to /data/data/com.android.chrome/app_chrome/Profile/Default but still each time a driver instance is created that directory is restored to its default state.

Answering Appium - running browser tests without clearing browser data one person states that "Chromedriver always starts totally fresh, nothing is keeping" while another person from Using selenium: How to keep logged in after closing Driver in Python confirms that in case of OSX "it worked perfectly fine, I don't need to login again".

I also encountered Appium Reset Strategies and tried to add the following to desired capabilities with no luck:

desired_caps['noReset'] = 'true'
desired_caps['fullReset'] = 'false'

Body:
Just to add to the above, around 4 months ago a flag was added to chromedriver which allows you to prevent the clearing of the app data directory called "androidKeepAppDataDir".

When setting up your desired caps this worked for me and it stops chromedriver from running the adb shell pm clear command:

    DesiredCapabilities appCapabilities = new DesiredCapabilities();
    appCapabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, "Android");
    appCapabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, "UiAutomator2");
    appCapabilities.setCapability(MobileCapabilityType.NO_RESET, true);
    appCapabilities.setCapability(MobileCapabilityType.BROWSER_NAME, "chrome");
    ChromeOptions options = new ChromeOptions();
    options.setExperimentalOption("androidKeepAppDataDir", true);
    appCapabilities.setCapability(ChromeOptions.CAPABILITY, options);


问:
Align single item left when Column crossAxisAlignment is center
Most contents in my column is centre so i preferred to choose crossAxisAlignment: CrossAxisAlignment.center but one top most content i want to be left aligned. How can i achieve this?

```<code>return Scaffold(
  body: Column(
    crossAxisAlignment: CrossAxisAlignment.center,
    children: <Widget>[
      Text('Left'), // It must be left aligned
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),

    ],
  ),
);
</code>```

答:
simple wrap the left item with a row and in the row add a expanded sized box like this:</p>
```<code>Column(
    crossAxisAlignment: CrossAxisAlignment.center,
    children: <Widget>[
      Row(
        children: [
          Text('Left'),
          // this is the same thing like a expanded widget with an sized box
          // in it but the expanded widget
          // makes problems on a real device
          Flexible(
            child: SizedBox(
              width: MediaQuery.of(context).size.width,
            ),
          ),
        ],
      ),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),

    ],
  ),
</code>```

Body:
Most contents in my column is centre so i preferred to choose crossAxisAlignment: CrossAxisAlignment.center but one top most content i want to be left aligned. How can i achieve this?

return Scaffold(
  body: Column(
    crossAxisAlignment: CrossAxisAlignment.center,
    children: <Widget>[
      Text('Left'), // It must be left aligned
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),

    ],
  ),
);

Body:
simple wrap the left item with a row and in the row add a expanded sized box like this:

Column(
    crossAxisAlignment: CrossAxisAlignment.center,
    children: <Widget>[
      Row(
        children: [
          Text('Left'),
          // this is the same thing like a expanded widget with an sized box
          // in it but the expanded widget
          // makes problems on a real device
          Flexible(
            child: SizedBox(
              width: MediaQuery.of(context).size.width,
            ),
          ),
        ],
      ),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),
      Text('Center'),

    ],
  ),


问:
new PerformanceObserver(cb).observe({ type: 'paint', buffered: true }) doesn't work in Safari
```<code>new PerformanceObserver((list) => {
  list.getEntries().forEach(console.log);
}).observe({ type: 'paint', buffered: true });
</code>```
```<code>performance.getEntriesByType('paint').forEach(console.log);
</code>```

These two snippets log matching paint entries in Chrome, Firefox, Edge, and Opera. However, in Safari 15.3 the PerformanceObserver approach doesn't log at all (the callback isn't invoked), but the getEntriesByType approach does log the "first-contentful-paint" entry. It seems that Safari supports PerformanceObserver.observe and supports the PerformancePaintTiming API. Why does the above PerformanceObserver approach not work in Safari?

If there is a bug in Safari do you think that getEntriesByTypes without a PerformanceObserver's buffer is OK to use instead? Thanks.

答:
This is being worked in Safari. Follow this bug: to see it: https://bugs.webkit.org/show_bug.cgi?id=225305

If there is a bug in Safari do you think that getEntriesByTypes without a PerformanceObserver's buffer is OK to use instead? Thanks.

The issue with not having buffered option is you can miss observations that happened before you registered the observer. See here where I noticed inconsistency with whether events were measured or not: https://github.com/GoogleChrome/web-vitals/pull/139

Body:
new PerformanceObserver((list) => {
  list.getEntries().forEach(console.log);
}).observe({ type: 'paint', buffered: true });

performance.getEntriesByType('paint').forEach(console.log);

These two snippets log matching paint entries in Chrome, Firefox, Edge, and Opera. However, in Safari 15.3 the PerformanceObserver approach doesn't log at all (the callback isn't invoked), but the getEntriesByType approach does log the "first-contentful-paint" entry. It seems that Safari supports PerformanceObserver.observe and supports the PerformancePaintTiming API. Why does the above PerformanceObserver approach not work in Safari?

If there is a bug in Safari do you think that getEntriesByTypes without a PerformanceObserver's buffer is OK to use instead? Thanks.


问:
Concatenate labels to an existing dataframe
I want to use a list of names "headers" to create a new column in my dataframe. In the initial table, the name of each division is positioned above the results for each team in that division. I want to add that header to each row entry for each divsion to make the data more identifiable like this. I have the headers stored in the "header" object in my code. How can I multiply each division header by the number of rows that appear in the division and append to the dataset?

Edit: here is another snippet of what I want the get from the end product.

```<code>df3 = df.iloc[0:6]
df3.insert(0, 'Divisions', ['na','L5 Junior', 'L5 Junior', 'na',
'L5 Senior - Medium', 'L5 Senior - Medium'])

df3
</code>```

.

```<code>import pandas as pd
import numpy as np
from bs4 import BeautifulSoup
import requests
</code>```

Import HTML

```<code>scr = 'https://tv.varsity.com/results/7361971-2022-spirit-unlimited-battle-at-the-
boardwalk-atlantic-city-grand-ntls/31220'
scr1 = requests.get(scr)
soup = BeautifulSoup(scr1.text, "html.parser")
</code>```

List of names to append

```<code>table_MN = pd.read_html(scr)
sp3 = soup.find(class_="full-content").find_all("h2")
headers = [elt.text for elt in sp3]

table_MN = pd.read_html(scr)
</code>```

Extract text and header from division info

```<code>div = pd.DataFrame(headers)
div.columns = ["division"]

df = pd.concat(table_MN, ignore_index=True)

df.columns = df.iloc[0]

df
</code>```

答:
It is still not clear what is the output you are looking for. However, may I suggest the following, which accomplishes selecting common headers from tables in table_MN and the concatenating the results. If it is going in the right direction pls let me know, and indicate what else you want to extract from the resulting table:

```<code>tmn_1 = [tbl.T.set_index(0).T for tbl in table_MN]
pd.concat(tmn_1, axis=0, ignore_index = True)
</code>```

output:

```<code>     Rank  Program Name                 Team Name            Raw Score    Deductions    Performance Score    Event Score
--  ------  ---------------------------  -----------------  -----------  ------------  -------------------  -------------
 0       1  Rockstar Cheer New Jersey    City Girls             47.8667          0                 95.7333        95.6833
 1       2  Cheer Factor                 Xtraordinary           46.6667          0.15              93.1833        92.8541
 2       1  Rockstar Cheer New Jersey    City Girls             47.7667          0                 95.5333        23.8833
 3       2  Cheer Factor                 Xtraordinary           46.0333          0.2               91.8667        22.9667
 4       1  Star Athletics               Roar                   47.5333          0.9               94.1667        93.9959
 5       1  Prime Time All Stars         Lady Onyx              43.9             1.35              86.45          86.6958
 6       1  Prime Time All Stars         Lady Onyx              44.1667          0.9               87.4333        21.8583
 7       1  Just Cheer All Stars         Jag 5                  46.4333          0.15              92.7167        92.2875
 8       1  Just Cheer All Stars         Jag 5                  45.8             0.6               91             22.75
 9       1  Quest Athletics              Black Ops              47.4333          0.45              94.4167        93.725
10       1  Quest Athletics              Black Ops              46.5             1.35              91.65          22.9125
11       1  The Stingray Allstars        X-Rays                 45.3             0.95              89.65          88.4375
12       1  Vortex Allstars              Lady Rays              45.7             0.5               90.9           91.1083
13       1  Vortex Allstars              Lady Rays              45.8667          0                 91.7333        22.9333
14       1  Upper Merion All Stars       Citrus                 46.4333          0                 92.8667        92.7
15       2  Cheer Factor                 JUNIOR X               45.9             1.1               90.7           90.6542
16       3  NJ Premier All Stars         Prodigy                44.6333          0.05              89.2167        89.8292
17       1  Upper Merion All Stars       Citrus                 46.1             0                 92.2           23.05
18       2  NJ Premier All Stars         Prodigy                45.8333          0                 91.6667        22.9167
19       3  Cheer Factor                 JUNIOR X               45.7333          0.95              90.5167        22.6292
20       1  Virginia Royalty Athletics   Dynasty                46.5             0                 93             92.9
21       1  Virginia Royalty Athletics   Dynasty                46.3             0                 92.6           23.15
22       1  South Jersey Storm           Lady Reign             47.2333          0                 94.4667        93.4875
...
</code>```

Body:
I want to use a list of names "headers" to create a new column in my dataframe. In the initial table, the name of each division is positioned above the results for each team in that division. I want to add that header to each row entry for each divsion to make the data more identifiable like this. I have the headers stored in the "header" object in my code. How can I multiply each division header by the number of rows that appear in the division and append to the dataset?

Edit: here is another snippet of what I want the get from the end product.

df3 = df.iloc[0:6]
df3.insert(0, 'Divisions', ['na','L5 Junior', 'L5 Junior', 'na',
'L5 Senior - Medium', 'L5 Senior - Medium'])

df3

.

import pandas as pd
import numpy as np
from bs4 import BeautifulSoup
import requests

Import HTML

scr = 'https://tv.varsity.com/results/7361971-2022-spirit-unlimited-battle-at-the-
boardwalk-atlantic-city-grand-ntls/31220'
scr1 = requests.get(scr)
soup = BeautifulSoup(scr1.text, "html.parser")

List of names to append

table_MN = pd.read_html(scr)
sp3 = soup.find(class_="full-content").find_all("h2")
headers = [elt.text for elt in sp3]

table_MN = pd.read_html(scr)

Extract text and header from division info

div = pd.DataFrame(headers)
div.columns = ["division"]

df = pd.concat(table_MN, ignore_index=True)

df.columns = df.iloc[0]

df

Body:
It is still not clear what is the output you are looking for. However, may I suggest the following, which accomplishes selecting common headers from tables in table_MN and the concatenating the results. If it is going in the right direction pls let me know, and indicate what else you want to extract from the resulting table:

tmn_1 = [tbl.T.set_index(0).T for tbl in table_MN]
pd.concat(tmn_1, axis=0, ignore_index = True)

output:

     Rank  Program Name                 Team Name            Raw Score    Deductions    Performance Score    Event Score
--  ------  ---------------------------  -----------------  -----------  ------------  -------------------  -------------
 0       1  Rockstar Cheer New Jersey    City Girls             47.8667          0                 95.7333        95.6833
 1       2  Cheer Factor                 Xtraordinary           46.6667          0.15              93.1833        92.8541
 2       1  Rockstar Cheer New Jersey    City Girls             47.7667          0                 95.5333        23.8833
 3       2  Cheer Factor                 Xtraordinary           46.0333          0.2               91.8667        22.9667
 4       1  Star Athletics               Roar                   47.5333          0.9               94.1667        93.9959
 5       1  Prime Time All Stars         Lady Onyx              43.9             1.35              86.45          86.6958
 6       1  Prime Time All Stars         Lady Onyx              44.1667          0.9               87.4333        21.8583
 7       1  Just Cheer All Stars         Jag 5                  46.4333          0.15              92.7167        92.2875
 8       1  Just Cheer All Stars         Jag 5                  45.8             0.6               91             22.75
 9       1  Quest Athletics              Black Ops              47.4333          0.45              94.4167        93.725
10       1  Quest Athletics              Black Ops              46.5             1.35              91.65          22.9125
11       1  The Stingray Allstars        X-Rays                 45.3             0.95              89.65          88.4375
12       1  Vortex Allstars              Lady Rays              45.7             0.5               90.9           91.1083
13       1  Vortex Allstars              Lady Rays              45.8667          0                 91.7333        22.9333
14       1  Upper Merion All Stars       Citrus                 46.4333          0                 92.8667        92.7
15       2  Cheer Factor                 JUNIOR X               45.9             1.1               90.7           90.6542
16       3  NJ Premier All Stars         Prodigy                44.6333          0.05              89.2167        89.8292
17       1  Upper Merion All Stars       Citrus                 46.1             0                 92.2           23.05
18       2  NJ Premier All Stars         Prodigy                45.8333          0                 91.6667        22.9167
19       3  Cheer Factor                 JUNIOR X               45.7333          0.95              90.5167        22.6292
20       1  Virginia Royalty Athletics   Dynasty                46.5             0                 93             92.9
21       1  Virginia Royalty Athletics   Dynasty                46.3             0                 92.6           23.15
22       1  South Jersey Storm           Lady Reign             47.2333          0                 94.4667        93.4875
...


问:
Azure Static Web App Authorization Link Issue - Redirecting to Wrong Identity Link
I have a web app hosted on Azure Static Web App via Azure Devops. The app works fine but cannot get Azure Static Web App authorization to work.

The web app can be access via ...6bde6303 .1. azurestaticapps.net link

Authentication is supposed to be accessed via ...6bde6303.1.azurestaticapps.net/.auth/login/aad which redirects to identity. 1 .azurestaticapps.net/.redirect/aad?hostName=... - which is a 'cannot be reached' tipe of site.

I noticed that identity .1. azurestaticapps.net is not the correct link and tried changing url to identity.azurestaticapps.net instead - it then redirected me to the sign in page and worked. However, once signed in, it redirects back to identity. 1 .azurestaticapps.net. I think this is an issue with the subdomain and I think it is controlled in system files. I'm stuck and was hoping maybe someone figured this out?..

My staticwebapp.config.json looks like this

{
  "routes": [
      {   // redirect /login to the Active Directory endpoint for authentication.
      "route": "/login",
      "rewrite": "/.auth/login/aad"
      },
      {   // Only allow people with the "reader" role to access ANY route.
      "route": "/docs",
      "allowedRoles": ["reader"]
      }
  ],
  "responseOverrides": {
      "401": {    // If access is denied because of a missing role (=anonymous users), redirect them to login.
      "redirect": "/login",
      "statusCode": 302
      }
  },
  "mimeTypes": {
      ".json": "text/json"
  }
}
```

答: Figured it out - my antivirus software had identity.1.azurestaticapps.net URL for some reason blacklisted (whereas identity.azurestaticapps.net was not). Once I got it in the exception list - it works.</p>


问:
Minimal HTTP server reply
I am trying to build an HTTP server with an AVR + ESP8266.

I can send commands back and forth via telnet, but now I want to implement a web interface.

As a starting point I tried to setup a website that outputs "text"
however, the browser displays an empty page. Can someone please let me know the minimum requirements for the page to be interpreted as HTML?

```<code>telnet 192.168.2.26 81
Trying 192.168.2.26...
Connected to 192.168.2.26.
Escape character is '^]'.

GET / HTTP/1.1
</code>```

AVR answer:

```<code>HTTP/1.1 200 OK
Content-Type: text/html
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<title>Zeitschaltuhr</title></head>
<body>
Text
</body></html>
Connection closed by foreign host.
</code>```

答:
Important to provide twice CR,LF before content.</p>
```<code>HTTP/1.1 200 OK\r\nContent-Length: 13\r\nContent-Type: text/html\r\n\r\nHello World!
</code>```

Title: Minimal HTTP server reply

Body:
I am trying to build an HTTP server with an AVR + ESP8266.

I can send commands back and forth via telnet, but now I want to implement a web interface.

As a starting point I tried to setup a website that outputs "text"
however, the browser displays an empty page. Can someone please let me know the minimum requirements for the page to be interpreted as HTML?

telnet 192.168.2.26 81
Trying 192.168.2.26...
Connected to 192.168.2.26.
Escape character is '^]'.

GET / HTTP/1.1

AVR answer:

HTTP/1.1 200 OK
Content-Type: text/html
<!DOCTYPE html>

<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<title>Zeitschaltuhr</title>

Text

Connection closed by foreign host.

Body:
Important to provide twice CR,LF before content.

HTTP/1.1 200 OK\r\nContent-Length: 13\r\nContent-Type: text/html\r\n\r\nHello World!


问:
extract key/value pairs where value is empty
I have a use case whereby an array must be created that contains the key/value pairs that have an empty value in the original array.

This sample data is a simplified representation of the actual data.  The code below results in the desired outcome but is there a more concise way to write this?  Is there an alternative to using a foreach that's shorter than the code below?

```<code>$data = ['beans' => 23, 'peas' => null, 'carrots' => 17, 'turnips' => '', 'potatoes' => 58];
$result = [];
foreach ($data as $key => $value) {
    if (empty($value)) $result[$key] = $value;
}
echo print_r($result, 1);
</code>```

Desired outcome:

答:
You can use array_filter() to do that:

```<code>$data = ['beans' => 23, 'peas' => null, 'carrots' => 17, 'turnips' => '', 'potatoes' => 58];
$result = array_filter($data, fn($e) => empty($e));
print_r($result);
</code>```

Output:

```<code>Array
(
  [peas] =>
  [turnips] =>
)
</code>```

Demo PHP 7.4 : https://3v4l.org/hgZg8

Before PHP 7.4 and arrow functions, you can use an anonymous function:

```<code>$data = ['beans' => 23, 'peas' => null, 'carrots' => 17, 'turnips' => '', 'potatoes' => 58];
$result = array_filter($data, function($e) { return empty($e); });
print_r($result);
</code>```

Body:
I have a use case whereby an array must be created that contains the key/value pairs that have an empty value in the original array.

This sample data is a simplified representation of the actual data.  The code below results in the desired outcome but is there a more concise way to write this?  Is there an alternative to using a foreach that's shorter than the code below?

$data = ['beans' => 23, 'peas' => null, 'carrots' => 17, 'turnips' => '', 'potatoes' => 58];
$result = [];
foreach ($data as $key => $value) {
    if (empty($value)) $result[$key] = $value;
}
echo print_r($result, 1);

Desired outcome:

Body:
You can use array_filter() to do that:

$data = ['beans' => 23, 'peas' => null, 'carrots' => 17, 'turnips' => '', 'potatoes' => 58];
$result = array_filter($data, fn($e) => empty($e));
print_r($result);

Output:

Array
(
  [peas] =>
  [turnips] =>
)

Demo PHP 7.4 : https://3v4l.org/hgZg8

Before PHP 7.4 and arrow functions, you can use an anonymous function:

$data = ['beans' => 23, 'peas' => null, 'carrots' => 17, 'turnips' => '', 'potatoes' => 58];
$result = array_filter($data, function($e) { return empty($e); });
print_r($result);


问:
PHP - The requested URL was not found on this server
I'm having trouble adding new page to my PHP website. I'm working on a project where previous developer has created two pages, "index" & "search". I'm completely new to PHP, so the problem may be something obvious..

Index is just a frontpage where users can make simple calculations. "search" shows calculation results. User can open "search" just by clicking a button on "index". This works completely fine.

However, now I'm adding a new page (about) & when I'm trying to open it, error "The requested URL was not found on this server" appears. (404 Not Found).

I created the new file to the root next to "index" & made sure everything is correct.

Links

```<code>http://localhost:84/Projects/Calculator/Calculator/index.php <-- WORKS
http://localhost:84/Projects/Calculator/Calculator/search.php <-- WORKS
http://localhost:84/Projects/Calculator/Calculator/about.php <-- DOES NOT WORK
</code>```

What have I tried?

1)First I made a button which links to the new page. Since this didn't work, I also tried to insert new pages link directly to the browser. Didn't work this way either.

2)Created multiple test files to the project with basic html code structure. None of them opened in the browser, always the same error. (Also tried to create them on different levels, next to root etc..)

3)Created completely new project just to test and created multiple pages there. Every one of them worked!

答: You can try by copying index.php file and save it as about.php. And then open file in browser. If it works, then edit about.php file with your desired content.</p>

Body:
I'm having trouble adding new page to my PHP website. I'm working on a project where previous developer has created two pages, "index" & "search". I'm completely new to PHP, so the problem may be something obvious..

Index is just a frontpage where users can make simple calculations. "search" shows calculation results. User can open "search" just by clicking a button on "index". This works completely fine.

However, now I'm adding a new page (about) & when I'm trying to open it, error "The requested URL was not found on this server" appears. (404 Not Found).

I created the new file to the root next to "index" & made sure everything is correct.

Links

http://localhost:84/Projects/Calculator/Calculator/index.php <-- WORKS
http://localhost:84/Projects/Calculator/Calculator/search.php <-- WORKS
http://localhost:84/Projects/Calculator/Calculator/about.php <-- DOES NOT WORK

What have I tried?

1)First I made a button which links to the new page. Since this didn't work, I also tried to insert new pages link directly to the browser. Didn't work this way either.

2)Created multiple test files to the project with basic html code structure. None of them opened in the browser, always the same error. (Also tried to create them on different levels, next to root etc..)

3)Created completely new project just to test and created multiple pages there. Every one of them worked!


问:
docker-compose volume full due to large data, can i prevent it copying to the container but still mount?
I have a very large project, it's large due to data files, i am switching to using docker as it's proving a pain for developers in different environments.

public_html/data is about 30gb in size on my local machine.

I have my docker image mapping ./ to /var/www/html which then includes the public_html folder

It can't copy the data folder to the container because there isn't enough space on the drive to have two copies of it. Is there a way that i can map the folder to the container so it can still use the folder, but have it only stored on my local machine? So in other works sort of like a sym link?

Here is my compose file

```<code>version: '3.4'
volumes:
  themecache:
  designercache:
services:
  utterly-web:
    ports:
      - 80:80
    environment:
      - APACHE_DOCUMENT_ROOT=/var/www/html/public_html
    build:
      context: .
    volumes:
      - .:/var/www/html
      - ./docker/vhost.conf:/etc/apache2/sites-available/000-default.conf
      - themecache:/var/www/html/public_html/themes/utterly/cache
      - designercache:/var/www/html/public_html/themes/utterly/designer/cache
</code>```

Correct me please if i misunderstand, i thought everything works from the volumes on my local machine i didn't realise it actually copied the files to the container,  i now don't understand how i can edit local files and it affects the file in the container, it's already like they can as sym links?

EDIT

I realised i am copying the files in Dockerfile below, i'm going to try the .dockerignore

```<code>FROM php:7.4-apache

RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer \
    && apt-get update && apt-get install -y git libzip-dev unzip \
    && docker-php-ext-install zip \
    && a2enmod rewrite headers

COPY . /var/www/html
</code>```

答:
A Linux bind mount, and by extension a Docker bind mount, does exactly what you describe: there are two different filesystem paths that point at the same underlying storage.  It is not unlike a kernel-managed symlink.

The extra copy of the data is coming from the COPY instruction in the Dockerfile.  Having that COPY instruction is generally good – you want the image to contain its own code – but you want to exclude the large data tree.

You can use a .dockerignore file to tell Docker to omit files from the image (technically, the build context).  For your setup this will also make the docker build step go substantially faster.

# .dockerignore
data
```
<p>Now you can leave the <code>Dockerfile</code> unchanged, but the final <code>COPY</code> line will include only the application code and not the data.</p>
<p>In your Compose setup, set up the bind mount to mount the data directory.  You frequently will not want to overwrite the image's code with a bind mount: this can hide differences between the two source trees if the Dockerfile setup does something interesting, and if you're deploying the application somewhere else, it means you need to both distribute the built application and its source.</p>
<pre class="lang-yaml prettyprint-override"><code>volumes:
  - ./data:/var/www/html/data
</code>```

Body:
I have a very large project, it's large due to data files, i am switching to using docker as it's proving a pain for developers in different environments.

public_html/data is about 30gb in size on my local machine.

I have my docker image mapping ./ to /var/www/html which then includes the public_html folder

It can't copy the data folder to the container because there isn't enough space on the drive to have two copies of it. Is there a way that i can map the folder to the container so it can still use the folder, but have it only stored on my local machine? So in other works sort of like a sym link?

Here is my compose file

version: '3.4'
volumes:
  themecache:
  designercache:
services:
  utterly-web:
    ports:
      - 80:80
    environment:
      - APACHE_DOCUMENT_ROOT=/var/www/html/public_html
    build:
      context: .
    volumes:
      - .:/var/www/html
      - ./docker/vhost.conf:/etc/apache2/sites-available/000-default.conf
      - themecache:/var/www/html/public_html/themes/utterly/cache
      - designercache:/var/www/html/public_html/themes/utterly/designer/cache

Correct me please if i misunderstand, i thought everything works from the volumes on my local machine i didn't realise it actually copied the files to the container,  i now don't understand how i can edit local files and it affects the file in the container, it's already like they can as sym links?

EDIT

I realised i am copying the files in Dockerfile below, i'm going to try the .dockerignore

FROM php:7.4-apache

RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer \
    && apt-get update && apt-get install -y git libzip-dev unzip \
    && docker-php-ext-install zip \
    && a2enmod rewrite headers

COPY . /var/www/html

Body:
A Linux bind mount, and by extension a Docker bind mount, does exactly what you describe: there are two different filesystem paths that point at the same underlying storage.  It is not unlike a kernel-managed symlink.

The extra copy of the data is coming from the COPY instruction in the Dockerfile.  Having that COPY instruction is generally good – you want the image to contain its own code – but you want to exclude the large data tree.

You can use a .dockerignore file to tell Docker to omit files from the image (technically, the build context).  For your setup this will also make the docker build step go substantially faster.

# .dockerignore
data

Now you can leave the Dockerfile unchanged, but the final COPY line will include only the application code and not the data.

In your Compose setup, set up the bind mount to mount the data directory.  You frequently will not want to overwrite the image's code with a bind mount: this can hide differences between the two source trees if the Dockerfile setup does something interesting, and if you're deploying the application somewhere else, it means you need to both distribute the built application and its source.

volumes:
  - ./data:/var/www/html/data


问:
Send UIButton touch event to didSelectRowAtIndexPath
I have a UIButton added to a UITableViewCell

In order to reduce code redundancy, I'd like to touch event of UIButton to fall through the cell - so it ends up in:

```<code>- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
</code>```

Can you tell me how?

答:
That's a bad idea. Instead, you should call the same function from didSelectRowAtIndexPath: & the button's action method & place your common code in that function. Something like-

```<code>- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//fetch the cell corresponding to this index path
MyCustomCell* cell = (MyCustomCell*)[self cellForRowAtIndexPath:indexPath] ;
[cell foo] ;

}

-(void) buttonClicked:(id)sender //In your custom cell class
{
    [self foo];
}
</code>```

HTH,

Akshay

Body:
I have a UIButton added to a UITableViewCell

In order to reduce code redundancy, I'd like to touch event of UIButton to fall through the cell - so it ends up in:

- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

Can you tell me how?

Body:
That's a bad idea. Instead, you should call the same function from didSelectRowAtIndexPath: & the button's action method & place your common code in that function. Something like-

- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//fetch the cell corresponding to this index path
MyCustomCell* cell = (MyCustomCell*)[self cellForRowAtIndexPath:indexPath] ;
[cell foo] ;

}

-(void) buttonClicked:(id)sender //In your custom cell class
{
    [self foo];
}

HTH,

Akshay


问:
Modify default C++ snippets in VS Code
I would like to modify the default code snippets for C++ in Visual Studio Code. I've found a similar question here, but they actually show how to create your own snippets - and not how to modify the default snippets.

The reason I want to do this is because I'm used to doing some things a bit differently than how they are done in the snippets. For example, this is what appears when I use the if snippet:

```<code>if (/* condition */)
{
    /* code */
}
</code>```

And I would like it to be like this:

```<code>if(/* condition */){
    /* code */
}
</code>```

Is there any way to achieve what I want to do? Thank you.

答:
Press Ctrl + ,(opens vs code settings);

Type "snippet" in settings search bar;

In Extentions List choose C/C++

Untick "Suggest Snippets" button;

Close settings tab.

Go to settings again and create new User Snippets as you liked.enter image description here

Title: Modify default C++ snippets in VS Code

Body:
I would like to modify the default code snippets for C++ in Visual Studio Code. I've found a similar question here, but they actually show how to create your own snippets - and not how to modify the default snippets.

The reason I want to do this is because I'm used to doing some things a bit differently than how they are done in the snippets. For example, this is what appears when I use the if snippet:

if (/* condition */)
{
    /* code */
}

And I would like it to be like this:

if(/* condition */){
    /* code */
}

Is there any way to achieve what I want to do? Thank you.


问:
ASP.NET Core 3.1 Azure App IsInRole/AuthorizeView work locally, but not when published
I have an ASP.NET Blazor server app which I am trying to add Roles to. I have got the Roles added on the Azure portal, and when testing locally on localhost the Roles work fine and I can control who sees what parts of the app. However, when I publish the app to App Service and test it out, no user has any roles and therefore can't use any of the app.

On my Azure App, the identity provider is set a Microsoft.

I added the following output to the top of a page of the app in order to determine what is going on.

```<code>foreach (var claim in authenticationState.User.Claims) {
    <b>@claim.Type:@claim.Value</b><br/>
}
</code>```

When testing locally, I see the following:

```<code>...
http://schemas.microsoft.com/ws/2008/06/identity/claims/role:qa
http://schemas.microsoft.com/ws/2008/06/identity/claims/role:patcher
...
</code>```

When it is published, I see:

```<code>...
roles:qa
roles:patcher
...
</code>```

So I'm assuming that my issue is that the AuthorizeView component and IsInRole method are failing because the claim type for the role is not what is expected. It would seem that it is expecting the full namespaced type, however when published we are being given just roles.

My ConfigureServices method is:

```<code>services.AddMicrosoftIdentityWebAppAuthentication(Configuration)
            .EnableTokenAcquisitionToCallDownstreamApi(new List<string> { "user.read" })
            .AddInMemoryTokenCaches();

services.AddControllersWithViews(options => {
    var policy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .Build();
    options.Filters.Add(new AuthorizeFilter(policy));
}).AddMicrosoftIdentityUI();

services.AddAuthorization(options => {
    options.FallbackPolicy = options.DefaultPolicy;
});

services.AddRazorPages();
services.AddServerSideBlazor().AddMicrosoftIdentityConsentHandler();
</code>```

I have tried adding each of and both of the commented lines below as well, however neither either fix it when published, or broke it locally, which leads me to think that the Configure is not having an effect.

```<code>services.Configure<OpenIdConnectOptions>(OpenIdConnectDefaults.AuthenticationScheme, options => {
    //options.TokenValidationParameters.RoleClaimType = "roles";
    //options.ClaimActions.MapJsonKey(ClaimTypes.Role, "roles");
});
</code>```

Anyone got any ideas why the claim types would be different when testing locally and when published, and how I can fix this so everything works in both environments?

Cheers

答: I am please to say I have now solved this. My problem was that I had Authentication setup on my App Services App. I didn't need this, as the authentication was being dealt with BY my App itself. So, after I had removed the authentication from the App (but left the App Registration and Enterise App bits untouched) it all works.</p>

Body:
I have an ASP.NET Blazor server app which I am trying to add Roles to. I have got the Roles added on the Azure portal, and when testing locally on localhost the Roles work fine and I can control who sees what parts of the app. However, when I publish the app to App Service and test it out, no user has any roles and therefore can't use any of the app.

On my Azure App, the identity provider is set a Microsoft.

I added the following output to the top of a page of the app in order to determine what is going on.

foreach (var claim in authenticationState.User.Claims) {
    @claim.Type:@claim.Value

}

When testing locally, I see the following:

...
http://schemas.microsoft.com/ws/2008/06/identity/claims/role:qa
http://schemas.microsoft.com/ws/2008/06/identity/claims/role:patcher
...

When it is published, I see:

...
roles:qa
roles:patcher
...

So I'm assuming that my issue is that the AuthorizeView component and IsInRole method are failing because the claim type for the role is not what is expected. It would seem that it is expecting the full namespaced type, however when published we are being given just roles.

My ConfigureServices method is:

services.AddMicrosoftIdentityWebAppAuthentication(Configuration)
            .EnableTokenAcquisitionToCallDownstreamApi(new List<string> { "user.read" })
            .AddInMemoryTokenCaches();

services.AddControllersWithViews(options => {
    var policy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .Build();
    options.Filters.Add(new AuthorizeFilter(policy));
}).AddMicrosoftIdentityUI();

services.AddAuthorization(options => {
    options.FallbackPolicy = options.DefaultPolicy;
});

services.AddRazorPages();
services.AddServerSideBlazor().AddMicrosoftIdentityConsentHandler();

I have tried adding each of and both of the commented lines below as well, however neither either fix it when published, or broke it locally, which leads me to think that the Configure is not having an effect.

services.Configure<OpenIdConnectOptions>(OpenIdConnectDefaults.AuthenticationScheme, options => {
    //options.TokenValidationParameters.RoleClaimType = "roles";
    //options.ClaimActions.MapJsonKey(ClaimTypes.Role, "roles");
});

Anyone got any ideas why the claim types would be different when testing locally and when published, and how I can fix this so everything works in both environments?

Cheers


问:
Returning cells as a Matrix VBA
I have a bunch of cells in a sheet that look like this:

Each rows has a gap of 3, and columns a gap of 5.

Id like to extract these values and copy it to some area:

How would I grab each cell and create a matrix like so. Im trying to use a VBA sub() for this, as the initial table size can vary but Im not sure how to do it. Any thoughts appreciated.

答:
Copy Gapped Data

It is written to get the values from your image into an array and the array is then written to another worksheet. Here gap means the number of empty rows or columns in-between.

Option Explicit

Sub CopyGapped()

    Const sName As String = "Sheet1"

    Const dName As String = "Sheet2"
    Const dfcAddress As String = "A1"

    Const rGap As Long = 2
    Const cGap As Long = 4

    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code

    Dim sws As Worksheet: Set sws = wb.Worksheets(sName)
    Dim srg As Range: Set srg = sws.UsedRange

    Dim srCount As Long: srCount = srg.Rows.Count
    Dim rOff As Long: rOff = rGap + 1
    If srCount < rOff + 1 Then Exit Sub

    Dim scCount As Long: scCount = srg.Columns.Count
    Dim cOff As Long: cOff = cGap + 1
    If scCount < cOff + 1 Then Exit Sub

    Dim sData As Variant: sData = srg.Value

    Dim drCount As Long: drCount = Int(srCount / rOff) + 1
    Dim dcCount As Long: dcCount = Int(scCount / cOff) + 1

    Dim dData As Variant: ReDim dData(1 To drCount, 1 To dcCount)

    Dim sr As Long
    Dim sc As Long
    Dim dr As Long
    Dim dc As Long

    For sr = 1 To srCount Step rOff
        dr = dr + 1
        dc = 0
        For sc = 1 To scCount Step cOff
            dc = dc + 1
            dData(dr, dc) = sData(sr, sc)
        Next sc
    Next sr

    Dim dws As Worksheet: Set dws = wb.Worksheets(dName)
    With dws.Range(dfcAddress).Resize(, dcCount)
        .Resize(drCount) = dData
        .Resize(dws.Rows.Count - .Row - drCount + 1).Offset(drCount).Clear
    End With

End Sub
```

Title: Returning cells as a Matrix VBA


问:
exclude flutter export from import suggestions
I often times import cupertino.dart instead of material.dart when having to import widgets because its the first suggested options.
Its not a real problem but for the sake of consistency I want to prevent importing cuppertino.dart so it is not listed in the import suggestions and only use widgets.dart or material.dart instead.

Is there a way to configure Android Studio or Dart Analyzer to prevent cuppertino.dart to show in suggestions?

答:
Seems no, but there is a workaround: You can write a linter to examine your code and warn (or error) whenever you see imports of cupertino.dart. That linter can even automatically correct the code (by replacing cupertino with material).

Some methodology thoughts: I often want something to be automatically performed ("import material not cupertino" in your case); but later I realized it is hard or not exist yet, but some verifier is good enough ("manually import; but warn if you import the wrong one").


问:
SQL select two rows in one table generating independant output
I would like to generate an output, where I count two rows from the same table but with different conditions.

Now I have this SQL Statement which works:

```<code>select Datum, Count(ID), Count(Fläche)
FROM gustavo
where Fläche > 200
Group by Datum;
</code>```

but it only gives me the sizes over 480 and the id's over 480 in both rows. In the first row I would like to have the count of all IDs though. Any idea how that would work?

Thanks a lot

答:
Try this (not checked)</p>
```<code>SELECT
   Datum,
   COUNT(ID) all_ID ,
   SUM(if(ID>480) THEN 1 ELSE 0 END IF)  ID_480,
   Count(Fläche) all_Flache
FROM
    gustavo
WHERE
   Fläche > 200
GROUP BY
   Datum;
</code>```

Body:
I would like to generate an output, where I count two rows from the same table but with different conditions.

Now I have this SQL Statement which works:

select Datum, Count(ID), Count(Fläche)
FROM gustavo
where Fläche > 200
Group by Datum;

but it only gives me the sizes over 480 and the id's over 480 in both rows. In the first row I would like to have the count of all IDs though. Any idea how that would work?

Thanks a lot

Body:
Try this (not checked)

SELECT
   Datum,
   COUNT(ID) all_ID ,
   SUM(if(ID>480) THEN 1 ELSE 0 END IF)  ID_480,
   Count(Fläche) all_Flache
FROM
    gustavo
WHERE
   Fläche > 200
GROUP BY
   Datum;


问:
Install applications or software on Azure VM with ARM Template
We're trying to install Kaspersky Network Agent on an Azure VM using ARM Template.

Also, we need to get the .exe or .msi file from VM storage using SAS token. I was searching for the Template examples to operate but couldn't come up with one that accomplishes the task. Do you know, if it's possible to do in this way?

If so,
Can you share a template that does a similar task?
Also, please explain how to modify the template for this case.

Thanks in advance

答:
•   Yes, you can successfully install an application using the custom script extension in an ARM template in an Azure VM as follows. Kindly check the ARM template file as deployed by me for this purpose. Also, I have used the SAS token to download the application package in the Azure VM during deployment itself and have also used a powershell script to invoke the silent install of the concerned application.

ARM Template: -

I am using the default quickstart template for deploying an Azure VM through ARM template as given in this link : - https://learn.microsoft.com/en-us/azure/virtual-machines/windows/quick-create-template?toc=/azure/azure-resource-manager/templates/toc.json

In this template, I have added the below custom script extension installation content in ‘resources’ section in the above ARM template. Please check the formatting of the ARM template code correctly, i.e., commas, curly brackets, square brackets, etc. Also, ensure to open HTTPS port 443 inbound also as below: -

```<code>"securityRules": [
      {
        "name": "default-allow-3389",
        "properties": {
          "priority": 1000,
          "access": "Allow",
          "direction": "Inbound",
          "destinationPortRange": "3389",
          "protocol": "Tcp",
          "sourcePortRange": "*",
          "sourceAddressPrefix": "*",
          "destinationAddressPrefix": "*"
        }
      },
      {
        "name": "AllowHTTPSInBound",
        "properties": {
          "priority": 1010,
          "access": "Allow",
          "direction": "Inbound",
          "destinationPortRange": "443",
          "protocol": "Tcp",
          "sourcePortRange": "*",
          "sourceAddressPrefix": "*",
          "destinationAddressPrefix": "*"
        }
      }
  ]
</code>```

Custom Script VM extension: -

```<code> {
          "type": "Microsoft.Compute/virtualMachines/extensions",
          "apiVersion": "2021-04-01",
          "name": "[concat(parameters('vmName'),'/', 'InstallWebServer')]",
          "location": "[parameters('location')]",
          "dependsOn": [
            "[concat('Microsoft.Compute/virtualMachines/',parameters('vmName'))]"
          ],
        "properties": {
        "publisher": "Microsoft.Compute",
        "type": "CustomScriptExtension",
        "typeHandlerVersion": "1.7",
        "autoUpgradeMinorVersion": true,
        "protectedSettings": {
          "storageAccountName": "techtrix",
          "storageAccountKey": "EN6iUzOfVe8Ht0xvyxnqK/iXEGTEunznASsumuz0FR4SCvc2mFFHUJfbMy1/GSK7gXk0MB38MMo7+AStoKxC/w==",
          "fileUris": [
            "https://techtrix.blob.core.windows.net/executable/Testdemo2.ps1"
          ],
          "commandToExecute": "powershell.exe -ExecutionPolicy Unrestricted -File Testdemo2.ps1"
        }
      }
    }
</code>```

Also, please note that you need to provision a storage account container already for storing the powershell script and the application package in it so that you can use that storage account’s key, its name and the powershell script’s blob URI in place of the same as requested above. Also, please change the name of the powershell script to be executed through the extension in ‘commandToExecute’ section.

Once the above has been done, please ensure the successful execution of silent installation commands for the application package to be installed locally so that they can be accordingly modified in the powershell script. I have used installed ‘7-zip’ application here for demonstration purposes. Please find my powershell script as below. Ensure that this script and the application package is uploaded beforehand, and the access level of the container is set to ‘Anonymous and public access’: -

```<code> Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force
 Install-Module -Name Az.Storage -AllowClobber -Force
 Import-Module -Name Az.Storage -Force
 $StorageAccountName = "techtrix"
 $ContainerName = "executable"
 $Blob1Name = "7z2107-x64.exe"
 $TargetFolderPath = "C:\"
 $context = New-AzStorageContext -StorageAccountName $StorageAccountName -SASToken "sp=r&st=2022-02-10T08:40:34Z&se=2022-02-10T16:40:34Z&spr=https&sv=2020-08-04&sr=b&sig=DRDulljKTJiRbVPAXAJkTHi8QlnlbjPpVR3aueEf9xU%3D"
 Get-AzStorageBlobContent -Blob $Blob1Name -Container $ContainerName -Context $context -Destination $TargetFolderPath
 $arg="/S"
 Start-Process -FilePath "C:\7z2107-x64.exe" -ArgumentList $arg ’
</code>```

Then edit the parameters file with the desired values in ‘adminUsername’, ‘adminPassword’ and ‘location’ and save it in the same location where template file is stored. Now, execute the commands below from powershell console with elevated privileges locally, i.e., through the path where these ARM template files are stored by browsing to that path in powershell itself.

```<code> az login
 az deployment group create -n <name of the deployment> -g <name of the resource group> --template-file "azuredeployVM.json" --parameters "azuredeployVM.parameters.json" ’
</code>```

After successful deployment, you will be able to see the application installed during the VM creation itself as below: -

In this way, you can install an '.exe' or '.msi' through the ARM template with custom script extension.

Body:
•   Yes, you can successfully install an application using the custom script extension in an ARM template in an Azure VM as follows. Kindly check the ARM template file as deployed by me for this purpose. Also, I have used the SAS token to download the application package in the Azure VM during deployment itself and have also used a powershell script to invoke the silent install of the concerned application.

ARM Template: -

I am using the default quickstart template for deploying an Azure VM through ARM template as given in this link : - https://learn.microsoft.com/en-us/azure/virtual-machines/windows/quick-create-template?toc=/azure/azure-resource-manager/templates/toc.json

In this template, I have added the below custom script extension installation content in ‘resources’ section in the above ARM template. Please check the formatting of the ARM template code correctly, i.e., commas, curly brackets, square brackets, etc. Also, ensure to open HTTPS port 443 inbound also as below: -

"securityRules": [
      {
        "name": "default-allow-3389",
        "properties": {
          "priority": 1000,
          "access": "Allow",
          "direction": "Inbound",
          "destinationPortRange": "3389",
          "protocol": "Tcp",
          "sourcePortRange": "*",
          "sourceAddressPrefix": "*",
          "destinationAddressPrefix": "*"
        }
      },
      {
        "name": "AllowHTTPSInBound",
        "properties": {
          "priority": 1010,
          "access": "Allow",
          "direction": "Inbound",
          "destinationPortRange": "443",
          "protocol": "Tcp",
          "sourcePortRange": "*",
          "sourceAddressPrefix": "*",
          "destinationAddressPrefix": "*"
        }
      }
  ]

Custom Script VM extension: -

 {
          "type": "Microsoft.Compute/virtualMachines/extensions",
          "apiVersion": "2021-04-01",
          "name": "[concat(parameters('vmName'),'/', 'InstallWebServer')]",
          "location": "[parameters('location')]",
          "dependsOn": [
            "[concat('Microsoft.Compute/virtualMachines/',parameters('vmName'))]"
          ],
        "properties": {
        "publisher": "Microsoft.Compute",
        "type": "CustomScriptExtension",
        "typeHandlerVersion": "1.7",
        "autoUpgradeMinorVersion": true,
        "protectedSettings": {
          "storageAccountName": "techtrix",
          "storageAccountKey": "EN6iUzOfVe8Ht0xvyxnqK/iXEGTEunznASsumuz0FR4SCvc2mFFHUJfbMy1/GSK7gXk0MB38MMo7+AStoKxC/w==",
          "fileUris": [
            "https://techtrix.blob.core.windows.net/executable/Testdemo2.ps1"
          ],
          "commandToExecute": "powershell.exe -ExecutionPolicy Unrestricted -File Testdemo2.ps1"
        }
      }
    }

Also, please note that you need to provision a storage account container already for storing the powershell script and the application package in it so that you can use that storage account’s key, its name and the powershell script’s blob URI in place of the same as requested above. Also, please change the name of the powershell script to be executed through the extension in ‘commandToExecute’ section.

Once the above has been done, please ensure the successful execution of silent installation commands for the application package to be installed locally so that they can be accordingly modified in the powershell script. I have used installed ‘7-zip’ application here for demonstration purposes. Please find my powershell script as below. Ensure that this script and the application package is uploaded beforehand, and the access level of the container is set to ‘Anonymous and public access’: -

 Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force
 Install-Module -Name Az.Storage -AllowClobber -Force
 Import-Module -Name Az.Storage -Force
 $StorageAccountName = "techtrix"
 $ContainerName = "executable"
 $Blob1Name = "7z2107-x64.exe"
 $TargetFolderPath = "C:\"
 $context = New-AzStorageContext -StorageAccountName $StorageAccountName -SASToken "sp=r&st=2022-02-10T08:40:34Z&se=2022-02-10T16:40:34Z&spr=https&sv=2020-08-04&sr=b&sig=DRDulljKTJiRbVPAXAJkTHi8QlnlbjPpVR3aueEf9xU%3D"
 Get-AzStorageBlobContent -Blob $Blob1Name -Container $ContainerName -Context $context -Destination $TargetFolderPath
 $arg="/S"
 Start-Process -FilePath "C:\7z2107-x64.exe" -ArgumentList $arg ’

Then edit the parameters file with the desired values in ‘adminUsername’, ‘adminPassword’ and ‘location’ and save it in the same location where template file is stored. Now, execute the commands below from powershell console with elevated privileges locally, i.e., through the path where these ARM template files are stored by browsing to that path in powershell itself.

 az login
 az deployment group create -n <name of the deployment> -g <name of the resource group> --template-file "azuredeployVM.json" --parameters "azuredeployVM.parameters.json" ’

After successful deployment, you will be able to see the application installed during the VM creation itself as below: -

In this way, you can install an '.exe' or '.msi' through the ARM template with custom script extension.


问:
How to prevent stack wind-up operator overloads
I am getting stack overflow in this apparently benign code:

```<code>    public static bool operator == (AccessLevel al1, AccessLevel al2)
    {
        if (al1 == null && al2 == null)
            return true;

        if (al1 == null || al2 == null)
            return false;

        if (al1._Value == al2._Value)
            return true;
        else
            return false;
    }
    public static bool operator != (AccessLevel al1, AccessLevel al2)
    {
        if (al1 == null && al2 == null)
            return false;

        if (al1 == null || al2 == null)
            return true;

        if (al1._Value != al2._Value)
            return true;
        else
            return false;
    }
</code>```

What appears to be happening is that in the test for null in operator overload, the == overload is called again, and again, and again until the stack wind up.
Possible solutions here is to use the "Equals" override, which would look like Equals(null) returning true... but how to code that without using the == overload ? Is this the correct implementation:

```<code>        public override bool Equals(object o)
        {
            if (o == null)
                return true;
            if ((AccessLevel)o == this)
                return true;
            return false;
        }
</code>```

Or could one say something like this:

```<code>        public static bool operator == (AccessLevel al1, AccessLevel al2)
        {
            if (al1 is null && al2 is null)
                return true;

            if (al1 is null || al2 is null)
                return false;

            if (al1._Value == al2._Value)
                return true;
            else
                return false;
        }
</code>```

Any insight on how to correctly handle this?

答:
Your first option would be semantically incorrect, as well as inefficient. Equals(null) should never return true. As per the documentation:

The following statements must be true for all implementations of the Equals(Object) method. [...]

...

x.Equals(null) returns false.

Your second approach of using is is correct and more idiomatic in modern C#, although I'd argue the final part would be clearer as just:

return al1._Value == al2._Value;
```
<p>Your <code>Equals</code> method can then just be implemented as:</p>
<pre class="lang-cs prettyprint-override"><code>public override bool Equals(object o) => this == o as AccessLevel;
</code>```

(It's up to you whether the semantics are implemented in the == operator or in the Equals method, but it's best to implement them in just one of the two places to avoid duplication and potential inconsistency.)

Body:
I am getting stack overflow in this apparently benign code:

    public static bool operator == (AccessLevel al1, AccessLevel al2)
    {
        if (al1 == null && al2 == null)
            return true;

        if (al1 == null || al2 == null)
            return false;

        if (al1._Value == al2._Value)
            return true;
        else
            return false;
    }
    public static bool operator != (AccessLevel al1, AccessLevel al2)
    {
        if (al1 == null && al2 == null)
            return false;

        if (al1 == null || al2 == null)
            return true;

        if (al1._Value != al2._Value)
            return true;
        else
            return false;
    }

What appears to be happening is that in the test for null in operator overload, the == overload is called again, and again, and again until the stack wind up.
Possible solutions here is to use the "Equals" override, which would look like Equals(null) returning true... but how to code that without using the == overload ? Is this the correct implementation:

        public override bool Equals(object o)
        {
            if (o == null)
                return true;
            if ((AccessLevel)o == this)
                return true;
            return false;
        }

Or could one say something like this:

        public static bool operator == (AccessLevel al1, AccessLevel al2)
        {
            if (al1 is null && al2 is null)
                return true;

            if (al1 is null || al2 is null)
                return false;

            if (al1._Value == al2._Value)
                return true;
            else
                return false;
        }

Any insight on how to correctly handle this?

Body:
Your first option would be semantically incorrect, as well as inefficient. Equals(null) should never return true. As per the documentation:

The following statements must be true for all implementations of the Equals(Object) method. [...]

...

x.Equals(null) returns false.

Your second approach of using is is correct and more idiomatic in modern C#, although I'd argue the final part would be clearer as just:

return al1._Value == al2._Value;

Your Equals method can then just be implemented as:

public override bool Equals(object o) => this == o as AccessLevel;

(It's up to you whether the semantics are implemented in the == operator or in the Equals method, but it's best to implement them in just one of the two places to avoid duplication and potential inconsistency.)


问:
How to plot data from different blocks with lines in Gnuplot?
I have a data file with blocks of x/y values. Each block contains 16 lines with x/y pairs and each block represents those positions in a different time. http://pastebin.com/0teRrfRU

I want to plot the trajectory of a specific particle. To do that, I've written plot 'pos.dat' u 2:3 every ::n:0:n:i, where n is the n-th particle and i is the time up to which I want the trajectory plotted (I can then loop over the i to generate an animation).

This runs fine, but when I add w lines nothing gets plotted, and I don't understand why. Is there a way to plot this with lines? The only alternative I see is writing a script to parse the data file and generate a new one with only the values I want (effectively acting as every), but I don't want to do that if I can do it in Gnuplot.

答:
After a closer look to your data, your case has some speciality.
Like in Plotting same line number of several blocks data with gnuplot you can plot the file into a table via with table which will remove the empty lines and hence lines will be connected.

However, some of your particles disappear on one side and re-appear on the opposite side. If you plot this with lines you will get a line through the whole graph which is certainly undesired. You can workaround this if you introduce a function Break() which returns NaN if the difference of two successive x- or y-values are larger than 90% (to be on the safe side) of the x- or y-range , respectively. The effect of NaN is that the line will interrupted.

Code: (works with gnuplot>=5.0.0 version at the time of OP's question)

```<code>### plotting trajectories
reset session

set term gif animate delay 3 size 400,400
set output "SO30744875.gif"
set size square

FILE = 'SO30744875.dat'

set key noautotitle
stats FILE u (N=column(-1),M=column(1),$2):3 nooutput
xrange = STATS_max_x-STATS_min_x
yrange = STATS_max_y-STATS_min_y

set table $Data
    plot FILE u 1:2:3 w table
unset table

Break(col1,col2) = (x0=x1,x1=column(col1), y0=y1,y1=column(col2), \
                   abs(x1-x0)<0.9*xrange && abs(y1-y0)<0.9*yrange ? column(col2) : NaN)

do for [i=0:N] {
    plot for [j=1:16] x1=y1=NaN $Data u 2:(Break(2,3))every M::j-1::(i+1)*M w l, \
                      FILE u 2:3   every :::i::i w p pt 7, \
                      FILE u 2:3:1 every :::i::i w labels offset 0.7,0.7
}
set output
### end of code
</code>```

Result:

Body:
After a closer look to your data, your case has some speciality.
Like in Plotting same line number of several blocks data with gnuplot you can plot the file into a table via with table which will remove the empty lines and hence lines will be connected.

However, some of your particles disappear on one side and re-appear on the opposite side. If you plot this with lines you will get a line through the whole graph which is certainly undesired. You can workaround this if you introduce a function Break() which returns NaN if the difference of two successive x- or y-values are larger than 90% (to be on the safe side) of the x- or y-range , respectively. The effect of NaN is that the line will interrupted.

Code: (works with gnuplot>=5.0.0 version at the time of OP's question)

### plotting trajectories
reset session

set term gif animate delay 3 size 400,400
set output "SO30744875.gif"
set size square

FILE = 'SO30744875.dat'

set key noautotitle
stats FILE u (N=column(-1),M=column(1),$2):3 nooutput
xrange = STATS_max_x-STATS_min_x
yrange = STATS_max_y-STATS_min_y

set table $Data
    plot FILE u 1:2:3 w table
unset table

Break(col1,col2) = (x0=x1,x1=column(col1), y0=y1,y1=column(col2), \
                   abs(x1-x0)<0.9*xrange && abs(y1-y0)<0.9*yrange ? column(col2) : NaN)

do for [i=0:N] {
    plot for [j=1:16] x1=y1=NaN $Data u 2:(Break(2,3))every M::j-1::(i+1)*M w l, \
                      FILE u 2:3   every :::i::i w p pt 7, \
                      FILE u 2:3:1 every :::i::i w labels offset 0.7,0.7
}
set output
### end of code

Result:


问:
Undefined Reference to ftdi_init
I am trying to run a code for FT245RL chip in kubuntu version 18.04. Which requires lftdi library. But it shows the error as undefined reference to ftdi_init

I have tried removing and installing the libraries again. I also tried to give the path in the command to execute. I even tried many improvized commands across the internet but was unable to succeed.

```<code>if (ftdi_init(&ftdic) < 0)
{
    fprintf(stderr, "ftdi_init failed\n");
    return EXIT_FAILURE;
}

f = ftdi_usb_open(&ftdic, 0x0403, 0x6001);

if (f < 0 && f != -5)
{
    fprintf(stderr, "unable to open ftdi device: %d (%s)\n", f, ftdi_get_error_string(&ftdic));
    exit(-1);
}
</code>```

The expected result is just to compile the program without any errors.

答:
I used:

gcc -lftdi -o test test.c

And it worked

Title: Undefined Reference to ftdi_init

Body:
I am trying to run a code for FT245RL chip in kubuntu version 18.04. Which requires lftdi library. But it shows the error as undefined reference to ftdi_init

I have tried removing and installing the libraries again. I also tried to give the path in the command to execute. I even tried many improvized commands across the internet but was unable to succeed.

if (ftdi_init(&ftdic) < 0)
{
    fprintf(stderr, "ftdi_init failed\n");
    return EXIT_FAILURE;
}

f = ftdi_usb_open(&ftdic, 0x0403, 0x6001);

if (f < 0 && f != -5)
{
    fprintf(stderr, "unable to open ftdi device: %d (%s)\n", f, ftdi_get_error_string(&ftdic));
    exit(-1);
}

The expected result is just to compile the program without any errors.


问:
Spring Cloud Sleuth instrumentation constantly prints TODO before/after removeServiceName=
After migrating from Spring Boot 2.3 to 2.6 I have weird behavior in Spring Cloud Sleuth.
Instrumentation constantly prints to the console these messages

2022-02-10 11:59:46.804  INFO [SERVICE,4b9b266d4e1cf475,0bd79e17d007e0ce] 6412 --- [nio-8890-exec-6] o.s.c.s.i.jdbc.TraceListenerStrategy     : TODO before removeServiceName=serviceDataSource
2022-02-10 11:59:46.804  INFO [SERVICE,4b9b266d4e1cf475,0bd79e17d007e0ce] 6412 --- [nio-8890-exec-6] o.s.c.s.i.jdbc.TraceListenerStrategy     : TODO after removeServiceName=serviceDataSource
```
<p>I have found this snippet code in Spring Cloud Sleuth source code</p>
<pre class="lang-java prettyprint-override"><code>    void afterGetConnection(CON connectionKey, @Nullable Connection connection, String dataSourceName,
            @Nullable Throwable t) {
        if (log.isTraceEnabled()) {
            log.trace("After get connection [" + connectionKey + "]. Current span is [" + tracer.currentSpan() + "]");
        }
        ConnectionInfo connectionInfo = this.openConnections.get(connectionKey);
        SpanAndScope connectionSpan = connectionInfo.span;
        if (connection != null) {
            log.info("TODO before removeServiceName=" + connectionInfo.remoteServiceName);
            parseAndSetServerIpAndPort(connectionInfo, connection, dataSourceName);
            log.info("TODO after removeServiceName=" + connectionInfo.remoteServiceName);
            if (connectionSpan != null) {
                connectionSpan.getSpan().remoteServiceName(connectionInfo.remoteServiceName);
                connectionSpan.getSpan().remoteIpAndPort(connectionInfo.url.getHost(), connectionInfo.url.getPort());
            }
        }
</code>```

Is this correct behavior? how to disable these messages? Or something is wrong with my database connection or Spring Cloud Sleuth after migration?

答: This has already been fixed https://github.com/spring-cloud/spring-cloud-sleuth/issues/2069 and will be released shortly. Until then you can set the logging level for that class to ERROR logging.level.org.springframework.cloud.sleuth.instrument.jdbc=ERROR

Body:
After migrating from Spring Boot 2.3 to 2.6 I have weird behavior in Spring Cloud Sleuth.
Instrumentation constantly prints to the console these messages

2022-02-10 11:59:46.804  INFO [SERVICE,4b9b266d4e1cf475,0bd79e17d007e0ce] 6412 --- [nio-8890-exec-6] o.s.c.s.i.jdbc.TraceListenerStrategy     : TODO before removeServiceName=serviceDataSource
2022-02-10 11:59:46.804  INFO [SERVICE,4b9b266d4e1cf475,0bd79e17d007e0ce] 6412 --- [nio-8890-exec-6] o.s.c.s.i.jdbc.TraceListenerStrategy     : TODO after removeServiceName=serviceDataSource

I have found this snippet code in Spring Cloud Sleuth source code

    void afterGetConnection(CON connectionKey, @Nullable Connection connection, String dataSourceName,
            @Nullable Throwable t) {
        if (log.isTraceEnabled()) {
            log.trace("After get connection [" + connectionKey + "]. Current span is [" + tracer.currentSpan() + "]");
        }
        ConnectionInfo connectionInfo = this.openConnections.get(connectionKey);
        SpanAndScope connectionSpan = connectionInfo.span;
        if (connection != null) {
            log.info("TODO before removeServiceName=" + connectionInfo.remoteServiceName);
            parseAndSetServerIpAndPort(connectionInfo, connection, dataSourceName);
            log.info("TODO after removeServiceName=" + connectionInfo.remoteServiceName);
            if (connectionSpan != null) {
                connectionSpan.getSpan().remoteServiceName(connectionInfo.remoteServiceName);
                connectionSpan.getSpan().remoteIpAndPort(connectionInfo.url.getHost(), connectionInfo.url.getPort());
            }
        }

Is this correct behavior? how to disable these messages? Or something is wrong with my database connection or Spring Cloud Sleuth after migration?


问:
Display all data of all tables
I want to display all data in my Database without writing a select for each table - how can I do this?

I do not want to do this:

```<code>select * from Customer
select * from Employee
select .............
</code>```

I am using TSQL with MSSQL Server.

答:
Your question feels rather limited to me. What language are you using? What is the purpose of this?
For that reason, this is a multipart answer.

First of all, for seeing all the data in a MySql database, phpMyAdmin is perfect for the job - a tool that I can almost guarantee most SQL guys are appreciative of.

For the second part of the question: I'm presuming you want to do this dynamically, or there's just too many tables to write a query for each time. I'll presume the dynamically one, because I have created databases in the past which automatically adds tables to itself as it grows.
This solution in PHP is one I've just written for you which should display everything in a table.
EDIT: This code is bugged - all the data is displayed but I've gotten the table formatting wrong. - EDIT: fixed.

```<code><?php
listAll("table_name");
function listAll($db) {
  mysql_connect("localhost","root","");
  mysql_select_db($db);
  $tables = mysql_query("SHOW TABLES FROM $db");
  while (list($tableName)=mysql_fetch_array($tables)) {
    $result = mysql_query("DESCRIBE $tableName");
    $rows = array();
    while (list($row)=mysql_fetch_array($result)) {
      $rows[] = $row;
    }
    $count = count($rows);
    if ($count>0) {
      echo '<p><strong>',htmlentities($tableName),'</strong><br /><table border="1"><tr>';
      foreach ($rows as &$value) {
        echo '<td><strong>',htmlentities($value),'</strong></td>';
      }
      echo '</tr>';
      $result = mysql_query("SELECT * FROM $tableName");
      while ($row=mysql_fetch_array($result)) {
        echo '<tr>';
        for ($i=0;$i<(count($row)/2);$i++) {
          echo '<td>',htmlentities($row[$i]),'</td>';
        }
        echo '</tr>';
      }
      echo '</table></p>';
    }
  }
return FALSE;
}
?>
</code>```

And hopefully that code snippet should work for you like it's worked for me!

Title: Display all data of all tables

Body:
I want to display all data in my Database without writing a select for each table - how can I do this?

I do not want to do this:

select * from Customer
select * from Employee
select .............

I am using TSQL with MSSQL Server.

Body:
Your question feels rather limited to me. What language are you using? What is the purpose of this?
For that reason, this is a multipart answer.

First of all, for seeing all the data in a MySql database, phpMyAdmin is perfect for the job - a tool that I can almost guarantee most SQL guys are appreciative of.

For the second part of the question: I'm presuming you want to do this dynamically, or there's just too many tables to write a query for each time. I'll presume the dynamically one, because I have created databases in the past which automatically adds tables to itself as it grows.
This solution in PHP is one I've just written for you which should display everything in a table.
EDIT: This code is bugged - all the data is displayed but I've gotten the table formatting wrong. - EDIT: fixed.

<?php
listAll("table_name");
function listAll($db) {
  mysql_connect("localhost","root","");
  mysql_select_db($db);
  $tables = mysql_query("SHOW TABLES FROM $db");
  while (list($tableName)=mysql_fetch_array($tables)) {
    $result = mysql_query("DESCRIBE $tableName");
    $rows = array();
    while (list($row)=mysql_fetch_array($result)) {
      $rows[] = $row;
    }
    $count = count($rows);
    if ($count>0) {
      echo '<p><strong>',htmlentities($tableName),'</strong><br /><table border="1"><tr>';
      foreach ($rows as &$value) {
        echo '<td><strong>',htmlentities($value),'</strong></td>';
      }
      echo '</tr>';
      $result = mysql_query("SELECT * FROM $tableName");
      while ($row=mysql_fetch_array($result)) {
        echo '<tr>';
        for ($i=0;$i<(count($row)/2);$i++) {
          echo '<td>',htmlentities($row[$i]),'</td>';
        }
        echo '</tr>';
      }
      echo '</table></p>';
    }
  }
return FALSE;
}
?>

And hopefully that code snippet should work for you like it's worked for me!


问:
How do I resolve my error message I got with Merge Query below?
I am writing a merge query but I am getting error when running it. I reviewed the query closely and I can not see why I am getting this error. I reviewed the different formats a SQL merge can take and still none of them worked. I am running this query on a SQL Develoer Version 19.1.0.094.

I realize I could use an 'Inner Join" for this solution but I was unsure of how to capture the 'When Matched' and 'When Not Matched' function.  Is there an equivalent to the Match function when not using the Merge function? I appreciate any assistance with this problem.

I would appreciate any assistance on this manner.

```<code>MERGE into LAB_SALES_Fact fact
USING (select * from lab_stage_good stage)

On
(fact.time_id = stage.time_id AND
fact.cust_id = stage.cust_id AND
fact.promo_id = stage.promo_id AND
fact.channel_id = stage.channel_id)

WHEN MATCHED THEN UPDATE SET
fact.amount_sold = stage.amount_sold

WHEN NOT MATCHED THEN INSERT VALUES
(stage.prod_id, stage.cust_id, stage.time_id, stage.channel_id, stage.promo_id,
stage.amount_sold)
</code>```

Error at Command Line : 6 Column : 22
 Error report -
 SQL
Error: ORA-00904: "STAGE"."CHANNEL_ID": invalid identifier

00904. 00000 - "%s: invalid identifier"

*Cause:

*Action:

答:
The table alias stage is not visible outside the subquery. Move the alias so that it is visible:

MERGE into LAB_SALES_Fact fact
USING (select * from lab_stage_good) stage
ON (fact.time_id = stage.time_id
AND fact.cust_id = stage.cust_id
AND fact.promo_id = stage.promo_id
AND fact.channel_id = stage.channel_id )
WHEN MATCHED THEN
  UPDATE
  SET fact.amount_sold = stage.amount_sold
WHEN NOT MATCHED THEN
  INSERT (
    prod_id,
    cust_id,
    time_id,
    channel_id,
    promo_id,
    amount_sold
  ) VALUES (
    stage.prod_id,
    stage.cust_id,
    stage.time_id,
    stage.channel_id,
    stage.promo_id,
    stage.amount_sold
  )
```
<p><em>Note: also name the columns you are inserting into.</em></p>
<p>Or, even simpler, do not use a sub-query:</p>
<pre class="lang-sql prettyprint-override"><code>MERGE into LAB_SALES_Fact fact
USING lab_stage_good stage
ON ...
</code>```

db<>fiddle here

Body:
I am writing a merge query but I am getting error when running it. I reviewed the query closely and I can not see why I am getting this error. I reviewed the different formats a SQL merge can take and still none of them worked. I am running this query on a SQL Develoer Version 19.1.0.094.

I realize I could use an 'Inner Join" for this solution but I was unsure of how to capture the 'When Matched' and 'When Not Matched' function.  Is there an equivalent to the Match function when not using the Merge function? I appreciate any assistance with this problem.

I would appreciate any assistance on this manner.

MERGE into LAB_SALES_Fact fact
USING (select * from lab_stage_good stage)

On
(fact.time_id = stage.time_id AND
fact.cust_id = stage.cust_id AND
fact.promo_id = stage.promo_id AND
fact.channel_id = stage.channel_id)

WHEN MATCHED THEN UPDATE SET
fact.amount_sold = stage.amount_sold

WHEN NOT MATCHED THEN INSERT VALUES
(stage.prod_id, stage.cust_id, stage.time_id, stage.channel_id, stage.promo_id,
stage.amount_sold)

Error at Command Line : 6 Column : 22
 Error report -
 SQL
Error: ORA-00904: "STAGE"."CHANNEL_ID": invalid identifier

00904. 00000 - "%s: invalid identifier"

*Cause:

*Action:

Body:
The table alias stage is not visible outside the subquery. Move the alias so that it is visible:

MERGE into LAB_SALES_Fact fact
USING (select * from lab_stage_good) stage
ON (fact.time_id = stage.time_id
AND fact.cust_id = stage.cust_id
AND fact.promo_id = stage.promo_id
AND fact.channel_id = stage.channel_id )
WHEN MATCHED THEN
  UPDATE
  SET fact.amount_sold = stage.amount_sold
WHEN NOT MATCHED THEN
  INSERT (
    prod_id,
    cust_id,
    time_id,
    channel_id,
    promo_id,
    amount_sold
  ) VALUES (
    stage.prod_id,
    stage.cust_id,
    stage.time_id,
    stage.channel_id,
    stage.promo_id,
    stage.amount_sold
  )

Note: also name the columns you are inserting into.

Or, even simpler, do not use a sub-query:

MERGE into LAB_SALES_Fact fact
USING lab_stage_good stage
ON ...

db<>fiddle here