问:
Eclipse 'com.google.common.collect.ForwardingMultimap cannot be resolved. Referenced in class files' when using custom skull generator (Minecraft)
I am using a SkullCreator class created by deanveloper (GitHub Page). When I added it to my project, the error appears on the first line on the first character of the package keyword. (Yes I made sure to change the package correctly). I did research and found I needed to add Google Guava as a dependency. I added it and made sure it contained the ForwardingMultimap class, but the error still persists. Am I missing something with adding the dependency?

Dependency code:

```<code><dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
        <version>31.0.1-jre</version>
</dependency>
</code>```

I am new to Maven and dependencies, so if I missed something that might be obvious please explain.

答: I have found a solution. For anyone who wants to know, you must put the line 'requires com.google.common;' into your module-info.java file. An error will appear saying you must add this to the project dependencies. Once you do this, then it should work.</p>

Body:
I am using a SkullCreator class created by deanveloper (GitHub Page). When I added it to my project, the error appears on the first line on the first character of the package keyword. (Yes I made sure to change the package correctly). I did research and found I needed to add Google Guava as a dependency. I added it and made sure it contained the ForwardingMultimap class, but the error still persists. Am I missing something with adding the dependency?

Dependency code:

<dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
        <version>31.0.1-jre</version>
</dependency>

I am new to Maven and dependencies, so if I missed something that might be obvious please explain.


来源: stackexchange

问:
Navigating to a new page from a viewmodel
I have used the WP7 DataBound app template for my program which utilises a form of MVVM. I would like to navigate from my mainpage to my settings page but since it is the VM that loads the data, which in turn determines if the settings pages needs to be loaded, I should like to call navigate code from the VM, not the view. However, NavigationService does not show the Navigate method in the VM, only in the view.  Does anyone have any suggesions about how I can/should call the Navigate method in the VM?

Thanks,

Jason.

答:
i tend to use one of the following

publish a event in the VM, subscribe in the view

implement a global NavigationService (using the ServiceLocator pattern or DI), you can for example implement such a Interface in your application-class

ContentLicense: CC BY-SA 3.0


问:
How to check if user is logged in or anonymous in Spring Security
When the root controller ("/") is called, I want to check if the user has authenticated or not. If he is not authenticated I want to display home page while if he is I want to display dashboard like so:

```<code>@GetMapping("/")
public String homePage() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    if(authentication == null) return "home";

    return "dashboard";
}
</code>```

But when I run the program, it tries to display dashboard, which means that clearly the if() condition returned false. But I know that I definitely did not log in. Why does this not work.

Also, I know I could override the configure(HttpSecurity http) method in the  WebSecurityConfigurerAdapter like so:

```<code>http.authorizeRequests().antMatchers("/").authenticated();
</code>```

But this would redirect me to the /login page, which is ok for any other request but not ("/") where I want to be redirected to "home" page if no session exists.

This is the value of authentication after a Sysout: org.springframework.security.authentication.AnonymousAuthenticationToken@52132976: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS

答:
Well, the fastest way to do so (worked with me in my app) is the following:

```<code>@GetMapping("/")
public Boolean isLoggedIn(Principal principal) {

    if(principal == null) return "home";

    return "dashboard";
}
</code>```

It should be noted that in my app I already configured all the security stuff. This means that if my solution won't work with you (hope not), know that you have to configure all the security stuff too (check Spring Security courses).

ContentLicense: CC BY-SA 4.0

Body:
When the root controller ("/") is called, I want to check if the user has authenticated or not. If he is not authenticated I want to display home page while if he is I want to display dashboard like so:

@GetMapping("/")
public String homePage() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    if(authentication == null) return "home";

    return "dashboard";
}

But when I run the program, it tries to display dashboard, which means that clearly the if() condition returned false. But I know that I definitely did not log in. Why does this not work.

Also, I know I could override the configure(HttpSecurity http) method in the  WebSecurityConfigurerAdapter like so:

http.authorizeRequests().antMatchers("/").authenticated();

But this would redirect me to the /login page, which is ok for any other request but not ("/") where I want to be redirected to "home" page if no session exists.

This is the value of authentication after a Sysout: org.springframework.security.authentication.AnonymousAuthenticationToken@52132976: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS

Body:
Well, the fastest way to do so (worked with me in my app) is the following:

@GetMapping("/")
public Boolean isLoggedIn(Principal principal) {

    if(principal == null) return "home";

    return "dashboard";
}

It should be noted that in my app I already configured all the security stuff. This means that if my solution won't work with you (hope not), know that you have to configure all the security stuff too (check Spring Security courses).


问:
Issue with nested scroll when both scroll are always visible (Flutter Stable Channel)
The issue is on web when we try to scroll the vertically scrollable widget which is a child of horizontally scrollable widget where scroll bar is always visible.

When we scroll the horizontally scrollable widget the scroll bar for horizontal scroll is correctly displayed as shown in picture
horizontal scroll

But when we scroll the vertically scrollable widget the horizontal scrollbar disappears and new vertical scroll bar is seen at right as shown in screenshot
vertical scroll

Code to reproduce the issue.

```<code>import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Scroll Issue Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Scroll Issue Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final ScrollController _horizontalController = ScrollController();

  final List<ScrollController> _verticalController = [];

  @override
  void initState() {
    super.initState();
    for (int i = 0; i < 6; i++) {
      _verticalController.add(ScrollController());
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Row(
        children: <Widget>[
          Expanded(
            child: _buildHorizontalScroll(),
          )
        ],
      ),
    );
  }

  Widget _buildHorizontalScroll() {
    return Scrollbar(
      isAlwaysShown: true,
      controller: _horizontalController,
      notificationPredicate: (predicate) {
        return predicate.depth == 0;
      },
      child: ListView.separated(
          controller: _horizontalController,
          scrollDirection: Axis.horizontal,
          itemBuilder: (context, index) => Container(
                margin: const EdgeInsets.all(30),
                width: 300,
                color: Colors.black12,
                child: Column(
                  children: [
                    Expanded(
                      child: _buildVerticalScroll(index),
                    )
                  ],
                ),
              ),
          separatorBuilder: (context, index) => const Divider(
                height: 30,
              ),
          itemCount: 6),
    );
  }

  Widget _buildVerticalScroll(int index) {
    return Scrollbar(
      scrollbarOrientation: ScrollbarOrientation.right,
      isAlwaysShown: true,
      controller: _verticalController[index],
      child: ListView.separated(
          controller: _verticalController[index],
          itemBuilder: (context, index) => Container(
                margin: const EdgeInsets.all(30),
                height: 100,
                color: Colors.green,
              ),
          separatorBuilder: (context, index) => const Divider(
                height: 30,
              ),
          itemCount: 200),
    );
  }
}
</code>```

Checking the notification predicate in the horizontal scroll bar, it detects the depth of scroll as both 0 and 1 when scrolling the vertically scrollable list. Is there a workaround for this problem? The problem started to appear since the upgrade to 2.5.0 for stable channel of flutter.

答:
Maybe this package will help you easily customize your thumb and scrolling track both horizontally and vertically

https://pub.dev/packages/cross_scroll

Body:
The issue is on web when we try to scroll the vertically scrollable widget which is a child of horizontally scrollable widget where scroll bar is always visible.

When we scroll the horizontally scrollable widget the scroll bar for horizontal scroll is correctly displayed as shown in picture
horizontal scroll

But when we scroll the vertically scrollable widget the horizontal scrollbar disappears and new vertical scroll bar is seen at right as shown in screenshot
vertical scroll

Code to reproduce the issue.

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Scroll Issue Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Scroll Issue Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final ScrollController _horizontalController = ScrollController();

  final List<ScrollController> _verticalController = [];

  @override
  void initState() {
    super.initState();
    for (int i = 0; i < 6; i++) {
      _verticalController.add(ScrollController());
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Row(
        children: <Widget>[
          Expanded(
            child: _buildHorizontalScroll(),
          )
        ],
      ),
    );
  }

  Widget _buildHorizontalScroll() {
    return Scrollbar(
      isAlwaysShown: true,
      controller: _horizontalController,
      notificationPredicate: (predicate) {
        return predicate.depth == 0;
      },
      child: ListView.separated(
          controller: _horizontalController,
          scrollDirection: Axis.horizontal,
          itemBuilder: (context, index) => Container(
                margin: const EdgeInsets.all(30),
                width: 300,
                color: Colors.black12,
                child: Column(
                  children: [
                    Expanded(
                      child: _buildVerticalScroll(index),
                    )
                  ],
                ),
              ),
          separatorBuilder: (context, index) => const Divider(
                height: 30,
              ),
          itemCount: 6),
    );
  }

  Widget _buildVerticalScroll(int index) {
    return Scrollbar(
      scrollbarOrientation: ScrollbarOrientation.right,
      isAlwaysShown: true,
      controller: _verticalController[index],
      child: ListView.separated(
          controller: _verticalController[index],
          itemBuilder: (context, index) => Container(
                margin: const EdgeInsets.all(30),
                height: 100,
                color: Colors.green,
              ),
          separatorBuilder: (context, index) => const Divider(
                height: 30,
              ),
          itemCount: 200),
    );
  }
}

Checking the notification predicate in the horizontal scroll bar, it detects the depth of scroll as both 0 and 1 when scrolling the vertically scrollable list. Is there a workaround for this problem? The problem started to appear since the upgrade to 2.5.0 for stable channel of flutter.


问:
Merging data frame generating extra coma
I have the following data frames

```<code>b = frozenset({'hi','how','are'})
c = frozenset({'we'})

d = frozenset({'hi','how'})
e = frozenset({'we','are'})

we = set()
we.add((b,c))

we2 =set()
we2.add((d,e))

import pandas as pd
df = pd.DataFrame({'we': [we,we],'value': [5,2]})
df2 = pd.DataFrame({'we': [we2,we],'value': [6,12]})
</code>```

df is :

```<code>               we             value
0   {((hi, how, are), (we))}    5
1   {((hi, how, are), (we))}    2
</code>```

Here is df2:

```<code>               we             value
0   {((hi, how), (are, we))}    6
1   {((hi, how, are), (we))}    12
</code>```

I left joined df and df2:

```<code>df.we = df.we.apply(tuple)
df2.we = df2.we.apply(tuple)
df3= pd.merge(df,df2,how='left',on='we')
</code>```

The result is correct in terms of data but I have no idea where did the comas come from:

```<code>                  we        value_x value_y
0   (((hi, how, are), (we)),)   5   12
1   (((hi, how, are), (we)),)   2   12
</code>```

How do I get:

```<code>                  we    value_x value_y
0   ((hi, how, are), (we))  5   12
1   ((hi, how, are), (we))  2   12
</code>```

答:
You do not want to convert the set to a tuple but extract its only element.

```<code>df.we = df.we.apply(lambda x: next(iter(x)))
df2.we = df2.we.apply(lambda x: next(iter(x)))
df3= pd.merge(df,df2,how='left',on='we')
</code>```

df3 is as expected

