问:
Tui-rs: flickering when drawing multiple widgets
Good evening!

I'm trying to write a very simple terminal application that draws two textboxes on screen, accepting input on one and showing output on the other, using Rust and tui-rs. The first part works perfectly, but my problems arose when i tried to draw two blocks at the same time: for some reason, it only shows the second block (in order of drawing) and if i move my mouse, it flickers between the two in a weird way. My best guess is that this is due to my drawing implementation, which somehow "clears" the screen whenever it needs to draw something, but if that's the case, i couldn't find any doc on it, and i wouldn't know how to go about working around this. I've provided some code that should be enough to replicate the issue on a smaller scale.

```<code>#![allow(unused_imports)]
#![allow(unused_variables)]

use crossterm::{
    event::{self, DisableMouseCapture, EnableMouseCapture, Event},
    execute,
    terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use std::io
use tui::{
    backend::CrosstermBackend,
    layout::Rect,
    widgets::{Block, Borders},
    Terminal,
};

struct FirstStruct {}

impl FirstStruct {
    pub fn draw(&self, term: &mut Terminal<CrosstermBackend<io::Stdout>>) -> io::Result<()> {
        term.draw(|f| {
            let size = f.size();
            let (w, h) = (size.width / 2, size.height);
            let (x, y) = (size.x, size.y);
            let rect = Rect::new(x, y, w, h);
            let block = Block::default()
                .title("One")
                .borders(Borders::ALL);

            f.render_widget(block, rect)
        })?;

        Ok(())
    }
}

struct SecondStruct {  }

impl SecondStruct {
    pub fn draw(&self, term: &mut Terminal<CrosstermBackend<io::Stdout>>) -> io::Result<()> {
        term.draw(|f| {
            let size = f.size();
            let (w, h) = (size.width / 2, size.height);
            let (x, y) = (size.x + w, size.y);
            let rect = Rect::new(x, y, w, h);
            let block = Block::default()
                .title("Two")
                .borders(Borders::ALL);

            f.render_widget(block, rect)
        })?;
        Ok(())
    }
}

fn main() -> io::Result<()>{
    enable_raw_mode()?;
    let mut stdout = io::stdout();
    execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::new(backend)?;

    let first = FirstStruct {};
    let second = SecondStruct {};
    let mut running = true;

    while running {
        if let Event::Key(key) = event::read()? {
            running = false;
        }
        second.draw(&mut terminal)?;
        first.draw(&mut terminal)?;
    }

    disable_raw_mode()?;
    execute!(
        terminal.backend_mut(),
        LeaveAlternateScreen,
        DisableMouseCapture
    )?;
    terminal.show_cursor()?;

    Ok(())
}

</code>```

Does anybody know how i can fix this issue? Thanks in advance!!

答:
Every time you call Terminal::draw(), you must draw everything that you want to be visible at once. Instead of passing Terminal to your own draw functions, pass the Frame that you get from Terminal::draw(). That is, replace

second.draw(&mut terminal)?;
first.draw(&mut terminal)?;
```
<p>with</p>
<pre class="lang-rust prettyprint-override"><code>terminal.draw(|f| {
    first.draw(f)?;
    second.draw(f)?;
});
</code>```

and change the signature of FirstStruct and SecondStruct to match.

Also, it would be more usual to, instead of computing the rectangle for each widget in the individual functions, decide at the top level (using Layout, perhaps) and pass Rects down to the drawing functions. That way, they can be positioned differently in different situations. What you have will work, but it's not as easy to change.

Layout code from the documentation's example, adjusted to your situation:

terminal.draw(|f| {
    let chunks = Layout::default()
        .direction(Direction::Horizontal)
        .constraints(
            [
                Constraint::Percentage(50),
                Constraint::Percentage(50),
            ].as_ref()
        )
        .split(f.size());
    first.draw(f, chunks[0])?;
    second.draw(f, chunks[1])?;
});
```

Body:
Good evening!

I'm trying to write a very simple terminal application that draws two textboxes on screen, accepting input on one and showing output on the other, using Rust and tui-rs. The first part works perfectly, but my problems arose when i tried to draw two blocks at the same time: for some reason, it only shows the second block (in order of drawing) and if i move my mouse, it flickers between the two in a weird way. My best guess is that this is due to my drawing implementation, which somehow "clears" the screen whenever it needs to draw something, but if that's the case, i couldn't find any doc on it, and i wouldn't know how to go about working around this. I've provided some code that should be enough to replicate the issue on a smaller scale.

#![allow(unused_imports)]
#![allow(unused_variables)]

use crossterm::{
    event::{self, DisableMouseCapture, EnableMouseCapture, Event},
    execute,
    terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use std::io
use tui::{
    backend::CrosstermBackend,
    layout::Rect,
    widgets::{Block, Borders},
    Terminal,
};

struct FirstStruct {}

impl FirstStruct {
    pub fn draw(&self, term: &mut Terminal<CrosstermBackend<io::Stdout>>) -> io::Result<()> {
        term.draw(|f| {
            let size = f.size();
            let (w, h) = (size.width / 2, size.height);
            let (x, y) = (size.x, size.y);
            let rect = Rect::new(x, y, w, h);
            let block = Block::default()
                .title("One")
                .borders(Borders::ALL);

            f.render_widget(block, rect)
        })?;

        Ok(())
    }
}

struct SecondStruct {  }

impl SecondStruct {
    pub fn draw(&self, term: &mut Terminal<CrosstermBackend<io::Stdout>>) -> io::Result<()> {
        term.draw(|f| {
            let size = f.size();
            let (w, h) = (size.width / 2, size.height);
            let (x, y) = (size.x + w, size.y);
            let rect = Rect::new(x, y, w, h);
            let block = Block::default()
                .title("Two")
                .borders(Borders::ALL);

            f.render_widget(block, rect)
        })?;
        Ok(())
    }
}

fn main() -> io::Result<()>{
    enable_raw_mode()?;
    let mut stdout = io::stdout();
    execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::new(backend)?;

    let first = FirstStruct {};
    let second = SecondStruct {};
    let mut running = true;

    while running {
        if let Event::Key(key) = event::read()? {
            running = false;
        }
        second.draw(&mut terminal)?;
        first.draw(&mut terminal)?;
    }

    disable_raw_mode()?;
    execute!(
        terminal.backend_mut(),
        LeaveAlternateScreen,
        DisableMouseCapture
    )?;
    terminal.show_cursor()?;

    Ok(())
}

Does anybody know how i can fix this issue? Thanks in advance!!

Body:
Every time you call Terminal::draw(), you must draw everything that you want to be visible at once. Instead of passing Terminal to your own draw functions, pass the Frame that you get from Terminal::draw(). That is, replace

second.draw(&mut terminal)?;
first.draw(&mut terminal)?;

with

terminal.draw(|f| {
    first.draw(f)?;
    second.draw(f)?;
});

and change the signature of FirstStruct and SecondStruct to match.

Also, it would be more usual to, instead of computing the rectangle for each widget in the individual functions, decide at the top level (using Layout, perhaps) and pass Rects down to the drawing functions. That way, they can be positioned differently in different situations. What you have will work, but it's not as easy to change.

Layout code from the documentation's example, adjusted to your situation:

terminal.draw(|f| {
    let chunks = Layout::default()
        .direction(Direction::Horizontal)
        .constraints(
            [
                Constraint::Percentage(50),
                Constraint::Percentage(50),
            ].as_ref()
        )
        .split(f.size());
    first.draw(f, chunks[0])?;
    second.draw(f, chunks[1])?;
});


来源: stackexchange

问:
How to delete duplicates within a large database on a column by column basis
I have a large set of data (over 3000 columns) for work, with text in every cell. Each column is unrelated to each other. Within each column there are potentially duplicates and I need to keep only the first instance , but there is no way to highlight the cells with duplicates on a column by column basis as when the whole data set is highlighted excel treats the rows as related data and looks for duplicates on a row by row basis. I have tried using macros (I am a total novice) but the macros don't work.

Image shows the columns of data with some duplicates in the columns.

答:
If you use the modern Excel, you could use the UNIQUE function, which returns the array of unique elements.

Just duplicate the sheet and in the copy delete everything below the lines with "Processor 1" and "Processor 2". Then in the first column use UNIQUE referring to the first respective column of the original sheet.

Just fill the formula right (Ctrl + R) and in the new sheet each column will have only the unique elements.

You can then paste the whole resulting table as values and delete the original one.

ContentLicense: CC BY-SA 4.0


问:
Locate a vehicle using RSSI under veins framework
Using the veins framework and the Omnet++ simulator, how do I get the RSSI value (RSU side) from the message sent from a vehicle? I need to locate this vehicle using this RSSI value.

How to send multiple messages from the same vehicle simultaneously? Thanks in advance.

答:
How do I get the RSSI value (RSU side) from the message sent from a vehicle?
Answer: Check: https://stackoverflow.com/a/54594801/7215379
has a similar Q & A.

How to send multiple messages from the same vehicle simultaneously?
Answer: Are you talking about sending multiple copies of the same message or sending message of different type.


问:
PHPickerViewController tapping on Search gets error... "Unable to load photos"
I'm trying to implement a PHPickerViewController using SwiftUI and The Composable Architecture. (Not that I think that's particularly relevant but it might explain why some of my code is like it is).

Sample project

I've been playing around with this to try and work it out. I created a little sample Project on GitHub which removes The Composable Architecture and keeps the UI super simple.

https://github.com/oliverfoggin/BrokenImagePickers/tree/main

It looks like iOS 15 is breaking on both the UIImagePickerViewController and the PHPickerViewController. (Which makes sense as they both use the same UI under the hood).

I guess the nest step is to determine if the same error occurs when using them in a UIKit app.

My code

My code is fairly straight forward. It's pretty much just a reimplementation of the same feature that uses UIImagePickerViewController but I wanted to try with the newer APIs.

My code looks like this...

```<code>public struct ImagePicker: UIViewControllerRepresentable {

// Vars and setup stuff...
  @Environment(\.presentationMode) var presentationMode

  let viewStore: ViewStore<ImagePickerState, ImagePickerAction>

  public init(store: Store<ImagePickerState, ImagePickerAction>) {
    self.viewStore = ViewStore(store)
  }

// UIViewControllerRepresentable required functions
  public func makeUIViewController(context: UIViewControllerRepresentableContext<ImagePicker>) -> some UIViewController {

    // Configuring the PHPickerViewController
    var config = PHPickerConfiguration()
    config.filter = PHPickerFilter.images

    let picker = PHPickerViewController(configuration: config)
    picker.delegate = context.coordinator
    return picker
  }

  public func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {}

  public func makeCoordinator() -> Coordinator {
    Coordinator(self)
  }

// This is the coordinator that acts as the delegate
  public class Coordinator: PHPickerViewControllerDelegate {
    let parent: ImagePicker

    init(_ parent: ImagePicker) {
      self.parent = parent
    }

    public func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
      picker.dismiss(animated: true)

      guard let itemProvider = results.first?.itemProvider,
        itemProvider.canLoadObject(ofClass: UIImage.self) else {
        return
      }

      itemProvider.loadObject(ofClass: UIImage.self) { [weak self] image, error in
        if let image = image as? UIImage {
          DispatchQueue.main.async {
            self?.parent.viewStore.send(.imagePicked(image: image))
          }
        }
      }
    }
  }
}
</code>```

All this works in the simple case

I can present the ImagePicker view and select a photo and it's all fine. I can cancel out of it ok. I can even scroll down the huge collection view of images that I have. I can even see the new image appear in my state object and display it within my app. (Note... this is still WIP and so the code is a bit clunky but that's only to get it working initially).

The problem case

The problem is that when I tap on the search bar in the PHPickerView (which is a search bar provided by Apple in the control, I didn't create it or code it). It seems to start to slide up the keyboard and then the view goes blank with a single message in the middle...

Unable to Load Photos

[Try Again]

I also get a strange looking error log. (I removed the time stamps to shorten the lines).

```<code>// These happen on immediately presenting the ImagePicker
AppName[587:30596] [Picker] Showing picker unavailable UI (reason: still loading) with error: (null)
AppName[587:30596] Writing analzed variants.

