冰雪梦之恋

文章 评论 浏览 28

冰雪梦之恋 2025-02-20 16:50:24
it = (gzip.open(f, 'rb') for f in jsonfilename)

这可能是给定GZIP产生二进制文件的正确参数。

it = (gzip.open(f, 'rb') for f in jsonfilename)

This may be the right argument given gzip produces a binary file.

如何在列中解压缩多个JSON GZIP文件?

冰雪梦之恋 2025-02-20 16:49:22

您可以创建 global 变量 isloading 并使用 valueNotifier valuelistenablebuilder 显示 cignularProgressIndicator()如果是。
我已经重构了您的代码。

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

void main() => runApp(const MaterialApp(home: PageLoadApp()));
final isLoading = ValueNotifier<bool>(true);

class PageLoadApp extends StatefulWidget {
  const PageLoadApp({Key? key}) : super(key: key);

  @override
  State<PageLoadApp> createState() => _PageLoadAppState();
}

class _PageLoadAppState extends State<PageLoadApp> {
  static String get _url {
    // await Future.delayed(const Duration(seconds: 10));
    return 'https://www.canada.ca/en/immigration-refugees-citizenship/corporate/publications-manuals/discover-canada/read-online/canadas-history.html';
  }

  @override
  Widget build(BuildContext context) => Scaffold(
          body: Scaffold(
        body: ValueListenableBuilder<bool>(
            valueListenable: isLoading,
            builder: (context, value, _) {
              return Scaffold(
                body: Stack(
                  children: <Widget>[
                    WebViewWidget(
                      url: _url,
                    ),
                    (value == true
                        ? Scaffold(
                            body: Center(
                              child: CircularProgressIndicator(),
                            ),
                          )
                        : Container()),
                  ],
                ),
              );
              ;
            }),
      ));
}

class WebViewWidget extends StatefulWidget {
  final String url;

  const WebViewWidget({
    required this.url,
  });

  @override
  _WebViewWidget createState() => _WebViewWidget();
}

class _WebViewWidget extends State<WebViewWidget> {
  late WebView _webView;
  final Completer<WebViewController> _controller =
      Completer<WebViewController>();

  Iterable<Future<void>> cleanupLoadedHtmlPage(WebViewController controller) {
    const List<String> javascriptToExecute = [
      'document.getElementById("wb-lng").hidden = true;',
      'document.getElementById("wb-srch").hidden = true',
      'document.getElementsByClassName("gcweb-menu")[0].hidden = true',
      'document.getElementsByClassName("mwsalerts")[0].hidden = true',
      'document.getElementById("wb-bc").hidden = true',
      'document.getElementsByClassName("pagination")[0].hidden = true',
      'document.getElementsByClassName("pagedetails")[0].hidden = true',
      'document.getElementsByClassName("global-footer")[0].hidden = true'
    ];
    return javascriptToExecute.map((js) {
      print("removing $js");
      return controller.runJavascript(js);
    });
  }

  @override
  void initState() {
    super.initState();
    _webView = WebView(
      initialUrl: widget.url,
      javascriptMode: JavascriptMode.unrestricted,
      onWebViewCreated: (WebViewController webViewController) {
        _controller.complete(webViewController);
      },
      onProgress: (int progress) {},
      onPageStarted: (String url) {
        isLoading.value = true;
        print('Page started loading: $url');
      },
      onPageFinished: (String url) async {
        // Navigator.pop(context);

        print('Page finished loading: $url');

        final controller = await _controller.future;
        var cleanupFuture = cleanupLoadedHtmlPage(controller);
        Future.wait(cleanupFuture).then((value) {
          print("Clean up done => $value");
        });
        // for demo purposes, wait for 3 seconds
        await Future.delayed(Duration(seconds: 3));
        isLoading.value = false;
      },
    );
  }

  @override
  void dispose() {
    super.dispose();
    //_webView = null;
  }

  @override
  Widget build(BuildContext context) => _webView;
}

You can create a global variable isLoading and use the help of ValueNotifier and ValueListenableBuilder to check if the value is loading to show a CircularProgressIndicator() if it is.
I've refactored your code.

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

void main() => runApp(const MaterialApp(home: PageLoadApp()));
final isLoading = ValueNotifier<bool>(true);

class PageLoadApp extends StatefulWidget {
  const PageLoadApp({Key? key}) : super(key: key);

  @override
  State<PageLoadApp> createState() => _PageLoadAppState();
}

class _PageLoadAppState extends State<PageLoadApp> {
  static String get _url {
    // await Future.delayed(const Duration(seconds: 10));
    return 'https://www.canada.ca/en/immigration-refugees-citizenship/corporate/publications-manuals/discover-canada/read-online/canadas-history.html';
  }

  @override
  Widget build(BuildContext context) => Scaffold(
          body: Scaffold(
        body: ValueListenableBuilder<bool>(
            valueListenable: isLoading,
            builder: (context, value, _) {
              return Scaffold(
                body: Stack(
                  children: <Widget>[
                    WebViewWidget(
                      url: _url,
                    ),
                    (value == true
                        ? Scaffold(
                            body: Center(
                              child: CircularProgressIndicator(),
                            ),
                          )
                        : Container()),
                  ],
                ),
              );
              ;
            }),
      ));
}

