问:
How do the locking object's work with synchronization in java
I am studying over my university's week 02 content on collaboration and interference for advanced programming.

Firstly, this class is given as an example of an unsynchronized implementation:

```<code>class UnsynchronizedCounter implements Counter {
  private int c = 0;
  public void increment() {
    this.c++;
  }
  public void decrement() {
    this.c--;
  }
  public int value() {
    return this.c;
  }
}
</code>```

Following this it is explained how this can be made thread safe through using synchronization either as a code block or as a method modifier. it is also explained how when synchronizing methods, they need to be given a locking object.

Here is the example solution for a code block approach

```<code>class SynchronizedCounter implements Counter {
  private int c = 0;
  public void increment() {
    synchronized(this){
      this.c++;
    }
  }
  public void decrement() {
    synchronized(this){
      this.c--;
    }
  }
  public int value() {
    synchronized(this){
      return this.c;
    }
  }
}
</code>```

and as you can see the this keyword is used to provide the Counter object as the locking method

Following this is the example using the method modifier approach

```<code>class SynchronizedCounterMod implements Counter {
  private int c = 0;
  public synchronized void increment() {
    this.c++;
  }
  public synchronized void decrement() {
    this.c--;
  }
  public synchronized int value() {
    return this.c;
  }
}
</code>```

However, what I do not understand is in this approach a locking object is not provided at any point, how does this approach know what to use as the locking object?, additionally, assuming this approach assumes the enclosing object is the locking object, does that mean using this approach you cannot provide an alternative locking object?

I tried looking about this online and could find anything I felt explained it properly, so it would be a great help if you could try and help me understand this.

答: Yes, it implicitly uses the enclosing object (this) for synchronization. If you do need to use another object, you'll have to explicitly use synchronized(...) {...} block and pass that object.

Body:
I am studying over my university's week 02 content on collaboration and interference for advanced programming.

Firstly, this class is given as an example of an unsynchronized implementation:

class UnsynchronizedCounter implements Counter {
  private int c = 0;
  public void increment() {
    this.c++;
  }
  public void decrement() {
    this.c--;
  }
  public int value() {
    return this.c;
  }
}

Following this it is explained how this can be made thread safe through using synchronization either as a code block or as a method modifier. it is also explained how when synchronizing methods, they need to be given a locking object.

Here is the example solution for a code block approach

class SynchronizedCounter implements Counter {
  private int c = 0;
  public void increment() {
    synchronized(this){
      this.c++;
    }
  }
  public void decrement() {
    synchronized(this){
      this.c--;
    }
  }
  public int value() {
    synchronized(this){
      return this.c;
    }
  }
}

and as you can see the this keyword is used to provide the Counter object as the locking method

Following this is the example using the method modifier approach

class SynchronizedCounterMod implements Counter {
  private int c = 0;
  public synchronized void increment() {
    this.c++;
  }
  public synchronized void decrement() {
    this.c--;
  }
  public synchronized int value() {
    return this.c;
  }
}

However, what I do not understand is in this approach a locking object is not provided at any point, how does this approach know what to use as the locking object?, additionally, assuming this approach assumes the enclosing object is the locking object, does that mean using this approach you cannot provide an alternative locking object?

I tried looking about this online and could find anything I felt explained it properly, so it would be a great help if you could try and help me understand this.


来源: stackexchange

问:
How to alias a prototype function using es6 syntax
The requirement is to have an alias to a prototype function.

Currently I'm doing this, which is adding an additional function and execution context, when called, as opposed to just a reference:

```<code>class X {
  x() {
    // stuff
  }

  y() {
    this.x();
  }
}
</code>```

Because I don't know how to do this, in es5:

```<code>function X() {

}
X.prototype.x = function () {
  // stuff
}
X.prototype.y = X.prototype.x;
</code>```

Is it possible?

答:
How about you add y in the constructor?

class X {
  constructor() {
    this.y = this.x;
  }
  x() {
    // stuff
  }
}
```
<p>Of course this will add it as an instance property; this should be no issue though because all instances simply hold a reference to the prototype method in their <code>y</code>.</p>
<p>If that does not meet your requirements I'm kindly asking for a clarification.</p>
<p>Here's how you add it to the prototype:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>class X {
  x() {
    console.dir(this.__proto__);
  }
}

X.prototype.y = X.prototype.x;

(new X).x();
(new X).y();</code>```

ContentLicense: CC BY-SA 4.0

Body:
The requirement is to have an alias to a prototype function.

Currently I'm doing this, which is adding an additional function and execution context, when called, as opposed to just a reference:

class X {
  x() {
    // stuff
  }

  y() {
    this.x();
  }
}

Because I don't know how to do this, in es5:

function X() {

}
X.prototype.x = function () {
  // stuff
}
X.prototype.y = X.prototype.x;

Is it possible?

Body:
How about you add y in the constructor?

class X {
  constructor() {
    this.y = this.x;
  }
  x() {
    // stuff
  }
}

Of course this will add it as an instance property; this should be no issue though because all instances simply hold a reference to the prototype method in their y.

If that does not meet your requirements I'm kindly asking for a clarification.

Here's how you add it to the prototype:

class X {
  x() {
    console.dir(this.__proto__);
  }
}

X.prototype.y = X.prototype.x;

(new X).x();
(new X).y();


问:
How to navegate to viewAreas betewen diferent Classes and Experiements?
I´m trying to implement a menu Bar.

The idea is an initial viewArea in Simulation Experiment to setup parameters of the model. Then I would like to be able to navegate to Main or to "UI" Class to show some KPIs, and then go back to a viewArea in Simulation Experiment.

I was able to implement a menubar to viewAreas inside Main only.
How to navegate to viewAreas on Simulation Experiment or other classes ?

答:
As per Felipe's comment you can use ((Main)getEngine().getRoot()).viewArea.navigateTo();

But it will only work if the engine has already started running, else Main has not yet been instantiated.


问:
Server-side change to disable Firefox Race Cache with Network (RCWN)?
I know that it's possible to disable RCWN in my copy of Firefox, but I'm trying to find if there is a way for the server-side to tell all Firefoxes in the world not to use RCWN against particular resources?

Our app uses cloud file storage and we get charged for network traffic. We've configured the server to send appropriate caching headers so that browsers will only download the images (potentially very large) one time and then load them from cache so that we don't get charged over and over again when someone reloads a particular page on our website.

This works very well in Chrome, but Firefox has a feature called Race Cache With Network. RCWN allows Firefox to try loading from cache but simultaneously load from the network and then which ever one finishes first is the winner. But that means that every user with FF is going to be constantly re-downloading these large images even though they are cached which means we're having to pay for the network traffic even though they've got a perfectly good cache of the image.

I would assume the cache could load a 22MB png file faster than the network does, but the FF inspector says it is still taking like 8 seconds to load during the race and the network download won. And even if the network download loses to the cache, it was still downloading most or all of the image anyway.

Are there any http response headers we can add to tell FF not to use RCWN with certain resources?

Here is an example of the headers we send back now:

```<code>Content-Type: image/png
Expires: Sat, 06 Jul 2030 21:06:51 GMT
Last-Modified: Tue, 07 Jul 2020 05:21:42 GMT
Pragma: cache
Cache-Control: max-age=315360000, private
Content-Disposition: inline; filename="bob-woodward-book-trade-deficits-lodestar.png"
</code>```

答:
Ideally, a Firefox dev will swing by and provide us all with a truly definitive answer to this.
Meanwhile though, having dug around a bit and waded through some of the source code, I'm pretty certain that the answer is "no". (Not very surprising, I guess, but perhaps a wee bit disappointing.)

Aside from the source code, useful nuggets can be found all over the place, including these slides from 2017 which explain the motivation for creating RCWN: https://slides.com/valentingosu/race-cache-with-network-2017

