指尖凝香

文章 评论 浏览 30

指尖凝香 2025-02-21 01:22:18

如果您想将挂钩

import React, { useState, useEffect } from "react";

export function useUserHook() {
  const [name, setName] = useState("");
  const [password, setPassword] = useState("");
  const [change, setChange] = useState(false);

  React.useEffect(() => {
    const loadSaved = async () => {
      setName(localStorage.getItem("Name"));
      setPassword(localStorage.getItem("Password"));
    };
    loadSaved();
  }, [name, password, change]);

  const saveData = async (name, password) => {
    setChange(!change);
    await localStorage.setItem("Name", name);
    await localStorage.setItem("Password", password);
  };

  const removeData = async () => {
    setChange(!change);
    await localStorage.removeItem("Name");
    await localStorage.removeItem("Password");
  };

  return {
    name,
    password,
    saveData,
    removeData
  };
}

导入挂钩添加到app.js中,

import { useUserHook } from "./userHook";

请在代码中添加一些更改,

import React, { useState, useEffect } from "react";
import { useUserHook } from "./userHook";
import "./styles.css";

const App = () => {
  const { name, password, saveData, removeData } = useUserHook();
  const [nameState, setName] = useState("");
  const [pwdState, setPwd] = useState("");

  const handle = () => {
    console.log("do save");
    saveData(nameState, pwdState);
  };
  const remove = () => {
    console.log("do remove");
    removeData();
  };
  return (
    <div className="App">
      <h1>Name of the user:</h1>
      <input
        placeholder="Name"
        value={nameState}
        onChange={(e) => setName(e.target.value)}
      />
      <h1>Password of the user:</h1>
      <input
        type="password"
        placeholder="Password"
        value={pwdState}
        onChange={(e) => setPwd(e.target.value)}
      />
      <div>
        <button onClick={handle}>Done</button>
      </div>
      {name && (
        <div>
          Name: <p>{name}</p>
        </div>
      )}
      {password && (
        <div>
          Password: <p>{password}</p>
        </div>
      )}
      <div>
        <button onClick={remove}>Remove</button>
      </div>
    </div>
  );
};

export default App;

希望它可以为您提供帮助

if you want to use hook

import React, { useState, useEffect } from "react";

export function useUserHook() {
  const [name, setName] = useState("");
  const [password, setPassword] = useState("");
  const [change, setChange] = useState(false);

  React.useEffect(() => {
    const loadSaved = async () => {
      setName(localStorage.getItem("Name"));
      setPassword(localStorage.getItem("Password"));
    };
    loadSaved();
  }, [name, password, change]);

  const saveData = async (name, password) => {
    setChange(!change);
    await localStorage.setItem("Name", name);
    await localStorage.setItem("Password", password);
  };

  const removeData = async () => {
    setChange(!change);
    await localStorage.removeItem("Name");
    await localStorage.removeItem("Password");
  };

  return {
    name,
    password,
    saveData,
    removeData
  };
}

import hook to App.js

import { useUserHook } from "./userHook";

add some changes in the code

import React, { useState, useEffect } from "react";
import { useUserHook } from "./userHook";
import "./styles.css";

const App = () => {
  const { name, password, saveData, removeData } = useUserHook();
  const [nameState, setName] = useState("");
  const [pwdState, setPwd] = useState("");

  const handle = () => {
    console.log("do save");
    saveData(nameState, pwdState);
  };
  const remove = () => {
    console.log("do remove");
    removeData();
  };
  return (
    <div className="App">
      <h1>Name of the user:</h1>
      <input
        placeholder="Name"
        value={nameState}
        onChange={(e) => setName(e.target.value)}
      />
      <h1>Password of the user:</h1>
      <input
        type="password"
        placeholder="Password"
        value={pwdState}
        onChange={(e) => setPwd(e.target.value)}
      />
      <div>
        <button onClick={handle}>Done</button>
      </div>
      {name && (
        <div>
          Name: <p>{name}</p>
        </div>
      )}
      {password && (
        <div>
          Password: <p>{password}</p>
        </div>
      )}
      <div>
        <button onClick={remove}>Remove</button>
      </div>
    </div>
  );
};

export default App;

I hope it can help you

