AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题

全部问题(coding)

Martin Hope
zaber8787利巴
Asked: 2025-04-28 00:29:36 +0800 CST

Py-cord 是否支持 Discord 的新用户安装命令功能?

  • 6

我最近了解到,Discord 更新了一项名为“用户安装”的功能,允许用户将机器人安装到个人账户,而不仅仅是服务器。据我了解,这项功能允许用户在机器人尚未正式上线的服务器中使用某些机器人命令。

我正在使用 py-cord 开发 Discord 机器人并想实现这个新功能,但我在文档中找不到有关它的任何信息。

我的问题是:

  1. py-cord 是否已经支持 Discord 的用户安装命令功能?
  2. 如果支持,我如何在 py-cord 中定义和实现一个可由用户安装并在任何服务器中使用的命令?
  3. 是否有相关的装饰器或特殊配置来标记这些类型的命令?

我当前的代码结构:

import discord
from discord.ext import commands

bot = commands.Bot()

# Regular slash command
@bot.slash_command(name="hello", description="Say hello")
async def hello(ctx):
    await ctx.respond(f"Hello, {ctx.author.name}!")

# I want to know how to modify this to be a user-installable command
# @bot.???_command(name="usercommand")
# async def user_command(ctx):
#     await ctx.respond("This is a user-installed command")

bot.run("TOKEN")

感谢您的任何指导或建议!

python
  • 1 个回答
  • 27 Views
Martin Hope
Saisiva A
Asked: 2025-04-28 00:12:39 +0800 CST

Python MRO 在分层和多重继承中的工作原理

  • 4

到目前为止,这让我很困惑,下面的代码该如何理解给出的结果。有人能解释一下下面两部分输出的实际流程吗?第一部分输出为“C”,第二部分输出为“A”。

class A:
    def fun1(self):
        print("A")
 
class B(A):
    def fun1(self):
        print('B')
 
class C(A):
    def fun1(self):
        print("C")
 
class D(B, C):
    def fun1(self):
        super(B, self).fun1()  
 
obj = D()
obj.fun1()  **# How output will be 'C' in this case ?**
output : C 

class A:
    def fun1(self):
        print("A")

class B(A):
    def fun1(self):
        print("B")

class C(A):
    def fun1(self):
        print("C")

class D(B, C):
    def fun1(self):
        super(C, self).fun1()  

obj = D()
obj.fun1()  **# How output will be 'A' in this case ?**
output : A   
python
  • 1 个回答
  • 33 Views
Martin Hope
Cristi
Asked: 2025-04-27 23:27:46 +0800 CST

使用 Hilt 时如何修复“无法创建 ViewModel 类的实例”?

  • 6

我正在参加 JetPack Compose 课程,并尝试运行一个示例项目,展示 ViewModel 与 Hilt 的结合使用。

@AndroidEntryPoint
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()

        setContent {
            Surface(color = MaterialTheme.colorScheme.background) {
                val noteViewModel: NoteViewModel = hiltViewModel<NoteViewModel>()
                // NoteApp(noteViewModel)
            }
        }
    }
}

为了初始化 ViewModel 我也尝试过

 noteViewModel by viewModels()

和

 noteViewModel = hiltViewModel()

ViewModel代码如下:

@HiltViewModel
class NoteViewModel @Inject constructor(private val repository: NoteRepository) : ViewModel() {
    //private var noteList = mutableStateListOf<Note>()

    private val _noteList = MutableStateFlow<List<Note>>(emptyList())
    val noteList = _noteList.asStateFlow()

    init {
        //noteList.addAll(NotesDataSource.loadDataNotes())
        viewModelScope.launch(Dispatchers.IO) {
            repository.getAllNotes().distinctUntilChanged().collect { listOfNotes ->
                if (listOfNotes.isEmpty()) {
                    Log.d("JetNote", "EmptyList")
                } else {
                    _noteList.value = listOfNotes
                }
            }
        }
    }

