月牙弯弯

文章 评论 浏览 463

月牙弯弯 2025-02-21 01:43:50

JavaScript中的对象为

从文章中:

如果它们是不同的对象,即使它们包含相同的属性,比较也会导致错误。

  var arr1 = ['hi!'];
var arr2 = ['hi!'];
console.log(arr1 === arr2); //  - >错误的
 

Objects in JavaScript are reference types, which means that when you create a new object in your function, JavaScript thinks they are different (even when they have the same values).

From the article:

If they’re distinct objects, even if they contain identical properties, the comparison will result in false.

var arr1 = ['Hi!'];
var arr2 = ['Hi!'];
console.log(arr1 === arr2); // -> false

为什么set()重复值?

月牙弯弯 2025-02-20 18:36:03

您的JavaScript将在客户端上执行,而不是在服务器上执行。这意味着foo未在服务器端进行评估,因此其值不能写入服务器上的文件。

思考此过程的最佳方法是,您正在动态生成文本文件。您要生成的文本仅一旦浏览器将其解释就变为可执行代码。只有您在服务器上评估<?php标签之间的位置。

顺便说一句,养成将随机的PHP逻辑嵌入HTML或JavaScript中的习惯可能导致严重的代码。我从痛苦的经历中说话。

Your Javascript will execute on the client, not on the server. This means that foo is not evaluated on the server side and therefore its value can't be written to a file on the server.

The best way to think about this process is as if you're generating a text file dynamically. The text you're generating only becomes executable code once the browser interprets it. Only what you place between <?php tags is evaluated on the server.

By the way, making a habit of embedding random pieces of PHP logic in HTML or Javascript can lead to seriously convoluted code. I speak from painful experience.

客户端和服务器端编程之间有什么区别?

月牙弯弯 2025-02-20 06:01:23

您可以考虑递归方法,原则是继续执行update_path,直到不存在儿童,当情况满足时,直接致电全局变量以附加列表元素,否则继续递归执行并更新祖先,祖先,子,表示所有父ID列表,子女列表,当前级别ID值:

items = [
    {
        "id": 24,
        "children": [
            {
                "id": 137,
                "children": [
                    {
                        "id": 237,
                        "children": [],
                    },
                    {
                        "id": 251,
                        "children": [],
                    }
                ],
            },
            {
                "id": 151,
                "children": [
                    {
                        "id": 155,
                        "children": [],
                    },
                    {
                        "id": 154,
                        "children": [],
                    }
                ],
            },
        ],
    },
]


class Node:
    def __init__(self, nid, ancestors, children):
        self.ancestors = ancestors
        self.children = children
        self.id = nid

    def update_path(self):
        if not self.children:
            global res
            res.append(self.ancestors + [self.id])
        else:
            for _item in self.children:
                node = Node(_item["id"], self.ancestors + [self.id], _item.get("children", []))
                node.update_path()

res = []
for item in items:
    Node(item["id"], [], item["children"]).update_path()

print(res)

输出:

[[24, 137, 237], [24, 137, 251], [24, 151, 155], [24, 151, 154]]

You can consider the recursive approach, the principle is to keep executing update_path until no children exist, when the condition is met, directly call the global variables to append the list elements, otherwise keep recursively executing down and update ancestors, ancestors、 children、 id represent all parent id list, children list, the current level id value:

items = [
    {
        "id": 24,
        "children": [
            {
                "id": 137,
                "children": [
                    {
                        "id": 237,
                        "children": [],
                    },
                    {
                        "id": 251,
                        "children": [],
                    }
                ],
            },
            {
                "id": 151,
                "children": [
                    {
                        "id": 155,
                        "children": [],
                    },
                    {
                        "id": 154,
                        "children": [],
                    }
                ],
            },
        ],
    },
]