```<code>                       we  value_x  value_y
0  ((are, how, hi), (we))        5       12
1  ((are, how, hi), (we))        2       12
</code>```

Alternatively, you could update your sets with the sequences instead of adding to them:

```<code>...
we = set()
we.update((b,c))

we2 =set()
we2.update((d,e))
</code>```

For example df would be:

```<code>                       we  value
0  ((we), (are, how, hi))      5
1  ((we), (are, how, hi))      2
</code>```

Now it makes sense to convert the set to a tuple and after:

```<code>df.we = df.we.apply(tuple)
df2.we = df2.we.apply(tuple)
df3= pd.merge(df,df2,how='left',on='we')
</code>```

we also get for df3:

```<code>                       we  value_x  value_y
0  ((hi, are, how), (we))        5       12
1  ((hi, are, how), (we))        2       12
</code>```

Body:
I have the following data frames

b = frozenset({'hi','how','are'})
c = frozenset({'we'})

d = frozenset({'hi','how'})
e = frozenset({'we','are'})

we = set()
we.add((b,c))

we2 =set()
we2.add((d,e))

import pandas as pd
df = pd.DataFrame({'we': [we,we],'value': [5,2]})
df2 = pd.DataFrame({'we': [we2,we],'value': [6,12]})

df is :

               we             value
0   {((hi, how, are), (we))}    5
1   {((hi, how, are), (we))}    2

Here is df2:

               we             value
0   {((hi, how), (are, we))}    6
1   {((hi, how, are), (we))}    12

I left joined df and df2:

df.we = df.we.apply(tuple)
df2.we = df2.we.apply(tuple)
df3= pd.merge(df,df2,how='left',on='we')

The result is correct in terms of data but I have no idea where did the comas come from:

                  we        value_x value_y
0   (((hi, how, are), (we)),)   5   12
1   (((hi, how, are), (we)),)   2   12

How do I get:

                  we    value_x value_y
0   ((hi, how, are), (we))  5   12
1   ((hi, how, are), (we))  2   12

Body:
You do not want to convert the set to a tuple but extract its only element.

df.we = df.we.apply(lambda x: next(iter(x)))
df2.we = df2.we.apply(lambda x: next(iter(x)))
df3= pd.merge(df,df2,how='left',on='we')

df3 is as expected

                       we  value_x  value_y
0  ((are, how, hi), (we))        5       12
1  ((are, how, hi), (we))        2       12

Alternatively, you could update your sets with the sequences instead of adding to them:

...
we = set()
we.update((b,c))

we2 =set()
we2.update((d,e))

For example df would be:

                       we  value
0  ((we), (are, how, hi))      5
1  ((we), (are, how, hi))      2

Now it makes sense to convert the set to a tuple and after:

df.we = df.we.apply(tuple)
df2.we = df2.we.apply(tuple)
df3= pd.merge(df,df2,how='left',on='we')

we also get for df3:

                       we  value_x  value_y
0  ((hi, are, how), (we))        5       12
1  ((hi, are, how), (we))        2       12


问:
Inconsistent result output with gensim index_to_key
Good afternoon,

first of all thanks to all who take the time to read this.
My problem is this, I would like to have a word2vec output the most common words.

I do this with the following command:

#how many words to print out ( sort at frequency)

x = list(model.wv.index_to_key[:2500])

Basically it works, but sometimes I get only 1948 or 2290 words printed out. I can't find any connection with the size of the original corpus (tokens, lines etc.) or deviation from the target value (if I increase the output value to e.g. 3500 it outputs 3207 words).

I would like to understand why this is the case, unfortunately I can't find anything on Google and therefore I don't know how to solve the problem. maybe by increasing the value and later deleting all rows after 2501 by using pandas

答:
If any Python list ranged-access, like my_list[:n], returns less than n items, then the original list my_list had less than n items in it.

So, if model.wv.index_to_key[:2500] is only returning a list of length 1948, then I'm pretty sure if you check len(model.wv.index_to_key), you'll see the source list is only 1948 items long. And of course, you can't take the 1st 2500 items from a list that's only 1948 items long!

Why might your model have fewer unique words than you expect, or even that you counted via other methods?

Something might be amiss in your preprocessing/tokenization, but most likely is that you're not considering the effect of the default min_count=5 parameter. That default causes all words that appear fewer than 5 times to be ignored during training, as if they weren't even in the source texts.

You may be tempted to use min_count=1, to keep all words, but that's almost always a bad idea in word2vec training. Word2vec needs many subtly-contrasting alternate uses of a word to train a good word-vector.

Keeping words which only have one, or a few, usage examples winds up not failing to get good generalizable vectors for those rare words, but also interferes with the full learning of vectors for other nearby more-frequent words – now that their training has to fight the noise & extra model-cycles from the insufficiently-represented rare words.

Instead of lowering min_count, it's better to get more data, or live with a smaller final vocabulary.


问:
How to fix textSize of title in FlexibleSpaceBar (SliverAppBar)?
How can I fix de textSize of title in FlexibleSpaceBar?

...
child: CustomScrollView(
                slivers: <Widget>[
                  new SliverAppBar(
                    backgroundColor:
                        Colors.white,
                    automaticallyImplyLeading: false,
                    actions: <Widget>[new Container()],
                    expandedHeight: 230.0,
                    floating: false,
                    pinned: true,
                    primary: true,
                    snap: false,

                    flexibleSpace: new FlexibleSpaceBar(
                    collapseMode: CollapseMode.pin,
                    titlePadding: EdgeInsetsDirectional.only(start: 10, bottom: 0),
                    title: new Text('Some Text Here', style: TextStyle(color: Colors.black, fontSize: 14)),
])
```

When I collapse the SliverAppBar making scroll up, the title of FlexibleSpaceBar automatically resize. I need to fix the textSize of tittle.

答:
The FlexibleSpaceBar has a paramter called expandedTitleScale. If this is set to 1 the titel and containing text does't change it's size when scrolling.</p>
```<code>FlexibleSpaceBar(
   expandedTitleScale: 1,
   ...
)
</code>```

Body:
How can I fix de textSize of title in FlexibleSpaceBar?

...
child: CustomScrollView(
                slivers: <Widget>[
                  new SliverAppBar(
                    backgroundColor:
                        Colors.white,
                    automaticallyImplyLeading: false,
                    actions: <Widget>[new Container()],
                    expandedHeight: 230.0,
                    floating: false,
                    pinned: true,
                    primary: true,
                    snap: false,

                    flexibleSpace: new FlexibleSpaceBar(
                    collapseMode: CollapseMode.pin,
                    titlePadding: EdgeInsetsDirectional.only(start: 10, bottom: 0),
                    title: new Text('Some Text Here', style: TextStyle(color: Colors.black, fontSize: 14)),
])

When I collapse the SliverAppBar making scroll up, the title of FlexibleSpaceBar automatically resize. I need to fix the textSize of tittle.

Body:
The FlexibleSpaceBar has a paramter called expandedTitleScale. If this is set to 1 the titel and containing text does't change it's size when scrolling.

FlexibleSpaceBar(
   expandedTitleScale: 1,
   ...
)


问:
when first if statement true continue with next if statement
python 3.8.11

I want to call the function num_okay in another file. and I want to return the specific "solu" for each number if the if statement is true.

rn it's only returning the first if statement. but I want it to return all the if statements that are correct, not only the first time

and if the first if statement is false I want to continue running the next if statement

thankss

```<code>numberA=1

numberB=2

numberC=3

numberD=4

def num_okay():

    if numberA < 20 or numberA > 30:
        solu= 'numberA is okay'
        return solu

    if numberB < 20 or numberB > 30:
        solu = 'numberB is okay'
        return solu

    if numberC < 20 or numberC > 30:
        solu = 'numberC is okay'
        return solu

    if numberD < 20 or numberD > 30:
        solu = 'numberD is okay'
        return solu

    else:
        return "NO number is okay"
</code>```

答:
I don't know if you'd like this result, but sure, if you like it, I think you should use the following code, since it doesn't use that many if... statements:

```<code>i = 0
numbers = [
  ["numberA", 19],
  ["numberB", 27],
  ["numberC", 83],
  ["numberD", 23]
]

def num_okay():
  global i
  while i != 4:
    if numbers[i][1] < 20 or numbers[i][1] > 30:
      print(numbers[i][0] + " is okay")
    else:
      print(numbers[i][0] + " is not okay")
    i += 1

num_okay()
</code>```

The output would be:

numberA is okay

numberB is not okay

numberC is okay

numberD is not okay

If you don't really understand the code, feel free to ask me, because I'd be more than happy to explain!

Body:
python 3.8.11

I want to call the function num_okay in another file. and I want to return the specific "solu" for each number if the if statement is true.

rn it's only returning the first if statement. but I want it to return all the if statements that are correct, not only the first time

and if the first if statement is false I want to continue running the next if statement

thankss

numberA=1

numberB=2

numberC=3

numberD=4

def num_okay():

    if numberA < 20 or numberA > 30:
        solu= 'numberA is okay'
        return solu

    if numberB < 20 or numberB > 30:
        solu = 'numberB is okay'
        return solu

    if numberC < 20 or numberC > 30:
        solu = 'numberC is okay'
        return solu

    if numberD < 20 or numberD > 30:
        solu = 'numberD is okay'
        return solu

    else:
        return "NO number is okay"

Body:
I don't know if you'd like this result, but sure, if you like it, I think you should use the following code, since it doesn't use that many if... statements:

i = 0
numbers = [
  ["numberA", 19],
  ["numberB", 27],
  ["numberC", 83],
  ["numberD", 23]
]

def num_okay():
  global i
  while i != 4:
    if numbers[i][1] < 20 or numbers[i][1] > 30:
      print(numbers[i][0] + " is okay")
    else:
      print(numbers[i][0] + " is not okay")
    i += 1

num_okay()

The output would be:

numberA is okay

numberB is not okay

numberC is okay

numberD is not okay

If you don't really understand the code, feel free to ask me, because I'd be more than happy to explain!


问:
Paypal pay later not working when currency is GBP
I have a paypal page that gives two options of funding, credit card and pay later service. When the currency is USD, the pay later button is visible and when the currency is GBP the pay later button is not visible.

The UK has pay later service but the button isnt displayed. This is the code.

```<code><script src="https://www.paypal.com/sdk/js?client-id=xxxxxxxxx&currency=GBP&enable-funding=credit,card&components=messages,buttons">
</script>

<div id="paypal-button-container"></div>

<script>
  paypal.Buttons({
    createOrder: function(data, actions) {
        return actions.order.create({
          purchase_units: [{
            amount: {
              value: '50.00'
            }
          }]
        });
      }
}).render('#paypal-button-container');
</script>

<div
  data-pp-message
  data-pp-amount="50.00">
</div>
</code>```

How can i display the paylater button when teh currency is GBP or EUR?

答:
You can't with the same account, rendering the Pay Later button is specific to the country and currency of the receiving account.  GBP would likely require a UK receiver, while EUR would likely require DE or FR.

Whether the button displays or not (mostly not when the country and currency isn't a match), Pay Later offers might still be available to the payer in the normal PayPal checkout flow.

Body:
I have a paypal page that gives two options of funding, credit card and pay later service. When the currency is USD, the pay later button is visible and when the currency is GBP the pay later button is not visible.

The UK has pay later service but the button isnt displayed. This is the code.

How can i display the paylater button when teh currency is GBP or EUR?


问:
Force Swiper.js to display only one slide on mobile viewport
I was working on a Swiper.js and I have the following HTML:

```<code><div class="swiper-container">
    <div class="swiper-wrapper">
      <div class="swiper-slide">
          <img src="images/img1.jpg" alt="">
          <div class="slide-text">
            <h2>Slide One</h2>
            <a class="btn-slider" href="#">LEARN MORE →</a>
          </div>
      </div>
      <div class="swiper-slide">
        <img src="images/img2.jpg" alt="">
        <div class="slide-text">
         <h2>Slide Two</h2>
         <a class="btn-slider" href="#">LEARN MORE →</a>
        </div>
    </div>
    <div class="swiper-slide">
        <img src="images/img3.jpg" alt="">
        <div class="slide-text">
         <h2>Slide Two</h2>
         <a class="btn-slider" href="#">LEARN MORE →</a>
        </div>
    </div>
</div>
</code>```

By default, you will have the following JS to make it work:

```<code>var swiper = new Swiper(".swiper-container", {
  autoplay: {
    slidesPerView: 1,
    disableOnInteraction: false,
  },
});
</code>```

I was wondering if its possible to force Swiper.js to only display one slide on mobile viewport instead of showing all 3 slides on mobile?

答:
YES, you can use breakpoints object alongside your autoplay, Like this

```<code>var swiper = new Swiper(".swiper-container", {
  autoplay: {
    slidesPerView: 1,
    disableOnInteraction: false,
  },
  breakpoints: {
    640: {
      slidesPerView: 1,
      spaceBetween: 20,
    },
    768: {
      slidesPerView: 2,
      spaceBetween: 40,
    },
    1024: {
      slidesPerView: 3,
      spaceBetween: 50,
    },
  },
});
</code>```

Here Is The Documentation Example For Responsive Sliders

https://codesandbox.io/s/3blv5?file=/index.html

Body:
I was working on a Swiper.js and I have the following HTML:

Slide One

            LEARN MORE →

Slide Two

         LEARN MORE →

Slide Two

         LEARN MORE →

By default, you will have the following JS to make it work:

var swiper = new Swiper(".swiper-container", {
  autoplay: {
    slidesPerView: 1,
    disableOnInteraction: false,
  },
});

I was wondering if its possible to force Swiper.js to only display one slide on mobile viewport instead of showing all 3 slides on mobile?

Body:
YES, you can use breakpoints object alongside your autoplay, Like this

var swiper = new Swiper(".swiper-container", {
  autoplay: {
    slidesPerView: 1,
    disableOnInteraction: false,
  },
  breakpoints: {
    640: {
      slidesPerView: 1,
      spaceBetween: 20,
    },
    768: {
      slidesPerView: 2,
      spaceBetween: 40,
    },
    1024: {
      slidesPerView: 3,
      spaceBetween: 50,
    },
  },
});

Here Is The Documentation Example For Responsive Sliders

https://codesandbox.io/s/3blv5?file=/index.html


问:
Order by best match of string column in EF Core
I am implementing a search feature for the users in our api. The search will query our db to fetch the first N users matching the search term. I want to order the user after "best match" so the most relevant user is on top.

What I'd like to do is something like:

```<code>var users = await _dbContext.Users
   .IncludeUserData()
   .Where(u => u.Name.Contains(searchTerm))
   .OrderBy(u => u.Name.IndexOf(searchTerm)) <- This row is not possible
   .ToListAsync();
</code>```

Where basically a name that contains the search term early is ordered before a user whose name contains the term late.

E.g.
Simon Carlsson should come before Carl Simonsson if the searchTerm is "Simon"

Using SQL Server as the DB provider

How would I achieve an order by query where users with names better matching the searchTerm are sorted higher up in the list?

答:
Have you tried the LIKE operator?

You may find this useful

Entity framework EF.Functions.Like vs string.Contains

Body:
I am implementing a search feature for the users in our api. The search will query our db to fetch the first N users matching the search term. I want to order the user after "best match" so the most relevant user is on top.

What I'd like to do is something like:

var users = await _dbContext.Users
   .IncludeUserData()
   .Where(u => u.Name.Contains(searchTerm))
   .OrderBy(u => u.Name.IndexOf(searchTerm)) <- This row is not possible
   .ToListAsync();

Where basically a name that contains the search term early is ordered before a user whose name contains the term late.

E.g.
Simon Carlsson should come before Carl Simonsson if the searchTerm is "Simon"

Using SQL Server as the DB provider

How would I achieve an order by query where users with names better matching the searchTerm are sorted higher up in the list?


问:
Cannot access API view on post request using decorator [AllowAny]
I have a simple function-based @api_view(['POST']) with @permission_classes([AllowAny])
and DRF settings in settings.py are:

```<code>REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ],
    'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',
}
</code>```

The documentation says:

The AllowAny permission class will allow unrestricted access,
regardless of if the request was authenticated or unauthenticated.

But I'm getting the following response on making a post request:

```<code>{
    "detail": "Authentication credentials were not provided."
}
</code>```

What might be the problem? Do I have to modify DEFAULT_AUTHENTICATION_CLASSES from the settings? I don't want the permissions to be required while making the request on this @api_view:

```<code>@api_view(['POST'])
@permission_classes([AllowAny])
def reset_password_request(email):
    try:
    #...