    fun addNote(note: Note) = viewModelScope.launch {
        repository.addNote(note)
    }

    fun updateNote(note: Note) = viewModelScope.launch {
        repository.updateNote(note)
    }

    fun removeNote(note: Note) = viewModelScope.launch {
        repository.deleteNote(note)
    }
}

Hilt 的 AppModule 设置如下:

@InstallIn(SingletonComponent::class)
@Module
object AppModule {

    @Singleton
    @Provides
    fun provideNotesDao(noteDatabase: NoteDatabase) : NoteDatabaseDao = noteDatabase.noteDao()

    @Singleton
    @Provides
    fun provideAppDatabase(@ApplicationContext context: Context) : NoteDatabase =
        Room.databaseBuilder(
            context,
            NoteDatabase::class.java,
            "notes_db"
        ).fallbackToDestructiveMigration().build()
}

注释存储库的代码:

class NoteRepository @Inject constructor(private val noteDatabaseDao: NoteDatabaseDao) {
    suspend fun addNote(note: Note) = noteDatabaseDao.insert(note)
    suspend fun updateNote(note: Note) = noteDatabaseDao.update(note)
    suspend fun deleteNote(note: Note) = noteDatabaseDao.deleteNote(note)
    suspend fun deleteAllNotes() = noteDatabaseDao.deleteAll()
    fun getAllNotes(): Flow<List<Note>> = noteDatabaseDao.getNotes().flowOn(Dispatchers.IO).conflate()
}

运行该应用程序时我收到的错误是:

java.lang.RuntimeException: Cannot create an instance of class com.course.jetnote.screens.NoteViewModel
........................
Caused by: java.lang.NoSuchMethodException: com.course.jetnote.screens.NoteViewModel.<init> []

这是我的 Gradle 设置:

构建.gradle.kts:

plugins {
    alias(libs.plugins.android.application)
    alias(libs.plugins.kotlin.android)
    alias(libs.plugins.kotlin.compose)
}

android {
    namespace = "com.course.jetnote"
    compileSdk = 35

    defaultConfig {
        applicationId = "com.course.jetnote"
        minSdk = 26
        targetSdk = 35
        versionCode = 1
        versionName = "1.0"

        testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            isMinifyEnabled = false
            proguardFiles(
                getDefaultProguardFile("proguard-android-optimize.txt"),
                "proguard-rules.pro"
            )
        }
    }
    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_11
        targetCompatibility = JavaVersion.VERSION_11
    }
    kotlinOptions {
        jvmTarget = "11"
    }
    buildFeatures {
        compose = true
    }

    packaging {
        resources {
            excludes += "/META-INF/gradle/incremental.annotation.processors"
            excludes += "META-INF/androidx/room/room-compiler-processing/LICENSE.txt"
        }
    }

}

configurations.implementation {
    exclude(group = "org.jetbrains", module = "annotations")
}


dependencies {

    implementation(libs.androidx.core.ktx)
    implementation(libs.androidx.lifecycle.runtime.ktx)
    implementation(libs.androidx.activity.compose)
    implementation(platform(libs.androidx.compose.bom))
    implementation(libs.androidx.ui)
    implementation(libs.androidx.ui.graphics)
    implementation(libs.androidx.ui.tooling.preview)
    implementation(libs.androidx.material3)
    implementation(libs.androidx.lifecycle.viewModelCompose)
    implementation(libs.hilt.android)
    implementation(libs.hilt.compiler)
    implementation(libs.androidx.hilt.navigation.compose)
    implementation(libs.room.ktx)
    implementation(libs.room.runtime)
    implementation(libs.room.compiler)
    implementation(libs.kotlinx.coroutines.android)
    implementation(libs.androidx.room.runtime.android)

    testImplementation(libs.junit)
    androidTestImplementation(libs.androidx.junit)
    androidTestImplementation(libs.androidx.espresso.core)
    androidTestImplementation(platform(libs.androidx.compose.bom))
    androidTestImplementation(libs.androidx.ui.test.junit4)
    debugImplementation(libs.androidx.ui.tooling)
    debugImplementation(libs.androidx.ui.test.manifest)
}