为什么本地存储无法实时使用JS?

指尖凝香 2025-02-21 00:45:16

我认为这会为你做

 FollowedHashtags.objects.filter(id=1).values('user').count()

I think this will do for you

 FollowedHashtags.objects.filter(id=1).values('user').count()

如何找到遵循主题标签的人的否-Django

指尖凝香 2025-02-20 05:43:44

删除默认行为(例如将事件发送到按钮)时,您不应覆盖MousePressEvent。另一方面,您必须将视图的坐标转换为场景的坐标。

self.proxy_widget = self.scene.addWidget(self.button)
def mousePressEvent(self, event):
    super().mousePressEvent(event)
    vp = event.pos()
    if self.proxy_widget in self.items(vp):
        return
    if self.button.isChecked():
        ellipse = QGraphicsEllipseItem(0, 0, 50, 20)
        self.scene.addItem(ellipse)
        sp = self.mapToScene(vp)
        ellipse.setPos(sp)

You should not override the mousePressEvent as you remove the default behavior such as sending the event to the button. On the other hand you have to convert the coordinates of the view to the coordinates of the scene.

self.proxy_widget = self.scene.addWidget(self.button)
def mousePressEvent(self, event):
    super().mousePressEvent(event)
    vp = event.pos()
    if self.proxy_widget in self.items(vp):
        return
    if self.button.isChecked():
        ellipse = QGraphicsEllipseItem(0, 0, 50, 20)
        self.scene.addItem(ellipse)
        sp = self.mapToScene(vp)
        ellipse.setPos(sp)

如何在鼠标上绘制一个数字单击qtapplication

指尖凝香 2025-02-20 01:22:38

就像Tkausl的评论所述,STD :: Thread :: Sleep select sheep sheck the the the the Thread Sleep,可以防止线程上的任何代码在睡眠期间执行。您可以使用 async_std ::在这种情况下,因为它是睡眠功能的异步版本。

async fn learn_song() -> &'static str {
    println!("learn_song");
    "some song"
}

#[allow(unused_variables)]
async fn sing_song(song: &str) {
    println!("sing_song");
}

async fn dance() {
    println!("dance");
}

async fn learn_and_sing() {
    let song = learn_song().await;
    async_std::task::sleep(std::time::Duration::from_secs(1)).await;
    sing_song(song).await;
}

#[async_std::main] 
async fn main() {
    let f1 = learn_and_sing();
    let f2 = dance();
    let f3 = learn_and_sing();

    futures::join!(f1, f2, f3);
}

Like tkausl's comment states, std::thread::sleep makes the whole thread sleep, which prevents any code on the thread from executing during the sleeping duration. You could use async_std::task::sleep in this situation, as it is an asynchronous version of the sleep function.

async fn learn_song() -> &'static str {
    println!("learn_song");
    "some song"
}

#[allow(unused_variables)]
async fn sing_song(song: &str) {
    println!("sing_song");
}

async fn dance() {
    println!("dance");
}

async fn learn_and_sing() {
    let song = learn_song().await;
    async_std::task::sleep(std::time::Duration::from_secs(1)).await;
    sing_song(song).await;
}

#[async_std::main] 
async fn main() {
    let f1 = learn_and_sing();
    let f2 = dance();
    let f3 = learn_and_sing();

    futures::join!(f1, f2, f3);
}

生锈:异步不同意

指尖凝香 2025-02-19 19:26:06

host.CreatedEfaultBuilder 定义了发现JSON配置并通过 ICONFIGURATION 实例将其公开的行为。从主机实例中,您可以向服务提供商询问 iconfiguration 实例,然后询问值。

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

using IHost host = Host.CreateDefaultBuilder(args).Build();

// Ask the service provider for the configuration abstraction.
IConfiguration config = host.Services.GetRequiredService<IConfiguration>();

// Get values from the config given their key and their target type.
var configValueInt = config.GetValue<int>("yourKeyName");
string configValueStr = config.GetValue<string>("yourKeyName");

有关更多信息,请阅读 docs

The Host.CreateDefaultBuilder defines the behavior to discover the JSON configuration and expose it through the IConfiguration instance. From the host instance, you can ask the service provider for the IConfiguration instance and then ask it for values.

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

