RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / user-273314

Zhihar's questions

Martin Hope
Zhihar
Asked: 2024-08-22 04:47:30 +0000 UTC

python:将系统从不带零的 N 进制转换为带零的十进制(我们的原生系统)

  • 7

我已经多次解决这个问题了,每次我都在挣扎,然后每次都忘记它:)

有一个带有字典的数字系统(即字母,而不是数字)并且没有零,即

A, B, ..., Z, AA, AB, ..., ZZ. AAA, ...

告诉我这些数字系统叫什么?!!!然后当我开始寻找时,我在第三天才找到它们

我什至不要求翻译算法,至少是名称:)(但你可以使用算法来节省精力)

本质上,这是 N 位数字典中 1..M 位数组合的序列号(itertools.product 的组合)

python
  • 3 个回答
  • 59 Views
Martin Hope
Zhihar
Asked: 2024-08-01 16:28:07 +0000 UTC

React:使用组件中调用的函数中的钩子,而不是组件本身

  • 5

在React中需要从函数(不是组件,而是从组件调用函数)执行导航

创建了一个钩子:

// хук для выполнения навигации
export const useCustomNavigate = () => {
    const navigate = useNavigate();
    return navigate;
  };

我在函数内部使用它:

    // обработать 401 ошибка: не авторизованный запрос
    if (errMessage === 'Unauthorized') {
        // выйти из системы
        logout()

        // перейти на страницу авторизации
        const navigate = useCustomNavigate();

        navigate('/auth/login');
    }

我收到错误:

React Hook“useCustomNavigate”在函数“queryCustom”中调用,该函数既不是 React 函数组件,也不是自定义 React Hook 函数。 React 组件名称必须以大写字母开头。 React Hook 名称必须以单词“use”开头react-hooks/rules-of-hooks

告诉我如何处理这个问题?

我不想在组件本身中执行此代码,在组件中我想使用 useNavigate() ,这样这样的东西(在很多地方使用)将被集中执行(代码将在实用程序中)作为一个单独的函数)并且最好不需要组件中的任何内容作为输入(如果可能的话)

告诉我如何解决这个问题?

聚苯乙烯

作为临时解决方案(我不知道它有多正确)我在 main.tsx 中使用(本质上是在主组件中)

const navigate = useNavigate();

我navigate把它放在一个单例中并navigate在整个项目中使用它

reactjs
  • 1 个回答
  • 21 Views
Martin Hope
Zhihar
Asked: 2024-05-02 21:43:40 +0000 UTC

css:拉伸 svg 蒙版以适合父 div

  • 6

我画了一个书签(见代码)

书签中心部分的遮罩必须拉伸/收缩到父元素的大小(这取决于元素内部文本的大小)

由于某种原因它不起作用,尽管看起来它足以使用clipPathUnits="objectBoundingBox"。

告诉我问题是什么以及如何解决它

    .cover-title {
        display                 :   flex;
        flex-direction          :   row;

        margin                  :   0px;
        padding                 :   0px;

        font-size               :   0px;
    }

    .cover-title-left {
        width                   :   26px;
        height                  :   91px;

        margin                  :   0px;
        padding                 :   0px;

        clip-path               :   url(#left);

        background-color        :   red;
    }

    .cover-title-middle {
        display                 :   flex;
        align-items             :   center;

        /*width                     :   233px;*/
        height                  :   91px;
        
        margin                  :   0px;
        padding                 :   0px;

        color                   :   white;
        font-size               :   38px;
        font-weight             :   400;
        
        white-space             :   nowrap;

        background-color        :   green;
       
        clip-path               :   url(#middle); 

    }

    .cover-title-right {
        width                   :   36px;
        height                  :   91px;

        margin                  :   0px;
        padding                 :   0px;

        background-color        :   blue;

        clip-path               :   url(#right);
    }
    
    .cover-subtitle {
        height                  :   50px;
        
        border-top-right-radius :   10px;
        
        background-color        :   orange;
    }
            <div class="cover">
                <div class='cover-title'>
                    <div class='cover-title-left'></div>
                    <div class='cover-title-middle'>WELCOME HOME</div>
                    <div class='cover-title-right'></div>
                </div>
                <div class='cover-subtitle'></div>
                
            </div>    

                <svg width="0" height="0" viewBox="0 0 25 91" xmlns="http://www.w3.org/2000/svg">
                    <clipPath id='left'>
                        <path d="M25 0.00724123H15.4637C7.00179 -0.251624 1.30391e-05 6.46316 1.17475e-05 14.8371L0 91H25V0.00724123Z" />
                    </clipPath>
                </svg>
    
                <svg width="0" height="0" viewBox="0 0 233 91" xmlns="http://www.w3.org/2000/svg">
                    <clipPath id='middle' clipPathUnits="objectBoundingBox">
                        <path d="M0 0L233 7V91H0V0Z" />
                    </clipPath>
                </svg>
        
                <svg width="0" height="0" viewBox="0 0 36 91" xmlns="http://www.w3.org/2000/svg">
                    <clipPath id='right'>
                        <path d="M0 91H35C28.6455 89.2663 23.9747 83.4607 23.9747 76.5657V22.2468C23.9747 14.1636 17.545 7.54183 9.45371 7.29195L0 7V91Z" />
                    </clipPath>
                </svg> 

html
  • 1 个回答
  • 29 Views
Martin Hope
Zhihar
Asked: 2024-04-09 16:14:21 +0000 UTC

React:仅渲染必要的组件

  • 6

有一个 React 组件WordsEditor,其中包含数百个组件WordBlock。

当状态改变时,WordsEditor它会被重新绘制,相应地,它的所有组件也会被重新绘制WordBlock,尽管事实上只有少数组件发生了变化WordBlock。

告诉我如何确保只重绘必要的组件。

文字编辑器:

// компонент: 'Редактор слов'
const WordsEditor: React.FC<IPropsWordsEditor> = (props) => {
  // контроль состояний
  const [selectedIndices, setSelectedIndices]       = useState<number[]>([]);               // список индексов выделенных слов
  const [selectedAuxIndices, setSelectedAuxIndices] = useState<number[]>([]);               // список вспомогательных индексов выделенных слов
  const [categoriesGroups, setCategoriesGroups]     = useState<IDataCategoryGroup[]>([]);   // список сформированных групп слов

  // ОСНОВНАЯ ЛОГИКА
  // ...    
 
  // отрисовать компонент
  const toolbarIndex: number = toolbar_enabled && selectedIndices.length > 0 ? Math.min(...selectedIndices) : -1;

  const content: any = words.map((wordInfo, index) => {
    if (wordInfo.active) {
      const wordBlock: any = <WordBlock 
          key         = {index} 
          index       = {index} 
          word        = {wordInfo.word}
          main        = {selectedIndices.includes(index)}
          aux         = {selectedAuxIndices.includes(index)}
          type        = {categoriesGroups.find(elem => elem.ids.includes(index))?.sentiment ?? ''}
      />;

      if (index === toolbarIndex)
        return (
          <ToolbarPanel
            key             = {index}
            selected        = {selectedIndices}
            groups          = {categoriesGroups}
            onClose         = {handleDisableSelections}
            onDisableTones  = {handleDisableTonesSelections}
            onRegroup       = {handleRegroupSelections}
            onCategoryze    = {handleCategoryzeSelections}
          >
            {wordBlock}
          </ToolbarPanel>
        );
      else
        return wordBlock;
    }
    return wordInfo.word;
  });

  return (
    <div className='words-editor' onClick={handleWordsEditorClick}>
      {content}
    </div>
  );
}

字块:

// компонент: 'Слово'
const WordBlock: React.FC<IPropsWordBlock> = (props) => {
  console.log('word');
  // функция определяющая тип класса
  function prepareClassName() {
    // определить название классов для разных состояний слова
    const main: string  = props.main ? 'selected' : '';
    const aux: string   = props.aux ? 'selected-aux' : '';
    const type: string  = props.type;

    // сформировать классы
    return [(main !== '') ? main : type, aux].join(' ').trim();
  }

  // отрисовать компонент
  return (
    <span
      data-index  = {props.index}
      className   = {prepareClassName()}
    >
      {props.word}
    </span>
  );
}
reactjs
  • 1 个回答
  • 25 Views
Martin Hope
Zhihar
Asked: 2023-09-22 14:04:19 +0000 UTC

npm:更新库时出错

  • 5

将raect项目更新到最新的npm包时,npm install出现错误

npm ERR! code ERESOLVE
npm ERR! ERESOLVE could not resolve
npm ERR!
npm ERR! While resolving: react-scripts@5.0.1
npm ERR! Found: typescript@5.2.2
npm ERR! node_modules/typescript
npm ERR!   typescript@"^5.2.2" from the root project
npm ERR!   peer typescript@">= 2.7" from fork-ts-checker-webpack-plugin@6.5.3
npm ERR!   node_modules/fork-ts-checker-webpack-plugin
npm ERR!     fork-ts-checker-webpack-plugin@"^6.5.0" from react-dev-utils@12.0.1
npm ERR!     node_modules/react-dev-utils
npm ERR!       react-dev-utils@"^12.0.1" from react-scripts@5.0.1
npm ERR!       node_modules/react-scripts
npm ERR!         react-scripts@"5.0.1" from the root project
npm ERR!   2 more (ts-node, tsutils)
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peerOptional typescript@"^3.2.1 || ^4" from react-scripts@5.0.1
npm ERR! node_modules/react-scripts
npm ERR!   react-scripts@"5.0.1" from the root project
npm ERR!
npm ERR! Conflicting peer dependency: typescript@4.9.5
npm ERR! node_modules/typescript
npm ERR!   node_modules/react-scripts
npm ERR!     react-scripts@"5.0.1" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR!

已更正npm install --force,但随后出现警告:

npm WARN using --force Recommended protections disabled.
npm WARN ERESOLVE overriding peer dependency
npm WARN While resolving: react-scripts@5.0.1
npm WARN Found: typescript@5.2.2
npm WARN node_modules/typescript
npm WARN   typescript@"^5.2.2" from the root project
npm WARN   3 more (fork-ts-checker-webpack-plugin, ts-node, tsutils)
npm WARN
npm WARN Could not resolve dependency:
npm WARN peerOptional typescript@"^3.2.1 || ^4" from react-scripts@5.0.1
npm WARN node_modules/react-scripts
npm WARN   react-scripts@"5.0.1" from the root project
npm WARN
npm WARN Conflicting peer dependency: typescript@4.9.5
npm WARN node_modules/typescript
npm WARN   peerOptional typescript@"^3.2.1 || ^4" from react-scripts@5.0.1
npm WARN   node_modules/react-scripts
npm WARN     react-scripts@"5.0.1" from the root project

added 24 packages, removed 49 packages, changed 237 packages, and audited 1596 packages in 2m

8 vulnerabilities (2 moderate, 6 high)

问题是:这正常吗?--force是否足以解决问题,或者有没有办法最终克服这个问题?

--legacy-peer-deps根本不合适,因为它会将一些包从所需版本回滚到旧版本

reactjs
  • 1 个回答
  • 24 Views
Martin Hope
Zhihar
Asked: 2023-09-14 17:47:53 +0000 UTC

Python:使用多个分隔符从字符串中提取子字符串

  • 11

告诉我如何最好地实现以下任务(我觉得我可以通过一个棘手的正则表达式来完成):

有一串单词,某些单词之间有功能词 AND 或 OR 例如

text = "word1 word2 OR word3 AND word4 word5"

有必要以 key=(words) 的形式在 OR 或 AND 之间转换所有单词组,将单词 OR 或 AND 保留在适当的位置

那些。在前面的例子中它应该是

text = "key=(word1 word2) OR key=(word3) AND key=(word4 word5)"
python
  • 3 个回答
  • 35 Views
Martin Hope
Zhihar
Asked: 2023-05-18 15:16:14 +0000 UTC

python:将字典参数传递给函数并添加自定义值

  • 5

告诉我如何简洁、漂亮、正确地将字典中包含的参数传递给函数+添加自己的参数

如果你只是传值过来,那是没有问题的:

data = {
    'v1':   123,
    'v3':   3.1415,
    'v2':   'abc'
}


def func(v1, v2, v3):
    print(v1, v2, v3, sep='\n')


func(**data)

但是,如果我想用一个值替换另一个值或添加一个新值怎么办?

在 JavaScript 中你可以这样做:

{...data, v1: 987}

python 中有任何简短而漂亮的模拟吗?

python
  • 2 个回答
  • 32 Views
Martin Hope
Zhihar
Asked: 2023-04-22 21:39:26 +0000 UTC

Python:判断字符串中写的是什么类型的值

  • 6

有一行包含一个整数,一个浮点数,或者只是一个字符串(你可以在堆之前想出更多的类型,比如日期)。

告诉我 - 您只能通过按类型进行强力搜索来确定这一点:

text = "13.6"

type = 'unknown'

try:
    value = int(text)
    type = 'int number'
except:
    try:
        value = float(text)
        type = 'float number'
    except:
        type = 'string'

或者有一些图书馆更优雅的方式吗?:)

python
  • 1 个回答
  • 57 Views
Martin Hope
Zhihar
Asked: 2023-04-19 16:37:32 +0000 UTC

python:获取异常的完整详细信息

  • 5

有这段代码:

print(func(123))

当我尝试执行时出现错误:

Traceback (most recent call last):
  File "debug.py", line 1, in <module>
    print(func(123))
          ^^^^
NameError: name 'func' is not defined

如果我发现异常:

try:
    print(func(123))
except BaseException as e:
    print(e)

然后我只得到这个信息:

name 'func' is not defined

是否可以通过异常得到完整的信息,包括发生异常的文件信息和发生异常的行号?

python
  • 2 个回答
  • 30 Views
Martin Hope
Zhihar
Asked: 2023-03-27 23:56:04 +0000 UTC

反应:如何在功能组件中理解属性值已更改

  • 6

有一个功能性的 React 组件Header:

const Header = (props) => {
    [value, setValue] = useState(() => {
        console.log('создание компонента');
        return props.attr;
    });

    return <div>{value}</div>

是这样称呼的:

<Header attr={attr} />

据我了解,Header在创建此组件时,useState 只会被调用一次。如果值发生变化,attr则不会进行重复调用(毕竟,组件保持在原位)

告诉我,在组件内部Header你如何理解属性已经改变(即新 props 与旧 props 不同)并执行一些与渲染无关的操作(处理数据等)?

那些。所有逻辑都应该只在组件内部Header,只有属性发生变化,仅此而已。

javascript
  • 1 个回答
  • 16 Views
Martin Hope
Zhihar
Asked: 2023-03-02 21:44:06 +0000 UTC

javascript:在一行中将值写入关联数组

  • 5

有这段代码:

    let tmp: any = this.state.states;
    tmp[event.target.id] = event.target.checked;

    this.setState({
        states: tmp
    });

告诉我如何在 1 行中更漂亮地形成一个 tmp 数组,即 就像是

    this.setState({
        states: [...this.state.states, event.target.id: event.target.checked]
    });
javascript
  • 1 个回答
  • 15 Views
Martin Hope
Zhihar
Asked: 2022-10-06 18:06:52 +0000 UTC

python:按键替换值并返回字典

  • 0

任务是:

有一本字典node = {'T': '', 'V': 0, 'E': []}

有必要返回这个字典,但是用键替换值E

可以这样做:

return {'T': node['T'], 'V': node['V']: 'E': [1, 2]}

有可能是这样的:

node['E'] = [1, 2]
return node

甚至像这样(理论上最可靠):

new = copy.deepcopy(node)
new ['E'] = [1, 2]
return new 

这样的问题 - 是否有可能在 1 行中以某种方式完美地做到这一点并且没有太多额外的功能,就像在 JS 中一样:

return {...node, 'E': [1, 2]}
python
  • 1 个回答
  • 30 Views
Martin Hope
Zhihar
Asked: 2022-10-06 06:12:05 +0000 UTC

python:紧凑表示法,根据它们的值选择两个变量之一

  • 0

有变量l并且r是字典

告诉我是否有可能以某种方式紧凑而精美;-) 重写此功能:

        if l == {} and r == {}:
            return {}

        if l == {}:
            return r

        if r == {}:
            return l

我理解它似乎很清晰,或多或少紧凑,但也许它可以更好

附言

至少您可以将第 1 行替换为

        if l == r == {}:
python
  • 2 个回答
  • 33 Views
Martin Hope
Zhihar
Asked: 2022-10-03 19:14:32 +0000 UTC

react: 在组件构造函数中使用 setState 进行异步操作

  • 0

在构造函数的组件中,我向服务器发出请求以获取必要的数据并将它们异步添加到状态中:

class MyComponent extends Component<any, any> {

    // конструктор
    constructor(
        props: any
    ) {
        super(props);

        // задать состояние компонента
        this.state = {
            data: [1, 2, 3]
        };

        // отправить запрос на сервер
        to_server().then((output: any) => {
            // установить состояния
            this.setState({
                data: output.data,
            });
        });    
    }

    // отрисовать компонент
    render() {
        return <>{this.state.data.length}</>;
    }
}

我得到一个警告,我应该在构造函数中使用直接状态设置:

警告:无法在尚未安装的组件上调用 setState。这是一个无操作,但它可能表明您的应用程序中存在错误。相反,在 MyComponent 组件中直接分配this.state或定义state = {}; 具有所需状态的类属性。

请告诉我如何纠正此问题并消除警告。

javascript
  • 1 个回答
  • 17 Views
Martin Hope
Zhihar
Asked: 2022-09-21 19:42:25 +0000 UTC

javascript:在常规数组中的数据上构建关联数组

  • 0

有一组数据结构

data = [
    {key: 'xxx', value: 123, other: X},
    {key: 'yyy', value: 456, other: Y},
    {key: 'zzz', value: 789, other: Z},
];

如何从中创建关联数组:

{
    'xxx': 123,
    'yyy': 456,
    'zzz': 789
}

我用方法reduce:

output = data.reduce((res, elem) => {
    res[elem.key] = elem.value;
    return res;
}, {});

但是是否可以在没有嵌套函数的情况下在 1 行中执行此操作,例如,使用相同的map?

javascript
  • 0 个回答
  • 0 Views
Martin Hope
Zhihar
Asked: 2022-09-16 19:26:21 +0000 UTC

反应:设计一个组件的问题,只有在满足某些条件时才会显示(使用)

  • 2

创建了一个在组件ComponentBottom内部使用的组件ComponentTop:

// компонент ComponentTop
render() {
    return (
        <div>
            <какие-то элементы />
            {this.state.flag ? <ComponentBottom /> : <></> }
        </div>
    );
}

我有一个新手问题 - 在这种情况下,最好将显示组件的功能添加到组件本身:

// компонент ComponentTop
render() {
    return (
        <div>
            <какие-то элементы />
            <ComponentBottom show = {this.state.flag} />
        </div>
    );
}

// компонент ComponentBottom
render() {
    if (!this.props.show)
        return <></>

    return (/*отрисовка компонента*/);
}

还是如上所述将所有渲染逻辑留在父组件中?

哪种方法更好?

javascript
  • 0 个回答
  • 0 Views
Martin Hope
Zhihar
Asked: 2022-09-12 22:05:12 +0000 UTC

javascript:从列表中替换字符串中的单词

  • 0

有一个字符串text和一个关键字数组this.state.keywords

需要将XXX行中的关键字替换为表格的表达式<span class = 'c0*'>XXX</span>

其中*是一个从 1 到 4 的值(本质上是字典中关键字的编号模 4)

写了这段代码:

highlightText = (text: string) => {
    let output: string = text;
    let index: number = 0;
    for (const keyword of this.state.keywords) {
        output = output.replace(new RegExp(keyword, 'ig'), `<span class='c0${index % 4 + 1}'>${keyword}</span>`, );
        index += 1;
    }

    return output;
}

对我来说,这是笨拙和多余的。

告诉我如何让它更优雅,有条件的它可以在几行内折叠

javascript
  • 0 个回答
  • 0 Views
Martin Hope
Zhihar
Asked: 2022-09-12 20:49:38 +0000 UTC

react: 将文本转换为 html 代码

  • 0

告诉我如何转换在 html 代码中也显示 html 标签的文本

更准确地说,我有一个包含 html 代码的字符串:

this.state = {
    text: 'test <b>BOLD</b> test2 <span class = "c01">Red text</span>'
};

我需要将此文本显示为 html 代码:

    render() {       
        return (
<div>{this.state.text}</div>
        );
    }
javascript
  • 0 个回答
  • 0 Views
Martin Hope
Zhihar
Asked: 2022-09-12 20:12:19 +0000 UTC

javascript:使用任何“空白”分隔符分割字符串

  • -1

告诉我如何更优雅地分割一行,使用空格、制表符或其他“空白”分隔符作为分隔符

使用正则表达式?

javascript
  • 0 个回答
  • 0 Views
Martin Hope
Zhihar
Asked: 2022-08-16 17:27:33 +0000 UTC

python:写入具有给定第一步值的列表

  • 1

需要arr将值value从位置start写入列表step

告诉我如何以最有效的方式做到这一点。

我用这种方式:

arr[start::step] = [value] * (len(arr) - start - 1)

但是有没有更有效的方法?

python python-3.x
  • 1 个回答
  • 28 Views

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    我看不懂措辞

    • 1 个回答
  • Marko Smith

    请求的模块“del”不提供名为“default”的导出

    • 3 个回答
  • Marko Smith

    "!+tab" 在 HTML 的 vs 代码中不起作用

    • 5 个回答
  • Marko Smith

    我正在尝试解决“猜词”的问题。Python

    • 2 个回答
  • Marko Smith

    可以使用哪些命令将当前指针移动到指定的提交而不更改工作目录中的文件?

    • 1 个回答
  • Marko Smith

    Python解析野莓

    • 1 个回答
  • Marko Smith

    问题:“警告:检查最新版本的 pip 时出错。”

    • 2 个回答
  • Marko Smith

    帮助编写一个用值填充变量的循环。解决这个问题

    • 2 个回答
  • Marko Smith

    尽管依赖数组为空,但在渲染上调用了 2 次 useEffect

    • 2 个回答
  • Marko Smith

    数据不通过 Telegram.WebApp.sendData 发送

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5