class WebViewWidget extends StatefulWidget {
  final String url;

  const WebViewWidget({
    required this.url,
  });

  @override
  _WebViewWidget createState() => _WebViewWidget();
}

class _WebViewWidget extends State<WebViewWidget> {
  late WebView _webView;
  final Completer<WebViewController> _controller =
      Completer<WebViewController>();

  Iterable<Future<void>> cleanupLoadedHtmlPage(WebViewController controller) {
    const List<String> javascriptToExecute = [
      'document.getElementById("wb-lng").hidden = true;',
      'document.getElementById("wb-srch").hidden = true',
      'document.getElementsByClassName("gcweb-menu")[0].hidden = true',
      'document.getElementsByClassName("mwsalerts")[0].hidden = true',
      'document.getElementById("wb-bc").hidden = true',
      'document.getElementsByClassName("pagination")[0].hidden = true',
      'document.getElementsByClassName("pagedetails")[0].hidden = true',
      'document.getElementsByClassName("global-footer")[0].hidden = true'
    ];
    return javascriptToExecute.map((js) {
      print("removing $js");
      return controller.runJavascript(js);
    });
  }

  @override
  void initState() {
    super.initState();
    _webView = WebView(
      initialUrl: widget.url,
      javascriptMode: JavascriptMode.unrestricted,
      onWebViewCreated: (WebViewController webViewController) {
        _controller.complete(webViewController);
      },
      onProgress: (int progress) {},
      onPageStarted: (String url) {
        isLoading.value = true;
        print('Page started loading: $url');
      },
      onPageFinished: (String url) async {
        // Navigator.pop(context);

        print('Page finished loading: $url');

        final controller = await _controller.future;
        var cleanupFuture = cleanupLoadedHtmlPage(controller);
        Future.wait(cleanupFuture).then((value) {
          print("Clean up done => $value");
        });
        // for demo purposes, wait for 3 seconds
        await Future.delayed(Duration(seconds: 3));
        isLoading.value = false;
      },
    );
  }

  @override
  void dispose() {
    super.dispose();
    //_webView = null;
  }

  @override
  Widget build(BuildContext context) => _webView;
}

如何显示加载屏幕,直到JavaScript在加载页面上执行?

冰雪梦之恋 2025-02-20 11:22:29

不要使事情复杂化

const {data} = useQuery('entitle', apiCall)
const {title=[], desc=[]} = data

Dont complicate the things

const {data} = useQuery('entitle', apiCall)
const {title=[], desc=[]} = data

如何驱动usequery的响应

冰雪梦之恋 2025-02-20 06:10:46

我知道有可能下降一个目录IE:

parendmodule.py:

from childDirectory.childScript import runChildMain
def runFunction():
    runChildMain()
runFunction()

childscript.py

def runChildMain():
    print("HIT Run child main")

if __name__ == "__main__":
    runChildMain()

如果必须使用该文件结构,则可能必须使用该文件结构:

sys.path.append( os.path.dirname(os.path.realpath(__file__))+'/..')

I know it is possible to go down a directory ie:

parentModule.py:

from childDirectory.childScript import runChildMain
def runFunction():
    runChildMain()
runFunction()

childScript.py

def runChildMain():
    print("HIT Run child main")

if __name__ == "__main__":
    runChildMain()

if the file structure has to be set up that way though you may have to use:

sys.path.append( os.path.dirname(os.path.realpath(__file__))+'/..')

来自父文件夹的导入模块,但仍在儿童目录中工作

冰雪梦之恋 2025-02-19 10:43:48

有几种方法可以解决这个问题。如果您知道第一行的大小,则应该能够使用 fseek 移动文件的位置,而不是使用 getline 以获取文件的每一行

int fseek(FILE *stream, long offset, int whence);

参数可以是:

  • seek_set :开始
  • seek_cur :当前位置
  • seek_end :结束

另一个选项将封装整个文件读取一段时间循环:

    char *line = NULL;
    size_t linecap = 0;
    ssize_t linelen;
    int counter = 0;

    while((linelen = getline(&line, &linecap, file)) != -1){
        if counter == 0{
            sscanf(line, "%d %d\n", &primNum, &secNum);
        }else{
            //Process your line
        }
        counter++; //This would give you your total line length
    }

There are a few ways to approach this; if you know the size of the first line, you should be able to use fseek to move the position of the file than use getline to get each line of the file:

int fseek(FILE *stream, long offset, int whence);

The whence parameter can be:

  • SEEK_SET : the Beginning
  • SEEK_CUR : the current position
  • SEEK_END : the End

The other option would to encapsulate the entire file read in a while loop:

    char *line = NULL;
    size_t linecap = 0;
    ssize_t linelen;
    int counter = 0;

    while((linelen = getline(&line, &linecap, file)) != -1){
        if counter == 0{
            sscanf(line, "%d %d\n", &primNum, &secNum);
        }else{
            //Process your line
        }
        counter++; //This would give you your total line length
    }