// These happen when tapping the search bar
AppName[587:30867] [lifecycle] [u A95D90FC-C77B-43CC-8FC6-C8E7C81DD22A:m (null)] [com.apple.mobileslideshow.photospicker(1.0)] Connection to plugin interrupted while in use.
AppName[587:31002] [lifecycle] [u A95D90FC-C77B-43CC-8FC6-C8E7C81DD22A:m (null)] [com.apple.mobileslideshow.photospicker(1.0)] Connection to plugin invalidated while in use.
AppName[587:30596] [Picker] Showing picker unavailable UI (reason: crashed) with error: (null)
AppName[587:30596] viewServiceDidTerminateWithError:: Error Domain=_UIViewServiceInterfaceErrorDomain Code=3 "(null)" UserInfo={Message=Service Connection Interrupted}
</code>```

Tapping the "Try Again" button reloads the initial scroll screen and I can carry on using it. But tapping the search bar again just shows the same error.

I'm usually the first one to point out that the error is almost definitely not with the Apple APIs but I'm stumped on this one. I'm not sure what it is that I'm doing that is causing this to happen?

Is it the fact that it's in a SwiftUI view?

Recreated the project in UIKit

I remade the same project using UIKit... https://github.com/oliverfoggin/UIKit-Image-Pickers

And I couldn't replicate the crash at all.

Also... if you are taking any sort of screen recording of the device the crash will not happen. I tried taking a recording on the device itself and couldn't replicate it. I also tried doing a movie recording from my Mac using the iPhone screen and couldn't replicate the crash. But... the instant I stopped the recording on QuickTime the crash was replicable again.

答:
This fixed it for me .ignoreSafeArea(.keyboard) like @Frustrated_Student mentions.

To elaborate on @Frustrated_Student this issue has to do with the UIViewControllerRepresentable treating the view like many SwiftUI views to automatically avoid the keyboard. If you are presenting the picker using a sheet as I am then you can simply add the .ignoreSafeArea(.keyboard) to the UIViewControllerRepresentable view in my case I called it ImagePicker here is a better example.

Where to add it the .ignoreSafeArea(.keyboard)

.sheet(isPresented: $imagePicker) {
    ImagePicker(store: store)
        .ignoresSafeArea(.keyboard)
}
```
<h3>This is @Fogmeister code:</h3>
<pre class="lang-swift prettyprint-override"><code>public struct ImagePicker: UIViewControllerRepresentable {

// Vars and setup stuff...
  @Environment(\.presentationMode) var presentationMode

  let viewStore: ViewStore<ImagePickerState, ImagePickerAction>

  public init(store: Store<ImagePickerState, ImagePickerAction>) {
    self.viewStore = ViewStore(store)
  }

// UIViewControllerRepresentable required functions
  public func makeUIViewController(context: UIViewControllerRepresentableContext<ImagePicker>) -> some UIViewController {

    // Configuring the PHPickerViewController
    var config = PHPickerConfiguration()
    config.filter = PHPickerFilter.images

    let picker = PHPickerViewController(configuration: config)
    picker.delegate = context.coordinator
    return picker
  }

  public func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {}

  public func makeCoordinator() -> Coordinator {
    Coordinator(self)
  }

// This is the coordinator that acts as the delegate
  public class Coordinator: PHPickerViewControllerDelegate {
    let parent: ImagePicker

    init(_ parent: ImagePicker) {
      self.parent = parent
    }

    public func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
      picker.dismiss(animated: true)

      guard let itemProvider = results.first?.itemProvider,
        itemProvider.canLoadObject(ofClass: UIImage.self) else {
        return
      }

      itemProvider.loadObject(ofClass: UIImage.self) { [weak self] image, error in
        if let image = image as? UIImage {
          DispatchQueue.main.async {
            self?.parent.viewStore.send(.imagePicked(image: image))
          }
        }
      }
    }
  }
}
</code>```

Body:
I'm trying to implement a PHPickerViewController using SwiftUI and The Composable Architecture. (Not that I think that's particularly relevant but it might explain why some of my code is like it is).

Sample project

I've been playing around with this to try and work it out. I created a little sample Project on GitHub which removes The Composable Architecture and keeps the UI super simple.

https://github.com/oliverfoggin/BrokenImagePickers/tree/main

It looks like iOS 15 is breaking on both the UIImagePickerViewController and the PHPickerViewController. (Which makes sense as they both use the same UI under the hood).

I guess the nest step is to determine if the same error occurs when using them in a UIKit app.

My code

My code is fairly straight forward. It's pretty much just a reimplementation of the same feature that uses UIImagePickerViewController but I wanted to try with the newer APIs.

My code looks like this...

public struct ImagePicker: UIViewControllerRepresentable {

// Vars and setup stuff...
  @Environment(\.presentationMode) var presentationMode

  let viewStore: ViewStore<ImagePickerState, ImagePickerAction>

  public init(store: Store<ImagePickerState, ImagePickerAction>) {
    self.viewStore = ViewStore(store)
  }

// UIViewControllerRepresentable required functions
  public func makeUIViewController(context: UIViewControllerRepresentableContext<ImagePicker>) -> some UIViewController {

    // Configuring the PHPickerViewController
    var config = PHPickerConfiguration()
    config.filter = PHPickerFilter.images

    let picker = PHPickerViewController(configuration: config)
    picker.delegate = context.coordinator
    return picker
  }

  public func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {}

  public func makeCoordinator() -> Coordinator {
    Coordinator(self)
  }

// This is the coordinator that acts as the delegate
  public class Coordinator: PHPickerViewControllerDelegate {
    let parent: ImagePicker

    init(_ parent: ImagePicker) {
      self.parent = parent
    }

    public func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
      picker.dismiss(animated: true)

      guard let itemProvider = results.first?.itemProvider,
        itemProvider.canLoadObject(ofClass: UIImage.self) else {
        return
      }

      itemProvider.loadObject(ofClass: UIImage.self) { [weak self] image, error in
        if let image = image as? UIImage {
          DispatchQueue.main.async {
            self?.parent.viewStore.send(.imagePicked(image: image))
          }
        }
      }
    }
  }
}

All this works in the simple case

I can present the ImagePicker view and select a photo and it's all fine. I can cancel out of it ok. I can even scroll down the huge collection view of images that I have. I can even see the new image appear in my state object and display it within my app. (Note... this is still WIP and so the code is a bit clunky but that's only to get it working initially).

The problem case

The problem is that when I tap on the search bar in the PHPickerView (which is a search bar provided by Apple in the control, I didn't create it or code it). It seems to start to slide up the keyboard and then the view goes blank with a single message in the middle...

Unable to Load Photos

[Try Again]

I also get a strange looking error log. (I removed the time stamps to shorten the lines).

// These happen on immediately presenting the ImagePicker
AppName[587:30596] [Picker] Showing picker unavailable UI (reason: still loading) with error: (null)
AppName[587:30596] Writing analzed variants.

// These happen when tapping the search bar
AppName[587:30867] [lifecycle] [u A95D90FC-C77B-43CC-8FC6-C8E7C81DD22A:m (null)] [com.apple.mobileslideshow.photospicker(1.0)] Connection to plugin interrupted while in use.
AppName[587:31002] [lifecycle] [u A95D90FC-C77B-43CC-8FC6-C8E7C81DD22A:m (null)] [com.apple.mobileslideshow.photospicker(1.0)] Connection to plugin invalidated while in use.
AppName[587:30596] [Picker] Showing picker unavailable UI (reason: crashed) with error: (null)
AppName[587:30596] viewServiceDidTerminateWithError:: Error Domain=_UIViewServiceInterfaceErrorDomain Code=3 "(null)" UserInfo={Message=Service Connection Interrupted}

Tapping the "Try Again" button reloads the initial scroll screen and I can carry on using it. But tapping the search bar again just shows the same error.

I'm usually the first one to point out that the error is almost definitely not with the Apple APIs but I'm stumped on this one. I'm not sure what it is that I'm doing that is causing this to happen?

Is it the fact that it's in a SwiftUI view?

Recreated the project in UIKit

I remade the same project using UIKit... https://github.com/oliverfoggin/UIKit-Image-Pickers

And I couldn't replicate the crash at all.

Also... if you are taking any sort of screen recording of the device the crash will not happen. I tried taking a recording on the device itself and couldn't replicate it. I also tried doing a movie recording from my Mac using the iPhone screen and couldn't replicate the crash. But... the instant I stopped the recording on QuickTime the crash was replicable again.

Body:
This fixed it for me .ignoreSafeArea(.keyboard) like @Frustrated_Student mentions.

To elaborate on @Frustrated_Student this issue has to do with the UIViewControllerRepresentable treating the view like many SwiftUI views to automatically avoid the keyboard. If you are presenting the picker using a sheet as I am then you can simply add the .ignoreSafeArea(.keyboard) to the UIViewControllerRepresentable view in my case I called it ImagePicker here is a better example.

Where to add it the .ignoreSafeArea(.keyboard)

.sheet(isPresented: $imagePicker) {
    ImagePicker(store: store)
        .ignoresSafeArea(.keyboard)
}

This is @Fogmeister code:

public struct ImagePicker: UIViewControllerRepresentable {

// Vars and setup stuff...
  @Environment(\.presentationMode) var presentationMode

  let viewStore: ViewStore<ImagePickerState, ImagePickerAction>

  public init(store: Store<ImagePickerState, ImagePickerAction>) {
    self.viewStore = ViewStore(store)
  }

// UIViewControllerRepresentable required functions
  public func makeUIViewController(context: UIViewControllerRepresentableContext<ImagePicker>) -> some UIViewController {

    // Configuring the PHPickerViewController
    var config = PHPickerConfiguration()
    config.filter = PHPickerFilter.images

    let picker = PHPickerViewController(configuration: config)
    picker.delegate = context.coordinator
    return picker
  }

  public func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {}

  public func makeCoordinator() -> Coordinator {
    Coordinator(self)
  }

// This is the coordinator that acts as the delegate
  public class Coordinator: PHPickerViewControllerDelegate {
    let parent: ImagePicker

    init(_ parent: ImagePicker) {
      self.parent = parent
    }

    public func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
      picker.dismiss(animated: true)

      guard let itemProvider = results.first?.itemProvider,
        itemProvider.canLoadObject(ofClass: UIImage.self) else {
        return
      }

      itemProvider.loadObject(ofClass: UIImage.self) { [weak self] image, error in
        if let image = image as? UIImage {
          DispatchQueue.main.async {
            self?.parent.viewStore.send(.imagePicked(image: image))
          }
        }
      }
    }
  }
}


问:
custom sort using linq based on Ranks
I am trying to sort data in a table based on Ranks. Not sure how to achieve this in linq's

Input Table:

Rank Table:

Based on the Input & Rank table, I am expecting the output as below:

答:
Assuming your classes look like this:

```<code>public class CodeRank{
  public CodeRank(string code, int rank){
    this.Code = code;
    this.Rank = rank;
  }

  public string Code {get;set;}
  public int Rank {get;set;}
}

