[旋木]

文章 评论 浏览 30

[旋木] 2025-02-20 20:55:36

widget.config(bg = color)是您想要的。

这是一个改变主题的应用程序的一个小示例:

from tkinter import *
from tkmacosx import Button

root = Tk()


def changethemetoblack():
    root.config(bg="#000000")


def changethemetowhite():
    root.config(bg="#ffffff")


def changethemetored():
    root.config(bg="#ff0000")


themeblackbutton = Button(root, text="Change Theme To Black", command=changethemetoblack, bg="#000000", fg="#ffffff")
themewhitebutton = Button(root, text="Change Theme To White", command=changethemetowhite)
themeredbutton = Button(root, text="Change Theme To Red", command=changethemetored, bg="#ff0000", fg="#ffffff")

themeblackbutton.pack()
themewhitebutton.pack()
themeredbutton.pack()

root.mainloop()

我将尝试更改它,以便它适用您的代码。
但是,您提供的脚本似乎并不是一个有效的脚本。我认为这是因为它只是真实的片段。我不是在推动您的整个代码,而是要编辑它,以便我们可以运行它。前任。 OpenCipher方法正在引起错误,因为我们尚未定义它。

Widget.config(bg=color) is what your looking for.

Here is a small example of a theme-changing app:

from tkinter import *
from tkmacosx import Button

root = Tk()


def changethemetoblack():
    root.config(bg="#000000")


def changethemetowhite():
    root.config(bg="#ffffff")


def changethemetored():
    root.config(bg="#ff0000")


themeblackbutton = Button(root, text="Change Theme To Black", command=changethemetoblack, bg="#000000", fg="#ffffff")
themewhitebutton = Button(root, text="Change Theme To White", command=changethemetowhite)
themeredbutton = Button(root, text="Change Theme To Red", command=changethemetored, bg="#ff0000", fg="#ffffff")

themeblackbutton.pack()
themewhitebutton.pack()
themeredbutton.pack()

root.mainloop()

I'll try to change it so that it applies for your code.
However, your provided script does not seem to be a working one. I assume this is because it is only a snippet of the real one. I'm not pushing for your entire code, but edit it so we can run it. Ex. openCipher method is causing errors as we have not defined it.

如何使用tkinter中的按钮更改背景颜色和前景颜色?

[旋木] 2025-02-20 20:38:45

是的,您可以使用浏览器的本地人的本机时间输入并解析其值(hh:mm格式,无论用户语言环境或输入的方式)。然后根据需要使用那些解析的值。这是一个示范:

body {
  font-family: sans-serif;
  font-size: 1rem;
}

.time-input { font-size: 1rem; }
.states { margin-top: 1rem; }
<div id="root"></div><script src="https://unpkg.com/[email protected]/umd/react.development.js"></script><script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script><script src="https://unpkg.com/@babel/[email protected]/babel.min.js"></script>
<script type="text/babel" data-type="module" data-presets="env,react">

// import ReactDOM from 'react-dom/client';
// import {useMemo, useState} from 'react';

// This Stack Overflow snippet demo uses UMD modules instead of the commented import statments above
const {useMemo, useState} = React;

function App () {
  const [rawTime, setRawTime] = useState('00:00');

  const [hours, minutes] = useMemo(
    () => rawTime.split(':').slice(0, 2).map(Number),
    [rawTime],
  );

  const statesJson = JSON.stringify({
    rawTime,
    hours,
    minutes,
  }, null, 2);

  return (
    <div>
      <input
        className="time-input"
        type="time"
        onChange={ev => setRawTime(ev.target.value)}
        value={rawTime}
      />
      <div className="states">
        <label>States:</label>
        <pre>
          <code>{statesJson}</code>
        </pre>
      </div>
    </div>
  );
}

const reactRoot = ReactDOM.createRoot(document.getElementById('root'));
reactRoot.render(<App />);

</script>

Yes, you can use a controlled version of the browser's native time input and parse its value (which is in hh:mm format, regardless of user locale or how the input is presented). Then use those parsed values however you want. Here's a demonstration:

body {
  font-family: sans-serif;
  font-size: 1rem;
}

.time-input { font-size: 1rem; }
.states { margin-top: 1rem; }
<div id="root"></div><script src="https://unpkg.com/[email protected]/umd/react.development.js"></script><script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script><script src="https://unpkg.com/@babel/[email protected]/babel.min.js"></script>
<script type="text/babel" data-type="module" data-presets="env,react">

// import ReactDOM from 'react-dom/client';
// import {useMemo, useState} from 'react';

// This Stack Overflow snippet demo uses UMD modules instead of the commented import statments above
const {useMemo, useState} = React;

function App () {
  const [rawTime, setRawTime] = useState('00:00');

  const [hours, minutes] = useMemo(
    () => rawTime.split(':').slice(0, 2).map(Number),
    [rawTime],
  );

  const statesJson = JSON.stringify({
    rawTime,
    hours,
    minutes,
  }, null, 2);

  return (
    <div>
      <input
        className="time-input"
        type="time"
        onChange={ev => setRawTime(ev.target.value)}
        value={rawTime}
      />
      <div className="states">
        <label>States:</label>
        <pre>
          <code>{statesJson}</code>
        </pre>
      </div>
    </div>
  );
}

const reactRoot = ReactDOM.createRoot(document.getElementById('root'));
reactRoot.render(<App />);

</script>

是否可以使用纯React方式添加时间输入检查文本字段?

[旋木] 2025-02-20 11:19:04

要解决此问题,我需要将Minsdk更新为21。之后,一切都按预期工作。

请参阅我的最终构建.gradle文件:

plugins {
    id 'com.android.application'
    id 'org.jetbrains.kotlin.android'
    id 'kotlin-kapt'
}