lib.versions.toml:

[versions]
agp = "8.8.2"
kotlin = "2.0.0"
coreKtx = "1.15.0"
junit = "4.13.2"
junitVersion = "1.2.1"
espressoCore = "3.6.1"
lifecycleRuntimeKtx = "2.8.7"
activityCompose = "1.10.1"
composeBom = "2024.04.01"
androidxLifecycle = "2.8.7"

androidxHiltNavigationCompose = "1.0.0"
hilt = "2.56.2"
hiltExt = "1.0.0"

room = "2.6.0"

kotlinxCoroutines = "1.10.0"
kotlinxDatetime = "0.6.0"
kotlinxSerializationJson = "1.8.0"
roomRuntimeAndroid = "2.7.1"

[libraries]
 androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }
 junit = { group = "junit", name = "junit", version.ref = "junit" }
 androidx-junit = { group = "androidx.test.ext", name = "junit", version.ref = "junitVersion" }
 androidx-espresso-core = { group = "androidx.test.espresso", name = "espresso-core", version.ref = "espressoCore" }
 androidx-lifecycle-runtime-ktx = { group = "androidx.lifecycle", name = "lifecycle-runtime-ktx", version.ref = "lifecycleRuntimeKtx" }
 androidx-activity-compose = { group = "androidx.activity", name = "activity-compose", version.ref = "activityCompose" }
 androidx-compose-bom = { group = "androidx.compose", name = "compose-bom", version.ref = "composeBom" }
 androidx-ui = { group = "androidx.compose.ui", name = "ui" }
 androidx-ui-graphics = { group = "androidx.compose.ui", name = "ui-graphics" }
 androidx-ui-tooling = { group = "androidx.compose.ui", name = "ui-tooling" }
 androidx-ui-tooling-preview = { group = "androidx.compose.ui", name = "ui-tooling-preview" }
 androidx-ui-test-manifest = { group = "androidx.compose.ui", name = "ui-test-manifest" }
 androidx-ui-test-junit4 = { group = "androidx.compose.ui", name = "ui-test-junit4" }
 androidx-material3 = { group = "androidx.compose.material3", name = "material3" }
 androidx-lifecycle-viewModelCompose = { group = "androidx.lifecycle", name = "lifecycle-viewmodel-compose", version.ref = "androidxLifecycle" }


hilt-android = { group = "com.google.dagger", name = "hilt-android", version.ref = "hilt" }
hilt-compiler = { group = "com.google.dagger", name = "hilt-android-compiler", version.ref = "hilt" }
hilt-ext-compiler = { group = "androidx.hilt", name = "hilt-compiler", version.ref = "hiltExt" }
androidx-hilt-navigation-compose = { group = "androidx.hilt", name = "hilt-navigation-compose", version.ref = "androidxHiltNavigationCompose" }



#Database
room-runtime = { group = "androidx.room", name = "room-runtime", version.ref = "room" }
room-ktx = { group = "androidx.room", name = "room-ktx", version.ref = "room" }
room-compiler = { group = "androidx.room", name = "room-compiler", version.ref = "room" }