public class StateCode{
  public StateCode(string state, string code){
    this.State = state;
    this.Code = code;
  }
  public string State {get;set;}
  public string Code {get;set;}

}
</code>```

You could use the below query.  If all codes have a rank, you could put the rank table into a dictionary and use it to find the rank instead of searching for it each iteration.

```<code>var result = stateCodes.Select(stateCode => new {State = stateCode.State, Code = stateCode.Code, Rank = ranks.SingleOrDefault(y => y.Code == stateCode.Code)?.Rank ?? 100})
        .OrderBy(x => x.Rank)
        .Select(x => new StateCode(x.State, x.Code))
        .ToList();

</code>```

Title: custom sort using linq based on Ranks

Body:
Assuming your classes look like this:

public class CodeRank{
  public CodeRank(string code, int rank){
    this.Code = code;
    this.Rank = rank;
  }

  public string Code {get;set;}
  public int Rank {get;set;}
}

public class StateCode{
  public StateCode(string state, string code){
    this.State = state;
    this.Code = code;
  }
  public string State {get;set;}
  public string Code {get;set;}

}

You could use the below query.  If all codes have a rank, you could put the rank table into a dictionary and use it to find the rank instead of searching for it each iteration.

var result = stateCodes.Select(stateCode => new {State = stateCode.State, Code = stateCode.Code, Rank = ranks.SingleOrDefault(y => y.Code == stateCode.Code)?.Rank ?? 100})
        .OrderBy(x => x.Rank)
        .Select(x => new StateCode(x.State, x.Code))
        .ToList();


问:
Why this upper column dataframe function doesn't work?
I want to create a function to upper columns, I already try this:

```<code>def upperColumn(DataframeColumn):
  DataframeColumn = DataframeColumn.str.upper()

upperColumn(df['ANYTHING'])

</code>```

I need this to be the same as:

```<code>df['ANYTHING'] = df['ANYTHING'].str.upper()
</code>```

obs. Pandas is imported and the dataframe is created already.

Thank you in advance.

答:
You can't quite do this because DataframeColumn a parameter to the function, so it's basically a variable local to the function. Therefore, when you overwrite it inside the function, it won't actually change the column's value.

Instead, you can pass the dataframe and the column name as separate parameters:

```<code>def upperColumn(Dataframe, Column):
  Dataframe[Column] = Dataframe[Column].str.upper()

upperColumn(df, 'ANYTHING')
</code>```

Body:
I want to create a function to upper columns, I already try this:

def upperColumn(DataframeColumn):
  DataframeColumn = DataframeColumn.str.upper()

upperColumn(df['ANYTHING'])

I need this to be the same as:

df['ANYTHING'] = df['ANYTHING'].str.upper()

obs. Pandas is imported and the dataframe is created already.

Thank you in advance.

Body:
You can't quite do this because DataframeColumn a parameter to the function, so it's basically a variable local to the function. Therefore, when you overwrite it inside the function, it won't actually change the column's value.

Instead, you can pass the dataframe and the column name as separate parameters:

def upperColumn(Dataframe, Column):
  Dataframe[Column] = Dataframe[Column].str.upper()

upperColumn(df, 'ANYTHING')


问:
ResourceInitializationError: failed to validate logger args: : signal: killed
Suddenly getting the message " ResourceInitializationError: failed to validate logger args: : signal: killed" while starting AWS ECS Fargate Service. Same service was running fine couple of days back.

Following is log driver configurations in related aws task:

Log Configuration

Log driver: awslogs

Key                       Value

awslogs-group           /ecs/analytics

awslogs-region          us-east-1

awslogs-stream-prefix   ecs

Any idea or help?

答:
I just experienced this. I have ECS Fargate running and I've just added a VPC endpoint for Cloudwatch Logs com.amazonaws.REGION.logs in my account. When I added the VPC endpoint my logs stopped appearing.

In order to remedy this without deleting the VPC endpoint again, for my setup with Fargate running with internet access I had to ensure that:

My ECS service had a security group rule that to allows HTTPS traffic outbound

```<code>{
   type: egress
   port_to: 443
   port_from: 443
   protocol: TCP
}
</code>```

That my new VPC Endpoint had a security group rule to allow HTTPS traffic inbound from my ECS security group

```<code>{
   type: ingress
   port_to: 443
   port_from: 443
   protocol: TCP
   source_security_group_id: [Your ECS SECURITY GROUP ID]
}
</code>```

Body:
I just experienced this. I have ECS Fargate running and I've just added a VPC endpoint for Cloudwatch Logs com.amazonaws.REGION.logs in my account. When I added the VPC endpoint my logs stopped appearing.

In order to remedy this without deleting the VPC endpoint again, for my setup with Fargate running with internet access I had to ensure that:

My ECS service had a security group rule that to allows HTTPS traffic outbound

{
   type: egress
   port_to: 443
   port_from: 443
   protocol: TCP
}

That my new VPC Endpoint had a security group rule to allow HTTPS traffic inbound from my ECS security group

{
   type: ingress
   port_to: 443
   port_from: 443
   protocol: TCP
   source_security_group_id: [Your ECS SECURITY GROUP ID]
}


问:
Pyspark Streaming with Pandas UDF
I am new to Spark Streaming and Pandas UDF. I am working on pyspark consumer from kafka, payload is of xml format and trying to parse the incoming xml by applying pandas udf

```<code>@pandas_udf("col1 string, col2 string",PandasUDFType.GROUPED_MAP)
def test_udf(df):
    import xmltodict
    from collections import MutableMapping
    xml_str=df.iloc[0,0]
    df_col=['col1', 'col2']
    doc=xmltodict.parse(xml_str,dict_constructor=dict)
    extract_needed_fields = { k:doc[k] for k in df_col }
    return pd.DataFrame( [{'col1': 'abc', 'col2': 'def'}] , index=[0] , dtype="string" )

data=df.selectExpr("CAST(value AS STRING) AS value")
data.groupby("value").apply(test_udf).writeStream.format("console").start()

</code>```

I get the below error

```<code>  File "pyarrow/array.pxi", line 859, in pyarrow.lib.Array.from_pandas
  File "pyarrow/array.pxi", line 215, in pyarrow.lib.array
  File "pyarrow/array.pxi", line 104, in pyarrow.lib._handle_arrow_array_protocol
ValueError: Cannot specify a mask or a size when passing an object that is converted with the __arrow_array__ protocol.

</code>```

Is this the right approach ? What am i doing wrong

答:
While converting a pandas dataframe to a pyspark one, I stumbled upon this error as well :

```<code>Cannot specify a mask or a size when passing an object that is converted with the __arrow_array__ protocol
</code>```

My pandas dataframe had datetime-like values that I tried to convert to "string". I initially used the astype("string") method, which looked like this :

df["time"] = (df["datetime"].dt.time).astype("string")
```
<p>When I tried to get the info of this dataframe, it seemed like it was indeed converted to a string type :</p>
<pre class="lang-py prettyprint-override"><code>df.info(verbose=True)
> ...
>  #   Column    Non-Null Count   Dtype
> ...
>  6   time      295452 non-null  string
</code>```

But the error kept coming back to me.

Solution

To avoid it, I instead went on to use the apply(str) method :

df["time"] = (df["datetime"].dt.time).apply(str)
```
<p>Which gave me a type of <code>object</code></p>
<pre class="lang-py prettyprint-override"><code>df.info(verbose=True)
> ...
>  #   Column    Non-Null Count   Dtype
> ...
>  6   time      295452 non-null  object
</code>```

After that, the conversion was successful

spark.createDataFrame(df)
# DataFrame[datetime: string, date: string, year: bigint, month: bigint, day: bigint, day_name: string, time: string, hour: bigint, minute: bigint]
```

Title: Pyspark Streaming with Pandas UDF

Body:
I am new to Spark Streaming and Pandas UDF. I am working on pyspark consumer from kafka, payload is of xml format and trying to parse the incoming xml by applying pandas udf

@pandas_udf("col1 string, col2 string",PandasUDFType.GROUPED_MAP)
def test_udf(df):
    import xmltodict
    from collections import MutableMapping
    xml_str=df.iloc[0,0]
    df_col=['col1', 'col2']
    doc=xmltodict.parse(xml_str,dict_constructor=dict)
    extract_needed_fields = { k:doc[k] for k in df_col }
    return pd.DataFrame( [{'col1': 'abc', 'col2': 'def'}] , index=[0] , dtype="string" )

data=df.selectExpr("CAST(value AS STRING) AS value")
data.groupby("value").apply(test_udf).writeStream.format("console").start()

I get the below error

  File "pyarrow/array.pxi", line 859, in pyarrow.lib.Array.from_pandas
  File "pyarrow/array.pxi", line 215, in pyarrow.lib.array
  File "pyarrow/array.pxi", line 104, in pyarrow.lib._handle_arrow_array_protocol
ValueError: Cannot specify a mask or a size when passing an object that is converted with the __arrow_array__ protocol.

Is this the right approach ? What am i doing wrong

Body:
While converting a pandas dataframe to a pyspark one, I stumbled upon this error as well :

Cannot specify a mask or a size when passing an object that is converted with the __arrow_array__ protocol

My pandas dataframe had datetime-like values that I tried to convert to "string". I initially used the astype("string") method, which looked like this :

df["time"] = (df["datetime"].dt.time).astype("string")

When I tried to get the info of this dataframe, it seemed like it was indeed converted to a string type :

df.info(verbose=True)
> ...
>  #   Column    Non-Null Count   Dtype
> ...
>  6   time      295452 non-null  string

But the error kept coming back to me.

Solution

To avoid it, I instead went on to use the apply(str) method :

df["time"] = (df["datetime"].dt.time).apply(str)

Which gave me a type of object

df.info(verbose=True)
> ...
>  #   Column    Non-Null Count   Dtype
> ...
>  6   time      295452 non-null  object

After that, the conversion was successful

spark.createDataFrame(df)
# DataFrame[datetime: string, date: string, year: bigint, month: bigint, day: bigint, day_name: string, time: string, hour: bigint, minute: bigint]


问:
Implications of using NetHttpTransport() over GoogleNetHttpTransport.newTrustedTransport()
I'm using google-api-services-admin-directory in a project, and the docs recommend using GoogleNetHttpTransport.newTrustedTransport() as the HTTP transport, but I kept getting certificate errors that I think were cause by my proxy. I switched over to new NetHttpTransport() instead, and everything now works fine, but I just want to make sure I'm not compromising on security by doing so.

Any thoughts?

Thanks,
Rhys

答:
Hope you don't mind the late reply. I was having the same issue and did some research.

According to the Java Docs of Google API the GoogleNetHttpTransport.newTrustedTransport() takes into account website certificates to use for Google APIs. However:

This helper method doesn't provide for customization of the NetHttpTransport, such as the ability to specify a proxy.

This confirms what you were saying about the certificates errors you are getting being caused by your proxy.

It is recommended, security wise, that instead of new NetHttpTransport() to use the  NetHttpTransport.Builder in order to get a Trusted Transport for a specified proxy, as show on the link's example:

```<code> static HttpTransport newProxyTransport() throws GeneralSecurityException, IOException {
   NetHttpTransport.Builder builder = new NetHttpTransport.Builder();
   builder.trustCertificates(GoogleUtils.getCertificateTrustStore());
   builder.setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 3128)));
   return builder.build();
 }
</code>```

Body:
Hope you don't mind the late reply. I was having the same issue and did some research.

According to the Java Docs of Google API the GoogleNetHttpTransport.newTrustedTransport() takes into account website certificates to use for Google APIs. However:

This helper method doesn't provide for customization of the NetHttpTransport, such as the ability to specify a proxy.

This confirms what you were saying about the certificates errors you are getting being caused by your proxy.

It is recommended, security wise, that instead of new NetHttpTransport() to use the  NetHttpTransport.Builder in order to get a Trusted Transport for a specified proxy, as show on the link's example:

 static HttpTransport newProxyTransport() throws GeneralSecurityException, IOException {
   NetHttpTransport.Builder builder = new NetHttpTransport.Builder();
   builder.trustCertificates(GoogleUtils.getCertificateTrustStore());
   builder.setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 3128)));
   return builder.build();
 }


问:
How do I constraint a view to the center of another view in android studio?
```<code><androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
    <Button
        android:id="@+id/open_explanation_button"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:background="@drawable/open_dialog"
        app:layout_constraintEnd_toEndOf="parent"
        />
    <TextView
        android:id="@+id/movieRatingText"
        android:layout_width="match_parent"
        android:layout_height="30dp"
        android:gravity="center"
        android:layout_weight="53"
        android:text="Rating: R"
        android:textColor="@color/white"
        android:textSize="20sp"
        app:autoSizeMaxTextSize="100sp"
        app:autoSizeMinTextSize="12sp"
        app:autoSizeStepGranularity="2sp"
        app:autoSizeTextType="uniform"
        app:layout_constraintTop_toBottomOf="@+id/inASeriesOrNoText"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        />
</code>```

I have a button with an id of open_explanation_button, I need to place that button to the end of the movieRatingText. The problem is that I need the movieRatingText to be with a width of match_parent to make sure that it's an autoresizable text. In a more simpler way, I need to constraint the start of the open_explanation_button to the center of the movieRatingText, in addition to adding some margins.
Any help?

答: You have to constraint end and start of your view, to its parent</p>

Body:
<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
    <Button
        android:id="@+id/open_explanation_button"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:background="@drawable/open_dialog"
        app:layout_constraintEnd_toEndOf="parent"
        />
    <TextView
        android:id="@+id/movieRatingText"
        android:layout_width="match_parent"
        android:layout_height="30dp"
        android:gravity="center"
        android:layout_weight="53"
        android:text="Rating: R"
        android:textColor="@color/white"
        android:textSize="20sp"
        app:autoSizeMaxTextSize="100sp"
        app:autoSizeMinTextSize="12sp"
        app:autoSizeStepGranularity="2sp"
        app:autoSizeTextType="uniform"
        app:layout_constraintTop_toBottomOf="@+id/inASeriesOrNoText"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        />

I have a button with an id of open_explanation_button, I need to place that button to the end of the movieRatingText. The problem is that I need the movieRatingText to be with a width of match_parent to make sure that it's an autoresizable text. In a more simpler way, I need to constraint the start of the open_explanation_button to the center of the movieRatingText, in addition to adding some margins.
Any help?


问:
XSLT sort parents by child value changes element arrangements
I have the following simplified XML:

```<code> <Data>
    <DataValue>Data</DataValue>
    <Product>
        <Price>60</Price>
        <Value>Product Value</Value>
    </Product>
    <Product>
        <Price>50</Price>
        <Value>Product Value</Value>
    </Product>
    <Information>
        <Entry>Some Information Text</Entry>
    </Information>
    <Description>
        <Entry>Some Description Text</Entry>
    </Description>
 </Data>
</code>```

I sort the product elements by the price value, with the following xslt code:

```<code><xsl:template match="@*">
    <xsl:attribute name="{name()}"><xsl:value-of select="normalize-space(.)"/></xsl:attribute>
</xsl:template>

<xsl:template match="*">
    <xsl:element name="{local-name()}">
        <xsl:apply-templates select="@*|node()"/>
    </xsl:element>
</xsl:template>

<xsl:template match="*[local-name()='Data']">
    <xsl:element name="{local-name()}">
        <xsl:apply-templates select="@*"/>
        <xsl:apply-templates select="*[not(local-name()='Product')]"/>
        <xsl:apply-templates select="*[local-name()='Product']" >
            <xsl:sort data-type="number" select="*[local-name()='Price']/text()" order="ascending"/>
        </xsl:apply-templates>
    </xsl:element>
</xsl:template>
</code>```

Which leads to the following wrong result:

```<code><Data>
   <DataValue>Data</DataValue>
   <Information>
      <Entry>Some Information Text</Entry>
   </Information>
   <Description>
      <Entry>Some Description Text</Entry>
   </Description>
   <Product>
      <Price>50</Price>
      <Value>Product Value</Value>
   </Product>
   <Product>
      <Price>60</Price>
      <Value>Product Value</Value>
   </Product>
</Data>
</code>```

The problem now is that the correctly sorted "Products" elements are placed at the end after the transformation. Is there a way to sort only parts of an xml while the other elements remain untouched and also remain on the same places?

答:
Why can't you do simply:

XSLT 1.0

```<code><xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/Data">
    <xsl:copy>
        <xsl:copy-of select="DataValue"/>
        <xsl:for-each select="Product">
            <xsl:sort select="Price" data-type="number"/>
            <xsl:copy-of select="."/>
        </xsl:for-each>
        <xsl:copy-of select="Information | Description"/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>
</code>```

P.S. There should never be a need to use a hack like *[local-name()='xyz']. If your input uses namespaces, deal with them properly - see here how: https://stackoverflow.com/a/34762628/3016153

Body:
I have the following simplified XML:

 <Data>
    <DataValue>Data</DataValue>
    <Product>
        <Price>60</Price>
        <Value>Product Value</Value>
    </Product>
    <Product>
        <Price>50</Price>
        <Value>Product Value</Value>
    </Product>
    <Information>
        <Entry>Some Information Text</Entry>
    </Information>
    <Description>
        <Entry>Some Description Text</Entry>
    </Description>
 </Data>

I sort the product elements by the price value, with the following xslt code:

<xsl:template match="@*">
    <xsl:attribute name="{name()}"><xsl:value-of select="normalize-space(.)"/></xsl:attribute>
</xsl:template>

<xsl:template match="*">
    <xsl:element name="{local-name()}">
        <xsl:apply-templates select="@*|node()"/>
    </xsl:element>
</xsl:template>

<xsl:template match="*[local-name()='Data']">
    <xsl:element name="{local-name()}">
        <xsl:apply-templates select="@*"/>
        <xsl:apply-templates select="*[not(local-name()='Product')]"/>
        <xsl:apply-templates select="*[local-name()='Product']" >
            <xsl:sort data-type="number" select="*[local-name()='Price']/text()" order="ascending"/>
        </xsl:apply-templates>
    </xsl:element>
</xsl:template>

Which leads to the following wrong result:

<Data>
   <DataValue>Data</DataValue>
   <Information>
      <Entry>Some Information Text</Entry>
   </Information>
   <Description>
      <Entry>Some Description Text</Entry>
   </Description>
   <Product>
      <Price>50</Price>
      <Value>Product Value</Value>
   </Product>
   <Product>
      <Price>60</Price>
      <Value>Product Value</Value>
   </Product>
</Data>

The problem now is that the correctly sorted "Products" elements are placed at the end after the transformation. Is there a way to sort only parts of an xml while the other elements remain untouched and also remain on the same places?

Body:
Why can't you do simply:

XSLT 1.0

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/Data">
    <xsl:copy>
        <xsl:copy-of select="DataValue"/>
        <xsl:for-each select="Product">
            <xsl:sort select="Price" data-type="number"/>
            <xsl:copy-of select="."/>
        </xsl:for-each>
        <xsl:copy-of select="Information | Description"/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

P.S. There should never be a need to use a hack like *[local-name()='xyz']. If your input uses namespaces, deal with them properly - see here how: https://stackoverflow.com/a/34762628/3016153


问:
MY 'image' attribute has no file associated with it
With my reading of many answers to questions similar to mine, all of those answers did not find a solution to my problem.. so I will present them so that I may find a solution that fits my problem:
my View file:
enter image description here

my Template File:
enter image description here

my Admin file:
enter image description here

The Error:
enter image description here
enter image description here

I tried every solution with no hope.

```<code>from datetime import datetime
</code>```

from ckeditor.fields import RichTextField
from multiselectfield import MultiSelectField
from django.db import models

class Car(models.Model):
state_choice = (
('AL', 'Alabama'),
('AK', 'Alaska'),
('AZ', 'Arizona'),
('AR', 'Arkansas'),
('CA', 'California'),
('CO', 'Colorado'),
('CT', 'Connecticut'),
('DE', 'Delaware'),
('DC', 'District Of Columbia'),
('FL', 'Florida'),
('GA', 'Georgia'),
('HI', 'Hawaii'),
('ID', 'Idaho'),
('IL', 'Illinois'),
('IN', 'Indiana'),
('IA', 'Iowa'),
('KS', 'Kansas'),
('KY', 'Kentucky'),
('LA', 'Louisiana'),
('ME', 'Maine'),
('MD', 'Maryland'),
('MA', 'Massachusetts'),
('MI', 'Michigan'),
('MN', 'Minnesota'),
('MS', 'Mississippi'),
('MO', 'Missouri'),
('MT', 'Montana'),
('NE', 'Nebraska'),
('NV', 'Nevada'),
('NH', 'New Hampshire'),
('NJ', 'New Jersey'),
('NM', 'New Mexico'),
('NY', 'New York'),
('NC', 'North Carolina'),
('ND', 'North Dakota'),
('OH', 'Ohio'),
('OK', 'Oklahoma'),
('OR', 'Oregon'),
('PA', 'Pennsylvania'),
('RI', 'Rhode Island'),
('SC', 'South Carolina'),
('SD', 'South Dakota'),
('TN', 'Tennessee'),
('TX', 'Texas'),
('UT', 'Utah'),
('VT', 'Vermont'),
('VA', 'Virginia'),
('WA', 'Washington'),
('WV', 'West Virginia'),
('WI', 'Wisconsin'),
('WY', 'Wyoming'),
)

```<code>features_choices = (
    ('Cruise Control', 'Cruise Control'),
    ('Audio Interface', 'Audio Interface'),
    ('Airbags', 'Airbags'),
    ('Air Conditioning', 'Air Conditioning'),
    ('Seat Heating', 'Seat Heating'),
    ('Alarm System', 'Alarm System'),
    ('ParkAssist', 'ParkAssist'),
    ('Power Steering', 'Power Steering'),
    ('Reversing Camera', 'Reversing Camera'),
    ('Direct Fuel Injection', 'Direct Fuel Injection'),
    ('Auto Start/Stop', 'Auto Start/Stop'),
    ('Wind Deflector', 'Wind Deflector'),
    ('Bluetooth Handset', 'Bluetooth Handset'),
)

door_choices = (
    ('2', '2'),
    ('3', '3'),
    ('4', '4'),
    ('5', '5'),
    ('6', '6'),
)

transmission_choice = (
    ('A', 'Auto_shift'),
    ('M', 'Manual_shift'),
)

fuel_type_choices = (
    ('P', 'Petrol'),
    ('D', 'Diesel'),
    ('CNG', 'Compressed Natural Gas'),
    ('Et', 'Ethanol'),
    ('E', 'Electricity'),
)

year_choice = []
for r in range(2000, (datetime.now().year+1)):
    year_choice.append((r, r))

car_title = models.CharField(max_length=255)
city = models.CharField(max_length=100)
state = models.CharField(choices=state_choice, max_length=100)
color = models.CharField(max_length=100)
model = models.CharField(max_length=100)
year = models.IntegerField(('year'), choices=year_choice)
condition = models.CharField(max_length=100)
price = models.IntegerField()
description = RichTextField()
car_photo = models.ImageField(upload_to='photo/%Y%m%d/', blank=True)
car_photo_1 = models.ImageField(upload_to='photo/%Y%m%d/', blank=True)
car_photo_2 = models.ImageField(upload_to='photo/%Y%m%d/', blank=True)
car_photo_3 = models.ImageField(upload_to='photo/%Y%m%d/', blank=True)
car_photo_4 = models.ImageField(upload_to='photo/%Y%m%d/', blank=True)
features = MultiSelectField(choices=features_choices)
body_style = models.CharField(max_length=100)
engine = models.CharField(max_length=100)
transmission = models.CharField(
    choices=transmission_choice, max_length=100)
interior = models.CharField(max_length=100)
miles = models.IntegerField()
doors = models.CharField(choices=door_choices, max_length=10)
passengers = models.IntegerField()
vin_no = models.CharField(max_length=100)
milage = models.IntegerField()
fuel_type = models.CharField(choices=fuel_type_choices, max_length=50)
no_of_owners = models.IntegerField()
is_featured = models.BooleanField(default=False)
created_date = models.DateTimeField(default=datetime.now, blank=True)
</code>```

after trying the proposed solution:
enter image description here

答:
It seems like it's just car 4 that has no image associated with it.  Look at the admin. Car 4 exists, but it has no image associated with it, and your template is not checking for that.

{% if car.car_photo_4 %}
```
<p>So try changing it to:</p>
<pre class="lang-html prettyprint-override"><code>{% if car.car_photo_4.url %}
</code>```

Note that this is probably also not correct, but I'd need to see your Car model to make it better.

Body:
With my reading of many answers to questions similar to mine, all of those answers did not find a solution to my problem.. so I will present them so that I may find a solution that fits my problem:
my View file:
enter image description here

my Template File:
enter image description here

my Admin file:
enter image description here

The Error:
enter image description here
enter image description here

I tried every solution with no hope.

from datetime import datetime

from ckeditor.fields import RichTextField
from multiselectfield import MultiSelectField
from django.db import models

class Car(models.Model):
state_choice = (
('AL', 'Alabama'),
('AK', 'Alaska'),
('AZ', 'Arizona'),
('AR', 'Arkansas'),
('CA', 'California'),
('CO', 'Colorado'),
('CT', 'Connecticut'),
('DE', 'Delaware'),
('DC', 'District Of Columbia'),
('FL', 'Florida'),
('GA', 'Georgia'),
('HI', 'Hawaii'),
('ID', 'Idaho'),
('IL', 'Illinois'),
('IN', 'Indiana'),
('IA', 'Iowa'),
('KS', 'Kansas'),
('KY', 'Kentucky'),
('LA', 'Louisiana'),
('ME', 'Maine'),
('MD', 'Maryland'),
('MA', 'Massachusetts'),
('MI', 'Michigan'),
('MN', 'Minnesota'),
('MS', 'Mississippi'),
('MO', 'Missouri'),
('MT', 'Montana'),
('NE', 'Nebraska'),
('NV', 'Nevada'),
('NH', 'New Hampshire'),
('NJ', 'New Jersey'),
('NM', 'New Mexico'),
('NY', 'New York'),
('NC', 'North Carolina'),
('ND', 'North Dakota'),
('OH', 'Ohio'),
('OK', 'Oklahoma'),
('OR', 'Oregon'),
('PA', 'Pennsylvania'),
('RI', 'Rhode Island'),
('SC', 'South Carolina'),
('SD', 'South Dakota'),
('TN', 'Tennessee'),
('TX', 'Texas'),
('UT', 'Utah'),
('VT', 'Vermont'),
('VA', 'Virginia'),
('WA', 'Washington'),
('WV', 'West Virginia'),
('WI', 'Wisconsin'),
('WY', 'Wyoming'),
)

features_choices = (
    ('Cruise Control', 'Cruise Control'),
    ('Audio Interface', 'Audio Interface'),
    ('Airbags', 'Airbags'),
    ('Air Conditioning', 'Air Conditioning'),
    ('Seat Heating', 'Seat Heating'),
    ('Alarm System', 'Alarm System'),
    ('ParkAssist', 'ParkAssist'),
    ('Power Steering', 'Power Steering'),
    ('Reversing Camera', 'Reversing Camera'),
    ('Direct Fuel Injection', 'Direct Fuel Injection'),
    ('Auto Start/Stop', 'Auto Start/Stop'),
    ('Wind Deflector', 'Wind Deflector'),
    ('Bluetooth Handset', 'Bluetooth Handset'),
)

door_choices = (
    ('2', '2'),
    ('3', '3'),
    ('4', '4'),
    ('5', '5'),
    ('6', '6'),
)

transmission_choice = (
    ('A', 'Auto_shift'),
    ('M', 'Manual_shift'),
)

fuel_type_choices = (
    ('P', 'Petrol'),
    ('D', 'Diesel'),
    ('CNG', 'Compressed Natural Gas'),
    ('Et', 'Ethanol'),
    ('E', 'Electricity'),
)

year_choice = []
for r in range(2000, (datetime.now().year+1)):
    year_choice.append((r, r))

car_title = models.CharField(max_length=255)
city = models.CharField(max_length=100)
state = models.CharField(choices=state_choice, max_length=100)
color = models.CharField(max_length=100)
model = models.CharField(max_length=100)
year = models.IntegerField(('year'), choices=year_choice)
condition = models.CharField(max_length=100)
price = models.IntegerField()
description = RichTextField()
car_photo = models.ImageField(upload_to='photo/%Y%m%d/', blank=True)
car_photo_1 = models.ImageField(upload_to='photo/%Y%m%d/', blank=True)
car_photo_2 = models.ImageField(upload_to='photo/%Y%m%d/', blank=True)
car_photo_3 = models.ImageField(upload_to='photo/%Y%m%d/', blank=True)
car_photo_4 = models.ImageField(upload_to='photo/%Y%m%d/', blank=True)
features = MultiSelectField(choices=features_choices)
body_style = models.CharField(max_length=100)
engine = models.CharField(max_length=100)
transmission = models.CharField(
    choices=transmission_choice, max_length=100)
interior = models.CharField(max_length=100)
miles = models.IntegerField()
doors = models.CharField(choices=door_choices, max_length=10)
passengers = models.IntegerField()
vin_no = models.CharField(max_length=100)
milage = models.IntegerField()
fuel_type = models.CharField(choices=fuel_type_choices, max_length=50)
no_of_owners = models.IntegerField()
is_featured = models.BooleanField(default=False)
created_date = models.DateTimeField(default=datetime.now, blank=True)

after trying the proposed solution:
enter image description here

Body:
It seems like it's just car 4 that has no image associated with it.  Look at the admin. Car 4 exists, but it has no image associated with it, and your template is not checking for that.

{% if car.car_photo_4 %}   <!-- just checks if car_photo_4 exists, which it does -->

So try changing it to:

{% if car.car_photo_4.url %}

Note that this is probably also not correct, but I'd need to see your Car model to make it better.


问:
How can I save a global variable value after dynamically loading a reference?
I have a Access 2003 database that will dynamically load MDB databases as a library reference. The reason for this is this database is a menu front-end for 60+ application databases. Rather than deal with permanently referencing all these databases, the menu front-end will dynamically reference what is needed when the user makes a selection. I was working on moving this database to Access 2010 and creating a custom ribbon. I started using the technique from here to capture the ribbon object in a global variable when the ribbon loads. I then ran into the problem where I could verify the code was running and the global variable was correctly being assigned the ribbon reference but after the database would run through it's startup routine, that global variable would get reset to Nothing.

To verify what was going on, I created a simple database for testing. In this database, I had a module with a global variable:

```<code>Public obj as Object
</code>```

I then had a function like this:

```<code>Public Function SetObj()

Set obj = Application

Debug.Print "IsNothing=" & (obj Is Nothing)

References.AddFromFile "Test.mdb"

Debug.Print "IsNothing=" & (obj Is Nothing)

End Function
</code>```

Obviously, in my code, "Test.mdb" refers to an actual file. If I run this code, Debug.Print gives me "IsNothing=False" for both instances, but after the function finishes and if I wait a couple seconds, Debug.Print will give me "IsNothing=True". If I comment out References.AddFromFile, Debug.Print gives me "IsNothing=False" no matter how long I wait.

It makes sense to me that since Access has to re-compile the VBA code after loading the library that all global variables are reset. I've experimented with moving the global variable into a class, but since I then need a global variable for the class, the class variable then gets reset instead. I tried using a local variable in the function to save the value of the global variable, but it looks like Access waits a couple seconds after the code is finished running to do the re-compile, so that doesn't work either. Does anyone have any other ideas to accomplish this?

答:
I figured out a solution to my problem, and thanks @David-W-Fenton, as your answer gave me the idea. I use your approach in a library database for caching frequently-accessed values that are stored in a table but don't change after the initial startup. Those values aren't lost every time the references change, and that's when the light bulb lit up.

The solution is to put the global variable in a library database. Access looks to be only resetting global variables in the database that the reference is being loaded into - which makes sense after thinking about it. So since the library database isn't the one being re-compiled, it doesn't get it's global (or private or static) variables reset.

What I ended up doing was creating a new module in an existing library database. It has a private variable and two methods - one to set the variable, one to retrieve the variable value. In my menu front-end database, when the ribbon loads and calls my callback function, rather than saving the ribbon object in the front-end database, I pass it to this module for saving. I now no longer lose that ribbon reference whenever new databases are added to the library references on the fly.

ContentLicense: CC BY-SA 3.0

Body:
I have a Access 2003 database that will dynamically load MDB databases as a library reference. The reason for this is this database is a menu front-end for 60+ application databases. Rather than deal with permanently referencing all these databases, the menu front-end will dynamically reference what is needed when the user makes a selection. I was working on moving this database to Access 2010 and creating a custom ribbon. I started using the technique from here to capture the ribbon object in a global variable when the ribbon loads. I then ran into the problem where I could verify the code was running and the global variable was correctly being assigned the ribbon reference but after the database would run through it's startup routine, that global variable would get reset to Nothing.

To verify what was going on, I created a simple database for testing. In this database, I had a module with a global variable:

Public obj as Object

I then had a function like this:

Public Function SetObj()

Set obj = Application

Debug.Print "IsNothing=" & (obj Is Nothing)

References.AddFromFile "Test.mdb"

Debug.Print "IsNothing=" & (obj Is Nothing)

End Function

Obviously, in my code, "Test.mdb" refers to an actual file. If I run this code, Debug.Print gives me "IsNothing=False" for both instances, but after the function finishes and if I wait a couple seconds, Debug.Print will give me "IsNothing=True". If I comment out References.AddFromFile, Debug.Print gives me "IsNothing=False" no matter how long I wait.

It makes sense to me that since Access has to re-compile the VBA code after loading the library that all global variables are reset. I've experimented with moving the global variable into a class, but since I then need a global variable for the class, the class variable then gets reset instead. I tried using a local variable in the function to save the value of the global variable, but it looks like Access waits a couple seconds after the code is finished running to do the re-compile, so that doesn't work either. Does anyone have any other ideas to accomplish this?


问:
PSQL throwing error: relation "serial" does not exist, when creating a table
It happens when i run this code:

```<code>CREATE TABLE distributors (
 did    integer PRIMARY KEY DEFAULT nextval('serial'),
 name   varchar(40) NOT NULL CHECK (name <> '')
);
</code>```

I have tried remover the nextval('serial') but to no avail

答:
You want to do this:

```<code>CREATE TABLE distributors (
 did    serial PRIMARY KEY DEFAULT,
 name   varchar(40) NOT NULL CHECK (name <> '')
);

</code>```

The serial type is actually a macro. That per docs (Serial) does:

```<code>CREATE SEQUENCE tablename_colname_seq AS integer;
CREATE TABLE tablename (
    colname integer NOT NULL DEFAULT nextval('tablename_colname_seq')
);
ALTER SEQUENCE tablename_colname_seq OWNED BY tablename.colname;
</code>```

Assuming you are on a recent version(10+) of Postgres generated always as identity(see Create Table) is the preferred alternative these days.

Body:
It happens when i run this code:

CREATE TABLE distributors (
 did    integer PRIMARY KEY DEFAULT nextval('serial'),
 name   varchar(40) NOT NULL CHECK (name <> '')
);

I have tried remover the nextval('serial') but to no avail

Body:
You want to do this:

CREATE TABLE distributors (
 did    serial PRIMARY KEY DEFAULT,
 name   varchar(40) NOT NULL CHECK (name <> '')
);

The serial type is actually a macro. That per docs (Serial) does:

CREATE SEQUENCE tablename_colname_seq AS integer;
CREATE TABLE tablename (
    colname integer NOT NULL DEFAULT nextval('tablename_colname_seq')
);
ALTER SEQUENCE tablename_colname_seq OWNED BY tablename.colname;

Assuming you are on a recent version(10+) of Postgres generated always as identity(see Create Table) is the preferred alternative these days.


问:
How to pull a range of data (plus/minus) around a specific date in SQL
I have Table 1 and Table 2, where Table 1 has unique customer id and their report date and Table 2 has the entire date range and corresponding values for each date for each customer id. Basically, I want to pull 2 dates before the report date and 2 dates after the report date for each customer id to get the Desired Output Table below. SQL - pull data for date range based on a start date seems to be the closest to what I want, but I don't know how to tweak the answer to suit my requirement.

Below is my code, but it does not work in Hive/Hue SQL. Appreciate your help :)

```<code>SELECT b.date, a.report_date, a.customer_id, b.value
FROM table1 a
  LEFT JOIN table2 b ON b.date = a.report_date AND b.customer_id = a.customer_id
WHERE b.date IN (DATE_ADD(a.report_date, 2)
   OR b.date IN (DATE_SUB(a.report_date, 2)
</code>```

TABLE 1

customer id
report date

123
15/01/2021

456
20/02/2021

TABLE 2

customer id
date
value

...
...
...

123
13/01/2021
10

123
14/01/2021
13

123
15/01/2021
9

123
16/01/2021
19

123
17/01/2021
20

...
...
...

...
...
...

456
18/02/2021
4

456
19/02/2021
5

456
20/02/2021
2

456
21/02/2021
9

456
22/02/2021
1

...
...
...

DESIRED OUTPUT TABLE

date
report date
customer id
value

13/01/2021
15/01/2021
123
10

14/01/2021
15/01/2021
123
13

15/01/2021
15/01/2021
123
9

16/01/2021
15/01/2021
123
19

17/01/2021
15/01/2021
123
20

18/02/2021
20/02/2021
456
4

19/02/2021
20/02/2021
456
5

20/02/2021
20/02/2021
456
2

21/02/2021
20/02/2021
456
9

22/02/2021
20/02/2021
456
1

答:
It's not clear that you actually need an outer join. When you do use one you can't filter on the inner table afterward though.</p>
```<code>LEFT JOIN table2 b ON
        b.customer_id = a.customer_id
    AND b.date BETWEEN DATE_SUB(a.report_date, 2) AND DATE_ADD(a.report_date, 2)
</code>```

Body:
I have Table 1 and Table 2, where Table 1 has unique customer id and their report date and Table 2 has the entire date range and corresponding values for each date for each customer id. Basically, I want to pull 2 dates before the report date and 2 dates after the report date for each customer id to get the Desired Output Table below. SQL - pull data for date range based on a start date seems to be the closest to what I want, but I don't know how to tweak the answer to suit my requirement.

Below is my code, but it does not work in Hive/Hue SQL. Appreciate your help :)

SELECT b.date, a.report_date, a.customer_id, b.value
FROM table1 a
  LEFT JOIN table2 b ON b.date = a.report_date AND b.customer_id = a.customer_id
WHERE b.date IN (DATE_ADD(a.report_date, 2)
   OR b.date IN (DATE_SUB(a.report_date, 2)

TABLE 1

customer id
report date

123
15/01/2021

456
20/02/2021

TABLE 2

customer id
date
value

...
...
...

123
13/01/2021
10

123
14/01/2021
13

123
15/01/2021
9

123
16/01/2021
19

123
17/01/2021
20

...
...
...

...
...
...

456
18/02/2021
4

456
19/02/2021
5

456
20/02/2021
2

456
21/02/2021
9

456
22/02/2021
1

...
...
...

DESIRED OUTPUT TABLE

date
report date
customer id
value

13/01/2021
15/01/2021
123
10

14/01/2021
15/01/2021
123
13

15/01/2021
15/01/2021
123
9

16/01/2021
15/01/2021
123
19

17/01/2021
15/01/2021
123
20

18/02/2021
20/02/2021
456
4

19/02/2021
20/02/2021
456
5

20/02/2021
20/02/2021
456
2

21/02/2021
20/02/2021
456
9

22/02/2021
20/02/2021
456
1

Body:
It's not clear that you actually need an outer join. When you do use one you can't filter on the inner table afterward though.

LEFT JOIN table2 b ON
        b.customer_id = a.customer_id
    AND b.date BETWEEN DATE_SUB(a.report_date, 2) AND DATE_ADD(a.report_date, 2)


问:
DATEIME_DIFF throwing error when using safe divide
I've created a query that I'm hoping to use to fill a table with daily budgets at the end of every day. To do this, I just need some simple maths:
monthly budget / number of days left in the month.

Then, at the end of the month, I can SUM all of the rows to calculate an accurate budget.

The query is as follows:

```<code>SELECT *,
ROUND(SAFE_DIVIDE(budget, DATETIME_DIFF(CURRENT_DATE(), LAST_DAY(CURRENT_DATE()), DAY)),2) AS daily_budget
FROM `mm-demo-project.marketing_hub.budget_manager`
</code>```

When executing the query, my results present as negative numbers, which according to the documentation for this function, is likely caused by the result overflowing the result type.

View the results of the query.

I've made a fools guess at rounding the calculation. Needless to say that it did not work at all.

How can I stop my query from returning negative number?

答:
use below</p>
```<code>SELECT *,
ROUND(SAFE_DIVIDE(budget, DATETIME_DIFF(LAST_DAY(CURRENT_DATE()), CURRENT_DATE(), DAY)),2) AS daily_budget
FROM `mm-demo-project.marketing_hub.budget_manager`
</code>```

Body:
I've created a query that I'm hoping to use to fill a table with daily budgets at the end of every day. To do this, I just need some simple maths:
monthly budget / number of days left in the month.

Then, at the end of the month, I can SUM all of the rows to calculate an accurate budget.

The query is as follows:

SELECT *,
ROUND(SAFE_DIVIDE(budget, DATETIME_DIFF(CURRENT_DATE(), LAST_DAY(CURRENT_DATE()), DAY)),2) AS daily_budget
FROM `mm-demo-project.marketing_hub.budget_manager`

When executing the query, my results present as negative numbers, which according to the documentation for this function, is likely caused by the result overflowing the result type.

View the results of the query.

I've made a fools guess at rounding the calculation. Needless to say that it did not work at all.

How can I stop my query from returning negative number?

Body:
use below

SELECT *,
ROUND(SAFE_DIVIDE(budget, DATETIME_DIFF(LAST_DAY(CURRENT_DATE()), CURRENT_DATE(), DAY)),2) AS daily_budget
FROM `mm-demo-project.marketing_hub.budget_manager`


问:
How can i put some information from a device to another device based on a parity condition?
I have to solve a problem at work in pandas where i have a .csv file where i have some information like this:

Element      --- Ticket

1-X1211  --- TT0045

1-X1212

I have 2 elements that form a pair based on 2 conditions:

The first 6 characters have to be the same for both of the elements in the pair.

The last number forms a pair like this 1 with 2, 3 with 4,  5&6, 7&8, 9&0.
In this case you can see the pair: 1-X1211 pair with 1-X1212.

What i need to do is to associate the ticket from an element of the pair to the other element in the pair (if a ticket exists in the first place). So in this case to copy the ticket from 1-X1211 -> TT0045 and put it on the other element of the pair 1-X1212. Final it should look like this:

Element

1-X1211 --- TT0045

1-X1212 --- TT0045

I can't share a code because i don't know how to do it.

Thank you,
Iulia

答:
Suppose the following dataframe:

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

df = pd.DataFrame({'ID': ['1-x1211', '1-x1212'], 'Ticket': ['TT0045', '']})
print(df)

# Output
        ID  Ticket
0  1-x1211  TT0045
1  1-x1212
</code>```

Create a mapping dict:

```<code># 1 -> 2, 3 -> 4, ..., 9 -> 0
odd_to_even = {'1': '2', '3': '4', '5': '6', '7': '8', '9': '0'}

# Extract last char of the ID and replace it by 2, 4, 6, 8 or 0
even_id = df['ID'].astype(str).str[:-1] + df['ID'].astype(str).str[-1].replace(odd_to_even)

# Now find the right ticket for pairwise ID
df['Ticket'] = df.replace('', np.nan).groupby(even_id)['Ticket'].transform('first')
print(df)

# Output
        ID  Ticket
0  1-x1211  TT0045
1  1-x1212  TT0045
</code>```

Body:
Suppose the following dataframe:

import pandas as pd
import numpy as np

df = pd.DataFrame({'ID': ['1-x1211', '1-x1212'], 'Ticket': ['TT0045', '']})
print(df)

# Output
        ID  Ticket
0  1-x1211  TT0045
1  1-x1212

Create a mapping dict:

# 1 -> 2, 3 -> 4, ..., 9 -> 0
odd_to_even = {'1': '2', '3': '4', '5': '6', '7': '8', '9': '0'}

# Extract last char of the ID and replace it by 2, 4, 6, 8 or 0
even_id = df['ID'].astype(str).str[:-1] + df['ID'].astype(str).str[-1].replace(odd_to_even)

# Now find the right ticket for pairwise ID
df['Ticket'] = df.replace('', np.nan).groupby(even_id)['Ticket'].transform('first')
print(df)

# Output
        ID  Ticket
0  1-x1211  TT0045
1  1-x1212  TT0045


问:
How do I split a string by a multi-character delimiter in C#?
What if I want to split a string using a delimiter that is a word?

For example, This is a sentence.

I want to split on is and get This and a sentence.

In Java, I can send in a string as a delimiter, but how do I accomplish this in C#?

答:
```<code>string strData = "This is much easier"
int intDelimiterIndx = strData.IndexOf("is");
int intDelimiterLength = "is".Length;
str1 = strData.Substring(0, intDelimiterIndx);
str2 = strData.Substring(intDelimiterIndx + intDelimiterLength, strData.Length - (intDelimiterIndx + intDelimiterLength));
</code>```


问:
How to highlight entire row in sap.ui.table.Table
I have been doing the below to highlight an entire row in a table:

this.byId("sampleTable").getRows()[i].addStyleClass("someClass");
```
<pre class="lang-css prettyprint-override"><code>.someClass{
  background: #b0c4de !important;
}
</code>```

Result:

It works but I learnt from other questions that doing this way and using oRow.addStyleClass is not recommended since it's not a public method.

Any links, recommendations or an answer are much appreciated.

答:
It's also possible to use these colors (source):

So highlight here:

```<code><Table xmlns="sap.ui.table">
  <rowSettingsTemplate>
    <RowSettings highlight="{= ${odataModel>foo} > 50 ? 'Error' : null}" />
  </rowSettingsTemplate>
  <columns> <!-- ... -->
</code>```

You can also have values IndicationXX where XX goes from 01 to 08.

Body:
I have been doing the below to highlight an entire row in a table:

this.byId("sampleTable").getRows()[i].addStyleClass("someClass");

.someClass{
  background: #b0c4de !important;
}

Result:

It works but I learnt from other questions that doing this way and using oRow.addStyleClass is not recommended since it's not a public method.

Any links, recommendations or an answer are much appreciated.

Body:
It's also possible to use these colors (source):

So highlight here:

<Table xmlns="sap.ui.table">
  <rowSettingsTemplate>
    <RowSettings highlight="{= ${odataModel>foo} > 50 ? 'Error' : null}" />
  </rowSettingsTemplate>
  <columns> <!-- ... -->

You can also have values IndicationXX where XX goes from 01 to 08.


问:
web3.exceptions.ValidationError: with tuple[], address, bytes
Getting the following validation error and could not point to why

Could not identify the intended function with name z, positional argument(s) of type (<class 'list'>, <class 'str'>, <class 'bytes'>) and keyword argument(s) of type {}.
Found 1 function(s) with the name z: ['z(tuple[],address,bytes)']
Function invocation failed due to no matching argument types.

Here is the function signature of the contract

```<code>function z(Tx[] memory d, address payable addr, bytes calldata data) public onlyOwners;
</code>```

Using the following web3.py code

```<code>tx = []
addr = "0x..."
data = "...."
data = data.encode()       <--- Tried with and without this

contract.functions.z(tx, addr, data).buildTransaction({...})
</code>```

答: The function asks for a type tuple[]. I found that you have to create your tx list like this: tx = [()] instead of tx = [].</p>

Body:
Getting the following validation error and could not point to why

Could not identify the intended function with name z, positional argument(s) of type (<class 'list'>, <class 'str'>, <class 'bytes'>) and keyword argument(s) of type {}.
Found 1 function(s) with the name z: ['z(tuple[],address,bytes)']
Function invocation failed due to no matching argument types.

Here is the function signature of the contract

function z(Tx[] memory d, address payable addr, bytes calldata data) public onlyOwners;

Using the following web3.py code

tx = []
addr = "0x..."
data = "...."
data = data.encode()       <--- Tried with and without this

contract.functions.z(tx, addr, data).buildTransaction({...})


问:
how to generate keypair from secret phrase (mnemonic) SOLANA
I am working with Solana and phantom wallet I have a wallet with a public key and I have it's secret phrase composed of 12 words.
when I generate keypairs from the secret phrase I use:

```<code>const getKeyPair = (mnemomic) => {
  const seed = bip39.mnemonicToSeedSync(mnemomic).slice(0, 32);
  const Keypair = web3.Keypair.fromSeed(seed);
  return Keypair;
};
</code>```

the generated keypair has publicKey and privateKey , but when am checking my balance using the generated public key I find the balance is always 0 even when I try to airdrop Sol using my code it's not getting in the account.

But if I check using my public key from phantom wallet I get the Sol I have and if I want to airdrop sols they also proceed normally.

Why is my generated public key not the same as the one in phantom wallet?

答:
First, we need to generate the publicKey and privateKey from the seed phrase  using this command :

solana-keygen recover 'prompt:?key=0/0' -o phantom_wallet.json

remark : our account may have many wallets the command above access
the first wallet , if we need to access wallet number 10 for example
we need to change the 'prompt:?key=0/0' to 'prompt:?key=10/0'
"only the first 0 is changing"

next this will generate public key "will be written in the console" and a  json file with secret key contains an array of 64 element which is the secret key.
now to generate the KEYPAIRS in solana web3 javascript SDK
we do the following:

```<code> let seed = Uint8Array.from(
    process.env.REACT_APP_OUR_SECRET_KEY.split(",")
  ).slice(0, 32);

  // create keypairs
  let KEYPAIRS = web3.Keypair.fromSeed(seed);
</code>```

IMPORTANT : in .env files REACT_APP_OUR_SECRET_KEY is stored without brackets [
]
example : 15,320,52,...
as we see a table without brackets [ ]

Body:
I am working with Solana and phantom wallet I have a wallet with a public key and I have it's secret phrase composed of 12 words.
when I generate keypairs from the secret phrase I use:

const getKeyPair = (mnemomic) => {
  const seed = bip39.mnemonicToSeedSync(mnemomic).slice(0, 32);
  const Keypair = web3.Keypair.fromSeed(seed);
  return Keypair;
};

the generated keypair has publicKey and privateKey , but when am checking my balance using the generated public key I find the balance is always 0 even when I try to airdrop Sol using my code it's not getting in the account.

But if I check using my public key from phantom wallet I get the Sol I have and if I want to airdrop sols they also proceed normally.

Why is my generated public key not the same as the one in phantom wallet?

Body:
First, we need to generate the publicKey and privateKey from the seed phrase  using this command :

solana-keygen recover 'prompt:?key=0/0' -o phantom_wallet.json

remark : our account may have many wallets the command above access
the first wallet , if we need to access wallet number 10 for example
we need to change the 'prompt:?key=0/0' to 'prompt:?key=10/0'
"only the first 0 is changing"

next this will generate public key "will be written in the console" and a  json file with secret key contains an array of 64 element which is the secret key.
now to generate the KEYPAIRS in solana web3 javascript SDK
we do the following:

 let seed = Uint8Array.from(
    process.env.REACT_APP_OUR_SECRET_KEY.split(",")
  ).slice(0, 32);

  // create keypairs
  let KEYPAIRS = web3.Keypair.fromSeed(seed);

IMPORTANT : in .env files REACT_APP_OUR_SECRET_KEY is stored without brackets [
]
example : 15,320,52,...
as we see a table without brackets [ ]


问:
Not able to Upload Artifacts along with their folder structure to Jfrog using Pipeline
I am using Pipeline Job which should upload all the jars to the Jfrog, it's working but it is uploading all the jars without its folder structure to Jfrog.

eg:

```<code>libs-release-local/one.jar

libs-release-local/two.jar
</code>```

But I want to upload all the jars along with their folder structure like below.

eg:

```<code>libs-release-local/abc/efg/abc/one.jar

libs-release-local/ABC/EFG/ABC/two.jar
</code>```

Note: here the folder structure may change based on the jar.

So how do I make changes in a script which will catch the folder structure and upload it for every jar?

Here is the current script am using

```<code>        stage('Uploading to artifactory'){
            steps{
                rtUpload (
                 serverId:"<server id>" ,
                  spec: '''{
                   "files": [
                      {
                      "pattern": "**/*.jar",
                      "target": "libs-bt-test-local/"
                      }
                            ]
                           }''',
                        )
            }
        }
</code>```

Let me know if there a possible way to include a loop which will dynamically change the directory structure for every jar.

答:
The target value can be edited with a placeholders in order to dynamically determine the uploaded path.

For example: libs-bt-test-local/{1}

For further information and examples, you may refer to the Artifactory REST API documentation page:

https://www.jfrog.com/confluence/display/JFROG/Using+File+Specs#UsingFileSpecs-UsingPlaceholders

Body:
I am using Pipeline Job which should upload all the jars to the Jfrog, it's working but it is uploading all the jars without its folder structure to Jfrog.

eg:

libs-release-local/one.jar

libs-release-local/two.jar

But I want to upload all the jars along with their folder structure like below.

eg:

libs-release-local/abc/efg/abc/one.jar

libs-release-local/ABC/EFG/ABC/two.jar

Note: here the folder structure may change based on the jar.

So how do I make changes in a script which will catch the folder structure and upload it for every jar?

Here is the current script am using

        stage('Uploading to artifactory'){
            steps{
                rtUpload (
                 serverId:"<server id>" ,
                  spec: '''{
                   "files": [
                      {
                      "pattern": "**/*.jar",
                      "target": "libs-bt-test-local/"
                      }
                            ]
                           }''',
                        )
            }
        }

Let me know if there a possible way to include a loop which will dynamically change the directory structure for every jar.


问:
Take row pairs in one pandas dataframe and iterate through another dataframe
I would like to iterate through row pairs of df_a, comparing firstname1 to lastname1 and firstname2 to lastname2. So for each row pair (Ex. firstname1 & lastname1), I would then like to iterate through df_b and identify non-overlapping coordinate ranges (coordinate_start, coordinate_end) for those names, for example the coordinate ranges assigned for firstname1 do not overlap with any of the coordinate ranges for lastname1.

Starting with df_a & df_b:

```<code>a = {'ID_a': ['firstname1', 'firstname2'], 'ID_b': ['lastname1', 'lastname2']}

df_a = pd.DataFrame(a)

b = {'coordinate_start' :[1,6,20,35,51,1,7,15,40,51,70,85,91,70,80,94], 'coordinate_end':[5,15,27,50,55,5,14,19,47,55,78,90,93,78,84,100],
 'name': ['firstname1', 'firstname1','firstname1', 'firstname1','firstname1',
 'lastname1','lastname1','lastname1','lastname1','lastname1',
 'firstname2','firstname2','firstname2',
 'lastname2','lastname2', 'lastname2'
 ]}

df_b = pd.DataFrame(b)
</code>```

I would like to return df_c, which contains the non-overlapping coordinates and the name it's associated with:

```<code>c = {'unique_coordinate_start': [20,85,80,91,94],
'unique_coordinate_end': [27,90,84,93,100],
'name': ['firstname1','firstname2', 'lastname2','firstname2','lastname2']}

df_c = pd.DataFrame(c)
</code>```

答:
In order to compare existing coordinates easily, I created an additional dataframe (df) whose index represents the coordinates.

Code:

target_indexes = []
col_cs, col_ce = 'coordinate_start', 'coordinate_end'
for _, (fn, ln) in df_a.iterrows():
    df_b_subset = df_b[df_b.name.isin([fn, ln])]
    co_min, co_max = df_b_subset.agg({col_cs: 'min',col_ce: 'max'})

    df = pd.DataFrame(index=range(co_min, co_max+1), columns=[fn, ln]).fillna(-1)

    for i, (co_s, co_e, col) in df_b_subset.iterrows():
        df.loc[co_s:co_e, col] = i

    for col in [fn, ln]:
        df_agg = df.groupby(col).max()
        target_indexes += df_agg[df_agg.values<0].index.tolist()

mask = df_b.index.isin(target_indexes)
rename_table = {col_cs: f'unique_{col_cs}', col_ce: f'unique_{col_ce}'}
df_c = df_b[mask].rename(columns=rename_table).reset_index(drop=True)
```

Output:

unique_coordinate_start
unique_coordinate_end
name

0
20
27
firstname1

1
85
90
firstname2

2
91
93
firstname2

3
80
84
lastname2

4
94
100
lastname2

Body:
I would like to iterate through row pairs of df_a, comparing firstname1 to lastname1 and firstname2 to lastname2. So for each row pair (Ex. firstname1 & lastname1), I would then like to iterate through df_b and identify non-overlapping coordinate ranges (coordinate_start, coordinate_end) for those names, for example the coordinate ranges assigned for firstname1 do not overlap with any of the coordinate ranges for lastname1.

Starting with df_a & df_b:

a = {'ID_a': ['firstname1', 'firstname2'], 'ID_b': ['lastname1', 'lastname2']}

df_a = pd.DataFrame(a)

b = {'coordinate_start' :[1,6,20,35,51,1,7,15,40,51,70,85,91,70,80,94], 'coordinate_end':[5,15,27,50,55,5,14,19,47,55,78,90,93,78,84,100],
 'name': ['firstname1', 'firstname1','firstname1', 'firstname1','firstname1',
 'lastname1','lastname1','lastname1','lastname1','lastname1',
 'firstname2','firstname2','firstname2',
 'lastname2','lastname2', 'lastname2'
 ]}

df_b = pd.DataFrame(b)

I would like to return df_c, which contains the non-overlapping coordinates and the name it's associated with:

c = {'unique_coordinate_start': [20,85,80,91,94],
'unique_coordinate_end': [27,90,84,93,100],
'name': ['firstname1','firstname2', 'lastname2','firstname2','lastname2']}

df_c = pd.DataFrame(c)

Body:
In order to compare existing coordinates easily, I created an additional dataframe (df) whose index represents the coordinates.

Code:

target_indexes = []
col_cs, col_ce = 'coordinate_start', 'coordinate_end'
for _, (fn, ln) in df_a.iterrows():
    df_b_subset = df_b[df_b.name.isin([fn, ln])]
    co_min, co_max = df_b_subset.agg({col_cs: 'min',col_ce: 'max'})

    df = pd.DataFrame(index=range(co_min, co_max+1), columns=[fn, ln]).fillna(-1)

    for i, (co_s, co_e, col) in df_b_subset.iterrows():
        df.loc[co_s:co_e, col] = i

    for col in [fn, ln]:
        df_agg = df.groupby(col).max()
        target_indexes += df_agg[df_agg.values<0].index.tolist()

mask = df_b.index.isin(target_indexes)
rename_table = {col_cs: f'unique_{col_cs}', col_ce: f'unique_{col_ce}'}
df_c = df_b[mask].rename(columns=rename_table).reset_index(drop=True)

Output:

unique_coordinate_start
unique_coordinate_end
name

0
20
27
firstname1

1
85
90
firstname2

2
91
93
firstname2

3
80
84
lastname2

4
94
100
lastname2


问:
Difference between copy /b and cat - windows refuses to execute file (self extracting archive)
I'm working on a script to package up an installer into a self extracting archive. Initially I was working on batch script using

```<code>copy /b .\7zSD.sfx + .\config.txt + .\installer.7z .\installer.exe
</code>```

and the self extracting archive functioned as expected.

As the developers are working in a cygwin environment I tried converting to a bash script for this particular part using

```<code>cat 7zSD.sfx config.txt installer.7z > installer.exe
</code>```

The file is properly created and can be extracted using for example winrar, yet executing results in the attached windows error:

Are there differences that I should be aware of or does somebody know of the right way to approach this?

答:
While I did unsuccessfully try yesterday to change the permissions via the windows file properties, I did not try changing the permissions with chmod.

Checking the permissions using ls -l installer.exe revealed them as only having read/write permissions for users and groups.
My solution was to do a

```<code>chmod 770 installer.exe
</code>```

to get this working.

Body:
I'm working on a script to package up an installer into a self extracting archive. Initially I was working on batch script using

copy /b .\7zSD.sfx + .\config.txt + .\installer.7z .\installer.exe

and the self extracting archive functioned as expected.

As the developers are working in a cygwin environment I tried converting to a bash script for this particular part using

cat 7zSD.sfx config.txt installer.7z > installer.exe

The file is properly created and can be extracted using for example winrar, yet executing results in the attached windows error:

Are there differences that I should be aware of or does somebody know of the right way to approach this?

Body:
While I did unsuccessfully try yesterday to change the permissions via the windows file properties, I did not try changing the permissions with chmod.

Checking the permissions using ls -l installer.exe revealed them as only having read/write permissions for users and groups.
My solution was to do a

chmod 770 installer.exe

to get this working.


问:
Promise / then returning prior to nested promise?
I feel like I'm missing something here, but can't quite figure it out even after reading all the other Stackoverflow questions on nested promises.

Using selenium to get a text value of an element, I use that text later, but it's null unless I manually put in a wait...

```<code>var someText = "";
await driver.findElement(By.css("span[title='crazyValue']")).then(function (element) {
    element.getText().then(function (text) {
        console.log("someText : " + text);
        someText = text;
    });
});

//Use someText variable immediately and it's blank...  My current solution adds an await new Promise(resolve => setTimeout(resolve, 2000)); to delay execution...
</code>```

How do I make the findElement promise also wait on the inner getText promise?

Per comment, this works:

```<code>var someText = "";
await driver.findElement(By.css("span[title='crazyValue']")).then(function (element) {
    return element.getText().then(function (text) {
        console.log("someText : " + text);
        someText = text;
    });
});
</code>```

But also, I think written better it should be this:

```<code>var someText = "";
await driver.findElement(By.css("span[title='crazyValue']")).then(function (element) {
    return element.getText();
}).then(function (text) {
        console.log("someText : " + text);
        someText = text;
});
</code>```

答:
Since you're already in an async function, use await on all promises, rather than calling .then(...):

```<code>const element = await driver.findElement(By.css("span[title='crazyValue']"));
const someText = await element.getText();
console.log("someText:", someText);
</code>```

async function - JavaScript | MDN

Body:
I feel like I'm missing something here, but can't quite figure it out even after reading all the other Stackoverflow questions on nested promises.

Using selenium to get a text value of an element, I use that text later, but it's null unless I manually put in a wait...

var someText = "";
await driver.findElement(By.css("span[title='crazyValue']")).then(function (element) {
    element.getText().then(function (text) {
        console.log("someText : " + text);
        someText = text;
    });
});

//Use someText variable immediately and it's blank...  My current solution adds an await new Promise(resolve => setTimeout(resolve, 2000)); to delay execution...

How do I make the findElement promise also wait on the inner getText promise?

Per comment, this works:

var someText = "";
await driver.findElement(By.css("span[title='crazyValue']")).then(function (element) {
    return element.getText().then(function (text) {
        console.log("someText : " + text);
        someText = text;
    });
});

But also, I think written better it should be this:

var someText = "";
await driver.findElement(By.css("span[title='crazyValue']")).then(function (element) {
    return element.getText();
}).then(function (text) {
        console.log("someText : " + text);
        someText = text;
});

Body:
Since you're already in an async function, use await on all promises, rather than calling .then(...):

const element = await driver.findElement(By.css("span[title='crazyValue']"));
const someText = await element.getText();
console.log("someText:", someText);

async function - JavaScript | MDN


问:
Typescript try catch function with generics
I am trying to make one line try catch function which accepts promise and generic type.
But when I use my function my generic type doesn't show my generic type

Object is of type 'unknown'.ts(2571)

Instead of showing {type: string}

Here is the function

export const tcatch = async <T extends unknown> (promise: Promise<any>) => {
  try {
    const tcData = await promise;
    return [tcData as T, null];
  } catch (tcError) {
    return [null, tcError];
  }
};
```
<p>And here is the usage</p>
<pre class="lang-js prettyprint-override"><code>const promise = WebBrowser.openAuthSessionAsync();
const [data, error] = await tcatch<{type: string}>(promise);
</code>```

答:
Typescript has update changed object inside catch to type unknown instead of any
so this

export const tcatch = async <T extends unknown> (promise: Promise<any>) => {
  try {
    const tcData = await promise;
    return [tcData as T, null];
  } catch (tcError) {
    return [null, tcError];
  }
};

```
<p>actually looks like this:</p>
<pre class="lang-js prettyprint-override"><code>export const tcatch = async <T extends unknown> (promise: Promise<any>) => {
  try {
    const tcData = await promise;
    return [tcData as T, null];
  } catch (tcError:unknown) {
    return [null, tcError];
  }
};

</code>```

that is why you getting object of type unknown to solve this you need to change it to your own interface / type or change it to any.

In your case just add this inside the catch:

  const urType  = tcError as YourInterfaceOrType
```

OR change to this catch(tcError:any)

Body:
I am trying to make one line try catch function which accepts promise and generic type.
But when I use my function my generic type doesn't show my generic type

Object is of type 'unknown'.ts(2571)

Instead of showing {type: string}

Here is the function

export const tcatch = async <T extends unknown> (promise: Promise<any>) => {
  try {
    const tcData = await promise;
    return [tcData as T, null];
  } catch (tcError) {
    return [null, tcError];
  }
};

And here is the usage

const promise = WebBrowser.openAuthSessionAsync();
const [data, error] = await tcatch<{type: string}>(promise);

Body:
Typescript has update changed object inside catch to type unknown instead of any
so this

export const tcatch = async <T extends unknown> (promise: Promise<any>) => {
  try {
    const tcData = await promise;
    return [tcData as T, null];
  } catch (tcError) {
    return [null, tcError];
  }
};

actually looks like this:

export const tcatch = async <T extends unknown> (promise: Promise<any>) => {
  try {
    const tcData = await promise;
    return [tcData as T, null];
  } catch (tcError:unknown) {
    return [null, tcError];
  }
};

that is why you getting object of type unknown to solve this you need to change it to your own interface / type or change it to any.

In your case just add this inside the catch:

  const urType  = tcError as YourInterfaceOrType

OR change to this catch(tcError:any)


问:
Why do the middle rows of my hollow right triangle all have the same size?
I have a task to create a hollow right triangle using a function. The question I have is how to print in numerical order.

So, starting with one in row one and ending in the last row with four characters. The code I have right now created the first and last rows. For the middle row I need it to have it in order but missing the middle if its greater than 2. I have a function that works and does this (hollow_row) but right now my code is just printing the given number without going from smallest to largest.

How can I fix this?

```<code>def triangle(char,n):
    middle_row = hollow_row(char,n)
    print(char*1)
    for i in range (n-2):
         print(middle_row)
    print(char*n)
</code>```

What it prints:

```<code>#
#  #
#  #
####
</code>```

What it needs to print:

```<code>#
##
# #
####
</code>```

答:
Currently you are creating one middle_row which has the size of the base of the triangle (n) and which is used multiple times.

Instead, you need to create a different middle_row for each row, which has the size of that row (i).

After defining the value of a variable by calling a function, the function is not called again automatically each time the variable is used.

You need to call hollow_row in every iteration of the loop, not only once before the loop.

Body:
I have a task to create a hollow right triangle using a function. The question I have is how to print in numerical order.

So, starting with one in row one and ending in the last row with four characters. The code I have right now created the first and last rows. For the middle row I need it to have it in order but missing the middle if its greater than 2. I have a function that works and does this (hollow_row) but right now my code is just printing the given number without going from smallest to largest.

How can I fix this?

def triangle(char,n):
    middle_row = hollow_row(char,n)
    print(char*1)
    for i in range (n-2):
         print(middle_row)
    print(char*n)

What it prints:

#
#  #
#  #
####

What it needs to print:

#
##
# #
####