class Node:
    def __init__(self, nid, ancestors, children):
        self.ancestors = ancestors
        self.children = children
        self.id = nid

    def update_path(self):
        if not self.children:
            global res
            res.append(self.ancestors + [self.id])
        else:
            for _item in self.children:
                node = Node(_item["id"], self.ancestors + [self.id], _item.get("children", []))
                node.update_path()

res = []
for item in items:
    Node(item["id"], [], item["children"]).update_path()

print(res)

OUTPUT:

[[24, 137, 237], [24, 137, 251], [24, 151, 155], [24, 151, 154]]

如何找到树上所有可能路径的列表

月牙弯弯 2025-02-20 05:42:18

您不能用数字启动变量名。
请参阅参考手册 dissinefiers

您可以更改<<<<<<<<<<<<<<<<<<<代码> 5minhma49 to min5hma49,以使其正确编译。

You cannot start a variable name with a digit.
See reference manual Identifiers

You could change 5minhma49 to min5hma49 for example, to make it compile properly.

如何从不同时间段绘制EMA? pinescript

月牙弯弯 2025-02-20 04:16:08

创建对话框时,您可以将主题作为第二个参数传递

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.MyDialogTheme);

,并设置自定义主题以覆盖所需的任何内容。对于背景颜色,类似的东西应该可以工作:

<style name="MyDialogTheme" parent="Theme.AppCompat.Light.Dialog.Alert">
    <item name="android:background">@color/customBG</item>
</style>

When you create your dialog, you can pass theme as a second param

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.MyDialogTheme);

and set the custom theme to override anything you need. For background color something like this should work:

<style name="MyDialogTheme" parent="Theme.AppCompat.Light.Dialog.Alert">
    <item name="android:background">@color/customBG</item>
</style>

尝试更改自定义对话框背景颜色

月牙弯弯 2025-02-20 02:43:09

我将以相反的顺序分解。

首先,promise.all()用于等待多个承诺,因此,

await Promise.all(other);

您可以做

await other;

第二个问题,即通常应该避免new Promise。它在您的情况下是错误的,您也不应使用async函数 新的Promise,这是没有意义的。这简化为:

const other = (async function () {
    updatedFields.last_login_at = newDateNow();
    if (updatedFields.isActivated) {
        updatedFields.activated_at = newDateNow();
        updatedFields.deactivated_at = null;
    } else if (updatedFields.isActivated === false) {
        updatedFields.deactivated_at = newDateNow();
        updatedFields.activated_at = null;
    }
})();

await other;

下一个问题是您在此功能中没有做任何实际利用异步/等待/承诺的任何事情,因此您实际上应该摆脱async在这些情况下等待

这样可以将您的代码段减少到:

updatedFields.last_login_at = newDateNow();
if (updatedFields.isActivated) {
  updatedFields.activated_at = newDateNow();
  updatedFields.deactivated_at = null;
} else if (updatedFields.isActivated === false) {
  updatedFields.deactivated_at = newDateNow();
  updatedFields.activated_at = null;
}

I'm going to break this down in reverse order.

First, Promise.all() is for waiting for multiple promises, so instead of:

await Promise.all(other);

You can just do

await other;

The second issue is that you should usually avoid new Promise. It's used incorrectly in your case, and you also shouldn't use async functions inside new Promise, it makes no sense. That simplifies it to:

const other = (async function () {
    updatedFields.last_login_at = newDateNow();
    if (updatedFields.isActivated) {
        updatedFields.activated_at = newDateNow();
        updatedFields.deactivated_at = null;
    } else if (updatedFields.isActivated === false) {
        updatedFields.deactivated_at = newDateNow();
        updatedFields.activated_at = null;
    }
})();

await other;

The next issue is that you're not doing anything in the this function that actually takes advantage of async/await/promises, so you should really just get rid of async and await for these cases.

That reduces your code snippet to:

updatedFields.last_login_at = newDateNow();
if (updatedFields.isActivated) {
  updatedFields.activated_at = newDateNow();
  updatedFields.deactivated_at = null;
} else if (updatedFields.isActivated === false) {
  updatedFields.deactivated_at = newDateNow();
  updatedFields.activated_at = null;
}

创造诺言

月牙弯弯 2025-02-19 14:46:42

如果您需要刷新所有VC,

let tabBarVC = UIStoryboard(name: "TabBarViewController", bundle: nil).instantiateViewController(withIdentifier: "CustomTabBarViewController") as! CustomTabBarViewController
tabBarVC.selectedIndex = 3
let nav = UINavigationController(rootViewController: tabBarVC)
nav.setAsRoot()

但是如果您只需要刷新最后一个VC,则

let tabBarVC = self.tabBarController as! CustomTabBarViewController
let vc = // load only 3rd vc from storyboard with it's identifier
tabBarVC.viewControllers![3] = vc

If you need to refresh all the vcs

let tabBarVC = UIStoryboard(name: "TabBarViewController", bundle: nil).instantiateViewController(withIdentifier: "CustomTabBarViewController") as! CustomTabBarViewController
tabBarVC.selectedIndex = 3
let nav = UINavigationController(rootViewController: tabBarVC)
nav.setAsRoot()

But if you need to refresh only the last vc then

let tabBarVC = self.tabBarController as! CustomTabBarViewController
let vc = // load only 3rd vc from storyboard with it's identifier
tabBarVC.viewControllers![3] = vc

更改TABBAR选择的索引

月牙弯弯 2025-02-19 07:33:22
FilesName = ['01-01-2001 Active File Name.xlsx', '01-01-2001 Inactive File Name.xlsx']
FinalName = ['01-01-2001 Active File Name--CORRECTION1.xlsx']

# Helper function to clean up the splitting
get_base_name = lambda x: x.split('.',1)[0].split('--', 1)[0]

# Remove the two first loops by checking for base name matches
# using set intersection
filesName_base = {get_base_name(x) for x in FilesName}
finalName_base = {get_base_name(x) for x in FinalName}
files_to_change_base = filesName_base.intersection(finalName_base)

# Potential candidates of files to be changed
files_to_change = [x for x in FilesName if get_base_name(x) in files_to_change_base]

# No need to call this on each iteration of the inner loop
files_in_dir = set(os.listdir(src))

for file_to_change in files_to_change:
    if file_to_change in files_in_dir:
        # rename files
        os.rename(os.path.join(src, item1), os.path.join(src, item2))
        # move files
        shutil.move(os.path.join(src, item2), os.path.join(dst, item2))

    else :
        logger.error(error_message)
        raise ValueError(error_message)

编辑:仅循环一次删除另一个循环并检查文件是否在目录中。 files_in_dir被移至集合中,因为集合成员资格是O(1)操作,而不是O(n)。

FilesName = ['01-01-2001 Active File Name.xlsx', '01-01-2001 Inactive File Name.xlsx']
FinalName = ['01-01-2001 Active File Name--CORRECTION1.xlsx']

# Helper function to clean up the splitting
get_base_name = lambda x: x.split('.',1)[0].split('--', 1)[0]

# Remove the two first loops by checking for base name matches
# using set intersection
filesName_base = {get_base_name(x) for x in FilesName}
finalName_base = {get_base_name(x) for x in FinalName}
files_to_change_base = filesName_base.intersection(finalName_base)

# Potential candidates of files to be changed
files_to_change = [x for x in FilesName if get_base_name(x) in files_to_change_base]

# No need to call this on each iteration of the inner loop
files_in_dir = set(os.listdir(src))

for file_to_change in files_to_change:
    if file_to_change in files_in_dir:
        # rename files
        os.rename(os.path.join(src, item1), os.path.join(src, item2))
        # move files
        shutil.move(os.path.join(src, item2), os.path.join(dst, item2))

    else :
        logger.error(error_message)
        raise ValueError(error_message)