using IHost host = Host.CreateDefaultBuilder(args).Build();

// Ask the service provider for the configuration abstraction.
IConfiguration config = host.Services.GetRequiredService<IConfiguration>();

// Get values from the config given their key and their target type.
var configValueInt = config.GetValue<int>("yourKeyName");
string configValueStr = config.GetValue<string>("yourKeyName");

For more information read the Docs.

如何通过主机企业从配置对象获取值?

指尖凝香 2025-02-19 10:06:48

数据和追溯信息的量仍然不够。但是我会猜测。

让我们制作一个简单的数据框架:

In [31]: df = pd.DataFrame(np.ones((3,4)))

In [32]: df
Out[32]: 
     0    1    2    3
0  1.0  1.0  1.0  1.0
1  1.0  1.0  1.0  1.0
2  1.0  1.0  1.0  1.0

预测可能会使用一些预期 c-contiguul 数据的编译代码。如果给出了一个数据框,它可能首先将其转换为数组,例如使用 np.Array(df)或有效:

In [35]: df.values
Out[35]: 
array([[1., 1., 1., 1.],
       [1., 1., 1., 1.],
       [1., 1., 1., 1.]])

In [36]: df.values.flags
Out[36]: 
  C_CONTIGUOUS : True
  F_CONTIGUOUS : False
  OWNDATA : False
  WRITEABLE : True
  ALIGNED : True
  WRITEBACKIFCOPY : False
  UPDATEIFCOPY : False

但是,如果您执行转换的连续性更改。这在数组中众所周知,看起来Pandas是兼容的:

In [37]: df.T.values.flags
Out[37]: 
  C_CONTIGUOUS : False
  F_CONTIGUOUS : True
  OWNDATA : False
  WRITEABLE : True
  ALIGNED : True
  WRITEBACKIFCOPY : False
  UPDATEIFCOPY : False

Pandas transpose 允许我们指定复制 - 请参阅其文档:

In [38]: df.transpose(copy=True).values.flags
Out[38]: 
  C_CONTIGUOUS : True
  F_CONTIGUOUS : False
  OWNDATA : False
  WRITEABLE : True
  ALIGNED : True
  WRITEBACKIFCOPY : False
  UPDATEIFCOPY : False

因此在您的代码中使用可能(?? ?)解决问题:

 features = convert_to_df(features).transpose(copy=True)

我不能过足够的压力,您应该在问题中包含足够的信息。

The amount of data and traceback information is still not enough. But I'll make a guess.

Let's make a simple dataframe:

In [31]: df = pd.DataFrame(np.ones((3,4)))

In [32]: df
Out[32]: 
     0    1    2    3
0  1.0  1.0  1.0  1.0
1  1.0  1.0  1.0  1.0
2  1.0  1.0  1.0  1.0

predict probably uses some compiled code that expect c-contiguous data. If given a dataframe it probably first converts it to an array, such as with np.array(df) or effectively:

In [35]: df.values
Out[35]: 
array([[1., 1., 1., 1.],
       [1., 1., 1., 1.],
       [1., 1., 1., 1.]])

In [36]: df.values.flags
Out[36]: 
  C_CONTIGUOUS : True
  F_CONTIGUOUS : False
  OWNDATA : False
  WRITEABLE : True
  ALIGNED : True
  WRITEBACKIFCOPY : False
  UPDATEIFCOPY : False

But if you do a transpose the contiguity changes. This is well known for arrays, and it looks like pandas is compatible:

In [37]: df.T.values.flags
Out[37]: 
  C_CONTIGUOUS : False
  F_CONTIGUOUS : True
  OWNDATA : False
  WRITEABLE : True
  ALIGNED : True
  WRITEBACKIFCOPY : False
  UPDATEIFCOPY : False

pandas transpose allows us to specify copy - see its docs:

In [38]: df.transpose(copy=True).values.flags
Out[38]: 
  C_CONTIGUOUS : True
  F_CONTIGUOUS : False
  OWNDATA : False
  WRITEABLE : True
  ALIGNED : True
  WRITEBACKIFCOPY : False
  UPDATEIFCOPY : False

So using in your code might(???) solve the problem:

 features = convert_to_df(features).transpose(copy=True)

I can't stress enough that you should include enough information in your question.

使用Scikit-Learn Knn.ndarray并不是c contigul。

指尖凝香 2025-02-19 08:04:22

根据文档,您必须添加/plugins/index.js 以下代码。

const cucumber = require('cypress-cucumber-preprocessor').default

module.exports = (on, config) => {
  on('file:preprocessor', cucumber())
}

https://www.npmjs.com/package/ppackage/ppackage/cypress-cypress-cucumbers-cucumber-preproperprocessor

As per documentation, you have to add in your /plugins/index.js following code.

const cucumber = require('cypress-cucumber-preprocessor').default

module.exports = (on, config) => {
  on('file:preprocessor', cucumber())
}

https://www.npmjs.com/package/cypress-cucumber-preprocessor

无法将黄瓜添加到赛普拉斯

指尖凝香 2025-02-19 07:47:35

首先,您需要获取发送的答复,您可以使用获得互动答复。您可以推迟回复,然后使用CreateTimestamp,而不是使用“ Pinging Bot ...”回复。 ping命令的一个基本示例是,

const { SlashCommandBuilder } = require('@discordjs/builders');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('ping')
        .setDescription('Replies with Pong!'),
    async execute(interaction) {
        const sent = await interaction.reply({ content: 'Pinging...', fetchReply: true });
        await interaction.editReply(`:ping_pong: Pong!\n:stopwatch: Uptime: ${Math.round(interaction.client.uptime / 60000)} minutes\n:sparkling_heart: Websocket heartbeat: ${interaction.client.ws.ping}ms.\n:round_pushpin: Rountrip Latency: ${sent.createdTimestamp - interaction.createdTimestamp}ms`);
    },
};

您可以将响应自定义为嵌入或随心所欲。 DJ指南在ping命令在这里

first you need to fetch the reply you send, u can use fetchReply to get the interaction reply. instead of replying with "Pinging bot..." you can defer the reply and then use the createdTimestamp. A basic example of a ping command would be

const { SlashCommandBuilder } = require('@discordjs/builders');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('ping')
        .setDescription('Replies with Pong!'),
    async execute(interaction) {
        const sent = await interaction.reply({ content: 'Pinging...', fetchReply: true });
        await interaction.editReply(`:ping_pong: Pong!\n:stopwatch: Uptime: ${Math.round(interaction.client.uptime / 60000)} minutes\n:sparkling_heart: Websocket heartbeat: ${interaction.client.ws.ping}ms.\n:round_pushpin: Rountrip Latency: ${sent.createdTimestamp - interaction.createdTimestamp}ms`);
    },
};

You can customize the response into an embed or however you like. The djs guide has a section on ping command here

eScord.js ping延迟从slash命令嵌入

指尖凝香 2025-02-18 11:44:10

我使用Env-CMD运行的NPM运行遇到了这个确切的问题。我回想起最近升级了我的NPM版本。我相信那是8.13.0。我刚刚降级到8.6.0,问题消失了。

如果您将NVM用于Windows,我建议使用此脚本来安装/更新/降级NPM。

I had this exact issue using npm run with env-cmd. I recalled recently upgrading my npm version. I believe it was 8.13.0. I just downgraded to 8.6.0 and the issue is gone.

If you are using NVM for windows, I recommend this script to install/update/downgrade NPM.

https://gist.github.com/johnmcase/d31b799b9030327091a0e74880e4c530

如何修复文件名,目录名称或卷标签语法不正确&#x27;试图开始环境

指尖凝香 2025-02-18 11:25:57

这是对类实例对象的明确引用。

it's an explicit reference to the class instance object.

“自我”参数的目的是什么?为什么需要它?

指尖凝香 2025-02-18 07:59:40
        your_string = "Namaskara"
        rep_char='a'
        occ1=your_string.find(rep_char)   #Searches for first occurence of replacing character
        occn=your_string.rfind(rep_char) #Searches for last occurence of replacing character
    
    #from startig poition of string to your first occurence of character  and last occurence of character to end of the string nothing will be replaced. for remaining string character will be replaced with uppercase
        your_string = f"{your_string[0:occ1+1]}{your_string[occ1+1:occn].replace(rep_char,rep_char.upper())}{your_string[occn:]}"
    
        print(your_string)

output: NamAskAra

我已经使用了@Jock逻辑,但已修改以使其通用。

        your_string = "Namaskara"
        rep_char='a'
        occ1=your_string.find(rep_char)   #Searches for first occurence of replacing character
        occn=your_string.rfind(rep_char) #Searches for last occurence of replacing character
    
    #from startig poition of string to your first occurence of character  and last occurence of character to end of the string nothing will be replaced. for remaining string character will be replaced with uppercase
        your_string = f"{your_string[0:occ1+1]}{your_string[occ1+1:occn].replace(rep_char,rep_char.upper())}{your_string[occn:]}"
    
        print(your_string)

output: NamAskAra

I have used @jock logic but modified to make it generic.

如何在字符串和特定索引中转换特定字符

指尖凝香 2025-02-18 06:31:35

尝试以下操作:

const Person = ({ strName, num, arr }) => {
  return (
  <div>
        { strName && typeof strName === "string" ? (
          strName
        ) : (
          <p>{Person.defaultProps.Name}</p>
        )}
    </div>
   
  );
};

try this :

const Person = ({ strName, num, arr }) => {
  return (
  <div>
        { strName && typeof strName === "string" ? (
          strName
        ) : (
          <p>{Person.defaultProps.Name}</p>
        )}
    </div>
   
  );
};

如何将道具从一个组件传递到另一个组件以及道具验证 - react钩子

指尖凝香 2025-02-18 02:05:32

没有任何附加的NPM软件包

//...
const BackendPageListing = () => {
    
    const [ myData, setMyData] = useState( {
        id: 1,
        content: "abc"
    })

    const myFunction = ( x ) => {
        
        setPagenateInfo({
        ...myData,
        content: x
        })

        console.log(myData) // not reflecting change immediately

        let myDataNew = {...myData, content: x };
        
        console.log(myDataNew) // Reflecting change immediately

    }

    return (
        <>
            <button onClick={()=>{ myFunction("New Content")} }>Update MyData</button>
        </>
    )

Without any addtional NPM package

//...
const BackendPageListing = () => {
    
    const [ myData, setMyData] = useState( {
        id: 1,
        content: "abc"
    })

    const myFunction = ( x ) => {
        
        setPagenateInfo({
        ...myData,
        content: x
        })

        console.log(myData) // not reflecting change immediately

        let myDataNew = {...myData, content: x };
        
        console.log(myDataNew) // Reflecting change immediately

    }

    return (
        <>
            <button onClick={()=>{ myFunction("New Content")} }>Update MyData</button>
        </>
    )

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

指尖凝香 2025-02-17 19:21:22

使用列表理解很容易:

>>> mylist = [1, 2, 7, 11, 8, 55, 89, 1, 3, 8]

>>> [mylist[i:i+5] for i in range(6)]
[[1, 2, 7, 11, 8], [2, 7, 11, 8, 55], [7, 11, 8, 55, 89], [11, 8, 55, 89, 1], [8, 55, 89, 1, 3], [55, 89, 1, 3, 8]]

It is easy to use a list comprehension:

>>> mylist = [1, 2, 7, 11, 8, 55, 89, 1, 3, 8]

>>> [mylist[i:i+5] for i in range(6)]
[[1, 2, 7, 11, 8], [2, 7, 11, 8, 55], [7, 11, 8, 55, 89], [11, 8, 55, 89, 1], [8, 55, 89, 1, 3], [55, 89, 1, 3, 8]]

如何创建列表列表

指尖凝香 2025-02-17 16:44:37

是的,实现这一结果的最佳方法是创建具有多个布局的回收模型,我认为这是使用XML的唯一方法。

但是,如果您使用 JetPack Compose 不需要回收式视图或适配器,则可以使用compose进行,这可能会容易得多,而您可以进行任何想要的自定义布局。

Yes the best way to achieve that result is by creating a recyclerview with multiple layouts and I think that it's the only way if you are using xml.

But this could be a lot easier if you make it using jetpack compose no need for recycler view or adapter anymore with compose and you can make any custom layout that you want.

如何创建RecyClerview游戏时间线事件

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

更多

友情链接

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