(PS: my own motivation for digging into this is connected to my own question from a few days ago. My tentative conclusion from everything I've seen so far is that the caching system within Firefox has some fairly fundamental performance issues. It may of course be awfully hard to do a better job than the current code does!)

Body:
I know that it's possible to disable RCWN in my copy of Firefox, but I'm trying to find if there is a way for the server-side to tell all Firefoxes in the world not to use RCWN against particular resources?

Our app uses cloud file storage and we get charged for network traffic. We've configured the server to send appropriate caching headers so that browsers will only download the images (potentially very large) one time and then load them from cache so that we don't get charged over and over again when someone reloads a particular page on our website.

This works very well in Chrome, but Firefox has a feature called Race Cache With Network. RCWN allows Firefox to try loading from cache but simultaneously load from the network and then which ever one finishes first is the winner. But that means that every user with FF is going to be constantly re-downloading these large images even though they are cached which means we're having to pay for the network traffic even though they've got a perfectly good cache of the image.

I would assume the cache could load a 22MB png file faster than the network does, but the FF inspector says it is still taking like 8 seconds to load during the race and the network download won. And even if the network download loses to the cache, it was still downloading most or all of the image anyway.

Are there any http response headers we can add to tell FF not to use RCWN with certain resources?

Here is an example of the headers we send back now:

Content-Type: image/png
Expires: Sat, 06 Jul 2030 21:06:51 GMT
Last-Modified: Tue, 07 Jul 2020 05:21:42 GMT
Pragma: cache
Cache-Control: max-age=315360000, private
Content-Disposition: inline; filename="bob-woodward-book-trade-deficits-lodestar.png"


问:
Any assumption in the RISC-V ISA preventing the stack from growing up rather than down?
I was wondering whether anything in the ISA would make a stack growing up (a push increases sp, a pop decreases it) less performant or otherwise inadvisable? I am aware that this is not how present day tooling works, including Linux and GCC ports, but is there any fundamental reason beyond "it would be an insane amount of work"?</p>

答:
I can think of two reasons why it would be problematic beyond only being a lot of work for software to change.

The first is about RISC V: the compressed instructions are designed to store into the stack at positive offsets having a range of sp+0 to sp+252 (in multiples of 4), rather expecting a descending stack: accessing sp+N where N>=0, which is allocated stack memory, either simple items pushed on the stack one by one, or the whole stack frame of a function.  With an ascending stack, sp+N where N>=4 is free stack memory that we generally wouldn't have any desire to access, so you'd loose the compressed instruction loads & stores for memory-based local variables & parameters.

The second is a practical matter rather than a RISC V issue: when using an ascending stack, the stack pointer refers to the end of the item that is on the top of the stack.  We normally refer to memory objects by their first & lowest address.
  When varying size items are place onto an ascending stack, then the address of the item on the top of the stack, in terms of an offset from sp changes depending on the item's size — this doesn't happen with a descending stack.

Other than the above, such as regarding performance, I don't think the hardware would care.


答:
A synchronized function is defined to synchronize on this, so your second example is exactly equivalent to the first.

Note that most modern style guides recommend against synchronizing on this, as other code might accidentally (or intentionally) be using the same object to synchronize, causing locks that block against unintended blocks of code. Instead, it's generally recommended to allocate private objects exclusively used for locking.

```<code>class SynchronizedCounter implements Counter {
  private int c = 0;
  private Object lock;
  public SynchronizedCounter() {
    this.lock = new Object();
  }
  public void increment() {
    synchronized(lock){
      this.c++;
    }
  }
  public void decrement() {
    synchronized(lock){
      this.c--;
    }
  }
  public int value() {
    synchronized(lock){
      return this.c;
    }
  }
}
</code>```

Now no other object can possibly "accidentally" synchronize against this.lock, since it's private and only accessible to this one instance.

Title: How do the locking object's work with synchronization in java

Body:
A synchronized function is defined to synchronize on this, so your second example is exactly equivalent to the first.

Note that most modern style guides recommend against synchronizing on this, as other code might accidentally (or intentionally) be using the same object to synchronize, causing locks that block against unintended blocks of code. Instead, it's generally recommended to allocate private objects exclusively used for locking.

class SynchronizedCounter implements Counter {
  private int c = 0;
  private Object lock;
  public SynchronizedCounter() {
    this.lock = new Object();
  }
  public void increment() {
    synchronized(lock){
      this.c++;
    }
  }
  public void decrement() {
    synchronized(lock){
      this.c--;
    }
  }
  public int value() {
    synchronized(lock){
      return this.c;
    }
  }
}

Now no other object can possibly "accidentally" synchronize against this.lock, since it's private and only accessible to this one instance.


问:
Pass event listener from popup.js to background.js script
I’m working on a simple time tracker extension. When I started out I had all the js code in one popup.js file, but I found that when the extension pop-up was closed the timer stopped running. I came across the use of a background script to use in junction with the already created popup.js script of mine. What I’ve now done is that I have the evenListener logic from the HTML page in the popup.js, I then use the browser.runtime.sendMessage to send the data to the background.js script to handle the timer. Is this a correct setup or should I do it differently?

I can’t figure out how to pass the click event from the post to the background script, and then use the eventListener in the background script to start the timer.

Here is my public GitHub repo for the timetracker extension. https://github.com/krullmizter/timetracker

答:
In your notifyBackgroundPage() function in the popup.js file, you don’t need to send the HTML button to the background script. Instead, you’d probably want something like this:

```<code>const sending = browser.runtime.sendMessage({
    action: startBtn.id
});
sending.then(handleRes, handleErr);
</code>```

That will send the background script an object that has a message object with “start” as the action. Then, in your background script, you can use a switch statement (or if/else statements if you really want to) to call the appropriate function.

The click event listeners need to all be in the popup.js file and each onclick should send a message to the background to perform the desired action.

So your background script would be become something like this:

```<code>function popupMsgReceived(msg, sender, sendRes) {
    console.log("Msg received", msg);

    switch (msg.action) {
        case "start":
            handleStart();
            break;
        case "stop":
            handleStop();
            break;
        case "reset":
            handleReset();
            break;
    }

    sendRes({response: "Response from background script"});
}

browser.runtime.onMessage.addListener(popupMsgReceived);

// Set the initial clock values
let hr  = 0;
let min = 0;
let sec = 0;

let interval;

/*
*  Three even listeners for the three buttons
*  The startBtn event will set an interval to run each 1000ms (1sec) and run the startTimer function
*  timerStartedAt function will also run och the btn event
*/
function handleStart() {
    timerStartedAt();
    clearInterval(interval);
    interval = setInterval(startTimer, 1000);
}

function handleStop() {
    clearInterval(interval);
}

function handleReset() {
    clearInterval(interval);
    hr  = 0;
    min = 0;
    sec = 0;
    timer.innerHTML = '00:00:00';
    displayDate.innerHTML = ''
}
</code>```

As far as for setting the timer, I’d recommend using the Alarms API instead of using Javascript timeouts or intervals. Alarms are a lot more stable for browser add-ons. Another be positive to that is that you could create and edit alarms from the popup.js without the need to send messages and the alarm will stay alive even after the popup page is closed.

Another thing to think of future-wise is that manifest version 3 will eventually be the standard in Firefox. That version of the API does not have persistent background pages. Therefore, Javascript timeouts and intervals won’t work in background scripts at that point and you will need to change your code later.

Body:
In your notifyBackgroundPage() function in the popup.js file, you don’t need to send the HTML button to the background script. Instead, you’d probably want something like this:

const sending = browser.runtime.sendMessage({
    action: startBtn.id
});
sending.then(handleRes, handleErr);

That will send the background script an object that has a message object with “start” as the action. Then, in your background script, you can use a switch statement (or if/else statements if you really want to) to call the appropriate function.

The click event listeners need to all be in the popup.js file and each onclick should send a message to the background to perform the desired action.

So your background script would be become something like this:

function popupMsgReceived(msg, sender, sendRes) {
    console.log("Msg received", msg);

    switch (msg.action) {
        case "start":
            handleStart();
            break;
        case "stop":
            handleStop();
            break;
        case "reset":
            handleReset();
            break;
    }

    sendRes({response: "Response from background script"});
}

browser.runtime.onMessage.addListener(popupMsgReceived);

// Set the initial clock values
let hr  = 0;
let min = 0;
let sec = 0;

let interval;

/*
*  Three even listeners for the three buttons
*  The startBtn event will set an interval to run each 1000ms (1sec) and run the startTimer function
*  timerStartedAt function will also run och the btn event
*/
function handleStart() {
    timerStartedAt();
    clearInterval(interval);
    interval = setInterval(startTimer, 1000);
}

function handleStop() {
    clearInterval(interval);
}

function handleReset() {
    clearInterval(interval);
    hr  = 0;
    min = 0;
    sec = 0;
    timer.innerHTML = '00:00:00';
    displayDate.innerHTML = ''
}

As far as for setting the timer, I’d recommend using the Alarms API instead of using Javascript timeouts or intervals. Alarms are a lot more stable for browser add-ons. Another be positive to that is that you could create and edit alarms from the popup.js without the need to send messages and the alarm will stay alive even after the popup page is closed.

Another thing to think of future-wise is that manifest version 3 will eventually be the standard in Firefox. That version of the API does not have persistent background pages. Therefore, Javascript timeouts and intervals won’t work in background scripts at that point and you will need to change your code later.


问:
How to pass onPress to props.children?
I'm trying to make a wrapper component in react-native that I can pass down all its props to the children it wraps around. What I really want is to pass down all function props down to all its children. It looks something like this below. I want the onPress in Wrapper to be called when the TouchableOpacity is pressed.

I tried this below but it doesn't work

const Wrapper = ({children,...props})=>{
      return <View {...props}>{children}</View>
}

const App = ()=>{
    return (
        <View style={{flex:1}}>
            <Wrapper onPress={()=>{console.log(2)}}>
                <TouchableOpacity/>
            </Wrapper>
        </View>
    )
}
```

答:
It looks like you're looking to map the children and apply the props to each one. That might look like this:

```<code>const Wrapper = ({children,...props})=>{
  return (<>
    {React.Children.map(children, child => (
      React.cloneElement(child, {...props})
    ))}
  </>);
}
</code>```

(method of mapping the children borrowed from this answer)

Title: How to pass onPress to props.children?

Body:
It looks like you're looking to map the children and apply the props to each one. That might look like this:

const Wrapper = ({children,...props})=>{
  return (<>
    {React.Children.map(children, child => (
      React.cloneElement(child, {...props})
    ))}
  </>);
}

(method of mapping the children borrowed from this answer)


问:
Cubit state shows 2 different values
I have basic auth cubit like this:

```<code>class AuthCubit extends Cubit<AuthState> {
  AuthCubit() : super(const _AuthState(isUserSignedIn: false)) {
    FirebaseAuth.instance.authStateChanges().listen((User? user) {
      if (user == null) {
        emit(state.copyWith(
          isUserSignedIn: false,
        ));

        print('user logged out');
      } else {
        print('user logged innnnn');
        emit(state.copyWith(isUserSignedIn: true));
      }
      print(state);
    });
  }
}
</code>```

When I print the statement above, it works correctly (When I log in, it  gives this: AuthState(isUserSignedIn: true)

Now, the problem starts here:
Main.dart

```<code>class AppWidget extends StatelessWidget {
  const AppWidget({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: BlocProvider(
      lazy: false,
      create: (context) => AuthCubit(),
      child: FlowBuilder<AuthState>(
          state: const AuthState(),
          onGeneratePages: (authState, pages) {
            print(("HERE MAIN.DART AuthState ${authState}"));
            if (authState.isUserSignedIn) {
              return [SignInPage.page()];
            } else {
              return [SignInPage.page()];
            }
          }),
    ));
  }
}
</code>```

I use flow builder. HERE MAIN.DART section of the code, gives false, although the real statement true.
By the way, auth state has default value (false), because of this it can give maybe I do not know.

Auth State here:

```<code>@freezed
class AuthState with _$AuthState {
  const factory AuthState({
    @Default(false) bool isUserSignedIn,
  }) = _AuthState;
}
</code>```

答: I solved with the  flow_builder package.

Title: Cubit state shows 2 different values

Body:
I have basic auth cubit like this:

class AuthCubit extends Cubit<AuthState> {
  AuthCubit() : super(const _AuthState(isUserSignedIn: false)) {
    FirebaseAuth.instance.authStateChanges().listen((User? user) {
      if (user == null) {
        emit(state.copyWith(
          isUserSignedIn: false,
        ));

        print('user logged out');
      } else {
        print('user logged innnnn');
        emit(state.copyWith(isUserSignedIn: true));
      }
      print(state);
    });
  }
}

When I print the statement above, it works correctly (When I log in, it  gives this: AuthState(isUserSignedIn: true)

Now, the problem starts here:
Main.dart

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: BlocProvider(
      lazy: false,
      create: (context) => AuthCubit(),
      child: FlowBuilder<AuthState>(
          state: const AuthState(),
          onGeneratePages: (authState, pages) {
            print(("HERE MAIN.DART AuthState ${authState}"));
            if (authState.isUserSignedIn) {
              return [SignInPage.page()];
            } else {
              return [SignInPage.page()];
            }
          }),
    ));
  }
}

I use flow builder. HERE MAIN.DART section of the code, gives false, although the real statement true.
By the way, auth state has default value (false), because of this it can give maybe I do not know.

Auth State here:

@freezed
class AuthState with _$AuthState {
  const factory AuthState({
    @Default(false) bool isUserSignedIn,
  }) = _AuthState;
}

Body: I solved with the  flow_builder package.


问:
How to make the article above cover the article below when it gets mor height?
I need some help when hovering over article , i want to cover the article below it instead of pushing the whole next row, i tried to give it some padding and then heigh but i'm getting the same result. I tried also with Jquery to use .hover() function and it gave the same result.

The whole container has a display flex , and every article has a width and height , and when hovering over the article it gets more height. The article without hovering has a 480px and then when hovering 500px

.container {
  width: 1400px;
  margin: 0 auto;
  padding: 20px;
}
.articles_container {
  border-radius: 4px;
  max-width: calc(100vw - 10px);
  margin-bottom: 1px;
  display: flex;
  flex-wrap: wrap;
}
article {
  width: 24%;
  border: 1px solid red;
  margin-left: -1px;
  margin-top: -1px;

  height: 480px;
}
img {
  width: auto;
  max-width: 100%;
  display: block;
  margin: 0 auto;
  height: auto;
}
.bottom {
  display: none;
}

article:hover {
  height: 500px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <link rel="stylesheet" href="style.css" />
    <title>Static Template</title>
  </head>
  <body>
    <div class="container">
      <div class="articles_container">
        <article>
          <img src="https://03.cdn37.se/zY/images/2.247758/elcykel-ecoride-ambassador-26-axs-h-8-dam-svart.jpeg" alt="bycekel" />
          <div class="info">
            <h4>Titel</h4>
            <p>
              Lorem, ipsum dolor sit amet consectetur adipisicing elit. Pariatur
              aut quibusdam ducimus totam modi culpa? Quisquam eius tempora
              libero aperiam fugit ex temporibus reprehenderit, recusandae
              necessitatibus quia, dignissimos accusamus asperiores!
            </p>
            <button>Click Me</button>
          </div>
          <div class="bottom">
            <p>25</p>
          </div>
        </article>
        <!--        -->
        <article>
          <img src="https://03.cdn37.se/zY/images/2.247758/elcykel-ecoride-ambassador-26-axs-h-8-dam-svart.jpeg" alt="bycekel" />
          <div class="info">
            <h4>Titel</h4>
            <p>
              Lorem, ipsum dolor sit amet consectetur adipisicing elit. Pariatur
              aut quibusdam ducimus totam modi culpa? Quisquam eius tempora
              libero aperiam fugit ex temporibus reprehenderit, recusandae
              necessitatibus quia, dignissimos accusamus asperiores!
            </p>
            <button>Click Me</button>
          </div>
          <div class="bottom">
            <p>25</p>
          </div>
        </article>
        <!--        -->
        <article>
          <img src="https://03.cdn37.se/zY/images/2.247758/elcykel-ecoride-ambassador-26-axs-h-8-dam-svart.jpeg" alt="bycekel" />
          <div class="info">
            <h4>Titel</h4>
            <p>
              Lorem, ipsum dolor sit amet consectetur adipisicing elit. Pariatur
              aut quibusdam ducimus totam modi culpa? Quisquam eius tempora
              libero aperiam fugit ex temporibus reprehenderit, recusandae
              necessitatibus quia, dignissimos accusamus asperiores!
            </p>
            <button>Click Me</button>
          </div>

          <div class="bottom">
            <p>25</p>
          </div>
        </article>
        <!--        -->
        <article>
          <img src="https://03.cdn37.se/zY/images/2.247758/elcykel-ecoride-ambassador-26-axs-h-8-dam-svart.jpeg" alt="bycekel" />
          <div class="info">
            <h4>Titel</h4>
            <p>
              Lorem, ipsum dolor sit amet consectetur adipisicing elit. Pariatur
              aut quibusdam ducimus totam modi culpa? Quisquam eius tempora
              libero aperiam fugit ex temporibus reprehenderit, recusandae
              necessitatibus quia, dignissimos accusamus asperiores!
            </p>
            <button>Click Me</button>
          </div>
          <div class="bottom">
            <p>25</p>
          </div>
        </article>
        <!--        -->
        <article>
          <img src="https://03.cdn37.se/zY/images/2.247758/elcykel-ecoride-ambassador-26-axs-h-8-dam-svart.jpeg" alt="bycekel" />
          <div class="info">
            <h4>Titel</h4>
            <p>
              Lorem, ipsum dolor sit amet consectetur adipisicing elit. Pariatur
              aut quibusdam ducimus totam modi culpa? Quisquam eius tempora
              libero aperiam fugit ex temporibus reprehenderit, recusandae
              necessitatibus quia, dignissimos accusamus asperiores!
            </p>
            <button>Click Me</button>
          </div>
        </article>
        <!--        -->
        <article>
          <img src="https://03.cdn37.se/zY/images/2.247758/elcykel-ecoride-ambassador-26-axs-h-8-dam-svart.jpeg" alt="bycekel" />
          <div class="info">
            <h4>Titel</h4>
            <p>
              Lorem, ipsum dolor sit amet consectetur adipisicing elit. Pariatur
              aut quibusdam ducimus totam modi culpa? Quisquam eius tempora
              libero aperiam fugit ex temporibus reprehenderit, recusandae
              necessitatibus quia, dignissimos accusamus asperiores!
            </p>
            <button>Click Me</button>
          </div>
        </article>
        <!--        -->
        <article>
          <img src="https://03.cdn37.se/zY/images/2.247758/elcykel-ecoride-ambassador-26-axs-h-8-dam-svart.jpeg" alt="bycekel" />
          <div class="info">
            <h4>Titel</h4>
            <p>
              Lorem, ipsum dolor sit amet consectetur adipisicing elit. Pariatur
              aut quibusdam ducimus totam modi culpa? Quisquam eius tempora
              libero aperiam fugit ex temporibus reprehenderit, recusandae
              necessitatibus quia, dignissimos accusamus asperiores!
            </p>
            <button>Click Me</button>
          </div>
        </article>
        <!--        -->
        <article>
          <img src="https://03.cdn37.se/zY/images/2.247758/elcykel-ecoride-ambassador-26-axs-h-8-dam-svart.jpeg" alt="bycekel" />
          <div class="info">
            <h4>Titel</h4>
            <p>
              Lorem, ipsum dolor sit amet consectetur adipisicing elit. Pariatur
              aut quibusdam ducimus totam modi culpa? Quisquam eius tempora
              libero aperiam fugit ex temporibus reprehenderit, recusandae
              necessitatibus quia, dignissimos accusamus asperiores!
            </p>
            <button>Click Me</button>
          </div>
        </article>
        <!--        -->
      </div>
    </div>

  </body>
</html></code>```

答:
Edit here is an example using javascript

const articleItem = document.querySelector('.article_item')
for(let i = 0; i<10;i++){
  articleItem.insertAdjacentHTML("afterend", articleItem.outerHTML);
}
const articles = document.querySelectorAll('article')

articles.forEach(a=>{
  a.addEventListener('mouseover',handleHover)
  a.addEventListener('mouseout',handleHoverEnd)
})

function handleHover(e){
  const width = e.currentTarget.clientWidth
  const top = e.currentTarget.offsetTop + 1 //>>adjust for margins set in css
  const left = e.currentTarget.offsetLeft + 1 //>>adjust for margins set in css
  e.currentTarget.classList.add('active')
  e.currentTarget.style.cssText = `top: ${top}px; left: ${left}px; width: ${width}px`
}
function handleHoverEnd(e){
  e.currentTarget.classList.remove('active')
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  width: 1400px;
  margin: 0 auto;
  padding: 20px;
}
.articles_container {
  border-radius: 4px;
  max-width: calc(100vw - 10px);
  margin-bottom: 1px;
  position: relative;
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
}
.article_item{
width: 24%;
}
article {
  display: flex;
  flex-direction: column;
  border: 1px solid red;
  margin-left: -1px;
  margin-top: -1px;
  height: 180px;
  background-color: white;
  overflow: hidden;
}
img {
  max-width: 100%;
}
.bottom {
  display: none;

}

.active {
  position: absolute;
  height: 300px;
  z-index: 3;
}</code>```

Titel

              Lorem, ipsum dolor sit amet consectetur adipisicing elit. Pariatur
              aut quibusdam ducimus totam modi culpa? Quisquam eius tempora
              libero aperiam fugit ex temporibus reprehenderit, recusandae
              necessitatibus quia, dignissimos accusamus asperiores!

            <button>Click Me</button>

25

  ```

Body:
I need some help when hovering over article , i want to cover the article below it instead of pushing the whole next row, i tried to give it some padding and then heigh but i'm getting the same result. I tried also with Jquery to use .hover() function and it gave the same result.

The whole container has a display flex , and every article has a width and height , and when hovering over the article it gets more height. The article without hovering has a 480px and then when hovering 500px

.container {
  width: 1400px;
  margin: 0 auto;
  padding: 20px;
}
.articles_container {
  border-radius: 4px;
  max-width: calc(100vw - 10px);
  margin-bottom: 1px;
  display: flex;
  flex-wrap: wrap;
}
article {
  width: 24%;
  border: 1px solid red;
  margin-left: -1px;
  margin-top: -1px;

  height: 480px;
}
img {
  width: auto;
  max-width: 100%;
  display: block;
  margin: 0 auto;
  height: auto;
}
.bottom {
  display: none;
}

article:hover {
  height: 500px;
}

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <link rel="stylesheet" href="style.css" />
    <title>Static Template</title>

Titel

              Lorem, ipsum dolor sit amet consectetur adipisicing elit. Pariatur
              aut quibusdam ducimus totam modi culpa? Quisquam eius tempora
              libero aperiam fugit ex temporibus reprehenderit, recusandae
              necessitatibus quia, dignissimos accusamus asperiores!

            <button>Click Me</button>

25

Titel

              Lorem, ipsum dolor sit amet consectetur adipisicing elit. Pariatur
              aut quibusdam ducimus totam modi culpa? Quisquam eius tempora
              libero aperiam fugit ex temporibus reprehenderit, recusandae
              necessitatibus quia, dignissimos accusamus asperiores!

            <button>Click Me</button>

25

Titel

              Lorem, ipsum dolor sit amet consectetur adipisicing elit. Pariatur
              aut quibusdam ducimus totam modi culpa? Quisquam eius tempora
              libero aperiam fugit ex temporibus reprehenderit, recusandae
              necessitatibus quia, dignissimos accusamus asperiores!

            <button>Click Me</button>

25

Titel

              Lorem, ipsum dolor sit amet consectetur adipisicing elit. Pariatur
              aut quibusdam ducimus totam modi culpa? Quisquam eius tempora
              libero aperiam fugit ex temporibus reprehenderit, recusandae
              necessitatibus quia, dignissimos accusamus asperiores!

            <button>Click Me</button>

25

Titel

              Lorem, ipsum dolor sit amet consectetur adipisicing elit. Pariatur
              aut quibusdam ducimus totam modi culpa? Quisquam eius tempora
              libero aperiam fugit ex temporibus reprehenderit, recusandae
              necessitatibus quia, dignissimos accusamus asperiores!

            <button>Click Me</button>

Titel

              Lorem, ipsum dolor sit amet consectetur adipisicing elit. Pariatur
              aut quibusdam ducimus totam modi culpa? Quisquam eius tempora
              libero aperiam fugit ex temporibus reprehenderit, recusandae
              necessitatibus quia, dignissimos accusamus asperiores!

            <button>Click Me</button>

Titel

              Lorem, ipsum dolor sit amet consectetur adipisicing elit. Pariatur
              aut quibusdam ducimus totam modi culpa? Quisquam eius tempora
              libero aperiam fugit ex temporibus reprehenderit, recusandae
              necessitatibus quia, dignissimos accusamus asperiores!

            <button>Click Me</button>

Titel

              Lorem, ipsum dolor sit amet consectetur adipisicing elit. Pariatur
              aut quibusdam ducimus totam modi culpa? Quisquam eius tempora
              libero aperiam fugit ex temporibus reprehenderit, recusandae
              necessitatibus quia, dignissimos accusamus asperiores!

            <button>Click Me</button>

Body:
Edit here is an example using javascript

const articleItem = document.querySelector('.article_item')
for(let i = 0; i<10;i++){
  articleItem.insertAdjacentHTML("afterend", articleItem.outerHTML);
}
const articles = document.querySelectorAll('article')

articles.forEach(a=>{
  a.addEventListener('mouseover',handleHover)
  a.addEventListener('mouseout',handleHoverEnd)
})

function handleHover(e){
  const width = e.currentTarget.clientWidth
  const top = e.currentTarget.offsetTop + 1 //>>adjust for margins set in css
  const left = e.currentTarget.offsetLeft + 1 //>>adjust for margins set in css
  e.currentTarget.classList.add('active')
  e.currentTarget.style.cssText = `top: ${top}px; left: ${left}px; width: ${width}px`
}
function handleHoverEnd(e){
  e.currentTarget.classList.remove('active')
}

.container {
  width: 1400px;
  margin: 0 auto;
  padding: 20px;
}
.articles_container {
  border-radius: 4px;
  max-width: calc(100vw - 10px);
  margin-bottom: 1px;
  position: relative;
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
}
.article_item{
width: 24%;
}
article {
  display: flex;
  flex-direction: column;
  border: 1px solid red;
  margin-left: -1px;
  margin-top: -1px;
  height: 180px;
  background-color: white;
  overflow: hidden;
}
img {
  max-width: 100%;
}
.bottom {
  display: none;

}

.active {
  position: absolute;
  height: 300px;
  z-index: 3;
}

<body>
    <div class="container">
      <div class="articles_container">
        <div class="article_item">
        <article>
          <img src="https://03.cdn37.se/zY/images/2.247758/elcykel-ecoride-ambassador-26-axs-h-8-dam-svart.jpeg" alt="bycekel" />
          <div class="info">
            <h4>Titel</h4>
            <p>
              Lorem, ipsum dolor sit amet consectetur adipisicing elit. Pariatur
              aut quibusdam ducimus totam modi culpa? Quisquam eius tempora
              libero aperiam fugit ex temporibus reprehenderit, recusandae
              necessitatibus quia, dignissimos accusamus asperiores!
            </p>
            <button>Click Me</button>
          </div>
          <div class="bottom">
            <p>25</p>
          </div>
        </article>
        </div>
      </div>
    </div>

  </body>


问:
Extracting element from table using selenium web scraping
Using selenium I am trying to scrape a table from a website,
however, data appears compressed into one single column rather than two separate columns; Date and Value- help would be greatly appreciated - now amended to included further improvement

```<code>driver.get("https://www.multpl.com/shiller-pe/table/by-year/")

table_trs = driver.find_elements(By.XPATH, '//table[@id="datatable"]/tbody/tr')

value_list = []
for v in range(len(table_trs )):
    value_list.append(table_trs [v].text)

print(value_list)
df = pd.DataFrame(value_list)
</code>```

The table I am trying to scrape appears on the website as follows....

..and the section of html associated to it.....

答:
Note: Answer is focused on correct usage of xpath and only based on your screenshot - Improving your question and posting code and examples as text would generate more specific answers

To get the
s of the table by xpath change it to //table[@id="datatable"]/tbody/tr

```<code>from selenium.webdriver.common.by import By

table_trs = driver.find_elements(By.XPATH, '//table[@id="datatable"]/tbody/tr')
</code>```

EDIT

Based on your improvements you can go with pandas.read_html() to convert the table directly into a dataframe. Just have to rename the columns, cause there are two span tag in the  that will lead to column name "Value Value":

```<code>driver.get("https://www.multpl.com/shiller-pe/table/by-year/")

df = pd.read_html(driver.page_source)[0]
df.columns = ['Date','Value']
</code>```

As alternative you could iterate like this:

```<code>driver.get("https://www.multpl.com/shiller-pe/table/by-year/")

table_trs = driver.find_elements(By.XPATH, '//table[@id="datatable"]/tbody/tr')
value_list = []
for row in table_trs[1:]:
    value_list.append({
        'Date':row.find_elements(By.TAG_NAME, "td")[0].text,
        'Value':row.find_elements(By.TAG_NAME, "td")[1].text
    })

df = pd.DataFrame(value_list)
</code>```

Output

Date
Value

Feb 4, 2022
37.18

Jan 1, 2022
39.63

Jan 1, 2021
34.51

Jan 1, 2020
30.99

Jan 1, 2019
28.38

Jan 1, 2018
33.31

Jan 1, 2017
28.06

Jan 1, 2016
24.21

Jan 1, 2015
26.49

...
...

Body:
Using selenium I am trying to scrape a table from a website,
however, data appears compressed into one single column rather than two separate columns; Date and Value- help would be greatly appreciated - now amended to included further improvement

driver.get("https://www.multpl.com/shiller-pe/table/by-year/")

table_trs = driver.find_elements(By.XPATH, '//table[@id="datatable"]/tbody/tr')

value_list = []
for v in range(len(table_trs )):
    value_list.append(table_trs [v].text)

print(value_list)
df = pd.DataFrame(value_list)

The table I am trying to scrape appears on the website as follows....

..and the section of html associated to it.....

Body:
Note: Answer is focused on correct usage of xpath and only based on your screenshot - Improving your question and posting code and examples as text would generate more specific answers

To get the <tr>s of the table by xpath change it to //table[@id="datatable"]/tbody/tr

from selenium.webdriver.common.by import By

table_trs = driver.find_elements(By.XPATH, '//table[@id="datatable"]/tbody/tr')

EDIT

Based on your improvements you can go with pandas.read_html() to convert the table directly into a dataframe. Just have to rename the columns, cause there are two span tag in the <th> that will lead to column name "Value Value":

driver.get("https://www.multpl.com/shiller-pe/table/by-year/")

df = pd.read_html(driver.page_source)[0]
df.columns = ['Date','Value']

As alternative you could iterate like this:

driver.get("https://www.multpl.com/shiller-pe/table/by-year/")

table_trs = driver.find_elements(By.XPATH, '//table[@id="datatable"]/tbody/tr')
value_list = []
for row in table_trs[1:]:
    value_list.append({
        'Date':row.find_elements(By.TAG_NAME, "td")[0].text,
        'Value':row.find_elements(By.TAG_NAME, "td")[1].text
    })

df = pd.DataFrame(value_list)

Output

Date
Value

Feb 4, 2022
37.18

Jan 1, 2022
39.63

Jan 1, 2021
34.51

Jan 1, 2020
30.99

Jan 1, 2019
28.38

Jan 1, 2018
33.31

Jan 1, 2017
28.06

Jan 1, 2016
24.21

Jan 1, 2015
26.49

...
...


问:
Create an array of strings
Is it possibe to create an array of strings in MATLAB within a for loop?

For example,

```<code>for i=1:10
Names(i)='Sample Text';
end
</code>```

I don't seem to be able to do it this way.

答:
Another option:</p>

```<code>names = repmat({'Sample Text'}, 10, 1)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Create an array of strings

Body:
Is it possibe to create an array of strings in MATLAB within a for loop?

For example,

for i=1:10
Names(i)='Sample Text';
end

I don't seem to be able to do it this way.

Body:
Another option:

names = repmat({'Sample Text'}, 10, 1)


问:
JSON_Normalize (nested json) to csv
I have been trying via pandas to extract data from a txt file containing json utf-8 encoded data.

Direct link to data file - http://download.companieshouse.gov.uk/psc-snapshot-2022-02-06_8of20.zip

Data's structure looks like the following examples:

```<code>{"company_number":"04732933","data":{"address":{"address_line_1":"Windsor Road","locality":"Torquay","postal_code":"TQ1 1ST","premises":"Windsor Villas","region":"Devon"},"country_of_residence":"England","date_of_birth":{"month":1,"year":1964},"etag":"5623f35e4bb5dc9cb37e134cb2ac0ca3151cd01f","kind":"individual-person-with-significant-control","links":{"self":"/company/04732933/persons-with-significant-control/individual/8X3LALP5gAh5dAYEOYimeiRiJMQ"},"name":"Ms Karen Mychals","name_elements":{"forename":"Karen","surname":"Mychals","title":"Ms"},"nationality":"British","natures_of_control":["ownership-of-shares-50-to-75-percent"],"notified_on":"2016-04-06"}}
{"company_number":"10118870","data":{"address":{"address_line_1":"Hilltop Road","address_line_2":"Bearpark","country":"England","locality":"Durham","postal_code":"DH7 7TL","premises":"54"},"ceased_on":"2019-04-15","country_of_residence":"England","date_of_birth":{"month":9,"year":1983},"etag":"5b3c984156794e5519851b7f1b22d1bbd2a5c5df","kind":"individual-person-with-significant-control","links":{"self":"/company/10118870/persons-with-significant-control/individual/hS6dYoZ234aXhmI6Q9y83QbAhSY"},"name":"Mr Patrick John Burns","name_elements":{"forename":"Patrick","middle_name":"John","surname":"Burns","title":"Mr"},"nationality":"British","natures_of_control":["ownership-of-shares-25-to-50-percent","voting-rights-25-to-50-percent"],"notified_on":"2017-04-06"}}
</code>```

The simplepd.read_json did not work  initially (I would get ValueError: Trailing data errors)  until lines=true was used (using jupyternotebook for this).

```<code>import pandas as pd
import json
df = pd.read_json(r'E:\JSON_data\psc-snapshot-2022-02-06_8of20.txt', encoding='utf8', lines=True)
</code>```

this is how the data structure is displayed via df.head() :

```<code>    company_number  data
0   06851805    {'address': {'address_line_1': 'Briar Road', '...
1   04732933    {'address': {'address_line_1': 'Windsor Road',...
2   10118870    {'address': {'address_line_1': 'Hilltop Road',...
3   10118870    {'address': {'address_line_1': 'Hilltop Road',...
4   09565353    {'address': {'address_line_1': 'Old Hertford R...
</code>```

After looking through stackoverflow and several online tutorials I tried using pd.json_normalize(df) but keep getting a AttributeError: 'str' object has no attribute 'values' error. I would like to ultimately export this json file into a csv file.

thank you in advance for any advice!

答:
You can solve that problem by applying the json_normalize just to the data column.

```<code>import pandas as pd
import json

df = pd.read_json(r'E:\JSON_data\psc-snapshot-2022-02-06_8of20.txt', encoding='utf8', lines=True)

#json_normalize
df2 = pd.json_normalize(df['data'])
df = pd.concat([df, df2], axis=1)

#output to csv
df.to_csv("./OUTPUT_FILE_NAME")

print(df)

   company_number  ... name_elements.middle_name
0         4732933  ...                       NaN
1        10118870  ...                      John

[2 rows x 24 columns]

</code>```

Title: JSON_Normalize (nested json) to csv

Body:
I have been trying via pandas to extract data from a txt file containing json utf-8 encoded data.

Direct link to data file - http://download.companieshouse.gov.uk/psc-snapshot-2022-02-06_8of20.zip

Data's structure looks like the following examples:

{"company_number":"04732933","data":{"address":{"address_line_1":"Windsor Road","locality":"Torquay","postal_code":"TQ1 1ST","premises":"Windsor Villas","region":"Devon"},"country_of_residence":"England","date_of_birth":{"month":1,"year":1964},"etag":"5623f35e4bb5dc9cb37e134cb2ac0ca3151cd01f","kind":"individual-person-with-significant-control","links":{"self":"/company/04732933/persons-with-significant-control/individual/8X3LALP5gAh5dAYEOYimeiRiJMQ"},"name":"Ms Karen Mychals","name_elements":{"forename":"Karen","surname":"Mychals","title":"Ms"},"nationality":"British","natures_of_control":["ownership-of-shares-50-to-75-percent"],"notified_on":"2016-04-06"}}
{"company_number":"10118870","data":{"address":{"address_line_1":"Hilltop Road","address_line_2":"Bearpark","country":"England","locality":"Durham","postal_code":"DH7 7TL","premises":"54"},"ceased_on":"2019-04-15","country_of_residence":"England","date_of_birth":{"month":9,"year":1983},"etag":"5b3c984156794e5519851b7f1b22d1bbd2a5c5df","kind":"individual-person-with-significant-control","links":{"self":"/company/10118870/persons-with-significant-control/individual/hS6dYoZ234aXhmI6Q9y83QbAhSY"},"name":"Mr Patrick John Burns","name_elements":{"forename":"Patrick","middle_name":"John","surname":"Burns","title":"Mr"},"nationality":"British","natures_of_control":["ownership-of-shares-25-to-50-percent","voting-rights-25-to-50-percent"],"notified_on":"2017-04-06"}}

The simplepd.read_json did not work  initially (I would get ValueError: Trailing data errors)  until lines=true was used (using jupyternotebook for this).

import pandas as pd
import json
df = pd.read_json(r'E:\JSON_data\psc-snapshot-2022-02-06_8of20.txt', encoding='utf8', lines=True)

this is how the data structure is displayed via df.head() :

    company_number  data
0   06851805    {'address': {'address_line_1': 'Briar Road', '...
1   04732933    {'address': {'address_line_1': 'Windsor Road',...
2   10118870    {'address': {'address_line_1': 'Hilltop Road',...
3   10118870    {'address': {'address_line_1': 'Hilltop Road',...
4   09565353    {'address': {'address_line_1': 'Old Hertford R...

After looking through stackoverflow and several online tutorials I tried using pd.json_normalize(df) but keep getting a AttributeError: 'str' object has no attribute 'values' error. I would like to ultimately export this json file into a csv file.

thank you in advance for any advice!

Body:
You can solve that problem by applying the json_normalize just to the data column.

import pandas as pd
import json

df = pd.read_json(r'E:\JSON_data\psc-snapshot-2022-02-06_8of20.txt', encoding='utf8', lines=True)

#json_normalize
df2 = pd.json_normalize(df['data'])
df = pd.concat([df, df2], axis=1)

#output to csv
df.to_csv("./OUTPUT_FILE_NAME")

print(df)

   company_number  ... name_elements.middle_name
0         4732933  ...                       NaN
1        10118870  ...                      John

[2 rows x 24 columns]


问:
How can I forward my selected items to another page in Flutter
I have some datas and I can see in the homepage.
I want to see also in the another page, how can i do this?

I have card for example, and It has some datas like fav_numbers, name, last_name etc. and I want to pass these informations to another page. Then, I can see these cards (only selected) in the another page. How can i do this?

I want to pass like this:

```<code>ElevatedButton(
onPressed: () {
AutoRouter.of(context).push(
PeopleRoute(
name: games[index]["name"],
surname: games[index]["surname"],
luckyNumber: games[index]["luckyNumber"]),
 );
 },
child: Icon(CupertinoIcons.add),
 ),
</code>```

and I can use these informations in people page like widget.name or widget.surname . But I need to a list right? Because I do not want to show just 1 card, I want to show when user click PLUS(+) button, then I want to show cards which are selected.

If you show simply, I can continue with using other state management ways...

答: Just I needed to create items in another widget, which I wanted.</p>

Body:
I have some datas and I can see in the homepage.
I want to see also in the another page, how can i do this?

I have card for example, and It has some datas like fav_numbers, name, last_name etc. and I want to pass these informations to another page. Then, I can see these cards (only selected) in the another page. How can i do this?

I want to pass like this:

ElevatedButton(
onPressed: () {
AutoRouter.of(context).push(
PeopleRoute(
name: games[index]["name"],
surname: games[index]["surname"],
luckyNumber: games[index]["luckyNumber"]),
 );
 },
child: Icon(CupertinoIcons.add),
 ),

and I can use these informations in people page like widget.name or widget.surname . But I need to a list right? Because I do not want to show just 1 card, I want to show when user click PLUS(+) button, then I want to show cards which are selected.

If you show simply, I can continue with using other state management ways...


问:
Why is my for loop not transferring all list items to my dictionary (PYTHON)
I have 3 lists: year, list1, list2.
I want to create a dictionary with {year1: list_item1, year2: list_item2, etc..}
My code:

```<code>list1 = [1,2,3,4,5]
list2 = [6,7,8,9,10]

years = []
for i in range(2018,2024):
    years.append(i)

predicted_change = {}
n = 0
while n < 6:
    for i in years:
        for t in list1:
            for e in list2:
                predicted_change[i] = t
                n += 1
    break

predicted_change
</code>```

Results: {2018: 5, 2019: 5, 2020: 5, 2021: 5, 2022: 5, 2023: 5}

Any ideas? I was looking for {2018: 1, 2019: 2, 2020: 3, etc...}
Thanks!

答:
You update entries in predicted_values dictionary at each iteration of list2 to the current value of t from list1. The final value for each key in predicted_values will always be the right-most value in list1:

```<code>while n < 6:
    for i in years:
        for t in list1:
            for e in list2:
                # When i = 2018 and t = 1, you assign predicted_change[2018] = 1 at each iteration of list2
                # When i = 2018 and t = 2, you assign predicted_change[2018] = 2 at each iteration of list2
                # ... and so on until t = 5, which results in predicted_change[2018] = 5. Same for when i = 2019, 2022, ...
                predicted_change[i] = t
                n += 1
</code>```

I agree with the comments under your question:

Iterating over list2 is redundant given your code and what you're saying you're trying to do

If you're trying to create a dict where the number of keys (years in your example) == number of items in list1 and each year should map to a value from list1 consecutively, there are better ways to do it.

For example:

```<code>initial_year = 2018
for k, t in zip(range(initial_year, initial_year + len(list1)), list1):
    predicted_change[k] = t

# predicted_change: {2018: 1, 2019: 2, 2020: 3, 2021: 4, 2022: 5}

</code>```

Hopefully it makes sense. Good luck with whatever you're trying to do!

Body:
I have 3 lists: year, list1, list2.
I want to create a dictionary with {year1: list_item1, year2: list_item2, etc..}
My code:

list1 = [1,2,3,4,5]
list2 = [6,7,8,9,10]

years = []
for i in range(2018,2024):
    years.append(i)

predicted_change = {}
n = 0
while n < 6:
    for i in years:
        for t in list1:
            for e in list2:
                predicted_change[i] = t
                n += 1
    break

predicted_change

Results: {2018: 5, 2019: 5, 2020: 5, 2021: 5, 2022: 5, 2023: 5}

Any ideas? I was looking for {2018: 1, 2019: 2, 2020: 3, etc...}
Thanks!

Body:
You update entries in predicted_values dictionary at each iteration of list2 to the current value of t from list1. The final value for each key in predicted_values will always be the right-most value in list1:

while n < 6:
    for i in years:
        for t in list1:
            for e in list2:
                # When i = 2018 and t = 1, you assign predicted_change[2018] = 1 at each iteration of list2
                # When i = 2018 and t = 2, you assign predicted_change[2018] = 2 at each iteration of list2
                # ... and so on until t = 5, which results in predicted_change[2018] = 5. Same for when i = 2019, 2022, ...
                predicted_change[i] = t
                n += 1

I agree with the comments under your question:

Iterating over list2 is redundant given your code and what you're saying you're trying to do

If you're trying to create a dict where the number of keys (years in your example) == number of items in list1 and each year should map to a value from list1 consecutively, there are better ways to do it.

For example:

initial_year = 2018
for k, t in zip(range(initial_year, initial_year + len(list1)), list1):
    predicted_change[k] = t

# predicted_change: {2018: 1, 2019: 2, 2020: 3, 2021: 4, 2022: 5}

Hopefully it makes sense. Good luck with whatever you're trying to do!


问:
Silverlight Formatting Strings In Bindings With StringFormat
I have a string of numbers stored in a string property:

```<code>1234567890
</code>```

I would like the output to display:

```<code>(123) 456-7890
</code>```

Can I format this in a TextBlock during binding using the StringFormat attribute? I have tried things like stringformat='{0:(###) ###-####}' in my binding expression without any sucess.

答:
Try this:</p>

```<code><TextBox Text="{Binding PhoneNumber, StringFormat='(###) ###-####'}" />
</code>```

Body:
I have a string of numbers stored in a string property:

1234567890

I would like the output to display:

(123) 456-7890

Can I format this in a TextBlock during binding using the StringFormat attribute? I have tried things like stringformat='{0:(###) ###-####}' in my binding expression without any sucess.

Body:
Try this:

<TextBox Text="{Binding PhoneNumber, StringFormat='(###) ###-####'}" />


问:
Chess Engine Wrong Number of 4 Plie Board States
I'm writing a chess engine, and am trying to make it as fast as possible, so I'm using bitboards to represent each type of piece. I was printing out the number of different board states at each plie (Plie = 1 person moving) and on plie 4 it gets the wrong number.

Is there any way to figure out what is going wrong without sifting through all 200k 4 plie positions?

Also, note I haven't implemented castling, check, en passent, pawn promotion or any draw rules yet, as none of them should have any affect until after the 4th plie.

(Wikipedia link that gives the number of board states per plie, vs mine: 20, 400, 8902, 197742)

```<code>import json

with open('White_Pawn.json', 'r') as f:
    white_pawn_table = json.load(f)
    white_pawn_table = {int(q):w for q, w in white_pawn_table.items()}

with open('White_Pawn_Captures.json', 'r') as f:
    white_pawn_captures_table = json.load(f)
    white_pawn_captures_table = {int(q):w for q, w in white_pawn_captures_table.items()}

with open('Black_Pawn.json', 'r') as f:
    black_pawn_table = json.load(f)
    black_pawn_table = {int(q):w for q, w in black_pawn_table.items()}

with open('Black_Pawn_Captures.json', 'r') as f:
    black_pawn_captures_table = json.load(f)
    black_pawn_captures_table = {int(q):w for q, w in black_pawn_captures_table.items()}

with open('Knight.json', 'r') as f:
    knight_table = json.load(f)
    knight_table = {int(q):w for q, w in knight_table.items()}

with open('Bishop.json', 'r') as f:
    bishop_table = json.load(f)
    bishop_table = {int(q):w for q, w in bishop_table.items()}

with open('Rook.json', 'r') as f:
    rook_table = json.load(f)
    rook_table = {int(q):w for q, w in rook_table.items()}

string_to_int = lambda x:int(x, 2)
int_to_string = lambda x:'0' * (66 - len(bin(x))) + bin(x)[2:]
x_in_y = lambda x, y:(x & y) != 0

def show(x):
    for q in range(8):
        print(' '.join([w for w in x[(q * 8):((q + 1) * 8)]]))
    print()

class Board:
    def __init__(self, args = False):
        if args:
            self.maps, self.turn = args
        else:
            self.maps, self.turn = {'White Pawns':65280, 'White Knights':66, 'White Bishops':36, 'White Rooks':129, 'White Queens':16, 'White Kings':8, 'Black Pawns':71776119061217280, 'Black Knights':4755801206503243776, 'Black Bishops':2594073385365405696, 'Black Rooks':9295429630892703744, 'Black Queens':1152921504606846976, 'Black Kings':576460752303423488}, 1

    def move(self, colour, not_colour, piece, move):
        board = Board(args = (self.maps.copy(), not self.turn))

        board.maps[f'{colour} {piece}s'] ^= move[0]
        board.maps[f'{colour} {piece}s'] |= move[1]

        for q in board.maps:
            if not_colour in q:
                board.maps[q] &= ~move[1]

        return board

    def moves(self):
        # Get Pieces and Colours
        colour, not_colour = ['White', 'Black'][::self.turn if self.turn else -1]
        pieces, not_pieces = 0, 0
        for q, w in self.maps.items():
            if colour in q:
                pieces |= w
            else:
                not_pieces |= w

        # Pawn
        if colour == 'White':
            move_table, capture_table = white_pawn_table, white_pawn_captures_table
        else:
            move_table, capture_table = black_pawn_table, black_pawn_captures_table

        temp_pawns = self.maps[f'{colour} Pawns']
        while temp_pawns:
            pawn = temp_pawns & -temp_pawns
            temp_pawns ^= pawn

            for next_pawn in move_table[pawn]:
                if x_in_y(next_pawn, pieces | not_pieces):
                    break
                else:
                    yield self.move(colour, not_colour, 'Pawn', (pawn, next_pawn))

            for next_pawn in capture_table[pawn]:
                if x_in_y(next_pawn, not_pieces):
                    yield self.move(colour, not_colour, 'Pawn', (pawn, next_pawn))

        # Knight
        temp_knights = self.maps[f'{colour} Knights']
        while temp_knights:
            knight = temp_knights & -temp_knights
            temp_knights ^= knight

            for next_knight in knight_table[knight]:
                if not x_in_y(next_knight, pieces):
                    yield self.move(colour, not_colour, 'Knight', (knight, next_knight))

        # Bishop
        temp_bishops = self.maps[f'{colour} Bishops']
        while temp_bishops:
            bishop = temp_bishops & -temp_bishops
            temp_bishops ^= bishop

            for direction in bishop_table[bishop]:
                for next_bishop in direction:
                    if x_in_y(next_bishop, pieces): break

                    yield self.move(colour, not_colour, 'Bishop', (bishop, next_bishop))

                    if x_in_y(next_bishop, not_pieces): break

        # Rook
        temp_rooks = self.maps[f'{colour} Rooks']
        while temp_rooks:
            rook = temp_rooks & -temp_rooks
            temp_rooks ^= rook

            for direction in rook_table[rook]:
                for next_rook in direction:
                    if x_in_y(next_rook, pieces): break

                    yield self.move(colour, not_colour, 'Rook', (rook, next_rook))

                    if x_in_y(next_rook, not_pieces): break

        # Queen
        temp_queens = self.maps[f'{colour} Queens']
        while temp_queens:
            queen = temp_queens & -temp_queens
            temp_queens ^= queen

            for direction in rook_table[queen]:
                for next_queen in direction:
                    if x_in_y(next_queen, pieces): break

                    yield self.move(colour, not_colour, 'Queen', (queen, next_queen))

                    if x_in_y(next_queen, not_pieces): break

            for direction in bishop_table[queen]:
                for next_queen in direction:
                    if x_in_y(next_queen, pieces): break

                    yield self.move(colour, not_colour, 'Queen', (queen, next_queen))

                    if x_in_y(next_queen, not_pieces): break

        # King
        king = self.maps[f'{colour} Kings']
        for direction in rook_table[king]:
            next_king = direction[0]
            if not x_in_y(next_king, pieces):
                yield self.move(colour, not_colour, 'King', (king , next_king))

        for direction in bishop_table[king]:
            next_king = direction[0]
            if not x_in_y(next_king, pieces):
                yield self.move(colour, not_colour, 'King', (king, next_king))

    def next_states(self):
        for q in self.moves():
            yield q

    def __str__(self):
        find = {'Black Kings':'♔ ', 'Black Queens':'♕ ', 'Black Rooks':'♖ ', 'Black Bishops':'♗ ', 'Black Knights':'♘ ', 'Black Pawns':'♙ ', 'White Pawns':'♟ ', 'White Knights':'♞ ', 'White Bishops':'♝ ', 'White Rooks':'♜ ', 'White Queens':'♛ ', 'White Kings':'♚ '}
        map = lambda y:([q for q in self.maps if self.maps[q] & (2**y)] + [False])[0]
        output = '    A    B    C    D    E    F    G    H\n  ╔════╤════╤════╤════╤════╤════╤════╤════╗\n'
        for q in range(8):
            if q % 2 == 0:
                output += '%i ║ %s │░%s░│ %s │░%s░│ %s │░%s░│ %s │░%s░║ %i\n  ╟────┼────┼────┼────┼────┼────┼────┼────╢\n' % tuple([8 - q] + [find[map(q * 8 + w)] if map(q * 8 + w) else '  ' if w % 2 == 0 else '░░' for w in range(8)] + [8 - q])
            else:
                output += '%i ║░%s░│ %s │░%s░│ %s │░%s░│ %s │░%s░│ %s ║ %i\n  ╟────┼────┼────┼────┼────┼────┼────┼────╢\n' % tuple([8 - q] + [find[map(q * 8 + w)] if map(q * 8 + w) else '░░' if w % 2 == 0 else '  ' for w in range(8)] + [8 - q])

        output += '\x1b[1A\x1b[2K' + '  ╚════╧════╧════╧════╧════╧════╧════╧════╝\n    A    B    C    D    E    F    G    H'
        return output

chess = Board()

next_states = [chess]
while True:
    current_states, next_states = next_states, []

    for state in current_states:
        for next_state in state.next_states():
            next_states.append(next_state)

    print(len(next_states))
</code>```

The json files are too large to put here but you can assume they're correct. Each file has a dictionary with keys 2^0-2^63 each representing a possible position for the piece the file is named after. The values are the different positions they can go from there.

答:
```<code>1.  e2-e3
2.  d7-d6
3. Bf1-b5 +
</code>```

Black's king is now in check, so the number of moves in the 4th ply is more limited. You will need to implement check rules to get the correct number.

Body:
I'm writing a chess engine, and am trying to make it as fast as possible, so I'm using bitboards to represent each type of piece. I was printing out the number of different board states at each plie (Plie = 1 person moving) and on plie 4 it gets the wrong number.

Is there any way to figure out what is going wrong without sifting through all 200k 4 plie positions?

Also, note I haven't implemented castling, check, en passent, pawn promotion or any draw rules yet, as none of them should have any affect until after the 4th plie.

(Wikipedia link that gives the number of board states per plie, vs mine: 20, 400, 8902, 197742)

import json

with open('White_Pawn.json', 'r') as f:
    white_pawn_table = json.load(f)
    white_pawn_table = {int(q):w for q, w in white_pawn_table.items()}

with open('White_Pawn_Captures.json', 'r') as f:
    white_pawn_captures_table = json.load(f)
    white_pawn_captures_table = {int(q):w for q, w in white_pawn_captures_table.items()}

with open('Black_Pawn.json', 'r') as f:
    black_pawn_table = json.load(f)
    black_pawn_table = {int(q):w for q, w in black_pawn_table.items()}

with open('Black_Pawn_Captures.json', 'r') as f:
    black_pawn_captures_table = json.load(f)
    black_pawn_captures_table = {int(q):w for q, w in black_pawn_captures_table.items()}

with open('Knight.json', 'r') as f:
    knight_table = json.load(f)
    knight_table = {int(q):w for q, w in knight_table.items()}

with open('Bishop.json', 'r') as f:
    bishop_table = json.load(f)
    bishop_table = {int(q):w for q, w in bishop_table.items()}

with open('Rook.json', 'r') as f:
    rook_table = json.load(f)
    rook_table = {int(q):w for q, w in rook_table.items()}

string_to_int = lambda x:int(x, 2)
int_to_string = lambda x:'0' * (66 - len(bin(x))) + bin(x)[2:]
x_in_y = lambda x, y:(x & y) != 0

def show(x):
    for q in range(8):
        print(' '.join([w for w in x[(q * 8):((q + 1) * 8)]]))
    print()

class Board:
    def __init__(self, args = False):
        if args:
            self.maps, self.turn = args
        else:
            self.maps, self.turn = {'White Pawns':65280, 'White Knights':66, 'White Bishops':36, 'White Rooks':129, 'White Queens':16, 'White Kings':8, 'Black Pawns':71776119061217280, 'Black Knights':4755801206503243776, 'Black Bishops':2594073385365405696, 'Black Rooks':9295429630892703744, 'Black Queens':1152921504606846976, 'Black Kings':576460752303423488}, 1

    def move(self, colour, not_colour, piece, move):
        board = Board(args = (self.maps.copy(), not self.turn))

        board.maps[f'{colour} {piece}s'] ^= move[0]
        board.maps[f'{colour} {piece}s'] |= move[1]

        for q in board.maps:
            if not_colour in q:
                board.maps[q] &= ~move[1]

        return board

    def moves(self):
        # Get Pieces and Colours
        colour, not_colour = ['White', 'Black'][::self.turn if self.turn else -1]
        pieces, not_pieces = 0, 0
        for q, w in self.maps.items():
            if colour in q:
                pieces |= w
            else:
                not_pieces |= w

        # Pawn
        if colour == 'White':
            move_table, capture_table = white_pawn_table, white_pawn_captures_table
        else:
            move_table, capture_table = black_pawn_table, black_pawn_captures_table

        temp_pawns = self.maps[f'{colour} Pawns']
        while temp_pawns:
            pawn = temp_pawns & -temp_pawns
            temp_pawns ^= pawn

            for next_pawn in move_table[pawn]:
                if x_in_y(next_pawn, pieces | not_pieces):
                    break
                else:
                    yield self.move(colour, not_colour, 'Pawn', (pawn, next_pawn))

            for next_pawn in capture_table[pawn]:
                if x_in_y(next_pawn, not_pieces):
                    yield self.move(colour, not_colour, 'Pawn', (pawn, next_pawn))

        # Knight
        temp_knights = self.maps[f'{colour} Knights']
        while temp_knights:
            knight = temp_knights & -temp_knights
            temp_knights ^= knight

            for next_knight in knight_table[knight]:
                if not x_in_y(next_knight, pieces):
                    yield self.move(colour, not_colour, 'Knight', (knight, next_knight))

        # Bishop
        temp_bishops = self.maps[f'{colour} Bishops']
        while temp_bishops:
            bishop = temp_bishops & -temp_bishops
            temp_bishops ^= bishop

            for direction in bishop_table[bishop]:
                for next_bishop in direction:
                    if x_in_y(next_bishop, pieces): break

                    yield self.move(colour, not_colour, 'Bishop', (bishop, next_bishop))

                    if x_in_y(next_bishop, not_pieces): break

        # Rook
        temp_rooks = self.maps[f'{colour} Rooks']
        while temp_rooks:
            rook = temp_rooks & -temp_rooks
            temp_rooks ^= rook

            for direction in rook_table[rook]:
                for next_rook in direction:
                    if x_in_y(next_rook, pieces): break

                    yield self.move(colour, not_colour, 'Rook', (rook, next_rook))

                    if x_in_y(next_rook, not_pieces): break

        # Queen
        temp_queens = self.maps[f'{colour} Queens']
        while temp_queens:
            queen = temp_queens & -temp_queens
            temp_queens ^= queen

            for direction in rook_table[queen]:
                for next_queen in direction:
                    if x_in_y(next_queen, pieces): break

                    yield self.move(colour, not_colour, 'Queen', (queen, next_queen))

                    if x_in_y(next_queen, not_pieces): break

            for direction in bishop_table[queen]:
                for next_queen in direction:
                    if x_in_y(next_queen, pieces): break

                    yield self.move(colour, not_colour, 'Queen', (queen, next_queen))

                    if x_in_y(next_queen, not_pieces): break

        # King
        king = self.maps[f'{colour} Kings']
        for direction in rook_table[king]:
            next_king = direction[0]
            if not x_in_y(next_king, pieces):
                yield self.move(colour, not_colour, 'King', (king , next_king))

        for direction in bishop_table[king]:
            next_king = direction[0]
            if not x_in_y(next_king, pieces):
                yield self.move(colour, not_colour, 'King', (king, next_king))

    def next_states(self):
        for q in self.moves():
            yield q

    def __str__(self):
        find = {'Black Kings':'♔ ', 'Black Queens':'♕ ', 'Black Rooks':'♖ ', 'Black Bishops':'♗ ', 'Black Knights':'♘ ', 'Black Pawns':'♙ ', 'White Pawns':'♟ ', 'White Knights':'♞ ', 'White Bishops':'♝ ', 'White Rooks':'♜ ', 'White Queens':'♛ ', 'White Kings':'♚ '}
        map = lambda y:([q for q in self.maps if self.maps[q] & (2**y)] + [False])[0]
        output = '    A    B    C    D    E    F    G    H\n  ╔════╤════╤════╤════╤════╤════╤════╤════╗\n'
        for q in range(8):
            if q % 2 == 0:
                output += '%i ║ %s │░%s░│ %s │░%s░│ %s │░%s░│ %s │░%s░║ %i\n  ╟────┼────┼────┼────┼────┼────┼────┼────╢\n' % tuple([8 - q] + [find[map(q * 8 + w)] if map(q * 8 + w) else '  ' if w % 2 == 0 else '░░' for w in range(8)] + [8 - q])
            else:
                output += '%i ║░%s░│ %s │░%s░│ %s │░%s░│ %s │░%s░│ %s ║ %i\n  ╟────┼────┼────┼────┼────┼────┼────┼────╢\n' % tuple([8 - q] + [find[map(q * 8 + w)] if map(q * 8 + w) else '░░' if w % 2 == 0 else '  ' for w in range(8)] + [8 - q])

        output += '\x1b[1A\x1b[2K' + '  ╚════╧════╧════╧════╧════╧════╧════╧════╝\n    A    B    C    D    E    F    G    H'
        return output

chess = Board()

next_states = [chess]
while True:
    current_states, next_states = next_states, []

    for state in current_states:
        for next_state in state.next_states():
            next_states.append(next_state)

    print(len(next_states))

The json files are too large to put here but you can assume they're correct. Each file has a dictionary with keys 2^0-2^63 each representing a possible position for the piece the file is named after. The values are the different positions they can go from there.

Body:
1.  e2-e3
2.  d7-d6
3. Bf1-b5 +

Black's king is now in check, so the number of moves in the 4th ply is more limited. You will need to implement check rules to get the correct number.


问:
_CastError (type 'Null' is not a subtype of type 'Map<String, dynamic>' in type cast)
I'm trying to get data from a nested collection in my fireabase which is inside 'user'->'discounts' and getting image download URL from same collection in 'user'->'images' I'm trying to get is according to a specific currentUser.uid and I'm getting this cast error.

```<code>body: FutureBuilder<DocumentSnapshot>(
    future: FirebaseFirestore.instance
        .collection('user')
        .doc(currentUser!.uid)
        .collection('discounts')
        .doc(currentUser!.uid)
        .get(),
    builder: (context, snapshot) {
      if (!snapshot.hasData) {
        Fluttertoast.showToast(msg: 'No Data.');
      }
      if (snapshot.connectionState == ConnectionState.waiting) {
        return const Center(
          child: CircularProgressIndicator(),
        );
      }
      Map<String, dynamic>? data =
          snapshot.data!.data() as Map<String, dynamic>;
      return ListView(
        children: [
          const SizedBox(
            height: 10.0,
          ),
          InkWell(
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => MerchantDiscounts(
                    id: '${data['docid']}',
                  ),
                ),
              );
            },
            child: Container(
              margin: const EdgeInsets.all(10.0),
              width: 370.0,
              height: 200.0,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(10.0),
                color: Colors.black26,
              ),
              child: Stack(
                children: [
                  Container(
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(10.0),
                      color: Colors.grey,
                      image: DecorationImage(
                        image: NetworkImage(
                          data['downloadURL'],
                        ),
                        fit: BoxFit.fill,
                        colorFilter: const ColorFilter.mode(
                          Colors.black38,
                          BlendMode.darken,
                        ),
                      ),
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.fromLTRB(320, 0, 0, 0),
                    child: IconButton(
                      onPressed: () {
                        deleteDiscount(data['docid']);
                      },
                      icon: const Icon(Icons.delete_forever_rounded),
                      color: Colors.white,
                      iconSize: 35.0,
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Text(
                      '${data['productName']}',
                      style: const TextStyle(
                        fontSize: 30,
                        fontWeight: FontWeight.bold,
                        color: Colors.white,
                      ),
                    ),
                  ),
                  Center(
                    child: Text(
                      '${data['discount']}',
                      style: const TextStyle(
                        fontSize: 80,
                        fontWeight: FontWeight.bold,
                        color: Colors.white,
                      ),
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.fromLTRB(10, 160, 8, 8),
                    child: Text(
                      '${data['category']}',
                      style: const TextStyle(
                        fontSize: 30,
                        fontWeight: FontWeight.bold,
                        color: Colors.white,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      );
    },
  ),
</code>```

This is the Image of the collection in my fireabase database from which I'm trying to get data

The image of nested collection from which I'm getting 'discounts' data

I'm new to flutter and I searched and tried to apply different fixes but I'm getting this error everytime. Help would be appreciated.

答:
From your code it seems you're typecasting a nulluble type as a non-nullable type. Removing the ? after the first Map<String, dynamic>? should work. Try replacing this

```<code>Map<String, dynamic>? data = snapshot.data!.data() as Map<String, dynamic>;
</code>```

With this

```<code>var data = snapshot.data!.data() as Map<String, dynamic>;
</code>```

Body:
I'm trying to get data from a nested collection in my fireabase which is inside 'user'->'discounts' and getting image download URL from same collection in 'user'->'images' I'm trying to get is according to a specific currentUser.uid and I'm getting this cast error.

body: FutureBuilder<DocumentSnapshot>(
    future: FirebaseFirestore.instance
        .collection('user')
        .doc(currentUser!.uid)
        .collection('discounts')
        .doc(currentUser!.uid)
        .get(),
    builder: (context, snapshot) {
      if (!snapshot.hasData) {
        Fluttertoast.showToast(msg: 'No Data.');
      }
      if (snapshot.connectionState == ConnectionState.waiting) {
        return const Center(
          child: CircularProgressIndicator(),
        );
      }
      Map<String, dynamic>? data =
          snapshot.data!.data() as Map<String, dynamic>;
      return ListView(
        children: [
          const SizedBox(
            height: 10.0,
          ),
          InkWell(
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => MerchantDiscounts(
                    id: '${data['docid']}',
                  ),
                ),
              );
            },
            child: Container(
              margin: const EdgeInsets.all(10.0),
              width: 370.0,
              height: 200.0,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(10.0),
                color: Colors.black26,
              ),
              child: Stack(
                children: [
                  Container(
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(10.0),
                      color: Colors.grey,
                      image: DecorationImage(
                        image: NetworkImage(
                          data['downloadURL'],
                        ),
                        fit: BoxFit.fill,
                        colorFilter: const ColorFilter.mode(
                          Colors.black38,
                          BlendMode.darken,
                        ),
                      ),
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.fromLTRB(320, 0, 0, 0),
                    child: IconButton(
                      onPressed: () {
                        deleteDiscount(data['docid']);
                      },
                      icon: const Icon(Icons.delete_forever_rounded),
                      color: Colors.white,
                      iconSize: 35.0,
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Text(
                      '${data['productName']}',
                      style: const TextStyle(
                        fontSize: 30,
                        fontWeight: FontWeight.bold,
                        color: Colors.white,
                      ),
                    ),
                  ),
                  Center(
                    child: Text(
                      '${data['discount']}',
                      style: const TextStyle(
                        fontSize: 80,
                        fontWeight: FontWeight.bold,
                        color: Colors.white,
                      ),
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.fromLTRB(10, 160, 8, 8),
                    child: Text(
                      '${data['category']}',
                      style: const TextStyle(
                        fontSize: 30,
                        fontWeight: FontWeight.bold,
                        color: Colors.white,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      );
    },
  ),

This is the Image of the collection in my fireabase database from which I'm trying to get data

The image of nested collection from which I'm getting 'discounts' data

I'm new to flutter and I searched and tried to apply different fixes but I'm getting this error everytime. Help would be appreciated.

Body:
From your code it seems you're typecasting a nulluble type as a non-nullable type. Removing the ? after the first Map<String, dynamic>? should work. Try replacing this

Map<String, dynamic>? data = snapshot.data!.data() as Map<String, dynamic>;

With this

var data = snapshot.data!.data() as Map<String, dynamic>;


问:
How to join strings when they are not 100% equal?
I have 2 tables (From 2 tools agents use) and I need to join them a different levels: country, etc...

One of levels I need to join them is a code that indicate your role in the company.
Problem is that this code is entered in 2 different ways in in both tools but they are the same meaning.

For example, in one tool is entered as "att/m T1" and in the other tool is entered as 'att/m" so a join would not join these 2. It is not only one case, but I have different scenarios where codes are entered somehow differently.

I need to join at this field. How could I solve this issue? I tried to create Case When, but it is not scalable. Any idea how I could tackle this?

Thanks!

答:
I can build and test only with Access database SQL. Consider:

```<code>SELECT Table1.*, Table2.*
FROM Table1, Table2
WHERE (((Table1.T1) Like [Table2].[T2] & "*"));
</code>```

Or

Extract the key value from first table string.

```<code>SELECT IIf(Instr(T1," ")>0,Left([T1],InStr([T1]," ")-1), T1) AS D, F1 FROM Table1;
</code>```

Join that query to second table.

```<code>SELECT Table2.*, Query1.* FROM Query1 INNER JOIN Table2 ON Query1.D = Table2.T2;
</code>```

Consistency of structure is critical when parsing strings. Any variation will complicate the extraction.

I don't know if one approach will be faster than other with large dataset.

Body:
I can build and test only with Access database SQL. Consider:

SELECT Table1.*, Table2.*
FROM Table1, Table2
WHERE (((Table1.T1) Like [Table2].[T2] & "*"));

Or

Extract the key value from first table string.

SELECT IIf(Instr(T1," ")>0,Left([T1],InStr([T1]," ")-1), T1) AS D, F1 FROM Table1;

Join that query to second table.

SELECT Table2.*, Query1.* FROM Query1 INNER JOIN Table2 ON Query1.D = Table2.T2;

Consistency of structure is critical when parsing strings. Any variation will complicate the extraction.

I don't know if one approach will be faster than other with large dataset.


问:
What's most performant way in iOS to check if a string is one of a list of strings?
I want to see if stringA is equal to any of a list of strings -- string1, string2, string3. What's the most performant way to do the comparison?

Since my comparison list is rather small, I'm currently trying this:

```<code>- (BOOL) isStringInList:(NSString *)testString{

if ([testString caseInsensitiveCompare:@"string1"] == NSOrderedSame)
   return YES;
else if ([testString caseInsensitiveCompare:@"string2"] == NSOrderedSame)
   return YES;
else if ([testString caseInsensitiveCompare:@"string3"] == NSOrderedSame)
   return YES;

return NO;
}
</code>```

This obviously does not scale well if I have many strings to compare against. I'd prefer more of a method signature like this -(BOOL) isString:(NSString *)testString inList:(NSString *)listString where listString is a space-separated string of keywords.

Any thoughts on how to improve performance would be appreciated.

答:
The most performant way is to construct an NSSet of the strings you want to compare against and use -member: to test. Once the set is constructed, this will be a constant-time test. If you have a space-separated list to start with, you can use

```<code>NSSet *set = [NSSet setWithArray:[listOfWords componentsSeparatedByString:@" "]]
</code>```

Constructing the set will be linear on the size of the input string. If your set is the same every time, you can construct it once and hold on to the result. To do the actual test you can use

```<code>[set member:myWord]
</code>```

If the result is nil, your word isn't in the set. If it's non-nil, it is. Note, this is a case-sensitive search. If you need case-insensitivity, then you should either lowercase or uppercase both the list of words and the input word before performing your test.

Body:
I want to see if stringA is equal to any of a list of strings -- string1, string2, string3. What's the most performant way to do the comparison?

Since my comparison list is rather small, I'm currently trying this:

- (BOOL) isStringInList:(NSString *)testString{

if ([testString caseInsensitiveCompare:@"string1"] == NSOrderedSame)
   return YES;
else if ([testString caseInsensitiveCompare:@"string2"] == NSOrderedSame)
   return YES;
else if ([testString caseInsensitiveCompare:@"string3"] == NSOrderedSame)
   return YES;

return NO;
}

This obviously does not scale well if I have many strings to compare against. I'd prefer more of a method signature like this -(BOOL) isString:(NSString *)testString inList:(NSString *)listString where listString is a space-separated string of keywords.

Any thoughts on how to improve performance would be appreciated.

Body:
The most performant way is to construct an NSSet of the strings you want to compare against and use -member: to test. Once the set is constructed, this will be a constant-time test. If you have a space-separated list to start with, you can use

NSSet *set = [NSSet setWithArray:[listOfWords componentsSeparatedByString:@" "]]

Constructing the set will be linear on the size of the input string. If your set is the same every time, you can construct it once and hold on to the result. To do the actual test you can use

[set member:myWord]

If the result is nil, your word isn't in the set. If it's non-nil, it is. Note, this is a case-sensitive search. If you need case-insensitivity, then you should either lowercase or uppercase both the list of words and the input word before performing your test.


问:
Regex for names
Just starting to explore the 'wonders' of regex.  Being someone who learns from trial and error, I'm really struggling because my trials are throwing up a disproportionate amount of errors...  My experiments are in PHP using ereg().

Anyway.  I work with first and last names separately but for now using the same regex.  So far I have:

```<code>^[A-Z][a-zA-Z]+$
</code>```

Any length string that starts with a capital and has only letters (capital or not) for the rest.  But where I fall apart is dealing with the special situations that can pretty much occur anywhere.

Hyphenated Names (Worthington-Smythe)

Names with Apostophies (D'Angelo)

Names with Spaces (Van der Humpton) - capitals in the middle which may or may not be required is way beyond my interest at this stage.

Joint Names (Ben & Jerry)

Maybe there's some other way a name can be that I'm no thinking of, but I suspect if I can get my head around this, I can add to it.  I'm pretty sure there will be instances where more than one of these situations comes up in one name.

So, I think the bottom line is to have my regex also accept a space, hyphens, ampersands and apostrophes - but not at the start or end of the name to be technically correct.

答:
This is what I use for full name:

```<code>$pattern = "/^((\p{Lu}{1})\S(\p{Ll}{1,20})[^0-9])+[-'\s]((\p{Lu}{1})\S(\p{Ll}{1,20}))*[^0-9]$/u";
</code>```

Supports all languages

Common names("Jane Doe", "John Doe")

Usefull for composed names("Marie-Josée Côté-Rochon", "Bill O'reilly")

Excludes digits(0-9)

Only excepts uppercase at beginning of names

First and last names from 2-21 characters

Adding trim() to remove whitespace

Does not except("John J. William", "Francis O'reilly Jr. III")

Must use full names, not: ("John", "Jane", "O'reilly", "Smith")

Edit:
It seems that both [^0-9] in the pattern above was matching at least a fourth digit/letter in each of either first and/or last names.

Therefore names of three letters/digits could not be matched.

Here is the edited regular expression:

$pattern = "/^(\p{Lu}{1}\S\p{Ll}{1,20}[-'\s]\p{Lu}{1}\S\p{Ll}{1,20})+([^\d]+)$/u";
```

OwnerDisplayName: Humpton

ContentLicense: CC BY-SA 2.5

Title: Regex for names

Body:
Just starting to explore the 'wonders' of regex.  Being someone who learns from trial and error, I'm really struggling because my trials are throwing up a disproportionate amount of errors...  My experiments are in PHP using ereg().

Anyway.  I work with first and last names separately but for now using the same regex.  So far I have:

^[A-Z][a-zA-Z]+$

Any length string that starts with a capital and has only letters (capital or not) for the rest.  But where I fall apart is dealing with the special situations that can pretty much occur anywhere.

Hyphenated Names (Worthington-Smythe)

Names with Apostophies (D'Angelo)

Names with Spaces (Van der Humpton) - capitals in the middle which may or may not be required is way beyond my interest at this stage.

Joint Names (Ben & Jerry)

Maybe there's some other way a name can be that I'm no thinking of, but I suspect if I can get my head around this, I can add to it.  I'm pretty sure there will be instances where more than one of these situations comes up in one name.

So, I think the bottom line is to have my regex also accept a space, hyphens, ampersands and apostrophes - but not at the start or end of the name to be technically correct.

Body:
This is what I use for full name:

$pattern = "/^((\p{Lu}{1})\S(\p{Ll}{1,20})[^0-9])+[-'\s]((\p{Lu}{1})\S(\p{Ll}{1,20}))*[^0-9]$/u";

Supports all languages

Common names("Jane Doe", "John Doe")

Usefull for composed names("Marie-Josée Côté-Rochon", "Bill O'reilly")

Excludes digits(0-9)

Only excepts uppercase at beginning of names

First and last names from 2-21 characters

Adding trim() to remove whitespace

Does not except("John J. William", "Francis O'reilly Jr. III")

Must use full names, not: ("John", "Jane", "O'reilly", "Smith")

Edit:
It seems that both [^0-9] in the pattern above was matching at least a fourth digit/letter in each of either first and/or last names.

Therefore names of three letters/digits could not be matched.

Here is the edited regular expression:

$pattern = "/^(\p{Lu}{1}\S\p{Ll}{1,20}[-'\s]\p{Lu}{1}\S\p{Ll}{1,20})+([^\d]+)$/u";


问:
Get N maximum values and indices along an axis in a NumPy array
I think this is an easy question for experienced numpy users.

I have a score matrix. The raw index corresponds to samples and column index corresponds to items. For example,

```<code>score_matrix =
  [[ 1. ,  0.3,  0.4],
   [ 0.2,  0.6,  0.8],
   [ 0.1,  0.3,  0.5]]
</code>```

I want to get top-M indices of items for each samples. Also I want to get top-M scores. For example,

```<code>top2_ind =
  [[0, 2],
   [2, 1],
   [2, 1]]

top2_score =
  [[1. , 0.4],
   [0,8, 0.6],
   [0.5, 0.3]]
</code>```

What is the best way to do this using numpy?

答:
Easy way would be:

To get top-2 indices

```<code>np.argsort(-score_matrix)[:, :2]
</code>```

To get top-2 values

```<code>-np.sort(-score_matrix)[:, :2]
</code>```

Body:
I think this is an easy question for experienced numpy users.

I have a score matrix. The raw index corresponds to samples and column index corresponds to items. For example,

score_matrix =
  [[ 1. ,  0.3,  0.4],
   [ 0.2,  0.6,  0.8],
   [ 0.1,  0.3,  0.5]]

I want to get top-M indices of items for each samples. Also I want to get top-M scores. For example,

top2_ind =
  [[0, 2],
   [2, 1],
   [2, 1]]

top2_score =
  [[1. , 0.4],
   [0,8, 0.6],
   [0.5, 0.3]]

What is the best way to do this using numpy?

Body:
Easy way would be:

To get top-2 indices

np.argsort(-score_matrix)[:, :2]

To get top-2 values

-np.sort(-score_matrix)[:, :2]


问:
writeFile not woking in exceljs
i am using exceljs and try to write value in a cell but it does not working. However workbook.xlsx.readFile(filename) is working but workbook.xlsx.writeFile(filename) won't.

Here is my code:-

```<code>var Excel = require('exceljs');
var fs = require('fs')
module.exports.summary = function(req, res, next) {
try {
    var filename = process.cwd() + '/template/report/summary.xlsx';
    var workbook = new Excel.Workbook();
    workbook.xlsx.writeFile(filename)
        .then(function() {
            var worksheet = workbook.getWorksheet(1);
            console.log('worksheet',worksheet);
            var row = worksheet.getRow(5);
            row.getCell('C').value = new Date();
            row.commit();
            worksheet.commit();

            workbook.commit().then(function() {
                console.log('xls file is written.');
            });
            res.json({ msg: done })
        });

 } catch (e) {
    next(e);
 }
}
</code>```

答: In my case i have name like "data2022/2023" the main problem is "/" when i remove the slash "data2020" its work. Dunno why cant use unicoden"/"</p>

Title: writeFile not woking in exceljs

Body:
i am using exceljs and try to write value in a cell but it does not working. However workbook.xlsx.readFile(filename) is working but workbook.xlsx.writeFile(filename) won't.

Here is my code:-

var Excel = require('exceljs');
var fs = require('fs')
module.exports.summary = function(req, res, next) {
try {
    var filename = process.cwd() + '/template/report/summary.xlsx';
    var workbook = new Excel.Workbook();
    workbook.xlsx.writeFile(filename)
        .then(function() {
            var worksheet = workbook.getWorksheet(1);
            console.log('worksheet',worksheet);
            var row = worksheet.getRow(5);
            row.getCell('C').value = new Date();
            row.commit();
            worksheet.commit();

            workbook.commit().then(function() {
                console.log('xls file is written.');
            });
            res.json({ msg: done })
        });

 } catch (e) {
    next(e);
 }
}