</code>```

accounts/urls.py:

```<code>urlpatterns = [
    path('user/<str:pk>/', views.getUserById, name='user'),
    path('user/password_reset_request/',
         views.resetPasswordRequest, name='password_reset_request'),
]
</code>```

答:
According to this, the position of decorator is wrong. The first decorator to be executed should be on the top. Change your decorator to the bottom like this:

```<code>@api_view(['POST'])
@permission_classes([AllowAny])
def reset_password_request(email):
    try:
    #...
</code>```

Check out the official documentation for reference.

Body:
I have a simple function-based @api_view(['POST']) with @permission_classes([AllowAny])
and DRF settings in settings.py are:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ],
    'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',
}

The documentation says:

The AllowAny permission class will allow unrestricted access,
regardless of if the request was authenticated or unauthenticated.

But I'm getting the following response on making a post request:

{
    "detail": "Authentication credentials were not provided."
}

What might be the problem? Do I have to modify DEFAULT_AUTHENTICATION_CLASSES from the settings? I don't want the permissions to be required while making the request on this @api_view:

@api_view(['POST'])
@permission_classes([AllowAny])
def reset_password_request(email):
    try:
    #...

accounts/urls.py:

urlpatterns = [
    path('user/<str:pk>/', views.getUserById, name='user'),
    path('user/password_reset_request/',
         views.resetPasswordRequest, name='password_reset_request'),
]

Body:
According to this, the position of decorator is wrong. The first decorator to be executed should be on the top. Change your decorator to the bottom like this:

@api_view(['POST'])
@permission_classes([AllowAny])
def reset_password_request(email):
    try:
    #...

Check out the official documentation for reference.


答:
You are applying the for loop over return as well and eventually returning the sample corresponding to the last scenario only.

Try this :

```<code>genereting_fuction<-function(n){
  sample <- list()
  for (i in 1:nrow(scenari)){
      X1=rnorm(n)+scenari[i,1]
      X4=rnorm(n)+scenari[i,4]
      X2=X1*p12+std_e2*rnorm(n)+scenari[i,2]
      X3=X1*p13+X4*p43+std_e3*rnorm(n)+scenari[i,3]
      X5=X2*p25+X3*p35+std_e5*rnorm(n)+scenari[i,5]
     sample[[i]]=cbind(X1,X2,X3,X4,X5)
  }
  sample
}
</code>```

The output will be a list and its ith element will be a sample corresponding to the ith scenario.

Title: Can't get data for all combinations

Body:
I have 31 possible scenarios for the value of the average and I would like to generate for each scenario samples but I do not get as much as I would like.
This is the scenarios

> scenari<-s*shift;scenari
   Var1 Var2 Var3 Var4 Var5
2   1.5  0.0  0.0  0.0  0.0
3   0.0  1.5  0.0  0.0  0.0
4   1.5  1.5  0.0  0.0  0.0
5   0.0  0.0  1.5  0.0  0.0
6   1.5  0.0  1.5  0.0  0.0
7   0.0  1.5  1.5  0.0  0.0
8   1.5  1.5  1.5  0.0  0.0
9   0.0  0.0  0.0  1.5  0.0
10  1.5  0.0  0.0  1.5  0.0
11  0.0  1.5  0.0  1.5  0.0
12  1.5  1.5  0.0  1.5  0.0
13  0.0  0.0  1.5  1.5  0.0
14  1.5  0.0  1.5  1.5  0.0
15  0.0  1.5  1.5  1.5  0.0
16  1.5  1.5  1.5  1.5  0.0
17  0.0  0.0  0.0  0.0  1.5
18  1.5  0.0  0.0  0.0  1.5
19  0.0  1.5  0.0  0.0  1.5
20  1.5  1.5  0.0  0.0  1.5
21  0.0  0.0  1.5  0.0  1.5
22  1.5  0.0  1.5  0.0  1.5
23  0.0  1.5  1.5  0.0  1.5
24  1.5  1.5  1.5  0.0  1.5
25  0.0  0.0  0.0  1.5  1.5
26  1.5  0.0  0.0  1.5  1.5
27  0.0  1.5  0.0  1.5  1.5
28  1.5  1.5  0.0  1.5  1.5
29  0.0  0.0  1.5  1.5  1.5
30  1.5  0.0  1.5  1.5  1.5
31  0.0  1.5  1.5  1.5  1.5
32  1.5  1.5  1.5  1.5  1.5

and this is the function

genereting_fuction<-function(n){
  for (i in 1:length(scenari)){
      X1=rnorm(n)+scenari[i,1]
      X4=rnorm(n)+scenari[i,4]
      X2=X1*p12+std_e2*rnorm(n)+scenari[i,2]
      X3=X1*p13+X4*p43+std_e3*rnorm(n)+scenari[i,3]
      X5=X2*p25+X3*p35+std_e5*rnorm(n)+scenari[i,5]
     sample=cbind(X1,X2,X3,X4,X5)
     return(sample)
  }
}
genereting_fuction(10)

I should get 31 samples of size 10X5 but I get only one sample

Body:
You are applying the for loop over return as well and eventually returning the sample corresponding to the last scenario only.

Try this :

genereting_fuction<-function(n){
  sample <- list()
  for (i in 1:nrow(scenari)){
      X1=rnorm(n)+scenari[i,1]
      X4=rnorm(n)+scenari[i,4]
      X2=X1*p12+std_e2*rnorm(n)+scenari[i,2]
      X3=X1*p13+X4*p43+std_e3*rnorm(n)+scenari[i,3]
      X5=X2*p25+X3*p35+std_e5*rnorm(n)+scenari[i,5]
     sample[[i]]=cbind(X1,X2,X3,X4,X5)
  }
  sample
}

The output will be a list and its ith element will be a sample corresponding to the ith scenario.


问:
React Testing with history passed

Problem Statement

I'm using create react app with Jest. In my test, I simply want to render out a component that needs history passed to the state before it can load. I've been researching and trying to get to this to work for awhile.
The source I've been using shows how to pass the history to the router - https://testing-library.com/docs/example-react-router/

When running the test an error says

"Cannot read property 'state' of undefined"

I believe it's because the history isn't being properly passed in during the test.

I'm really new to testing and am hoping someone can point me in the right direction to having it render the component during the test successfully. Thanks!

Code

The rendered component:

```<code>const [data, setData] = useState({
            pack: props && props.location.state && props.location.state.hasOwnProperty('package')
                ? props.location.state.package
                : ''
        });

const ContactPage = (props) => (
    Contact &&
    <Layout>

            <div className="contact-Letter">
                    {Contact(props)}
            </div>

    </Layout>
);
</code>```

The test component "attempts":

```<code>import React from 'react';
import Contacts from './contact'
import { BrowserRouter as Router, } from "react-router-dom";
import { render, screen } from '@testing-library/react';
import { createMemoryHistory } from "history";

const {
    ContactPage
} = Contacts();

test("renders location state", () => {
    const history = createMemoryHistory();

    render(
      <Router history={history}>
        <ContactPage />
      </Router>
    );

  });
</code>```

The Error:

```<code> TypeError: Cannot read property 'state' of undefined

    > 29 |             pack: props && props.location.state && props.location.state.hasOwnProperty('package')
         |                                           ^
      30 |                 ? props.location.state.package
      31 |                 : ''
      32 |         });
</code>```

答:
I was following the testing-library.com example and realized all I had to do differently was pass the history as props to my main component and not the router. so my test code simply needed to look like this.</p>
```<code>it("renders location state", () => {
    const history = createMemoryHistory();

    render(
        <Router>
            <ContactPage location={history}/>
        </Router>
    )
  });
</code>```

Title: React Testing with history passed

Body:
Problem Statement

I'm using create react app with Jest. In my test, I simply want to render out a component that needs history passed to the state before it can load. I've been researching and trying to get to this to work for awhile.
The source I've been using shows how to pass the history to the router - https://testing-library.com/docs/example-react-router/

When running the test an error says

"Cannot read property 'state' of undefined"

I believe it's because the history isn't being properly passed in during the test.

I'm really new to testing and am hoping someone can point me in the right direction to having it render the component during the test successfully. Thanks!

Code

The rendered component:

const [data, setData] = useState({
            pack: props && props.location.state && props.location.state.hasOwnProperty('package')
                ? props.location.state.package
                : ''
        });

const ContactPage = (props) => (
    Contact &&
    <Layout>

                    {Contact(props)}

    </Layout>
);

The test component "attempts":

import React from 'react';
import Contacts from './contact'
import { BrowserRouter as Router, } from "react-router-dom";
import { render, screen } from '@testing-library/react';
import { createMemoryHistory } from "history";

const {
    ContactPage
} = Contacts();

test("renders location state", () => {
    const history = createMemoryHistory();

    render(
      <Router history={history}>
        <ContactPage />
      </Router>
    );

  });

The Error:

 TypeError: Cannot read property 'state' of undefined

    > 29 |             pack: props && props.location.state && props.location.state.hasOwnProperty('package')
         |                                           ^
      30 |                 ? props.location.state.package
      31 |                 : ''
      32 |         });

Body:
I was following the testing-library.com example and realized all I had to do differently was pass the history as props to my main component and not the router. so my test code simply needed to look like this.

it("renders location state", () => {
    const history = createMemoryHistory();

    render(
        <Router>
            <ContactPage location={history}/>
        </Router>
    )
  });


问:
Regex for detecting keys in the yaml file
I am writing a regex to detect the exposed passwords/secrets/keys in a yaml file.  Below is the example of the yaml file. The data key is common to all my yaml files. subkeys under the data key will vary for each file.

Scenario 1:

```<code>apiVersion: v1
data:
    PASSWORD: mypass123
    USER: {$USER_NAME}
metadata:
    Timestamp: 2021-03-31T14:29:09Z
</code>```

Scenario 2:

```<code>apiVersion: v1
data:
    DATABASE: {$DATABASE_NAME}
    USER: {$USER_NAME}
    API_KEY: mykey456=
metadata:
    Timestamp: 2021-03-31T14:29:09Z
</code>```

As you can see above sensitive information is exposed for the keys PASSWORD & API_KEY. I need a regex to match the data key & exposed values of sensitive information.

```<code>import re
import sys
from ruamel.yaml import YAML

yaml_str = """\
apiVersion: v1
data:
    PASSWORD: mypass123
    USER: {$USER_NAME}
metadata:
    Timestamp: 2021-03-31T14:29:09Z
"""

regex = r'data:\s*-\s*\b[a-z0-9_ .\-,]:([a-z0-9=_\-]{1,4096})'
</code>```

I have tried the above regex but it is not working. Any help is appreciated.

答:
My guess is that YAML parsing is going to be much easier and more maintainable. For example:</p>
```<code>import yaml

yaml_str = """\
apiVersion: v1
data:
    PASSWORD: mypass123
    USER: username123
metadata:
    Timestamp: 2021-03-31T14:29:09Z
"""

try:
    data = yaml.safe_load(yaml_str)
except yaml.YAMLError as exc:
    # handle exception ...
    pass

for field_of_interest in ["PASSWORD", "USER"]:
    print(data["data"][field_of_interest])
</code>```

Body:
I am writing a regex to detect the exposed passwords/secrets/keys in a yaml file.  Below is the example of the yaml file. The data key is common to all my yaml files. subkeys under the data key will vary for each file.

Scenario 1:

apiVersion: v1
data:
    PASSWORD: mypass123
    USER: {$USER_NAME}
metadata:
    Timestamp: 2021-03-31T14:29:09Z

Scenario 2:

apiVersion: v1
data:
    DATABASE: {$DATABASE_NAME}
    USER: {$USER_NAME}
    API_KEY: mykey456=
metadata:
    Timestamp: 2021-03-31T14:29:09Z

As you can see above sensitive information is exposed for the keys PASSWORD & API_KEY. I need a regex to match the data key & exposed values of sensitive information.

import re
import sys
from ruamel.yaml import YAML

yaml_str = """\
apiVersion: v1
data:
    PASSWORD: mypass123
    USER: {$USER_NAME}
metadata:
    Timestamp: 2021-03-31T14:29:09Z
"""

regex = r'data:\s*-\s*\b[a-z0-9_ .\-,]:([a-z0-9=_\-]{1,4096})'

I have tried the above regex but it is not working. Any help is appreciated.

Body:
My guess is that YAML parsing is going to be much easier and more maintainable. For example:

import yaml

yaml_str = """\
apiVersion: v1
data:
    PASSWORD: mypass123
    USER: username123
metadata:
    Timestamp: 2021-03-31T14:29:09Z
"""

try:
    data = yaml.safe_load(yaml_str)
except yaml.YAMLError as exc:
    # handle exception ...
    pass

for field_of_interest in ["PASSWORD", "USER"]:
    print(data["data"][field_of_interest])


问:
What does external mean in Dart?
What does external mean in Dart? For example: external DateTime._now();

I'm new to Dart, I can't find documentation for external, so can you give an example to help explain？

答: In my opinion it is an equivalent of Java native keyword. For example, since current time milliseconds is implemented differently on Android, iOS, Linux etc, DateTime.now().millisecondsSinceEpoch will be linked to different implementations at runtime. So it is not initially known how this method will look like. For this reason it is marked as external meaning it is platform dependent.

Title: What does external mean in Dart?


问:
How do I place an Angular material button at a particular position?
I want to place the following button at the bottom-center of the mat-grid-tile, how can I do it?

.html file:

```<code><mat-grid-list cols="1" rowHeight="400">
  <mat-grid-tile class="example-grid" >
    <div class="button">
      <button mat-button (click)="getQuestions()" routerLink="questions/getAllQuestions" routerLinkActive="active"><strong>Show!</strong> </button>
    </div>
</mat-grid-tile>
  <mat-grid-tile>...</mat-grid-tile>
</mat-grid-list>
</code>```

.css file:

```<code>.button{
  display: table-cell;
  width: 700px;
  color: rgb(0, 0, 0);

}
</code>```

答:
You could use a little bit of CSS Flexbox for that.

```<code>.button {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    align-items: center;
    align-content: flex-end;
}
</code>```

Then your <button> will align to the bottom center of its container. Have a play around with Flexbox on this Playground to get better at it.

Body:
I want to place the following button at the bottom-center of the mat-grid-tile, how can I do it?

.html file:

<mat-grid-list cols="1" rowHeight="400">
  <mat-grid-tile class="example-grid" >

      <button mat-button (click)="getQuestions()" routerLink="questions/getAllQuestions" routerLinkActive="active">Show! </button>

</mat-grid-tile>
  <mat-grid-tile>...</mat-grid-tile>
</mat-grid-list>

.css file:

.button{
  display: table-cell;
  width: 700px;
  color: rgb(0, 0, 0);

}

Body:
You could use a little bit of CSS Flexbox for that.

.button {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    align-items: center;
    align-content: flex-end;
}

Then your <button> will align to the bottom center of its container. Have a play around with Flexbox on this Playground to get better at it.


问:
Sending messages from main process to renderer in Electron in 2022
In my App I have two windows: mainWindow and actionWindow. On my mainWindow I use the ipcRenderer.on listener to receive as message from the main process when the actionWindow is closed. The message however doesn't come through.

The mainWindow is used to control actions that take place on the actionWindow (e.g. navigate to an URL, remotely close the window, ...). I want to give the user the power to move and close the actionWindow manually as well, which is why its title bar is visible and usable.

I expose ipcRenderer.invoke for two-way communication and ipcRenderer.on to the mainWindow's renderer via contextBridge in a preload file.

This is what the code looks like (based on vite-electron-builder template)

main process

const mainWindow = new BrowserWindow({
  show: false, // Use 'ready-to-show' event to show window
  webPreferences: {
    nativeWindowOpen: true,
    webviewTag: false,
    preload: join(__dirname, "../../preload/dist/index.cjs"),
  },
});
const actionWindow = new BrowserWindow({
  // some props
})
actionWindow.on("close", () => {
  console.log("window closed")
  mainWindow.webContents.send("closed", { message: "window closed" });
});

```
<p><strong>preload</strong></p>
<pre class="lang-js prettyprint-override"><code>contextBridge.exposeInMainWorld("ipcRenderer", {
  invoke: ipcRenderer.invoke,
  on: ipcRenderer.on,
});
</code>```

renderer (mainWindow)

window.ipcRenderer.on("closed", () => {
  console.log("message received")
  // do something
  });
```

I know for a fact that

mainWindow has access to the exposed listeners, since invoke works and the actions it fires on the main process are executed on the actionWindow as supposed + the response also comes back to the renderer.

the close listener on the actionWindow works since I can see the log window closed in my console

message received doesn't appear in my dev tools console

To me this means that either

mainWindow.webContents.send doesn't work -> the message is never sent

window.ipcRenderer.on doesn't work -> the message never reaches its destination

So either my code is buggy or Electron has recently put some restrictions on one of these methods which I'm not aware of.

Any ideas?
If there is a smarter way to do this than IPC I'm also open to that.

答:
Ok after hours of searching, trying and suffering I (almost accidentaly) found a solution to my problem. It really seems to be the case that electron simply doesn't do anything anymore when you call the on method from your renderer.
Studying the docs about contextBridge again I saw that the way I exposed invoke and on to the renderer, was considered bad code. The safer way to do this is expose a function for EVERY ipc channel you want to use. In my case using TypeScript it looks like this:

preload

contextBridge.exposeInMainWorld("ipcRenderer", {
  invokeOpen: async (optionsString: string) => {
    await ipcRenderer.invoke("open", optionsString);
  },
  onClose: (callback: () => void) => {
    ipcRenderer.on("closed", callback);
  },
  removeOnClose: (callback: () => void) => {
    ipcRenderer.removeListener("closed", callback);
  },
});
```
<p><strong>renderer(mainWindow)</strong></p>
<pre class="lang-js prettyprint-override"><code>window.ipcRenderer.onClose(() => {
  // do sth
});
window.ipcRenderer.invokeOpen(JSON.stringify(someData)).then(() => {
  // do sth when response came back
});

</code>```

NOTE: To prevent memory leaks by creating listeners on every render of the mainWindow you also have to use a cleanup function which is provided with removeOnClose (see preload). How to use this function differs depending on the frontend framework. Using React it looks like this:

const doSth= () => {
    console.log("doing something")
    ...
  };

  useEffect(() => {
    window.ipcRenderer.onClose(doSth);
    return () => {
      window.ipcRenderer.removeOnClose(doSth);
    };
  }, []);
```

Not only is this a safer solution, it actually suddenly works :O
Using the cleanup function we also take care of leaks.

Body:
In my App I have two windows: mainWindow and actionWindow. On my mainWindow I use the ipcRenderer.on listener to receive as message from the main process when the actionWindow is closed. The message however doesn't come through.

The mainWindow is used to control actions that take place on the actionWindow (e.g. navigate to an URL, remotely close the window, ...). I want to give the user the power to move and close the actionWindow manually as well, which is why its title bar is visible and usable.

I expose ipcRenderer.invoke for two-way communication and ipcRenderer.on to the mainWindow's renderer via contextBridge in a preload file.

This is what the code looks like (based on vite-electron-builder template)

main process

const mainWindow = new BrowserWindow({
  show: false, // Use 'ready-to-show' event to show window
  webPreferences: {
    nativeWindowOpen: true,
    webviewTag: false,
    preload: join(__dirname, "../../preload/dist/index.cjs"),
  },
});
const actionWindow = new BrowserWindow({
  // some props
})
actionWindow.on("close", () => {
  console.log("window closed")
  mainWindow.webContents.send("closed", { message: "window closed" });
});

preload

contextBridge.exposeInMainWorld("ipcRenderer", {
  invoke: ipcRenderer.invoke,
  on: ipcRenderer.on,
});

renderer (mainWindow)

window.ipcRenderer.on("closed", () => {
  console.log("message received")
  // do something
  });

I know for a fact that

mainWindow has access to the exposed listeners, since invoke works and the actions it fires on the main process are executed on the actionWindow as supposed + the response also comes back to the renderer.

the close listener on the actionWindow works since I can see the log window closed in my console

message received doesn't appear in my dev tools console

To me this means that either

mainWindow.webContents.send doesn't work -> the message is never sent

window.ipcRenderer.on doesn't work -> the message never reaches its destination

So either my code is buggy or Electron has recently put some restrictions on one of these methods which I'm not aware of.

Any ideas?
If there is a smarter way to do this than IPC I'm also open to that.

Body:
Ok after hours of searching, trying and suffering I (almost accidentaly) found a solution to my problem. It really seems to be the case that electron simply doesn't do anything anymore when you call the on method from your renderer.
Studying the docs about contextBridge again I saw that the way I exposed invoke and on to the renderer, was considered bad code. The safer way to do this is expose a function for EVERY ipc channel you want to use. In my case using TypeScript it looks like this:

preload

contextBridge.exposeInMainWorld("ipcRenderer", {
  invokeOpen: async (optionsString: string) => {
    await ipcRenderer.invoke("open", optionsString);
  },
  onClose: (callback: () => void) => {
    ipcRenderer.on("closed", callback);
  },
  removeOnClose: (callback: () => void) => {
    ipcRenderer.removeListener("closed", callback);
  },
});

renderer(mainWindow)

window.ipcRenderer.onClose(() => {
  // do sth
});
window.ipcRenderer.invokeOpen(JSON.stringify(someData)).then(() => {
  // do sth when response came back
});

NOTE: To prevent memory leaks by creating listeners on every render of the mainWindow you also have to use a cleanup function which is provided with removeOnClose (see preload). How to use this function differs depending on the frontend framework. Using React it looks like this:

const doSth= () => {
    console.log("doing something")
    ...
  };

  useEffect(() => {
    window.ipcRenderer.onClose(doSth);
    return () => {
      window.ipcRenderer.removeOnClose(doSth);
    };
  }, []);

Not only is this a safer solution, it actually suddenly works :O
Using the cleanup function we also take care of leaks.


问:
Pytest test function that creates plots
I have several functions that create plots, which I use in Jupyter notebooks to visualise data.

I want to create basic tests for these, checking that they still run without erroring on various inputs if I make changes. However, if I call these functions using pytest, creating the plots causes the program to hang until I manually minimise the plot.

```<code>import pytest
import matplotlib.pyplot as plt

def plot_fn():
    plt.plot([1,2,3])
    plt.show()

def test_plot_fn():
   plot_fn()
</code>```

How can I test that functions like 'plot_fn' run without erroring using Pytest? I tried the following, but it doesn't work, I think because plt.show() causes the script to hang, and so not reach plt.close('all').

```<code>def test_plot_fn():
   plot_fn()
   plt.close('all')
</code>```

I'm happy to change the behaviour of my plotting function, for example to return the plt object?

答:
This one-line decorator will patch the plt.show() behavior and suppress the wait/hang part of showing the pyplot figure during a unit test, like this:

```<code>import pytest
import unittest
try:
    # python 3.4+ should use builtin unittest.mock not mock package
    from unittest.mock import patch
except ImportError:
    from mock import patch

@patch("methylcheck.qc_plot.plt.show")
def test_plot_fn(mock_this):
   plot_fn()
   plt.close('all')
</code>```

Note: you have to patch the show() function within the namespace path of the module/package you are testing, so in this case, the methylcheck package has a qc_plot file that imports pyplot in the usual way (import matplotlib.pyplot as plt) and THAT import gets patched.

Title: Pytest test function that creates plots

Body:
I have several functions that create plots, which I use in Jupyter notebooks to visualise data.

I want to create basic tests for these, checking that they still run without erroring on various inputs if I make changes. However, if I call these functions using pytest, creating the plots causes the program to hang until I manually minimise the plot.

import pytest
import matplotlib.pyplot as plt

def plot_fn():
    plt.plot([1,2,3])
    plt.show()

def test_plot_fn():
   plot_fn()

How can I test that functions like 'plot_fn' run without erroring using Pytest? I tried the following, but it doesn't work, I think because plt.show() causes the script to hang, and so not reach plt.close('all').

def test_plot_fn():
   plot_fn()
   plt.close('all')

I'm happy to change the behaviour of my plotting function, for example to return the plt object?

Body:
This one-line decorator will patch the plt.show() behavior and suppress the wait/hang part of showing the pyplot figure during a unit test, like this:

import pytest
import unittest
try:
    # python 3.4+ should use builtin unittest.mock not mock package
    from unittest.mock import patch
except ImportError:
    from mock import patch

@patch("methylcheck.qc_plot.plt.show")
def test_plot_fn(mock_this):
   plot_fn()
   plt.close('all')

Note: you have to patch the show() function within the namespace path of the module/package you are testing, so in this case, the methylcheck package has a qc_plot file that imports pyplot in the usual way (import matplotlib.pyplot as plt) and THAT import gets patched.


问:
How Applay Filter to Observable and get the length of list to count notification for each user
How Applay Filter to Observable and get the length of list to count notification for each user:
how can I get the count of notification type number for each user by
html code

      {{ onlineusermodel.userName }}

It seems logical that the

    05 min

      {{ getUserNotification(onlineusermodel) }}

```
<p><strong>component ts</strong></p>
<pre class="lang-js prettyprint-override"><code>getUserNotification(onlineUserModel: OnlineUserModel): Number {
 // var count = this.allNotifications$.subscribe((n) =>
 //   n.filter((u) => u.onlineUserModel == onlineUserModel).length
 // );
 var count = this.store
   .pipe(select(selectDirectNotifications))
   .subscribe(
     (n) => n.filter((u) => u.onlineUserModel == onlineUserModel).length
   );

 return count;
}
</code>```

Reducer

const directMessagesReducerInternal = createReducer(
 initialState,
 on(
   directMessagesAction.receivedNotificationForUserAction,
   (state, { payload }) => {
     const directNotification: DirectNotification = {
       onlineUserModel: payload.onlineUserModel,
       notificationModel: payload.notificationModel,
     };
     return {
       ...state,
       allNotifications: [...state.allNotifications, directNotification],
     };
   }
 ),
```
<p><strong>state</strong></p>
<pre class="lang-js prettyprint-override"><code>allNotifications: DirectNotification[];
</code>```

selector

export const selectDirectNotifications = createSelector(
 selectDirectMessageStore,
 (state: DirectMessagesState) => state.allNotifications
);
```
<p><strong>Action</strong></p>
<pre class="lang-js prettyprint-override"><code>export const receivedNotificationForUserAction = createAction(
 "[DN] RECEIVED_DIRECT_NOTIFICATION",
 props<{ payload: ReceivedNotificationForUserDto }>()
);
</code>```

答:
Not Recommended Way: You can achieve that by returning the Observable instead of subscribing to it from getUserNotification, then subscribe to it in the template using the async pipe, like the following:

getUserNotification(onlineUserModel: OnlineUserModel): Observable<number> {
  return this.store.pipe(
    select(selectDirectNotifications),
    map((n) => n.filter((u) => u.onlineUserModel == onlineUserModel).length)
  );
}
```
<pre class="lang-html prettyprint-override"><code><div class="users-list-body">
  <div>
    <h5>
      {{ onlineusermodel.userName }}
    </h5>
    <p>It seems logical that the</p>
  </div>
  <div class="last-chat-time">
    <small class="text-muted">05 min</small>
    <div class="new-message-count">
      {{ getUserNotification(onlineusermodel) | async }}
    </div>
  </div>
</div>
</code>```

However, it's not recommended to use the functions directly in the component template (HTML file), because Angular will call it on each change detection, which is not preferred from the performance point of view.

Instead, the recommended way is to assign the value of getUserNotification to an Observable once the data is ready and then subscribe to that Observable in the component template, like the following:

ngOnInit(): void {
  // ngOnInit is used here as an example.
  // You can assing the result of `getUserNotification` function each time the `onlineUserModel` has been changed:
  this.userNotificationCount$ = this.getUserNotification(onlineUserModel);
}

getUserNotification(onlineUserModel: OnlineUserModel): Observable<number> {
  return this.store.pipe(
    select(selectDirectNotifications),
    map((n) => n.filter((u) => u.onlineUserModel == onlineUserModel).length)
  );
}
```
<pre class="lang-html prettyprint-override"><code><div class="users-list-body">
  <div>
    <h5>
      {{ onlineusermodel.userName }}
    </h5>
    <p>It seems logical that the</p>
  </div>
  <div class="last-chat-time">
    <small class="text-muted">05 min</small>
    <div class="new-message-count">
      {{ userNotificationCount | async }}
    </div>
  </div>
</div>
</code>```

Body:
How Applay Filter to Observable and get the length of list to count notification for each user:
how can I get the count of notification type number for each user by
html code

      {{ onlineusermodel.userName }}

It seems logical that the

    05 min

      {{ getUserNotification(onlineusermodel) }}

component ts

getUserNotification(onlineUserModel: OnlineUserModel): Number {
 // var count = this.allNotifications$.subscribe((n) =>
 //   n.filter((u) => u.onlineUserModel == onlineUserModel).length
 // );
 var count = this.store
   .pipe(select(selectDirectNotifications))
   .subscribe(
     (n) => n.filter((u) => u.onlineUserModel == onlineUserModel).length
   );

 return count;
}

Reducer

const directMessagesReducerInternal = createReducer(
 initialState,
 on(
   directMessagesAction.receivedNotificationForUserAction,
   (state, { payload }) => {
     const directNotification: DirectNotification = {
       onlineUserModel: payload.onlineUserModel,
       notificationModel: payload.notificationModel,
     };
     return {
       ...state,
       allNotifications: [...state.allNotifications, directNotification],
     };
   }
 ),

state

allNotifications: DirectNotification[];

selector

export const selectDirectNotifications = createSelector(
 selectDirectMessageStore,
 (state: DirectMessagesState) => state.allNotifications
);

Action

export const receivedNotificationForUserAction = createAction(
 "[DN] RECEIVED_DIRECT_NOTIFICATION",
 props<{ payload: ReceivedNotificationForUserDto }>()
);

Body:
Not Recommended Way: You can achieve that by returning the Observable instead of subscribing to it from getUserNotification, then subscribe to it in the template using the async pipe, like the following:

getUserNotification(onlineUserModel: OnlineUserModel): Observable<number> {
  return this.store.pipe(
    select(selectDirectNotifications),
    map((n) => n.filter((u) => u.onlineUserModel == onlineUserModel).length)
  );
}

<div class="users-list-body">
  <div>
    <h5>
      {{ onlineusermodel.userName }}
    </h5>
    <p>It seems logical that the</p>
  </div>
  <div class="last-chat-time">
    <small class="text-muted">05 min</small>
    <div class="new-message-count">
      {{ getUserNotification(onlineusermodel) | async }}
    </div>
  </div>
</div>

However, it's not recommended to use the functions directly in the component template (HTML file), because Angular will call it on each change detection, which is not preferred from the performance point of view.

Instead, the recommended way is to assign the value of getUserNotification to an Observable once the data is ready and then subscribe to that Observable in the component template, like the following:

ngOnInit(): void {
  // ngOnInit is used here as an example.
  // You can assing the result of `getUserNotification` function each time the `onlineUserModel` has been changed:
  this.userNotificationCount$ = this.getUserNotification(onlineUserModel);
}

getUserNotification(onlineUserModel: OnlineUserModel): Observable<number> {
  return this.store.pipe(
    select(selectDirectNotifications),
    map((n) => n.filter((u) => u.onlineUserModel == onlineUserModel).length)
  );
}

<div class="users-list-body">
  <div>
    <h5>
      {{ onlineusermodel.userName }}
    </h5>
    <p>It seems logical that the</p>
  </div>
  <div class="last-chat-time">
    <small class="text-muted">05 min</small>
    <div class="new-message-count">
      {{ userNotificationCount | async }}
    </div>
  </div>
</div>


问:
Error: It is not supported to use minDist with activeOffsetX or activeOffsetY
is there any fix for this now?

https://github.com/jeremybarbet/react-native-modalize/issues/374

答:
I updated the react-native-modalize version to "^2.0.8" and the error stopped showing for me

Try running: yarn upgrade react-native-modalize


问:
What's causing JsonException: The JSON value could not be converted?
C# 10 / .NET 6 / System.Text.Json

I'm working with an API that returns as JSON response.  I'm trying to use System.Text.Json to deserialize the JSON response into a class.  I'm receiving a JsonException and could use help understanding what I'm doing wrong.

I call the API and store the JSON response:
string json = await Retreive.Fetch(target);

Here's the output of Console.WriteLine(json):

```<code>[{"id": 1148082,"name": "TestGroup","group_type":"console_group","provisioning_guid": null,"member_count": 1,"current_risk_score": 36.3,"status": "active"},{"id": 1148788,"name": "Group2","group_type": "smart_group","provisioning_guid": null,"member_count": 9,"current_risk_score": 39.7,"status": "active"},{"id": 1148792,"name": "Group3","group_type": "smart_group","provisioning_guid": null,"member_count": 9,"current_risk_score": 39.7,"status": "active"}]
</code>```

Here's a pretty-printed version if it helps:

```<code>[
  {
    "id": 1148082,
    "name": "TestGroup",
    "group_type": "console_group",
    "provisioning_guid": null,
    "member_count": 1,
    "current_risk_score": 36.3,
    "status": "active"
  },
  {
    "id": 1148788,
    "name": "Group2",
    "group_type": "smart_group",
    "provisioning_guid": null,
    "member_count": 9,
    "current_risk_score": 39.7,
    "status": "active"
  },
  {
    "id": 1148792,
    "name": "Group3",
    "group_type": "smart_group",
    "provisioning_guid": null,
    "member_count": 9,
    "current_risk_score": 39.7,
    "status": "active"
  }
]
</code>```

Using Visual Studio 2022's Paste JSON As Classes function, I get the following class structure:

```<code>public class Rootobject
{
    public Class1[] Property1 { get; set; }
}

public class Class1
{
    public int id { get; set; }
    public string name { get; set; }
    public string group_type { get; set; }
    public object provisioning_guid { get; set; }
    public int member_count { get; set; }
    public float current_risk_score { get; set; }
    public string status { get; set; }
}
</code>```

I'm trying: Rootobject? gag = JsonSerializer.Deserialize<Rootobject>(json);

A JsonException is thrown:

Unhandled exception. System.Text.Json.JsonException: The JSON value
could not be converted to KB4.Rootobject. Path: $ | LineNumber: 0 |
BytePositionInLine: 1.    at
System.Text.Json.ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(Type
propertyType)    at
System.Text.Json.Serialization.Converters.ObjectDefaultConverter1.OnTryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value)    at System.Text.Json.Serialization.JsonConverter1.TryRead(Utf8JsonReader&
reader, Type typeToConvert, JsonSerializerOptions options, ReadStack&
state, T& value)    at
System.Text.Json.Serialization.JsonConverter1.ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)    at System.Text.Json.JsonSerializer.ReadFromSpan[TValue](ReadOnlySpan1
utf8Json, JsonTypeInfo jsonTypeInfo, Nullable1 actualByteCount)    at System.Text.Json.JsonSerializer.ReadFromSpan[TValue](ReadOnlySpan1
json, JsonTypeInfo jsonTypeInfo)    at
System.Text.Json.JsonSerializer.Deserialize[TValue](String json,
JsonSerializerOptions options)    at KB4.Kb4.Main() in
C:<REDACTED>\Program.cs:line 188    at
KB4.Kb4.()

Some things I have tried:

Changing the name of the Rootobject class to GetAllGroups

Thinking the JSON may be somehow malformed in the response, I pasted it into a text file and load the JSON from there and then attempt deserialization again.

Reviewed Deserialize a JSON array in C# but that's using JavaScriptSerializer.

Neither of the above produces a different result.

What am I doing wrong?

答:
your Rootobject class would be working if your json starts with this

```<code>{ "property1": [{"id": 1148082,"name": .....] }
</code>```

and the array had a property name. but  your json don't  have property1, so you should start to deserialize json array directly

```<code>Class1[] result = System.Text.Json.JsonSerializer.Deserialize<Class1[]>(json);
</code>```

Body:
C# 10 / .NET 6 / System.Text.Json

I'm working with an API that returns as JSON response.  I'm trying to use System.Text.Json to deserialize the JSON response into a class.  I'm receiving a JsonException and could use help understanding what I'm doing wrong.

I call the API and store the JSON response:
string json = await Retreive.Fetch(target);

Here's the output of Console.WriteLine(json):

[{"id": 1148082,"name": "TestGroup","group_type":"console_group","provisioning_guid": null,"member_count": 1,"current_risk_score": 36.3,"status": "active"},{"id": 1148788,"name": "Group2","group_type": "smart_group","provisioning_guid": null,"member_count": 9,"current_risk_score": 39.7,"status": "active"},{"id": 1148792,"name": "Group3","group_type": "smart_group","provisioning_guid": null,"member_count": 9,"current_risk_score": 39.7,"status": "active"}]

Here's a pretty-printed version if it helps:

[
  {
    "id": 1148082,
    "name": "TestGroup",
    "group_type": "console_group",
    "provisioning_guid": null,
    "member_count": 1,
    "current_risk_score": 36.3,
    "status": "active"
  },
  {
    "id": 1148788,
    "name": "Group2",
    "group_type": "smart_group",
    "provisioning_guid": null,
    "member_count": 9,
    "current_risk_score": 39.7,
    "status": "active"
  },
  {
    "id": 1148792,
    "name": "Group3",
    "group_type": "smart_group",
    "provisioning_guid": null,
    "member_count": 9,
    "current_risk_score": 39.7,
    "status": "active"
  }
]

Using Visual Studio 2022's Paste JSON As Classes function, I get the following class structure:

public class Rootobject
{
    public Class1[] Property1 { get; set; }
}

public class Class1
{
    public int id { get; set; }
    public string name { get; set; }
    public string group_type { get; set; }
    public object provisioning_guid { get; set; }
    public int member_count { get; set; }
    public float current_risk_score { get; set; }
    public string status { get; set; }
}

I'm trying: Rootobject? gag = JsonSerializer.Deserialize<Rootobject>(json);

A JsonException is thrown:

Unhandled exception. System.Text.Json.JsonException: The JSON value
could not be converted to KB4.Rootobject. Path: $ | LineNumber: 0 |
BytePositionInLine: 1.    at
System.Text.Json.ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(Type
propertyType)    at
System.Text.Json.Serialization.Converters.ObjectDefaultConverter1.OnTryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value)    at System.Text.Json.Serialization.JsonConverter1.TryRead(Utf8JsonReader&
reader, Type typeToConvert, JsonSerializerOptions options, ReadStack&
state, T& value)    at
System.Text.Json.Serialization.JsonConverter1.ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)    at System.Text.Json.JsonSerializer.ReadFromSpan[TValue](ReadOnlySpan1
utf8Json, JsonTypeInfo jsonTypeInfo, Nullable1 actualByteCount)    at System.Text.Json.JsonSerializer.ReadFromSpan[TValue](ReadOnlySpan1
json, JsonTypeInfo jsonTypeInfo)    at
System.Text.Json.JsonSerializer.Deserialize[TValue](String json,
JsonSerializerOptions options)    at KB4.Kb4.Main() in
C:<REDACTED>\Program.cs:line 188    at
KB4.Kb4.()

Some things I have tried:

Changing the name of the Rootobject class to GetAllGroups

Thinking the JSON may be somehow malformed in the response, I pasted it into a text file and load the JSON from there and then attempt deserialization again.

Reviewed Deserialize a JSON array in C# but that's using JavaScriptSerializer.

Neither of the above produces a different result.

What am I doing wrong?

Body:
your Rootobject class would be working if your json starts with this

{ "property1": [{"id": 1148082,"name": .....] }

and the array had a property name. but  your json don't  have property1, so you should start to deserialize json array directly

Class1[] result = System.Text.Json.JsonSerializer.Deserialize<Class1[]>(json);


问:
How to specify multiple Callback URLs for Autodesk Forge App?

"You can register more than one callback URL."

is said in Callback URL tooltip.

But there is no example on how to enter multiple URLs.

What is the correct separator?

I've tried ";", "\n".

答:
Although the tooltip says it's possible, I got confirmation from AutoDesk's support that multiple URLs as in different hostnames is not supported currently. It is supposed to come in the next couple of months though.

If the hostname is only one, you can add * as a wildcard to support multiple routes and query strings.


问:
Run the same app on 2 web browsers / tabs on the same time ( Flutter )
I am trying to run 2 different web instances of the same code (either chrome chrome or chrome edge). It's like with phone emulators (It's possible ofc, I can open 2 different emulators at the same time) but is it possible with web? If yes any ideas on how?
I still can run 1 chrome instance with F5 tho

I first run

```<code>flutter devices
</code>```

it gives back 3 connected devices (Windows, Chrome, and Edge)
when I try to run

```<code>flutter run -d all
</code>```

it gives back no devices found.

I am using Flutter 2.10 and "flutter doctor" has 0 issues.

答:
You can't run -d all, flutter thinks you are trying to run on a device called "all", which is not the case.

If you want to run the same app on multiple devices, I recommend you run the app multiple times, to do this, you will have to open your terminal multiple times, (if you are using windows terminal you can open multiple tabs and run on them like that)

Also keep in mind that when you run the app on the web, you are running it on your computer on a specific port, so let's say you want to run the app on both chrome and internet explorer, you can just run the app on chrome and then copy the URL at the top (should say something like http://localhost:52955/) and go to edge and paste the same URL.

If you want to run the same app on someone else's device (for example on two computers at the same time) you can replace localhost with your computer's network IP and you will have the same effect.

For obvious reasons the above only works on web.

Body:
I am trying to run 2 different web instances of the same code (either chrome chrome or chrome edge). It's like with phone emulators (It's possible ofc, I can open 2 different emulators at the same time) but is it possible with web? If yes any ideas on how?
I still can run 1 chrome instance with F5 tho

I first run

flutter devices

it gives back 3 connected devices (Windows, Chrome, and Edge)
when I try to run

flutter run -d all

it gives back no devices found.

I am using Flutter 2.10 and "flutter doctor" has 0 issues.


问:
Print Value from Key and Value in one list in a new empty list based on matching elements
Logic Behind Problem:
When building a route you need two steps in order to perform a direction. For example if you go from Step1 to Step2 that is right. But Step1 to Step3 is left. The steps need to be in pairs in order to determine direction.

Issue:
I have a function that produces a 'Direction' based on a pair of elements in 'StepName'. If a routes 'StepName' pair is already defined with 'Direction' it should be able to produce the same 'Direction' in another route dictionary if it contains the same pair of elements in a sequence of pairs. Doesn't matter at what index the pair is located in the list

For example:

104-1 to 104-2 produces 'Left' in 'Direction'

104-2 to 105-A produces 'Right' in 'Direction'

105-A to 105-D produces 'Right' in 'Direction'

Code:

```<code>route1 = {
    'RouteID': 1,
    'StepID': [1, 2, 3, 4],
    'StepName': ['104-1', '104-2', '105-A', '105-D'],
    'Direction': ['Left', 'Right', 'Right']}

route2 = {
    'RouteID': 2,
    'StepID': [1, 2, 3, 4],
    'StepName': ['104-2', '105-A', '105-C', '105-B'],
    'Direction': []}

def routeMapper(longRoute, subRoute):
    for i, v in enumerate(subRoute['StepName']):
        found = False
        for j, b in enumerate(longRoute['StepName']):
            if v == b:
                found = True
                subRoute['Direction'].append(longRoute['Direction'][j])
        if not found:
            subRoute['Direction'].append(False)

routeMapper(route1, route2)
print(route2)
</code>```

Output:

```<code>{'RouteID': 2, 'StepID': [1, 2, 3, 4], 'StepName': ['104-2', '105-A', '105-C', '105-B'], 'Direction': ['Right', 'Right', False, False]}
</code>```

As you can see it is comparing what each index element direction it is assigned to. I want it to be seen in pairs instead of single.

Desired Output: (for 'Direction')

```<code>{'RouteID': 2, 'StepID': [1, 2, 3, 4], 'StepName': ['104-2', '105-A', '105-C', '105-B'], 'Direction': ['Right', False, False, False]}
</code>```

The reason this output makes sense is because in route1 104-2 to 105-A produces 'Right' even though it is 1 and 2 in the index as a pair compared to it being at the 0 and 1 index in route2. As long as the pair is found in the list it should be able to produce the direction.

答:
I think the best solution would be to:

create a dictionary mapping location pairs (104-1 to 104-2) to their respective directions (Left): function route_directions

then, using this dictionary we could compute the second route directions quite easily: function derive_directions

```<code>def route_directions(route):
    directions = route['Direction']
    steps = route_steps(route)
    return {step:direction for step, direction in zip(steps, directions)}

# Utility function (we could also use itertools.pairwise instead of this)
def route_steps(route):
    return zip(route['StepName'], route['StepName'][1:])

def derive_directions(route, existing_directions):
    return [existing_directions.get(step, False) for step in route_steps(route)]
</code>```

Using all these functions, we can simply derive route2 directions from  route1:

```<code>route_directions = route_dict(route1)
route2['Direction'] = derive_directions(route2, route_directions)
</code>```

Few things used here

zip() that I also tried to describe a bit here. Basically it match two (or more) list element-wise, for example, zip([1, 2, 3], [10, 20, 30]), will produce the following tuples (1, 10), (2, 20), (3, 30).

This code also uses the fact that tuples can be used as dictionary keys, here is what the route_directions looks like:

```<code>{('104-1', '104-2'): 'Left',
 ('104-2', '105-A'): 'Right',
 ('105-A', '105-D'): 'Right'}
</code>```

Body:
Logic Behind Problem:
When building a route you need two steps in order to perform a direction. For example if you go from Step1 to Step2 that is right. But Step1 to Step3 is left. The steps need to be in pairs in order to determine direction.

Issue:
I have a function that produces a 'Direction' based on a pair of elements in 'StepName'. If a routes 'StepName' pair is already defined with 'Direction' it should be able to produce the same 'Direction' in another route dictionary if it contains the same pair of elements in a sequence of pairs. Doesn't matter at what index the pair is located in the list

For example:

104-1 to 104-2 produces 'Left' in 'Direction'

104-2 to 105-A produces 'Right' in 'Direction'

105-A to 105-D produces 'Right' in 'Direction'

Code:

route1 = {
    'RouteID': 1,
    'StepID': [1, 2, 3, 4],
    'StepName': ['104-1', '104-2', '105-A', '105-D'],
    'Direction': ['Left', 'Right', 'Right']}

route2 = {
    'RouteID': 2,
    'StepID': [1, 2, 3, 4],
    'StepName': ['104-2', '105-A', '105-C', '105-B'],
    'Direction': []}

def routeMapper(longRoute, subRoute):
    for i, v in enumerate(subRoute['StepName']):
        found = False
        for j, b in enumerate(longRoute['StepName']):
            if v == b:
                found = True
                subRoute['Direction'].append(longRoute['Direction'][j])
        if not found:
            subRoute['Direction'].append(False)

routeMapper(route1, route2)
print(route2)

Output:

{'RouteID': 2, 'StepID': [1, 2, 3, 4], 'StepName': ['104-2', '105-A', '105-C', '105-B'], 'Direction': ['Right', 'Right', False, False]}

As you can see it is comparing what each index element direction it is assigned to. I want it to be seen in pairs instead of single.

Desired Output: (for 'Direction')

{'RouteID': 2, 'StepID': [1, 2, 3, 4], 'StepName': ['104-2', '105-A', '105-C', '105-B'], 'Direction': ['Right', False, False, False]}

The reason this output makes sense is because in route1 104-2 to 105-A produces 'Right' even though it is 1 and 2 in the index as a pair compared to it being at the 0 and 1 index in route2. As long as the pair is found in the list it should be able to produce the direction.

Body:
I think the best solution would be to:

create a dictionary mapping location pairs (104-1 to 104-2) to their respective directions (Left): function route_directions

then, using this dictionary we could compute the second route directions quite easily: function derive_directions

def route_directions(route):
    directions = route['Direction']
    steps = route_steps(route)
    return {step:direction for step, direction in zip(steps, directions)}

# Utility function (we could also use itertools.pairwise instead of this)
def route_steps(route):
    return zip(route['StepName'], route['StepName'][1:])

def derive_directions(route, existing_directions):
    return [existing_directions.get(step, False) for step in route_steps(route)]

Using all these functions, we can simply derive route2 directions from  route1:

route_directions = route_dict(route1)
route2['Direction'] = derive_directions(route2, route_directions)

Few things used here

zip() that I also tried to describe a bit here. Basically it match two (or more) list element-wise, for example, zip([1, 2, 3], [10, 20, 30]), will produce the following tuples (1, 10), (2, 20), (3, 30).

This code also uses the fact that tuples can be used as dictionary keys, here is what the route_directions looks like:

{('104-1', '104-2'): 'Left',
 ('104-2', '105-A'): 'Right',
 ('105-A', '105-D'): 'Right'}


问:
Unexpected error in `pandas.cut` internals related to indexing
I've isolated some behavior within pd.cut (https://github.com/pandas-dev/pandas/blob/1.3.x/pandas/core/reshape/tile.py#L424) that I don't understand the failure mode of. It seems to be indexing-related: with the default RangeIndex on the series all runs as expected; when the index is "0'd out", the code will crash out with a KeyError: 1 (trace at the bottom of the question).

I'd like to understand why exactly the ids[x == bins[0]] = 1 line crashes out with a KeyError: 1 in this case.

A short, self-contained reproduction of the failure:

import numpy as np
import pandas as pd

ids = np.array([3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 4, 4, 4, 4, 5, 5])
x = pd.Series([1.0839999914,1.1859999895,1.2050000429,1.2250000238,1.3220000267,1.3999999762,1.5529999733,1.7710000277,1.1859999895,1.2259999514,1.2669999599,1.3400000334,1.4579999447,1.6599999666,1.9950000048,1.1859999895,1.2269999981,1.3680000305,1.5249999762,1.7079999447,2.0309998989,2.5539999008])

bins = np.array([-np.inf, 0.25, 1.0, 2.0, 3.0, np.inf])

# long story short, dask.dataframe.read_parquet will effectively do this to the indices (down to the index type & dtypes)
x.index = [0] * len(x)

# this crashes unless we remove the problem statement above
ids[x == bins[0]] = 1
```
<p>Trace:</p>
<pre class="lang-py prettyprint-override"><code>problem.py:9: FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`. In the future this will be interpreted as an array index, `arr[np.array(seq)]`, which will result either in an error or a different result.
  ids[x == bins[0]] = 1
Traceback (most recent call last):
  File "/Users/user/miniconda3/lib/python3.8/site-packages/pandas/core/indexes/base.py", line 3621, in get_loc
    return self._engine.get_loc(casted_key)
  File "pandas/_libs/index.pyx", line 136, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/index.pyx", line 160, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/index.pyx", line 195, in pandas._libs.index.IndexEngine._get_loc_duplicates
KeyError: 1

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "problem.py", line 9, in <module>
    ids[x == bins[0]] = 1
  File "/Users/user/miniconda3/lib/python3.8/site-packages/pandas/core/series.py", line 959, in __getitem__
    return self._get_value(key)
  File "/Users/user/miniconda3/lib/python3.8/site-packages/pandas/core/series.py", line 1070, in _get_value
    loc = self.index.get_loc(label)
  File "/Users/user/miniconda3/lib/python3.8/site-packages/pandas/core/indexes/base.py", line 3623, in get_loc
    raise KeyError(key) from err
KeyError: 1
</code>```

答:
Seems like this method is going to be interpreted as an array index,and you should be using tuple:

Using a non-tuple sequence for multidimensional indexing is deprecated; use arr[tuple(seq)] instead of arr[seq]. In the future this will be interpreted as an array index, arr[np.array(seq)], which will result either in an error or a different result.
ids[x == bins[0]] = 1

```<code>ids[tuple(x == bins[0])] = 1
</code>```

Body:
I've isolated some behavior within pd.cut (https://github.com/pandas-dev/pandas/blob/1.3.x/pandas/core/reshape/tile.py#L424) that I don't understand the failure mode of. It seems to be indexing-related: with the default RangeIndex on the series all runs as expected; when the index is "0'd out", the code will crash out with a KeyError: 1 (trace at the bottom of the question).

I'd like to understand why exactly the ids[x == bins[0]] = 1 line crashes out with a KeyError: 1 in this case.

A short, self-contained reproduction of the failure:

import numpy as np
import pandas as pd

ids = np.array([3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 4, 4, 4, 4, 5, 5])
x = pd.Series([1.0839999914,1.1859999895,1.2050000429,1.2250000238,1.3220000267,1.3999999762,1.5529999733,1.7710000277,1.1859999895,1.2259999514,1.2669999599,1.3400000334,1.4579999447,1.6599999666,1.9950000048,1.1859999895,1.2269999981,1.3680000305,1.5249999762,1.7079999447,2.0309998989,2.5539999008])

bins = np.array([-np.inf, 0.25, 1.0, 2.0, 3.0, np.inf])

# long story short, dask.dataframe.read_parquet will effectively do this to the indices (down to the index type & dtypes)
x.index = [0] * len(x)

# this crashes unless we remove the problem statement above
ids[x == bins[0]] = 1

Trace:

problem.py:9: FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`. In the future this will be interpreted as an array index, `arr[np.array(seq)]`, which will result either in an error or a different result.
  ids[x == bins[0]] = 1
Traceback (most recent call last):
  File "/Users/user/miniconda3/lib/python3.8/site-packages/pandas/core/indexes/base.py", line 3621, in get_loc
    return self._engine.get_loc(casted_key)
  File "pandas/_libs/index.pyx", line 136, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/index.pyx", line 160, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/index.pyx", line 195, in pandas._libs.index.IndexEngine._get_loc_duplicates
KeyError: 1

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "problem.py", line 9, in <module>
    ids[x == bins[0]] = 1
  File "/Users/user/miniconda3/lib/python3.8/site-packages/pandas/core/series.py", line 959, in __getitem__
    return self._get_value(key)
  File "/Users/user/miniconda3/lib/python3.8/site-packages/pandas/core/series.py", line 1070, in _get_value
    loc = self.index.get_loc(label)
  File "/Users/user/miniconda3/lib/python3.8/site-packages/pandas/core/indexes/base.py", line 3623, in get_loc
    raise KeyError(key) from err
KeyError: 1

Body:
Seems like this method is going to be interpreted as an array index,and you should be using tuple:

Using a non-tuple sequence for multidimensional indexing is deprecated; use arr[tuple(seq)] instead of arr[seq]. In the future this will be interpreted as an array index, arr[np.array(seq)], which will result either in an error or a different result.
ids[x == bins[0]] = 1

ids[tuple(x == bins[0])] = 1


问:
How to build and install gcc with built-in rpath?
I'm trying to build and install my own gcc 4.7.2 in /usr/local to use in place of the gcc 4.4.6 in /usr. (This is on CentOS 6.3.)

gcc makes executables and dynamic libraries that dynamically link to its own dynamic libraries, e.g. libstdc++.so. How do I build and install gcc so that the generated binaries automatically get a linker -rpath option (-rpath /usr/local/lib64) that causes dynamic libraries in /usr/local/lib64 to be linked instead of those in /usr/lib64 or /lib64?

If it works properly, after I build an executable with the gcc without specifying "-Wl,-rpath=/usr/local/lib64", when I ldd the executable, it should show /usr/local/lib64/libstdc++.so.6 instead of /usr/lib64/libstdc++.so.6. Similarly for the libgcc_s.so.1.

I have tried different approaches, including specifying LDFLAGS_FOR_TARGET=-Wl,-rpath=/usr/local/lib64,-rpath=/usr/local/lib on the 'configure' command-line, but nothing worked.

答:
I was installing httpd-2.4.51 and needed to specify -rpath to compile the program. I use the linker flag -Wl,-rpath -Wl,LIBDIR.

Use commands:

```<code>sudo mv httpd.c /usr/lib #create a .c file and move it to the default directory for the library file
sudo gcc -o httpd httpd.c -L$--prefix=/usr/lib -lhttpd -Wl,-rpath=$--prefix=/usr/lib
</code>```

Your can check where you have gcc installed:

```<code>whereis gcc
</code>```

gcc: /usr/bin/gcc /usr/lib/gcc /usr/share/man/man1/gcc.1.gz

Body:
I was installing httpd-2.4.51 and needed to specify -rpath to compile the program. I use the linker flag -Wl,-rpath -Wl,LIBDIR.

Use commands:

sudo mv httpd.c /usr/lib #create a .c file and move it to the default directory for the library file
sudo gcc -o httpd httpd.c -L$--prefix=/usr/lib -lhttpd -Wl,-rpath=$--prefix=/usr/lib

Your can check where you have gcc installed:

whereis gcc

gcc: /usr/bin/gcc /usr/lib/gcc /usr/share/man/man1/gcc.1.gz


问:
Add days to event.getTime() in angular
I am trying to add days selected from dropdown. But the dates coming up after adding is way back in 1700s. What am I doing wrong here?

```<code>  selectedDays: number = 0;
  //event handler for the select element's change event
  selectDaystoadd (event: any) {
    //update the ui
    this.selectedDays = event.target.value;
    console.log(this.selectedDays);
  }

  formatDateField(event: Date, formControl: string) {
    this.form
      .get(formControl)
      .patchValue(
        this.datePipe.transform(event.getTime() + this.selectedDays, "yyyy-MM-dd'T'HH:mm:ss")
      );
      console.log(event);
  }

</code>```

HTML code..

```<code>     <label>Date</label>
        <input id="input--payout-date"
          class="form-control"
          formControlName="payoutDate"
          [owlDateTime]="payoutDate"
          (dateTimeInput)="formatDateField($event.value, 'payoutDate')"
          [owlDateTimeTrigger]="payoutDate"
        />
        <owl-date-time [pickerType]="'calendar'" #payoutDate></owl-date-time>
        <label>Add days to date</label>
        <select (change)="selectDaystoadd($event)">
          <option value="0">0</option>
          <option value="20">+20</option>
          <option value="50">+30</option>
          <option value="90">+90</option>
        </select>

</code>```

答:
```<code>this.datePipe.transform(event.setDate(event.getDate() + this.selectedDays), "yyyy-MM-dd'T'HH:mm:ss")
</code>```

Title: Add days to event.getTime() in angular

Body:
I am trying to add days selected from dropdown. But the dates coming up after adding is way back in 1700s. What am I doing wrong here?

  selectedDays: number = 0;
  //event handler for the select element's change event
  selectDaystoadd (event: any) {
    //update the ui
    this.selectedDays = event.target.value;
    console.log(this.selectedDays);
  }

  formatDateField(event: Date, formControl: string) {
    this.form
      .get(formControl)
      .patchValue(
        this.datePipe.transform(event.getTime() + this.selectedDays, "yyyy-MM-dd'T'HH:mm:ss")
      );
      console.log(event);
  }

HTML code..

     Date
        <input id="input--payout-date"
          class="form-control"
          formControlName="payoutDate"
          [owlDateTime]="payoutDate"
          (dateTimeInput)="formatDateField($event.value, 'payoutDate')"
          [owlDateTimeTrigger]="payoutDate"
        />
        <owl-date-time [pickerType]="'calendar'" #payoutDate></owl-date-time>
        Add days to date
        <select (change)="selectDaystoadd($event)">
          <option value="0">0</option>
          <option value="20">+20</option>
          <option value="50">+30</option>
          <option value="90">+90</option>
        </select>