android {
    compileSdk 32

    defaultConfig {
        applicationId "co.megusta.c3"
        minSdk 21
        targetSdk 32
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

    buildFeatures {
        viewBinding true
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
}

def lifeCycleExtensionsVersion = '2.5.0'
def recyclerViewVersion = '1.2.1'
def recyclerViewSelectVersion = '1.1.0'
def retrofitVersion = '2.9.0'
def daggerVersion = '2.42'
def glideVersion = '4.13.2'
def mockitoVersion = '4.6.1'
def rxJavaVersion = '3.0.0'

dependencies {

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.4.2'
    implementation 'com.google.android.material:material:1.6.1'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'

    implementation "com.squareup.retrofit2:retrofit:$retrofitVersion"
    implementation "com.squareup.retrofit2:converter-gson:$retrofitVersion"
    implementation "com.squareup.retrofit2:adapter-rxjava3:$retrofitVersion"

    implementation "io.reactivex.rxjava3:rxjava:$rxJavaVersion"
    implementation "io.reactivex.rxjava3:rxandroid:$rxJavaVersion"

    implementation "com.google.dagger:dagger:$daggerVersion"
    implementation "com.google.dagger:dagger-android-support:$daggerVersion"

    kapt "com.google.dagger:dagger-compiler:$daggerVersion"
    kapt "com.google.dagger:dagger-android-processor:$daggerVersion"

    implementation "com.github.bumptech.glide:glide:$glideVersion"

    implementation "androidx.recyclerview:recyclerview:$recyclerViewVersion"
    implementation "androidx.recyclerview:recyclerview-selection:$recyclerViewSelectVersion"
    implementation "androidx.swiperefreshlayout:swiperefreshlayout:$recyclerViewSelectVersion"

    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifeCycleExtensionsVersion"
    implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifeCycleExtensionsVersion"
    implementation "androidx.lifecycle:lifecycle-viewmodel-compose:$lifeCycleExtensionsVersion"
    implementation "androidx.lifecycle:lifecycle-viewmodel-savedstate:$lifeCycleExtensionsVersion"
    kapt "androidx.lifecycle:lifecycle-compiler:$lifeCycleExtensionsVersion"

    testImplementation 'junit:junit:4.13.2'
    testImplementation "org.mockito:mockito-inline:$mockitoVersion"
    testImplementation "android.arch.core:core-testing:1.1.1"

    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}

To fix this problem I need to update the minSdk to 21. After that everything works as expected.

See my final build.gradle file:

plugins {
    id 'com.android.application'
    id 'org.jetbrains.kotlin.android'
    id 'kotlin-kapt'
}

android {
    compileSdk 32

    defaultConfig {
        applicationId "co.megusta.c3"
        minSdk 21
        targetSdk 32
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

    buildFeatures {
        viewBinding true
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
}

def lifeCycleExtensionsVersion = '2.5.0'
def recyclerViewVersion = '1.2.1'
def recyclerViewSelectVersion = '1.1.0'
def retrofitVersion = '2.9.0'
def daggerVersion = '2.42'
def glideVersion = '4.13.2'
def mockitoVersion = '4.6.1'
def rxJavaVersion = '3.0.0'

dependencies {

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.4.2'
    implementation 'com.google.android.material:material:1.6.1'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'

    implementation "com.squareup.retrofit2:retrofit:$retrofitVersion"
    implementation "com.squareup.retrofit2:converter-gson:$retrofitVersion"
    implementation "com.squareup.retrofit2:adapter-rxjava3:$retrofitVersion"

    implementation "io.reactivex.rxjava3:rxjava:$rxJavaVersion"
    implementation "io.reactivex.rxjava3:rxandroid:$rxJavaVersion"

    implementation "com.google.dagger:dagger:$daggerVersion"
    implementation "com.google.dagger:dagger-android-support:$daggerVersion"

    kapt "com.google.dagger:dagger-compiler:$daggerVersion"
    kapt "com.google.dagger:dagger-android-processor:$daggerVersion"

    implementation "com.github.bumptech.glide:glide:$glideVersion"

    implementation "androidx.recyclerview:recyclerview:$recyclerViewVersion"
    implementation "androidx.recyclerview:recyclerview-selection:$recyclerViewSelectVersion"
    implementation "androidx.swiperefreshlayout:swiperefreshlayout:$recyclerViewSelectVersion"

    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifeCycleExtensionsVersion"
    implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifeCycleExtensionsVersion"
    implementation "androidx.lifecycle:lifecycle-viewmodel-compose:$lifeCycleExtensionsVersion"
    implementation "androidx.lifecycle:lifecycle-viewmodel-savedstate:$lifeCycleExtensionsVersion"
    kapt "androidx.lifecycle:lifecycle-compiler:$lifeCycleExtensionsVersion"

    testImplementation 'junit:junit:4.13.2'
    testImplementation "org.mockito:mockito-inline:$mockitoVersion"
    testImplementation "android.arch.core:core-testing:1.1.1"

    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}

找不到匕首-2.13-2.13.jar(com.google.dagger:匕首:2.13)

[旋木] 2025-02-19 19:17:14

“我得到错误'mainwindow'不参考一个值”

我看不到你有任何“ mainwindow”命名变量的地方,
但是您还提到mainWindow是父级,这意味着您可以随时获得参考,例如:

MainWindow *mainWindow = qobject_cast<MainWindow *>(this->parent());

您的信号操作器(changeText(...) slot)应该将QString作为参数(而不是QDIR),这样您就可以处理如何确切处理转换的方法,以防用户在输入段中输入一些随机文本(text-text--编辑)。

void changeText(const QString &input);

最后,您要么需要指定类型:

QObject::connect(ui->outLineEdit, SIGNAL(textChanged(QString)), mainWindow, SLOT(changeText(QString));

或者,使用新的QT-5语法:

connect(ui->outLineEdit, &QLineEdit::textChanged,
        mainWindow, &MainWindow::changeText);

"I get the error 'mainWindow' does not refer to a value"

I don't see you having any "mainWindow" named variable anywhere,
but you also mentioned that the MainWindow is the parent, which means you could get reference anytime, like:

MainWindow *mainWindow = qobject_cast<MainWindow *>(this->parent());

Also, your signal-handler (changeText(...) slot) should take QString as parameter (instead of QDir), this way you handle how exactly the conversion is handled, in case users type some random text in input-field (text-edit).

void changeText(const QString &input);

Finally, you either need to specify type:

QObject::connect(ui->outLineEdit, SIGNAL(textChanged(QString)), mainWindow, SLOT(changeText(QString));

Or, use the new Qt-5 syntax:

connect(ui->outLineEdit, &QLineEdit::textChanged,
        mainWindow, &MainWindow::changeText);

QT连接不同Windows/ Mirror的信号和插槽

[旋木] 2025-02-19 16:37:18

我喜欢 >也提出了一个上下文管理器表格,该表格更适合我的需求。

import datetime as dt
import timeit

class TimingManager(object):
    """Context Manager used with the statement 'with' to time some execution.

    Example:

    with TimingManager() as t:
       # Code to time
    """

    clock = timeit.default_timer

    def __enter__(self):
        """
        """
        self.start = self.clock()
        self.log('\n=> Start Timing: {}')

        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        """
        """
        self.endlog()

        return False

    def log(self, s, elapsed=None):
        """Log current time and elapsed time if present.
        :param s: Text to display, use '{}' to format the text with
            the current time.
        :param elapsed: Elapsed time to display. Dafault: None, no display.
        """
        print s.format(self._secondsToStr(self.clock()))

        if(elapsed is not None):
            print 'Elapsed time: {}\n'.format(elapsed)

    def endlog(self):
        """Log time for the end of execution with elapsed time.
        """
        self.log('=> End Timing: {}', self.now())

    def now(self):
        """Return current elapsed time as hh:mm:ss string.
        :return: String.
        """
        return str(dt.timedelta(seconds = self.clock() - self.start))

    def _secondsToStr(self, sec):
        """Convert timestamp to h:mm:ss string.
        :param sec: Timestamp.
        """
        return str(dt.datetime.fromtimestamp(sec))

I liked Paul McGuire's answer too and came up with a context manager form which suited my needs more.

import datetime as dt
import timeit

class TimingManager(object):
    """Context Manager used with the statement 'with' to time some execution.

    Example:

    with TimingManager() as t:
       # Code to time
    """

    clock = timeit.default_timer

    def __enter__(self):
        """
        """
        self.start = self.clock()
        self.log('\n=> Start Timing: {}')

        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        """
        """
        self.endlog()

        return False

    def log(self, s, elapsed=None):
        """Log current time and elapsed time if present.
        :param s: Text to display, use '{}' to format the text with
            the current time.
        :param elapsed: Elapsed time to display. Dafault: None, no display.
        """
        print s.format(self._secondsToStr(self.clock()))

        if(elapsed is not None):
            print 'Elapsed time: {}\n'.format(elapsed)

    def endlog(self):
        """Log time for the end of execution with elapsed time.
        """
        self.log('=> End Timing: {}', self.now())

    def now(self):
        """Return current elapsed time as hh:mm:ss string.
        :return: String.
        """
        return str(dt.timedelta(seconds = self.clock() - self.start))

    def _secondsToStr(self, sec):
        """Convert timestamp to h:mm:ss string.
        :param sec: Timestamp.
        """
        return str(dt.datetime.fromtimestamp(sec))

如何获得Python程序的执行时间?

[旋木] 2025-02-19 14:05:54

这里有一些错误。我们不会在SwiftUI中使用查看模型对象进行查看数据,这样做是相当低效率的/错误的。相反,将带有@State突变弹性的结构使用。将参数传递给子视图,作为让读取访问的让@binding仅在您需要写入访问时才是。在渲染方面,首先仅在 的情况然后有任何差异,然后SwiftUi代表您添加/删除/更新实际的Uikit Uiviews,然后由这些Uiview的实际渲染,例如drawRect,由Coregraphics。

struct ContentViewConfig {
    
    var firstTitle = "firstTitle"
    var secondTitle = "secondTitle"
    
    mutating func changeFirstTitle() {
        firstTitle = "hello world"
    }
}

struct ContentView: View {
    @State var config = Config()
    ...

struct ThirdView: View {
    let text: String
    ...

Combine的observableObject通常仅在需要使用组合时使用,例如使用combineLatest与多个发布者或用于store> Store对象保持模型结构阵列在@published属性中,这些属性与视图的寿命没有@state。您的用例看起来不像observableObject的有效用途。

A few things wrong here. We don't use view model objects in SwiftUI for view data, it's quite inefficient/buggy to do so. Instead, use a struct with mutating funcs with an @State. Pass in params to sub-Views as lets for read access, @Binding is only when you need write access. In terms of rendering, first of all body is only called if the let property is different from the last time the sub-View is init, then it diffs the body from the last time it was called, if there are any differences then SwiftUI adds/removes/updates actual UIKit UIViews on your behalf, then actual rendering of those UIViews, e.g. drawRect, is done by CoreGraphics.

struct ContentViewConfig {
    
    var firstTitle = "firstTitle"
    var secondTitle = "secondTitle"
    
    mutating func changeFirstTitle() {
        firstTitle = "hello world"
    }
}

struct ContentView: View {
    @State var config = Config()
    ...

struct ThirdView: View {
    let text: String
    ...

Combine's ObservableObject is usually only used when needing to use Combine, e.g. using combineLatest with multiple publishers or for a Store object to hold the model struct arrays in @Published properties that are not tied to a View's lifetime like @State. Your use case doesn't look like a valid use of ObservableObject.

更新属性包装器,例如@StateObject,会影响不使用该属性的其他视图渲染

[旋木] 2025-02-19 10:51:27

计数器示例:

int具有宽度31加上标志的位,无符号短具有宽度16。使用A类型的B无符号简短,在积分促销之后,该操作将在int中执行。

如果ab具有值2^16-1,则是a * b的数学确切结果自然数将是2^32-2^17 + 1。这大于2^31-1,因此不能用int表示。

签名的积分类型中的算术溢出导致不确定的行为。因此,a *= b具有未定义的行为。如果使用未签名的算术模量2^宽度(未签名短),则不会具有这种不确定的行为。

(适用于所有C和C ++版本。)

Counter example:

int has width 31 plus one bit for sign, unsigned short has width 16. With a and b of type unsigned short, after integral promotions, the operation is performed in int.

If a and b have value 2^16 - 1, then the mathematical exact result of a * b in the natural numbers would be 2^32 - 2^17 + 1. This is larger than 2^31 - 1 and therefore cannot be represented by int.

Arithmetic overflow in signed integral types results in undefined behavior. Therefore a *= b has undefined behavior. It would not have this undefined behavior if unsigned arithmetic modulo 2^width(unsigned short) was used.

(Applies to all C and C++ versions.)

同一类型的两个无符号整数的复合分配是否总是像使用该类型的模块化算术一样运行?

[旋木] 2025-02-19 03:26:35

您应该将列表分配给名称以再次访问它。

mylist <- list('Chicago' = 1, 'New York' = 2, 'Los Angeles' = 3)

mylist$Chicago
# [1] 1

You should assign your list to a name to access it again.

mylist <- list('Chicago' = 1, 'New York' = 2, 'Los Angeles' = 3)

mylist$Chicago
# [1] 1

命名列表中的元素

[旋木] 2025-02-18 21:17:52

使用以下内容:

return Arrays.equals(perm1, perm2)

代替:

return perm1.equals(perm2);

请必须查看 this

Use this:

return Arrays.equals(perm1, perm2)

Instead of this:

return perm1.equals(perm2);

Please have to look this

比较Java的阵列

[旋木] 2025-02-17 15:02:15

您需要与应用程序中的容器相同的CSS创建样式的CS。我已经更新了您的代码,它应该适合您。

styles.js

import styled from "styled-components";
import AcUnitIcon from "@mui/icons-material/AcUnit";

export const ListCotainer = styled.div`
  margin: 100px;
  width: 200px;
  color: pink;
`;

export const Container = styled.div`
  font-family: sans-serif;
  text-align: center;
  background-color: red;
`;

export const Icon = styled(AcUnitIcon)`
  background-color: blue;
  margin: 100px;
  padding: 20px;
  ${Container}:hover & {
    background-color: green;
  }
`;

list.js

import React from "react";
import { ListCotainer } from "./styles";

const List = () => {
  return (
    <ListCotainer>
      <h1>Hello styled component</h1>
    </ListCotainer>
  );
};

export default List;

app.js

import { Container, Icon } from "./styles";
import List from "./List";

export default function App() {
  return (
    <Container>
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <List />
      <Icon />
    </Container>
  );

you need to create styled CSS same as you have created for Container in your App.js. i have update your code it should work for you.

styles.js

import styled from "styled-components";
import AcUnitIcon from "@mui/icons-material/AcUnit";

export const ListCotainer = styled.div`
  margin: 100px;
  width: 200px;
  color: pink;
`;

export const Container = styled.div`
  font-family: sans-serif;
  text-align: center;
  background-color: red;
`;

export const Icon = styled(AcUnitIcon)`
  background-color: blue;
  margin: 100px;
  padding: 20px;
  ${Container}:hover & {
    background-color: green;
  }
`;

List.js

import React from "react";
import { ListCotainer } from "./styles";

const List = () => {
  return (
    <ListCotainer>
      <h1>Hello styled component</h1>
    </ListCotainer>
  );
};

export default List;

App.js

import { Container, Icon } from "./styles";
import List from "./List";

export default function App() {
  return (
    <Container>
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <List />
      <Icon />
    </Container>
  );

如何将样式添加到具有样式组件的组件中?

[旋木] 2025-02-17 05:19:35

Alertrepository是一个实体不是正确的类,您只需要在 onModeLcreating 中映射警报实体

替换,

modelBuilder.Entity<AlertRepository>().ToTable("Alert");

或者

modelBuilder.Entity<Alert>().ToTable("Alert")

您只能删除此行,因为实体框架将为您创建一个与您的名称相同的表格实体。

AlertRepository is not right class to be an entity, you just have to map the Alert entity in OnModelCreating

Replace

modelBuilder.Entity<AlertRepository>().ToTable("Alert");

with

modelBuilder.Entity<Alert>().ToTable("Alert")

or you can just remove this line because entity framework will create a table for you with same name as your entity.

EF核心:实体需要一个钥匙 - 但它确实有一个钥匙

[旋木] 2025-02-17 03:29:20

我想您正在使用Cython 0.29。 0.29 pep-489 python版本已启用了多相模块初始化。这意味着,使用pyinit_xxx不再足够,因为您正在经历。

inittab机制,即您的main main - 功能应该看起来像:

#include "Python.h"
#include "transcendentals.h"
#include <math.h>
#include <stdio.h>

int main(int argc, char **argv) {
  int status=PyImport_AppendInittab("transcendentals", PyInit_transcendentals);
  if(status==-1){
    return -1;//error
  } 
  Py_Initialize();
  PyObject *module = PyImport_ImportModule("transcendentals");

  if(module==NULL){
     Py_Finalize();
     return -1;//error
  }
  
  printf("pi**e: %f\n", pow(PI, get_e()));
  Py_Finalize();
  return 0;
}

恢复旧行为的另一种可能性是定义宏cython_pep489_multi_phase_init = 0,从而通过EG传递-dcycy> -dcycython_pep489_multi_phase_phase_init = 0 gcc在编译时在命令行上。

I guess you are using Cython 0.29. Since 0.29, PEP-489 multi-phase module initialisation has been enabled for Python versions >=3.5. This means, using PyInit_XXX is no longer sufficient, as you are experiencing.

Cython's documentation suggest to use inittab mechanism, i.e. your main-function should look something like:

#include "Python.h"
#include "transcendentals.h"
#include <math.h>
#include <stdio.h>

int main(int argc, char **argv) {
  int status=PyImport_AppendInittab("transcendentals", PyInit_transcendentals);
  if(status==-1){
    return -1;//error
  } 
  Py_Initialize();
  PyObject *module = PyImport_ImportModule("transcendentals");

  if(module==NULL){
     Py_Finalize();
     return -1;//error
  }
  
  printf("pi**e: %f\n", pow(PI, get_e()));
  Py_Finalize();
  return 0;
}

Another possibility to restore the old behavior would be to define macro CYTHON_PEP489_MULTI_PHASE_INIT=0 and thus overriding the default by e.g. passing -DCYTHON_PEP489_MULTI_PHASE_INIT=0 to gcc on the command line while compiling.

从C代码调用Cython函数增加分割故障

[旋木] 2025-02-16 23:29:05

使用Worksheet_change事件时,更改ActiveCell并不是一个好主意,因为ActiveCell可能是任何事物,具体取决于用户如何进入值。

  • 如果他们点击Enter并将系统配置为下一行向下,那么ActiveCell将是下一个行,
  • 可以更改该行为并进行ENTER进行,而不是向下
  • 访问用户,可以通过单击一个单击一个单击电子表格中的随机单元格,IE ActiveCell可以在任何地方。
  • 用户可以单击公式栏旁边的绿色刻度标记,并且单元选择根本不会改变。

您不知道活动单元将是什么,因此请使用activecell.offset(rowoffset:= - 1可以最终到达任何地方

。对象

If Target = "" Then
    ' do nothing, or maybe you want to clear any previously existing time stamp like this
    'Cells(Target.Row, "E").clearContents
Else
    Cells(Target.Row, "E").Value = Now()
End If

。设置更改导致实际值,而不是空白单元格

It's not a good idea to change the ActiveCell when using the Worksheet_Change event, because the ActiveCell could be anything, depending how the user enters the value.

  • if they hit Enter and the system is configured to go to the next row down, then ActiveCell will be the next row down,
  • it is possible to change that behaviour and Enter goes across instead of down
  • the user could confirm the cell entry by clicking a random cell in the spreadsheet, i.e. ActiveCell could be anywhere.
  • the user could click the green tick mark next to the formula bar and the cell selection does not change at all.

You cannot know what the active cell will be, so using ActiveCell.Offset(rowOffset:=-1 could end up anywhere.

Instead of the active cell, operate on the target object. You don't need to call another sub for that, you can do it right in the Change event

If Target = "" Then
    ' do nothing, or maybe you want to clear any previously existing time stamp like this
    'Cells(Target.Row, "E").clearContents
Else
    Cells(Target.Row, "E").Value = Now()
End If

Now you don't need to muck around with offset to get the row where the change happened, and the time stamp will only be set if the change resulted in a real value, not a blank cell.

If, for some reason you want to use a separate sub, just feed it the row number of Target as a parameter.

我想区分清除单元格与更改单元格

[旋木] 2025-02-16 19:44:32

如果您没有静态数据,但是有动态数据,则可以执行以下解决方案:

const sample = {
  links: {
"compositions": [
  {
    "modelId": 103889,
    "id": 164703
  },
  {
    "modelId": 103888,
    "id": 164704
  }
]
 }
}

const objToAdd = {
   compositions: []
};

const keyToMap = 'compositions';
const keyToAdd = 'compositions';

function findArray(object){
    if(object.hasOwnProperty(keyToMap))
        return object;

    for(var i=0; i<Object.keys(object).length; i++){
        if(typeof object[Object.keys(object)[i]] == "object"){
            var o = findArray(object[Object.keys(object)[i]]);
            if(o != null)
                return o;
        }
    }
    return null;
}

const compositionsObject = findArray(sample);

objToAdd[keyToAdd].push(compositionsObject[Object.keys(compositionsObject)[0]]);

console.log('Result', objToAdd)

您可以将要映射的密钥的名称保留在“ KeyTomApp” const中,以及要将此数据添加到“ KeyToAdd”中的密钥。

添加一个递归函数findarray,其中一个参数是您映射的对象,在这种情况下为示例对象。第一个条件是“最终”结果,我们询问示例对象是否具有键入键,在这种情况下为“构图”。如果使用此键找到对象,它将返回该对象。
如果它找不到使用该键的对象,它将通过对象键迭代,直到找到一个对象(typeof object)并与找到的新对象重试(重新输入函数=递归)。

在CompositionSobject中,我们将其保留为键= keytomap的对象。
之后,我们将其值推到对象上的值= keytoAdd

If you don't have static data but you have dynamic data you can do the following solution:

const sample = {
  links: {
"compositions": [
  {
    "modelId": 103889,
    "id": 164703
  },
  {
    "modelId": 103888,
    "id": 164704
  }
]
 }
}

const objToAdd = {
   compositions: []
};

const keyToMap = 'compositions';
const keyToAdd = 'compositions';

function findArray(object){
    if(object.hasOwnProperty(keyToMap))
        return object;

    for(var i=0; i<Object.keys(object).length; i++){
        if(typeof object[Object.keys(object)[i]] == "object"){
            var o = findArray(object[Object.keys(object)[i]]);
            if(o != null)
                return o;
        }
    }
    return null;
}

const compositionsObject = findArray(sample);

objToAdd[keyToAdd].push(compositionsObject[Object.keys(compositionsObject)[0]]);

console.log('Result', objToAdd)

You can keep the name of the key you want to map in the 'keyToMapp' const and the key you want to add this data to as 'keyToAdd'.

Add a recursive function findArray that has one parameter the object you map, in this case the sample object. The first condition is the 'final' result, we ask if the sample object has the keyToMap which in this case is 'compositions'. If it finds the object with this key, it returns that object.
If it doesn't find the object with that key, it iterates through object keys until it finds an object (typeof object) and retries (re-enters the function = recursive) with the new object found.

In the compositionsObject we keep the object we find with the key = keyToMap.
After that we push it's values to the object with key = keyToAdd

将另一个对象添加到另一个对象,然后循环数据到其中

[旋木] 2025-02-16 15:49:02

像这样:

Dim addr As String
addr = Sheets("Reference").Range("D2").Value   'get the cell address

Sheets("Operator").Range(addr).Value = "Test"  'pass the address to Range()

Like this:

Dim addr As String
addr = Sheets("Reference").Range("D2").Value   'get the cell address

Sheets("Operator").Range(addr).Value = "Test"  'pass the address to Range()

如何使用Excel VBA使用单元格在另一个工作表中的单元格中更改单元格的值?

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

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