如何在C上的.txt文件上从第二行中读取内容

冰雪梦之恋 2025-02-19 09:04:24

它不是浮点或任何其他合并:

let in_file_name: PathBuf;
if let Some(infile) = matches.get_one::<PathBuf>("infile") {
    in_file_name = infile.to_owned().into();

工作时遇到相同的问题

let in_file_name: PathBuf;

if let Some(infile) = matches.get_one::<String>("infile") {
    in_file_name = infile.to_owned().into();


-Michael

It's not floating point or any other comnversion:

let in_file_name: PathBuf;
if let Some(infile) = matches.get_one::<PathBuf>("infile") {
    in_file_name = infile.to_owned().into();

has the same issue while

let in_file_name: PathBuf;

if let Some(infile) = matches.get_one::<String>("infile") {
    in_file_name = infile.to_owned().into();

works.
-Michael

argmatches&#x27; get_one不能击落f64

冰雪梦之恋 2025-02-19 03:08:36

很难确切说明您的含义,因为片段并没有真正渲染任何内容,并且不包括每个部分的CSS,但是,我确实看到HTML代码中可能导致渲染不一致的两个小问题。

首先,项目div没有按钮。其次,Talk Div中的&lt; p&gt; 在className中具有错别字。它说 talk-desc&gt; 而不是 talk-desc

也就是说,如果我添加按钮并从您的文件中删除特定的CSS,则它们都相同。因此,容器谈话 div实际上是正确继承的,您看到的渲染差异在您添加了CSS样式的嵌套元素中。

/************/
/* base.css */
/************/


/* color palette from <https://github.com/vuejs/theme> */

 :root {
  --vt-c-white: #ffffff;
  --vt-c-white-soft: #f8f8f8;
  --vt-c-white-mute: #f2f2f2;
  --vt-c-black: #181818;
  --vt-c-black-soft: #222222;
  --vt-c-black-mute: #282828;
  --vt-c-indigo: #2c3e50;
  --vt-c-divider-light-1: rgba(60, 60, 60, 0.29);
  --vt-c-divider-light-2: rgba(60, 60, 60, 0.12);
  --vt-c-divider-dark-1: rgba(84, 84, 84, 0.65);
  --vt-c-divider-dark-2: rgba(84, 84, 84, 0.48);
  --vt-c-text-light-1: var(--vt-c-indigo);
  --vt-c-text-light-2: rgba(60, 60, 60, 0.66);
  --vt-c-text-dark-1: var(--vt-c-white);
  --vt-c-text-dark-2: rgba(235, 235, 235, 0.64);
}


/* semantic color variables for this project */

 :root {
  --color-background: var(--vt-c-white);
  --color-background-soft: var(--vt-c-white-soft);
  --color-background-mute: var(--vt-c-white-mute);
  --color-border: var(--vt-c-divider-light-2);
  --color-border-hover: var(--vt-c-divider-light-1);
  --color-heading: var(--vt-c-text-light-1);
  --color-text: var(--vt-c-text-light-1);
  --section-gap: 160px;
}

@media (prefers-color-scheme: dark) {
   :root {
    --color-background: var(--vt-c-black);
    --color-background-soft: var(--vt-c-black-soft);
    --color-background-mute: var(--vt-c-black-mute);
    --color-border: var(--vt-c-divider-dark-2);
    --color-border-hover: var(--vt-c-divider-dark-1);
    --color-heading: var(--vt-c-text-dark-1);
    --color-text: var(--vt-c-text-dark-2);
  }
}

*,
*::before,
*::after {
  box-sizing: border-box;
  margin: 0;
  font-weight: normal;
  position: relative;
}

body {
  min-height: 100vh;
  color: var(--color-text);
  background: var(--color-background-soft);
  transition: color 0.5s, background-color 0.5s;
  line-height: 1.6;
  font-family: Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
  text-rendering: optimizeLegibility;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}



/************/
/* main.css */
/************/


/* Just has a bunch of normal stylings like- */

// .talk-button {
//   border: #ffff00;
//   border-width: 2px;
//   border-style: solid;
//   border-radius: 0.5rem;
//   background-color: transparent;
//   color: rgb(224, 224, 224);
//   opacity: 80%;
//   margin-top: 4rem;
//   padding-top: 1rem;
//   padding-left: 0.3rem;
//   padding-right: 0.3rem;
//   padding: 1rem;
//   font-size: 16px;
// }

// .talk-desc {
//   padding-top: 2rem;
//   padding-bottom: 2rem;
//   max-width: 65%;
//   font-size: 20px;
//   color: rgb(165, 165, 165);
// }

// .talk-subtitle {
//   margin-top: 10rem;
// }
<div class="encompass">
  <div class="hero-section">
    <h1 class="small-heading">
      <span class=""></span>
      <span class="period" style="color: yellow"></span>
    </h1>
    <div class="big-heading">
      <h2>
      <span class="build"></span>
      <span class="random-text"></span>
      </h2>
    </div>
    <p class="main-desc"></p>
    <button class="linkedin">LinkedIn Button</button>
  </div>

  <div class="about">
    <h1 class="subtitle">About Subhead</h1>
    <p class="about-desc">About description</p>
    <button class="coffee">About Button</button>
  </div>

  <div class="projects">
    <h1 class="proj-subtitle">Projects Subhead</h1>
    <p class="proj-desc">Projects description</p>
        <button class="proj-button">Projects Button</button>
  </div>

  <div class="talk">
    <h1 class="talk-subtitle">Talk Subhead</h1>
    <p class="talk-desc">Talk description</p>
    <button class="talk-button">Talk Button</button>
  </div>

</div>

Hard to tell exactly what you mean since the snippet doesn't really render anything and the CSS for each section isn't included, however, I do see two minor issues in the HTML code that could be causing rendering inconsistencies.

First, the Projects div doesn't have a button. And second the <p> inside the Talk div has a typo in the classname. it says talk-desc> instead of talk-desc.

That said, if I add the button in and remove the "talk" specific CSS from your file, they all render the same. So the container talk div is actually inheriting correctly, the rendering difference you are seeing is in the nested elements that you have added CSS stylings for.

/************/
/* base.css */
/************/


/* color palette from <https://github.com/vuejs/theme> */

 :root {
  --vt-c-white: #ffffff;
  --vt-c-white-soft: #f8f8f8;
  --vt-c-white-mute: #f2f2f2;
  --vt-c-black: #181818;
  --vt-c-black-soft: #222222;
  --vt-c-black-mute: #282828;
  --vt-c-indigo: #2c3e50;
  --vt-c-divider-light-1: rgba(60, 60, 60, 0.29);
  --vt-c-divider-light-2: rgba(60, 60, 60, 0.12);
  --vt-c-divider-dark-1: rgba(84, 84, 84, 0.65);
  --vt-c-divider-dark-2: rgba(84, 84, 84, 0.48);
  --vt-c-text-light-1: var(--vt-c-indigo);
  --vt-c-text-light-2: rgba(60, 60, 60, 0.66);
  --vt-c-text-dark-1: var(--vt-c-white);
  --vt-c-text-dark-2: rgba(235, 235, 235, 0.64);
}


/* semantic color variables for this project */

 :root {
  --color-background: var(--vt-c-white);
  --color-background-soft: var(--vt-c-white-soft);
  --color-background-mute: var(--vt-c-white-mute);
  --color-border: var(--vt-c-divider-light-2);
  --color-border-hover: var(--vt-c-divider-light-1);
  --color-heading: var(--vt-c-text-light-1);
  --color-text: var(--vt-c-text-light-1);
  --section-gap: 160px;
}

@media (prefers-color-scheme: dark) {
   :root {
    --color-background: var(--vt-c-black);
    --color-background-soft: var(--vt-c-black-soft);
    --color-background-mute: var(--vt-c-black-mute);
    --color-border: var(--vt-c-divider-dark-2);
    --color-border-hover: var(--vt-c-divider-dark-1);
    --color-heading: var(--vt-c-text-dark-1);
    --color-text: var(--vt-c-text-dark-2);
  }
}

*,
*::before,
*::after {
  box-sizing: border-box;
  margin: 0;
  font-weight: normal;
  position: relative;
}

body {
  min-height: 100vh;
  color: var(--color-text);
  background: var(--color-background-soft);
  transition: color 0.5s, background-color 0.5s;
  line-height: 1.6;
  font-family: Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
  text-rendering: optimizeLegibility;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}



/************/
/* main.css */
/************/


/* Just has a bunch of normal stylings like- */

// .talk-button {
//   border: #ffff00;
//   border-width: 2px;
//   border-style: solid;
//   border-radius: 0.5rem;
//   background-color: transparent;
//   color: rgb(224, 224, 224);
//   opacity: 80%;
//   margin-top: 4rem;
//   padding-top: 1rem;
//   padding-left: 0.3rem;
//   padding-right: 0.3rem;
//   padding: 1rem;
//   font-size: 16px;
// }

// .talk-desc {
//   padding-top: 2rem;
//   padding-bottom: 2rem;
//   max-width: 65%;
//   font-size: 20px;
//   color: rgb(165, 165, 165);
// }

// .talk-subtitle {
//   margin-top: 10rem;
// }
<div class="encompass">
  <div class="hero-section">
    <h1 class="small-heading">
      <span class=""></span>
      <span class="period" style="color: yellow"></span>
    </h1>
    <div class="big-heading">
      <h2>
      <span class="build"></span>
      <span class="random-text"></span>
      </h2>
    </div>
    <p class="main-desc"></p>
    <button class="linkedin">LinkedIn Button</button>
  </div>

  <div class="about">
    <h1 class="subtitle">About Subhead</h1>
    <p class="about-desc">About description</p>
    <button class="coffee">About Button</button>
  </div>

  <div class="projects">
    <h1 class="proj-subtitle">Projects Subhead</h1>
    <p class="proj-desc">Projects description</p>
        <button class="proj-button">Projects Button</button>
  </div>

  <div class="talk">
    <h1 class="talk-subtitle">Talk Subhead</h1>
    <p class="talk-desc">Talk description</p>
    <button class="talk-button">Talk Button</button>
  </div>

</div>

为什么我的div从主CSS文件继承而不是最后一个DIV?

冰雪梦之恋 2025-02-19 02:54:20

是的,Sudo特权在Studio Lab中不可用。最好的选择是找到一个可以安装而无需Sudo特权的库。

您也可以尝试 - conda install -c conda -forge rdki

Yes, sudo privileges are not available in Studio Lab. Your best bet is to find a different library that you can install without sudo privileges.

You can also try - conda install -c conda-forge rdki

Amazon-Sagemaker-Lab :: libxrender.so.1软件包

冰雪梦之恋 2025-02-18 18:01:33

您可以使您的 student (从 重命名)类以实现可比性接口为了使用 arrays.sort.sort.sort.sort 方法。在这种情况下,您必须添加到 compareTo 方法。

class Student implements Comparable<Student> { //DaftarSiswa
    public int number;
    public String name;

    public Student(int number, String name) {
        this.number = number;
        this.name = name;
    }

    @Override
    public int compareTo(Student o) {
        return this.number - o.number;
    }

    @Override
    public String toString() {
        return "Student {number=" + number + ", name='" + name +"'}\n";
    }
}

public class Test { //NomorUrut
    public static void main(String[] args) {
        Student[] data = new Student[10];
        data[0] = new Student(10, "Brycen");
        data[1] = new Student(6, "Devan");
        data[2] = new Student(3, "Rylan");
        data[3] = new Student(1, "Gordy");
        data[4] = new Student(2, "Tim");
        data[5] = new Student(4, "Curtis");
        data[6] = new Student(5, "Abe");
        data[7] = new Student(9, "Melvin");
        data[8] = new Student(8, "Ansel");
        data[9] = new Student(7, "Dalton");

        Arrays.sort(data);

        System.out.println(Arrays.toString(data));
    }
}

You can make your Student (renamed from StudentList) class to implement Comparable interface in order to sort your array using Arrays.sort method. In this case you must add to Student class implementation of compareTo method.

class Student implements Comparable<Student> { //DaftarSiswa
    public int number;
    public String name;

    public Student(int number, String name) {
        this.number = number;
        this.name = name;
    }

    @Override
    public int compareTo(Student o) {
        return this.number - o.number;
    }

    @Override
    public String toString() {
        return "Student {number=" + number + ", name='" + name +"'}\n";
    }
}

public class Test { //NomorUrut
    public static void main(String[] args) {
        Student[] data = new Student[10];
        data[0] = new Student(10, "Brycen");
        data[1] = new Student(6, "Devan");
        data[2] = new Student(3, "Rylan");
        data[3] = new Student(1, "Gordy");
        data[4] = new Student(2, "Tim");
        data[5] = new Student(4, "Curtis");
        data[6] = new Student(5, "Abe");
        data[7] = new Student(9, "Melvin");
        data[8] = new Student(8, "Ansel");
        data[9] = new Student(7, "Dalton");

        Arrays.sort(data);

        System.out.println(Arrays.toString(data));
    }
}

通过按数字显示排序,使包含数字和名称数据的对象数组

冰雪梦之恋 2025-02-18 10:56:14

如果要连接 azure托管身份与azure databricks,

请按照此操作。 -Identity“> so 线程 @Alex Ott

示例代码

 来自Databricks导入SQL
    来自azure.Identity Import cluttratecretcredential
    导入操作系统
    tenant_id ='enter_tenant_id'
    client_id ='enter_client_id'
    client_secret = os.environ ['sp_secret']
    csc = clienterecretcredential(tenant_id,client_id,client_secret)
    范围='2xxxxx/.default'
    token = csc.get_token(dbx_scope).token
 

请参阅此 用于将SQL连接到Azure Databricks

If you want to connect azure managed identity with azure Databricks

Follow this SO thread by @Alex Ott

Sample code

from databricks import sql
    from azure.identity import ClientSecretCredential
    import os
    tenant_id = 'enter_tenant_id'
    client_id = 'enter_client_id'
    client_secret = os.environ['SP_SECRET']
    csc = ClientSecretCredential(tenant_id, client_id, client_secret)
    scope = '2xxxxx/.default'
    token = csc.get_token(dbx_scope).token

Refer this document for connecting SQL to azure Databricks

是否可以使用来自数据砖中Azure托管身份的对象ID连接SQL Server

冰雪梦之恋 2025-02-18 10:35:09

带有子选项的子句中的不是最优雅的(至少在过去,也不是执行查询的最佳方法)。

为了使用 JOIN 具有绝对相同结果的子句,请尝试下面的查询,这很简洁:

q = session.query(Course).filter(Course.students.any(Student.id == 2))

并将产生以下 sql

SELECT course.id,
       course.name
FROM course
WHERE EXISTS
    (SELECT 1
     FROM association,
          student
     WHERE course.id = association.course_id
       AND student.id = association.student_id
       AND student.id = ?)

但是,避免在 student 表格,以下更明确的查询将产生相同的结果:

q = (
    session
    .query(Course)
    .join(
        association_table, 
        (Course.id == association_table.c.course_id) & (association_table.c.student_id == 2),
    )
)

这将导致 sql 与以下相似:

SELECT  course.id,
        course.name
FROM    course
   JOIN association
     ON course.id = association.course_id
    AND association.student_id = ?

The IN clause with sub-select is not the most elegant (and at least in the past, also not the most optimal way to execute the query).

In order to use JOIN clause with absolutely the same result please try the query below which is very succinct:

q = session.query(Course).filter(Course.students.any(Student.id == 2))

and will produce following SQL:

SELECT course.id,
       course.name
FROM course
WHERE EXISTS
    (SELECT 1
     FROM association,
          student
     WHERE course.id = association.course_id
       AND student.id = association.student_id
       AND student.id = ?)

However, to avoid joining on the student table alltogether, the below more explicit query will result in the same outcome:

q = (
    session
    .query(Course)
    .join(
        association_table, 
        (Course.id == association_table.c.course_id) & (association_table.c.student_id == 2),
    )
)

which will result in the SQL similar to below:

SELECT  course.id,
        course.name
FROM    course
   JOIN association
     ON course.id = association.course_id
    AND association.student_id = ?

如何使用协会表,in子句和子查询查询sqlalchemy?

冰雪梦之恋 2025-02-18 10:26:19

编写循环时,您需要考虑如何存储每次迭代的输出。我怀疑 getBb 的输出非常复杂(也许是两个列矩阵?“ bb”用于“边界框”?),所以我将使用“列表”进行存储。

cities <- c("Name1", "Name2")

## initialize storage
output <- vector("list", length(cities))
## add names to list entries
names(output) <- cities

## a loop with numeric index
for (i in 1:length(cities)) {
      output[[i]] <- getbb(
      cities[i],
      format_out = "matrix",
      base_url = "https://nominatim.openstreetmap.org",
      featuretype = "settlement",
      limit = 10,
    )
}

最后,您可以使用城市名称从列表中提取值:

## result for city "Names1"
output[["Names1"]]

When you write a loop, you need to think about how to store the output of each iteration. I suspect that the output of getbb is quite complicated (maybe a two column matrix? "bb" for "bounding box"?), so I would use a "list" for storage.

cities <- c("Name1", "Name2")

## initialize storage
output <- vector("list", length(cities))
## add names to list entries
names(output) <- cities

## a loop with numeric index
for (i in 1:length(cities)) {
      output[[i]] <- getbb(
      cities[i],
      format_out = "matrix",
      base_url = "https://nominatim.openstreetmap.org",
      featuretype = "settlement",
      limit = 10,
    )
}

In the end, you can use city name to extract value from the list:

## result for city "Names1"
output[["Names1"]]

在r中循环中的分类变量值索引

冰雪梦之恋 2025-02-18 03:29:43

您需要为每个项目都有单独的标志。
例如,您可以参考下面的摘要。

您需要检查索引,然后将值分配给该标志

const tempData = [...arryData];
          tempData[index] = {
            ...tempData[index],
            isActive: value,
          };
          setState(tempData);

you need to have separate flag for each items.
For Example you can refer below snippet.

You need to check the index then assign value to that flag

const tempData = [...arryData];
          tempData[index] = {
            ...tempData[index],
            isActive: value,
          };
          setState(tempData);

如何更改React Onclick中点击组件的背景颜色

冰雪梦之恋 2025-02-18 02:05:32

并不是说要这样做,但是在没有使用效果的情况下做OP要求的事情并不难。

使用承诺在设置器函数的正文中解析新状态:

const getState = <T>(
  setState: React.Dispatch<React.SetStateAction<T>>
): Promise<T> => {
  return new Promise((resolve) => {
    setState((currentState: T) => {
      resolve(currentState);
      return currentState;
    });
  });
};

这就是您的使用方式(示例显示了 Count OUTOFSYNCCOUNT /之间的比较UI渲染中的Synccount ):

const App: React.FC = () => {
  const [count, setCount] = useState(0);
  const [outOfSyncCount, setOutOfSyncCount] = useState(0);
  const [syncCount, setSyncCount] = useState(0);

  const handleOnClick = async () => {
    setCount(count + 1);

    // Doesn't work
    setOutOfSyncCount(count);

    // Works
    const newCount = await getState(setCount);
    setSyncCount(newCount);
  };

  return (
    <>
      <h2>Count = {count}</h2>
      <h2>Synced count = {syncCount}</h2>
      <h2>Out of sync count = {outOfSyncCount}</h2>
      <button onClick={handleOnClick}>Increment</button>
    </>
  );
};

Not saying to do this, but it isn't hard to do what the OP asked without useEffect.

Use a promise to resolve the new state in the body of the setter function:

const getState = <T>(
  setState: React.Dispatch<React.SetStateAction<T>>
): Promise<T> => {
  return new Promise((resolve) => {
    setState((currentState: T) => {
      resolve(currentState);
      return currentState;
    });
  });
};

And this is how you use it (example shows the comparison between count and outOfSyncCount/syncCount in the UI rendering):

const App: React.FC = () => {
  const [count, setCount] = useState(0);
  const [outOfSyncCount, setOutOfSyncCount] = useState(0);
  const [syncCount, setSyncCount] = useState(0);

  const handleOnClick = async () => {
    setCount(count + 1);

    // Doesn't work
    setOutOfSyncCount(count);

    // Works
    const newCount = await getState(setCount);
    setSyncCount(newCount);
  };

  return (
    <>
      <h2>Count = {count}</h2>
      <h2>Synced count = {syncCount}</h2>
      <h2>Out of sync count = {outOfSyncCount}</h2>
      <button onClick={handleOnClick}>Increment</button>
    </>
  );
};

USESTATE SET方法不是立即反映更改

冰雪梦之恋 2025-02-18 00:37:02

如果您有各种对象列,例如74个对象列的此数据框和2列的2列,其中每个值都有代表单元的字母:

import pandas as pd 
import numpy as np

dataurl = 'https://raw.githubusercontent.com/RubenGavidia/Pandas_Portfolio.py/main/Wes_Mckinney.py/nutrition.csv'
nutrition = pd.read_csv(dataurl,index_col=[0])
nutrition.head(3)

输出:

    name    serving_size    calories    total_fat    saturated_fat    cholesterol    sodium    choline    folate    folic_acid    ...    fat    saturated_fatty_acids    monounsaturated_fatty_acids    polyunsaturated_fatty_acids    fatty_acids_total_trans    alcohol    ash    caffeine    theobromine    water
0    Cornstarch    100 g    381    0.1g    NaN    0    9.00 mg    0.4 mg    0.00 mcg    0.00 mcg    ...    0.05 g    0.009 g    0.016 g    0.025 g    0.00 mg    0.0 g    0.09 g    0.00 mg    0.00 mg    8.32 g
1    Nuts, pecans    100 g    691    72g    6.2g    0    0.00 mg    40.5 mg    22.00 mcg    0.00 mcg    ...    71.97 g    6.180 g    40.801 g    21.614 g    0.00 mg    0.0 g    1.49 g    0.00 mg    0.00 mg    3.52 g
2    Eggplant, raw    100 g    25    0.2g    NaN    0    2.00 mg    6.9 mg    22.00 mcg    0.00 mcg    ...    0.18 g    0.034 g    0.016 g    0.076 g    0.00 mg    0.0 g    0.66 g    0.00 mg    0.00 mg    92.30 g
3 rows × 76 columns

nutrition.dtypes
name             object
serving_size     object
calories          int64
total_fat        object
saturated_fat    object
                  ...
alcohol          object
ash              object
caffeine         object
theobromine      object
water            object
Length: 76, dtype: object

nutrition.dtypes.value_counts()
object    74
int64      2
dtype: int64

转换为数字的好方法所有列使用正则表达式来替换单位nothing and astype( float)为了将列数据类型更改为float:

nutrition.index = pd.RangeIndex(start = 0, stop = 8789, step= 1)
nutrition.set_index('name',inplace = True)
nutrition.replace('[a-zA-Z]','', regex= True, inplace=True)
nutrition=nutrition.astype(float)
nutrition.head(3)

输出:

serving_size    calories    total_fat    saturated_fat    cholesterol    sodium    choline    folate    folic_acid    niacin    ...    fat    saturated_fatty_acids    monounsaturated_fatty_acids    polyunsaturated_fatty_acids    fatty_acids_total_trans    alcohol    ash    caffeine    theobromine    water
name
Cornstarch    100.0    381.0    0.1    NaN    0.0    9.0    0.4    0.0    0.0    0.000    ...    0.05    0.009    0.016    0.025    0.0    0.0    0.09    0.0    0.0    8.32
Nuts, pecans    100.0    691.0    72.0    6.2    0.0    0.0    40.5    22.0    0.0    1.167    ...    71.97    6.180    40.801    21.614    0.0    0.0    1.49    0.0    0.0    3.52
Eggplant, raw    100.0    25.0    0.2    NaN    0.0    2.0    6.9    22.0    0.0    0.649    ...    0.18    0.034    0.016    0.076    0.0    0.0    0.66    0.0    0.0    92.30
3 rows × 75 columns

nutrition.dtypes
serving_size     float64
calories         float64
total_fat        float64
saturated_fat    float64
cholesterol      float64
                  ...
alcohol          float64
ash              float64
caffeine         float64
theobromine      float64
water            float64
Length: 75, dtype: object

nutrition.dtypes.value_counts()
float64    75
dtype: int64

现在数据集很干净,您只能使用Regex和Astype()使用此数据框进行数字操作。

如果要收集单元并粘贴在标题上,例如胆固醇_mg可以使用此代码:

nutrition.index = pd.RangeIndex(start = 0, stop = 8789, step= 1)
nutrition.set_index('name',inplace = True)
nutrition.astype(str).replace('[^a-zA-Z]','', regex= True)
units = nutrition.astype(str).replace('[^a-zA-Z]','', regex= True)
units = units.mode()
units = units.replace('', np.nan).dropna(axis=1)
mapper = { k: k + "_" + units[k].at[0] for k in units}
nutrition.rename(columns=mapper, inplace=True)
nutrition.replace('[a-zA-Z]','', regex= True, inplace=True)
nutrition=nutrition.astype(float)

In case you have various objects columns like this Dataframe of 74 Objects columns and 2 Int columns where each value have letters representing units:

import pandas as pd 
import numpy as np

dataurl = 'https://raw.githubusercontent.com/RubenGavidia/Pandas_Portfolio.py/main/Wes_Mckinney.py/nutrition.csv'
nutrition = pd.read_csv(dataurl,index_col=[0])
nutrition.head(3)

Output:

    name    serving_size    calories    total_fat    saturated_fat    cholesterol    sodium    choline    folate    folic_acid    ...    fat    saturated_fatty_acids    monounsaturated_fatty_acids    polyunsaturated_fatty_acids    fatty_acids_total_trans    alcohol    ash    caffeine    theobromine    water
0    Cornstarch    100 g    381    0.1g    NaN    0    9.00 mg    0.4 mg    0.00 mcg    0.00 mcg    ...    0.05 g    0.009 g    0.016 g    0.025 g    0.00 mg    0.0 g    0.09 g    0.00 mg    0.00 mg    8.32 g
1    Nuts, pecans    100 g    691    72g    6.2g    0    0.00 mg    40.5 mg    22.00 mcg    0.00 mcg    ...    71.97 g    6.180 g    40.801 g    21.614 g    0.00 mg    0.0 g    1.49 g    0.00 mg    0.00 mg    3.52 g
2    Eggplant, raw    100 g    25    0.2g    NaN    0    2.00 mg    6.9 mg    22.00 mcg    0.00 mcg    ...    0.18 g    0.034 g    0.016 g    0.076 g    0.00 mg    0.0 g    0.66 g    0.00 mg    0.00 mg    92.30 g
3 rows × 76 columns

nutrition.dtypes
name             object
serving_size     object
calories          int64
total_fat        object
saturated_fat    object
                  ...
alcohol          object
ash              object
caffeine         object
theobromine      object
water            object
Length: 76, dtype: object

nutrition.dtypes.value_counts()
object    74
int64      2
dtype: int64

A good way to convert to numeric all columns is using regular expressions to replace the units for nothing and astype(float) for change the columns data type to float:

nutrition.index = pd.RangeIndex(start = 0, stop = 8789, step= 1)
nutrition.set_index('name',inplace = True)
nutrition.replace('[a-zA-Z]','', regex= True, inplace=True)
nutrition=nutrition.astype(float)
nutrition.head(3)

Output:

serving_size    calories    total_fat    saturated_fat    cholesterol    sodium    choline    folate    folic_acid    niacin    ...    fat    saturated_fatty_acids    monounsaturated_fatty_acids    polyunsaturated_fatty_acids    fatty_acids_total_trans    alcohol    ash    caffeine    theobromine    water
name
Cornstarch    100.0    381.0    0.1    NaN    0.0    9.0    0.4    0.0    0.0    0.000    ...    0.05    0.009    0.016    0.025    0.0    0.0    0.09    0.0    0.0    8.32
Nuts, pecans    100.0    691.0    72.0    6.2    0.0    0.0    40.5    22.0    0.0    1.167    ...    71.97    6.180    40.801    21.614    0.0    0.0    1.49    0.0    0.0    3.52
Eggplant, raw    100.0    25.0    0.2    NaN    0.0    2.0    6.9    22.0    0.0    0.649    ...    0.18    0.034    0.016    0.076    0.0    0.0    0.66    0.0    0.0    92.30
3 rows × 75 columns

nutrition.dtypes
serving_size     float64
calories         float64
total_fat        float64
saturated_fat    float64
cholesterol      float64
                  ...
alcohol          float64
ash              float64
caffeine         float64
theobromine      float64
water            float64
Length: 75, dtype: object

nutrition.dtypes.value_counts()
float64    75
dtype: int64

Now the dataset is clean and you are able to do numeric operations with this Dataframe only with regex and astype().

If you want to collect the units and paste on the headers like cholesterol_mg you can use this code:

nutrition.index = pd.RangeIndex(start = 0, stop = 8789, step= 1)
nutrition.set_index('name',inplace = True)
nutrition.astype(str).replace('[^a-zA-Z]','', regex= True)
units = nutrition.astype(str).replace('[^a-zA-Z]','', regex= True)
units = units.mode()
units = units.replace('', np.nan).dropna(axis=1)
mapper = { k: k + "_" + units[k].at[0] for k in units}
nutrition.rename(columns=mapper, inplace=True)
nutrition.replace('[a-zA-Z]','', regex= True, inplace=True)
nutrition=nutrition.astype(float)

更改Pandas中的列类型

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

更多

友情链接

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文