Edit: Removed another for loop by just looping once and checking if the files are in the directory. files_in_dir is moved into a set because set membership is a O(1) operation as opposed to O(n).

是否有更有效的方法,而不是循环的多个语句?

月牙弯弯 2025-02-19 03:39:01

您无法直接从云存储中读取文件,因为它将它们存储为对象,如下所示,答案

您从Google存储中读取的字符串是A 多部分形式。它不仅包含上传的文件内容,还包含一些元数据。

要根据需要逐行读取文件,我建议将其加载到变量上,然后根据需要解析变量。您可以使用此<

const { Storage } = require("@google-cloud/storage");
const storage = new Storage();

//Read file from Storage
var downloadedFile = storage
  .bucket(bucketName)
  .file(fileName)
  .createReadStream();

// Concat Data
let fileBuffer = "";
downloadedFile
  .on("data", function (data) {
    fileBuffer += data;
  })
  .on("end", function () {
    // CSV file data
    //console.log(fileBuffer);

    //Parse data using new line character as delimiter
    var rows;
    Papa.parse(fileBuffer, {
      header: false,
      delimiter: "\n",
      complete: function (results) {
        // Shows the parsed data on console
        console.log("Finished:", results.data);
        rows = results.data;
      },
    });

a href =“ https://stackoverflow.com/a/51974921/13171940” papaparse 如下所示to-parse-or-read-csv-files-in-reactcjs-81E8EE4870B0#:%7E:文本=4。%20Now%20IMPORT%20 the%20module“ rel =“ nofollow noreferrer”> tutorial 。

You could not read a file line by line directly from Cloud Storage, as it stores them as objects , as shown on this answer:

The string you read from Google Storage is a string representation of a multipart form. It contains not only the uploaded file contents but also some metadata.

To read the file line by line as desired, I suggest loading it onto a variable and then parse the variable as needed. You could use the sample code provided on this answer:

const { Storage } = require("@google-cloud/storage");
const storage = new Storage();

//Read file from Storage
var downloadedFile = storage
  .bucket(bucketName)
  .file(fileName)
  .createReadStream();

// Concat Data
let fileBuffer = "";
downloadedFile
  .on("data", function (data) {
    fileBuffer += data;
  })
  .on("end", function () {
    // CSV file data
    //console.log(fileBuffer);

    //Parse data using new line character as delimiter
    var rows;
    Papa.parse(fileBuffer, {
      header: false,
      delimiter: "\n",
      complete: function (results) {
        // Shows the parsed data on console
        console.log("Finished:", results.data);
        rows = results.data;
      },
    });

To parse the data, you could use a library like PapaParse as shown on this tutorial.

Google Buckets /逐行阅读

月牙弯弯 2025-02-19 03:21:12

谢谢!这项工作

var formatMoney = System.Globalization.CultureInfo.GetCultureInfo("vi-VN");
@String.Format(formatMoney, "{0:c}", @item.TotalPaid)

thanks! it's work

var formatMoney = System.Globalization.CultureInfo.GetCultureInfo("vi-VN");
@String.Format(formatMoney, "{0:c}", @item.TotalPaid)

enter image description here

C#中的格式货币字符串无货币代码

月牙弯弯 2025-02-19 02:24:21

您可以在JavaScript中使用异步等待方法轻​​松地做到这一点。

以下是一个示例,检索a webrtc 使用超时使用超时。

function await_getipv4(timeout = 1000) {
    var t1 = new Date();
    while(!window.ipv4) {
        var stop = new Date() - t1 >= timeout;
        if(stop) {
            console.error('timeout exceeded for await_getipv4.');
            return false;
        }
    }
    return window.ipv4;
}

function async_getipv4() {
    var ipv4 = null;
    var findIP = new Promise(r=>{var w=window,a=new (w.RTCPeerConnection||w.mozRTCPeerConnection||w.webkitRTCPeerConnection)({iceServers:[]}),b=()=>{};a.createDataChannel("");a.createOffer(c=>a.setLocalDescription(c,b,b),b);a.onicecandidate=c=>{try{c.candidate.candidate.match(/([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g).forEach(r)}catch(e){}}})
    findIP.then(ip => window.ipv4 = ip);
    return await_getipv4();
};

You can easily do that using an async wait method in JavaScript.

Below is an example retrieving a WebRTC promise value using a timeout.

function await_getipv4(timeout = 1000) {
    var t1 = new Date();
    while(!window.ipv4) {
        var stop = new Date() - t1 >= timeout;
        if(stop) {
            console.error('timeout exceeded for await_getipv4.');
            return false;
        }
    }
    return window.ipv4;
}

function async_getipv4() {
    var ipv4 = null;
    var findIP = new Promise(r=>{var w=window,a=new (w.RTCPeerConnection||w.mozRTCPeerConnection||w.webkitRTCPeerConnection)({iceServers:[]}),b=()=>{};a.createDataChannel("");a.createOffer(c=>a.setLocalDescription(c,b,b),b);a.onicecandidate=c=>{try{c.candidate.candidate.match(/([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g).forEach(r)}catch(e){}}})
    findIP.then(ip => window.ipv4 = ip);
    return await_getipv4();
};

如何获得承诺的价值?

月牙弯弯 2025-02-19 01:27:34

您可以声明指向行的指针并将其初始化以用以下行指向第一行:

double (*p_first_row)[4] = &a[0];

由于阵列到驱动器decinter ,您还可以写:

double (*p_first_row)[4] = a;

括号是必要的,因为声明

double *p[4];

声明了一系列指针,而声明则

double (*p)[4];

声明了指向数组的指针。

You can declare a pointer to a row and initialize it to point to the first row with the following line:

double (*p_first_row)[4] = &a[0];

Due to array to pointer decay, you can also write:

double (*p_first_row)[4] = a;

The parentheses are necessary, because the declaration

double *p[4];

declares an array of pointers, whereas the declaration

double (*p)[4];

declares a pointer to an array.

使用指针指向C中的一行

月牙弯弯 2025-02-19 00:35:49

您提供的信息有点缺乏。据我了解,这些可能是可能的聚合选项。

使用 date_trunc

from pyspark.sql import functions as F

df = df.groupBy(
        F.date_trunc('hour', 'tpep_pickup_datetime').alias('hour'),
        'PULocationID',
    ).count()

df.show()
# +-------------------+------------+-----+
# |               hour|PULocationID|count|
# +-------------------+------------+-----+
# |2020-01-01 00:00:00|         238|    1|
# |2020-01-01 02:00:00|         238|    2|
# |2020-01-01 02:00:00|         193|    1|
# |2020-01-01 01:00:00|         238|    2|
# |2020-01-01 00:00:00|           7|    1|
# +-------------------+------------+-----+

使用 window> window> window

from pyspark.sql import functions as F

df = df.groupBy(
        F.window('tpep_pickup_datetime', '1 hour').alias('hour'),
        'PULocationID',
    ).count()

df.show(truncate=0)
# +------------------------------------------+------------+-----+
# |hour                                      |PULocationID|count|
# +------------------------------------------+------------+-----+
# |[2020-01-01 02:00:00, 2020-01-01 03:00:00]|238         |2    |
# |[2020-01-01 01:00:00, 2020-01-01 02:00:00]|238         |2    |
# |[2020-01-01 00:00:00, 2020-01-01 01:00:00]|238         |1    |
# |[2020-01-01 02:00:00, 2020-01-01 03:00:00]|193         |1    |
# |[2020-01-01 00:00:00, 2020-01-01 01:00:00]|7           |1    |

The information you provided is a bit lacking. From what I understood, these could be possible aggregation options.

Using date_trunc

from pyspark.sql import functions as F

df = df.groupBy(
        F.date_trunc('hour', 'tpep_pickup_datetime').alias('hour'),
        'PULocationID',
    ).count()

df.show()
# +-------------------+------------+-----+
# |               hour|PULocationID|count|
# +-------------------+------------+-----+
# |2020-01-01 00:00:00|         238|    1|
# |2020-01-01 02:00:00|         238|    2|
# |2020-01-01 02:00:00|         193|    1|
# |2020-01-01 01:00:00|         238|    2|
# |2020-01-01 00:00:00|           7|    1|
# +-------------------+------------+-----+

Using window

from pyspark.sql import functions as F

df = df.groupBy(
        F.window('tpep_pickup_datetime', '1 hour').alias('hour'),
        'PULocationID',
    ).count()

df.show(truncate=0)
# +------------------------------------------+------------+-----+
# |hour                                      |PULocationID|count|
# +------------------------------------------+------------+-----+
# |[2020-01-01 02:00:00, 2020-01-01 03:00:00]|238         |2    |
# |[2020-01-01 01:00:00, 2020-01-01 02:00:00]|238         |2    |
# |[2020-01-01 00:00:00, 2020-01-01 01:00:00]|238         |1    |
# |[2020-01-01 02:00:00, 2020-01-01 03:00:00]|193         |1    |
# |[2020-01-01 00:00:00, 2020-01-01 01:00:00]|7           |1    |

如何将火花中的时间戳数据汇总到较小的时间范围

月牙弯弯 2025-02-18 13:43:14

任何被设置为字典键或设定项目的对象都需要进行哈希。哈希意味着将Python对象(例如浮点数,字符串或元组)转换为唯一数字。此数字可以轻松查找字典。但是,它要求不能更改哈希元素,因为这也需要更改数字。

元组本身是可占用的,因为它们无法更改。但是,只有当它们的内容也是可用的,它们才能使用。字符串是完美的,但词典不是。这意味着您不能将字典用作字典键。

因此,问题需要另一种解决方案。最简单的是创建一个新列表,然后将列表中的每个唯一项目附加到它:

new_list = []

for x in my_list:
    if x not in new_list:
        new_list.append(x)

当您需要更改时,这意味着分配给该列表的每个变量也会更改,您可以添加以下行:

my_list[:] = new_list

Any object being set as a dictionary key or a set item, needs to be hashable. hashing means that a python object, like a float number, string or tuple is converted to a unique number. This number allows easy lookup for the dictionary. However, it requires that the hashed element can't be changed, as this would also require the number to change.

Tuples themselves are hashable, as they can't be changed. However, they are only hashable if their content is also hashable. The strings are perfectly hashable, but dictionaries aren't. This means that you can't use dictionaries as dictionary keys.

Thus, the problem requires another solution. The simplest one would be to create a new list and then append every unique item in the list to it:

new_list = []

for x in my_list:
    if x not in new_list:
        new_list.append(x)

When you need the change to be in place, meaning that every variable assigned to that list also changes, you can add the following line:

my_list[:] = new_list

从dicts列表中删除重复项,例外?

月牙弯弯 2025-02-18 13:38:48

自2022年5月30日起,Google不会将应用程序登录到Gmail使用通常的帐户密码。 : https://support.google.com/accogle.com/accounts/accounts/anccounts/answer/601010255

请参阅 解决此问题,您必须使用Google“应用程序密码”。在myaccount.google.com上进行安全性,打开2FA,然后创建一个应用程序密码。

使用应用程序密码代替帐户密码,它将起作用。

Effective May 30 2022, Google won't let an app login to Gmail with the usual account password. See: https://support.google.com/accounts/answer/6010255

To work around this you must use a Google "App Password". At myaccount.google.com go to Security, turn on 2FA, then create an App Password.

Use the App Password in place of the account password and it will work.

将Django send_mail后端主机设置为gmail

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

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