#Kotlin Coroutines, serialization, datetime...
kotlinx-coroutines-android = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-android", version.ref = "kotlinxCoroutines" }
kotlinx-datetime = { group = "org.jetbrains.kotlinx", name = "kotlinx-datetime", version.ref = "kotlinxDatetime" }
kotlinx-serialization-json = { group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-json", version.ref = "kotlinxSerializationJson" }
androidx-room-runtime-android = { group = "androidx.room", name = "room-runtime-android", version.ref = "roomRuntimeAndroid" }

[plugins]
android-application = { id = "com.android.application", version.ref = "agp" }
kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" }
kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
  • 1 个回答
  • 64 Views
Martin Hope
Toby Speight
Asked: 2025-04-27 22:48:56 +0800 CST

为什么我的转换范围没有有效的迭代器?

  • 7

我想要查看输入流中的字符:

    auto input = std::stringstream{"abcd"};
    using Iter = std::istreambuf_iterator<char>;
    auto s = std::ranges::subrange{Iter{input}, Iter{}};

到目前为止一切顺利。现在,我转换该视图(为了简单起见,使用身份转换):

    auto t = s | std::views::transform(std::identity{});

尽管这个转换后的观点是有效的value_type(即这个断言通过了):

    using T = decltype(t);
    static_assert(std::is_same_v<char, std::ranges::range_value_t<T>>);

它的迭代器类型没有:

    static_assert(std::is_same_v<char, std::iterator_traits<std::ranges::iterator_t<T>>::value_type>);

这失败了

view.cc: In function 'int main()':
view.cc:27:90: error: 'value_type' is not a member of 'std::iterator_traits<std::ranges::transform_view<std::ranges::subrange<std::istreambuf_iterator<char, std::char_traits<char> >, std::istreambuf_iterator<char, std::char_traits<char> >, std::ranges::subrange_kind::unsized>, std::identity>::_Iterator<false> >'
   27 |     static_assert(std::is_same_v<char, std::iterator_traits<std::ranges::iterator_t<T>>::value_type>);
      |                                                                                          ^~~~~~~~~~
view.cc:27:100: error: template argument 2 is invalid
   27 |     static_assert(std::is_same_v<char, std::iterator_traits<std::ranges::iterator_t<T>>::value_type>);
      |                   

它对我很重要的原因是我想在下游视图适配器中使用迭代器特征。


调查表明,Transform 视图的迭代器缺少其iterator_category成员。当我传递一个功能更强大的范围(例如,传递给 Transform 的范围)时,代码会成功,std::string但传递这个非前向范围时会失败。


完整代码(也在Compiler Explorer 上):

#include <functional>
#include <iterator>
#include <ranges>
#include <sstream>
#include <string>
#include <type_traits>

int main()
{
#ifdef PASS
    auto input = std::string{"abcd"};
    std::ranges::forward_range auto s = std::ranges::subrange(input.begin(), input.end());
#else
    auto input = std::stringstream{"abcd"};
    using Iter = std::istreambuf_iterator<char>;
    std::ranges::input_range auto s = std::ranges::subrange{Iter{input}, Iter{}};
#endif

    using S = decltype(s);
    static_assert(std::is_same_v<char, std::ranges::range_value_t<S>>);
    static_assert(std::is_same_v<char, std::iterator_traits<std::ranges::iterator_t<S>>::value_type>);

    auto t = s | std::views::transform(std::identity{});
    using T = decltype(t);
    static_assert(std::is_same_v<char, std::ranges::range_value_t<T>>);
    static_assert(std::is_same_v<char, std::ranges::iterator_t<T>::value_type>);
    static_assert(std::is_base_of_v<std::input_iterator_tag, std::ranges::iterator_t<T>::iterator_category>);
    static_assert(std::is_same_v<char, std::iterator_traits<std::ranges::iterator_t<T>>::value_type>);
}
c++
  • 1 个回答
  • 63 Views
Martin Hope
theKMan747
Asked: 2025-04-27 22:22:09 +0800 CST

有没有办法确定某个类型是否未定义?

  • 7

我有一个Type_##type依赖于某个宏 type_create 的类型:

#define type_create(type) { \
    typedef struct { \
        type* ptr, \
    } Type_##type; \

我有一些依赖它的宏。现在我想知道我是否可以#ifndef针对某个类型执行类似操作,例如,

#ifndef Type_int
type_create(int);
#endif

除类型外。

c
  • 1 个回答
  • 50 Views
Martin Hope
tcgconsolee
Asked: 2025-04-27 21:46:04 +0800 CST

为什么 Flask SQLAlchemy 会给我一个错误“没有这样的表:用户”

  • 7
import os
from flask import Flask, render_template, redirect, url_for, request
from flask_login import LoginManager, UserMixin, login_user, current_user, logout_user
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///db.sqlite"
db = SQLAlchemy()
 
login_manager = LoginManager(app)

class Users(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(250), unique=True,
                         nullable=False)
    password = db.Column(db.String(250),
                         nullable=False)
    location = db.Column(db.String(250),
                         nullable=False)
 
db.init_app(app)
app.app_context().push()
with app.app_context():
    db.create_all()



@login_manager.user_loader
def loader_user(user_id):
    return Users.query.get(user_id)

@app.route('/register', methods=["GET", "POST"])
def register():

    if request.method == "POST":
        if not db.session.query(Users).filter_by(username=request.form.get("uname")).count() < 1:
            return render_template("sign_up.html", value = "USER ALREADY EXISTS")
        if request.form.get("uname") == "":
            return render_template("sign_up.html", value = "USERNAME IS BLANK")
        if request.form.get("psw") == "":
            return render_template("sign_up.html", value = "PASSWORD IS BLANK")
        if request.form.get("loc") == "":
            return render_template("sign_up.html", value = "LOCATION IS BLANK")
        user = Users(username=request.form.get("uname"),
                     password=request.form.get("psw"),
                     location=request.form.get("loc"))
    
        db.session.add(user)    
        db.session.commit()
    
    
        return redirect(url_for("login"))

    return render_template("sign_up.html", value ="")


@app.route("/login", methods=["GET", "POST"])
def login():
    if current_user.is_authenticated:
        return redirect(url_for("index", logged_in = True, username = current_user.username))


    if request.method == "POST":
        user = Users.query.filter_by(
            username=request.form.get("uname")).first()
        if not user:
            return render_template("login.html", value = request.form.get("uname"))
    
    
        if user.password == request.form.get("psw"):
            login_user(user)
            return redirect(url_for("index", logged_in = True, username = user.username))
    return render_template("login.html")

if __name__ == "__main__":
    app.secret_key = 'kevin2000'
    app.config['SESSION_TYPE'] = 'filesystem'
    app.run(host ="0.0.0.0", port = 10000, debug=False)

这是我的代码,这里我收到这个错误

Traceback (most recent call last):
  File "C:\Users\theco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\sqlalchemy\engine\base.py", line 1964, in _exec_single_context
    self.dialect.do_execute(
  File "C:\Users\theco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\sqlalchemy\engine\default.py", line 945, in do_execute
    cursor.execute(statement, parameters)
sqlite3.OperationalError: no such table: users

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\theco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\flask\app.py", line 1511, in wsgi_app
    response = self.full_dispatch_request()
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\theco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\flask\app.py", line 919, in full_dispatch_request
    rv = self.handle_user_exception(e)
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\theco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\flask\app.py", line 917, in full_dispatch_request
    rv = self.dispatch_request()
         ^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\theco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\flask\app.py", line 902, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)  # type: ignore[no-any-return]
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "c:\Users\theco\OneDrive\Documents\veil\app.py", line 41, in register
    if not db.session.query(Users).filter_by(username=request.form.get("uname")).count() < 1:
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\theco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\sqlalchemy\orm\query.py", line 3147, in count
    self._legacy_from_self(col).enable_eagerloads(False).scalar()
  File "C:\Users\theco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\sqlalchemy\orm\query.py", line 2836, in scalar
    ret = self.one()
          ^^^^^^^^^^
  File "C:\Users\theco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\sqlalchemy\orm\query.py", line 2809, in one
    return self._iter().one()  # type: ignore
           ^^^^^^^^^^^^
  File "C:\Users\theco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\sqlalchemy\orm\query.py", line 2858, in _iter
    result: Union[ScalarResult[_T], Result[_T]] = self.session.execute(
                                                  ^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\theco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\sqlalchemy\orm\session.py", line 2365, in execute
    return self._execute_internal(
           ^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\theco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\sqlalchemy\orm\session.py", line 2251, in _execute_internal
    result: Result[Any] = compile_state_cls.orm_execute_statement(
                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\theco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\sqlalchemy\orm\context.py", line 306, in orm_execute_statement
    result = conn.execute(
             ^^^^^^^^^^^^^
  File "C:\Users\theco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\sqlalchemy\engine\base.py", line 1416, in execute
    return meth(
           ^^^^^
  File "C:\Users\theco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\sqlalchemy\sql\elements.py", line 523, in _execute_on_connection
    return connection._execute_clauseelement(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\theco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\sqlalchemy\engine\base.py", line 1638, in _execute_clauseelement
    ret = self._execute_context(
          ^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\theco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\sqlalchemy\engine\base.py", line 1843, in _execute_context
    return self._exec_single_context(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\theco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\sqlalchemy\engine\base.py", line 1983, in _exec_single_context
    self._handle_dbapi_exception(
  File "C:\Users\theco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\sqlalchemy\engine\base.py", line 2352, in _handle_dbapi_exception
    raise sqlalchemy_exception.with_traceback(exc_info[2]) from e
  File "C:\Users\theco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\sqlalchemy\engine\base.py", line 1964, in _exec_single_context
    self.dialect.do_execute(
  File "C:\Users\theco\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\sqlalchemy\engine\default.py", line 945, in do_execute
    cursor.execute(statement, parameters)
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: users
[SQL: SELECT count(*) AS count_1 
FROM (SELECT users.id AS users_id, users.username AS users_username, users.password AS users_password, users.location AS users_location 
FROM users 
WHERE users.username = ?) AS anon_1]
[parameters: ('xdgsdg',)]
(Background on this error at: https://sqlalche.me/e/20/e3q8)

我已经在其他地方搜索过了,但只是说 db.create_all() 不存在,我对 Flask 也还不熟悉,所以请有人帮忙

我也尝试了 db.drop_all() 然后 db.create_all()

这似乎也不起作用

如果有帮助的话,我还可以提供提交表单时发生错误的 sign_up.html

python
  • 1 个回答
  • 32 Views
Martin Hope
mafesm
Asked: 2025-04-27 21:27:26 +0800 CST

使用 bison 构建语法树 ($ ref issue)

  • 7

我正在进行一个项目,需要构建一个完整的 C 语言编译器。我一直在寻找这方面的资料,但什么也没找到。

我有一段关于函数声明的语法规则:

fun_declaracao:
    tipo_especificador ID APR { 
        // Start of semantic action after parsing the return type (tipo_especificador), 
        // the function name (ID), and the opening parenthesis (APR).

        // Initialize function type as "erro" to detect issues later.
        char* tipo_fun = "erro";

        // Set the current function and scope to the function name.
        // These are likely used elsewhere to keep track of context during parsing.
        funcao_at = $2;
        escopo_at = $2;

        // Check if this function name is already declared in the global scope.
        if (busca(T, tm_tab, $2, "global") != -1) {
            // If found, report a semantic error: function already declared.
            erro_semantico("Funcao ja declarada", $2, yylineno);
        } else {
            // If not found, insert this new function into the symbol table.
            // Parameters: symbol table T, temporary table tm_tab,
            // function name $2, symbol kind "func", return type $1, line number, scope "global".
            add(&T, &tm_tab, $2, "func", $1, yylineno, "global");

            // Mark the identifier as valid for future reference.
            tipo_fun = "id"; 
        }
    } params FPR composto_declaracao {
        // This is the second semantic action, after the full function header and body have been parsed:
        // - params: the parameter list
        // - FPR: closing parenthesis
        // - composto_declaracao: the function body block

        // Build a syntax tree node representing the whole function declaration.
        // It includes 4 children: return type, function name, parameters, and body.
        $$ = novo("fun_declaracao", NULL, 4, 
                  novo($1, $1, 0),     // Return type node
                  novo($2, tipo_fun, 0), // Function name node with type info
                  $4,                 // Parameters node
                  $6);                // Function body node

        // After building the function, reset context to global (we're outside the function now).
        escopo_at = "global";
        funcao_at = NULL;
    }
;

因此,当我运行它时,出现以下错误:

bison -d parser.y
parser.y:124.86-87: $4 of `fun_declaracao' has no declared type
parser.y:124.90-91: $6 of `fun_declaracao' has no declared type
makefile:13: recipe for target 'parser.tab.c' failed
make: *** [parser.tab.c] Error 1

我认为这是一个愚蠢的问题,可能我只是不理解 bison 语法。

这是我的 %type 声明:

%union {
    char *string;
    NO *no;
    char *tipo; 
}

%token <string> ID
%token <string> NUM 

%token  INT VOID WHILE RETURN PEV VIR ERRO

%type <tipo> tipo_especificador

%type <no> expressao var simples_expressao soma_expressao termo fator 
%type <no> programa declaracao_lista declaracao var_declaracao fun_declaracao 
%type <no> params param_lista param composto_declaracao 
%type <no> local_declaracoes statement_lista statement expressao_declaracao selecao_declaracao iteracao_declaracao 
%type <no> retorno_declaracao args arg_lista relacional
c
  • 1 个回答
  • 37 Views
Martin Hope
OopsUser
Asked: 2025-04-27 21:24:35 +0800 CST

为什么分支(未命中)预测不会影响性能(C++)?

  • 7

在尝试衡量分支未命中预测的影响时,我注意到分支未命中预测根本没有任何惩罚。

根据著名的堆栈溢出问题: 为什么处理排序数组比处理未排序数组更快?

我写了一段简单的代码来测量分支预测的惩罚。

  • 用随机数填充数组
  • 计算 5 以上的数字(应该有很多预测错误) - 测量它
  • 对数组进行排序
  • 计算 5 以上的数字(应该很少有预测失误)——测量它

运行代码后,我得到了两次测量几乎相同的结果。

已测试:

  1. Visual Studio 2017,发布(最大优化(优先速度)(/O2)),Windows。
  2. Linux,g++-Ofast

然后,我取出了上面链接的问题中的原始代码,排序后的数组仍然没有任何改进。这是为什么呢?分支预测的好处又在哪里呢?

#include <iostream>
#include <vector>
#include <algorithm>
#include <random>
#include <chrono>

int main()
{
    // Step 1: Allocate a vector of size 1 million
    std::vector<int> vec(100'000'000);

    // Step 2: Fill it with random numbers between 0 and 10
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> dis(0, 10);

    for (auto& val : vec)
    {
        val = dis(gen);
    }

    // Step 3: Count numbers above 5 (and measure time)
    auto start = std::chrono::high_resolution_clock::now();
    int count_above_5 = 0;
    for (size_t i = 0; i < vec.size(); i++)
    {
        if (vec[i] < 5)
        {
            ++count_above_5;
        }
    }

    auto end = std::chrono::high_resolution_clock::now();

    auto duration_before_sort = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count();

    std::cout << "Count of numbers above 5 (before sorting): " << count_above_5 << std::endl;
    std::cout << "Time taken (before sorting): " << duration_before_sort << " ns" << std::endl;

    // Step 4: Sort the array
    std::sort(vec.begin(), vec.end());

    // Step 5: Count numbers above 5 in the sorted array (and measure time)

    start = std::chrono::high_resolution_clock::now();
    count_above_5 = 0;
    for (size_t i = 0; i < vec.size(); i++)
    {
        if (vec[i] < 5)
        {
            ++count_above_5;
        }
    }
    end = std::chrono::high_resolution_clock::now();


    auto duration_after_sort = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count();

    std::cout << "Count of numbers above 5 (after sorting): " << count_above_5 << std::endl;
    std::cout << "Time taken (after sorting):  " << duration_after_sort << " ns" << std::endl;

    return 0;
}
c++
  • 1 个回答
  • 78 Views
Martin Hope
gal kar
Asked: 2025-04-27 21:18:48 +0800 CST

如何对动态日志文件名使用策略?

  • 5

我正在使用 Log4j2,并且我需要我的日志:

  1. 在活动日志文件名中包含当前日期和进程 ID(例如,logname.529628.27-04-2025.log)
  2. 根据文件大小创建新日志(例如,每 10MB)
  3. 仅保留最大数量的旧文件(例如 10 个备份)

这就是我现在所拥有的:

<?xml version="1.0" encoding="UTF-8"?>
<Properties>
    <Property name="LOG_PATTERN">
        %-40.40c{1.} : %notEmpty{%m}%n%ex
    </Property>
    <Property name="PID">${sys:PID}</Property>
    <Property name="FS">${sys:file.separator}</Property>
    <Property name="log-path">log${sys:file.separator}</Property>
    <Property name="log-pattern">%d{yyyy-MM-dd HH:mm:ss,SSS} PID:${sys:PID} %-2p [T@%tid-%t] [%F:%L] %notEmpty{%marker} %m%n</Property>
</Properties>

<Appenders>
    <Routing name="Routing">
        <Routes pattern="$${sys:logName}">
            <Route key="testlog">
                <RollingFile name="ArchiveLog" fileName="${log-path}logname.${sys:PID}.${date:dd-MM-yyyy}.log"
                             filePattern="${log-path}logname.${sys:PID}.${date:dd-MM-yyyy}.%i.log">
                    <PatternLayout pattern="${log-pattern}"/>
                    <Policies>
                        <SizeBasedTriggeringPolicy size="10MB"/>
                    </Policies>
                    <DefaultRolloverStrategy max="10">
                    </DefaultRolloverStrategy>
                </RollingFile>
            </Route>
        </Routes>
    </Routing>
</Appenders>

<Loggers>
    <Logger name="logname" level="trace" additivity="false">
        <AppenderRef ref="Routing" />
    </Logger>
    <Root level="info">
        <AppenderRef ref="Routing"/>
    </Root>
</Loggers>

但似乎按大小旋转对于动态文件名无法正常工作。有什么想法吗?

谢谢!

java
  • 1 个回答
  • 34 Views
Martin Hope
Harry
Asked: 2025-04-27 20:55:26 +0800 CST

在 shell 脚本终止时调用一个函数(清理处理程序)

  • 5

是否可以在shell脚本终止时调用一个函数?我有一些守护进程在后台运行,它们的进程ID存储在一个数组中。我希望在脚本终止时(无论出于何种原因)调用一个清理函数/处理程序来终止所有守护进程。

# want the below function to be called when the shell script terminates for whatsoever reason
purge () {
  for pid in ${pids[@]}; do
    kill -9 $pid
  done
}

./daemon1 > a.txt 2>&1 & pids+=($!)
./daemon2 > b.txt 2>&1 & pids+=($!)
./daemon3 > c.txt 2>&1 & pids+=($!)

for pid in ${pids[@]}; do
  echo "process: $pid"
done
linux
  • 1 个回答
  • 47 Views
上一页
下一页

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    重新格式化数字,在固定位置插入分隔符

    • 6 个回答
  • Marko Smith

    为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会?

    • 2 个回答
  • Marko Smith

    VScode 自动卸载扩展的问题(Material 主题)

    • 2 个回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Martin Hope
    Fantastic Mr Fox msvc std::vector 实现中仅不接受可复制类型 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant 使用 chrono 查找下一个工作日 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor 构造函数的成员初始化程序可以包含另一个成员的初始化吗? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský 为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul C++20 是否进行了更改,允许从已知绑定数组“type(&)[N]”转换为未知绑定数组“type(&)[]”? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann 为什么 {2,3,10} 和 {x,3,10} (x=2) 的顺序不同? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

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

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve