问:
How to update time value for a unique constraint in TimescaleDB without making duplicate rows?
I want to have rows in my table with unique domains (ex: google.com) with a time associated with each domain.

The domains should be unique, and I want to update the time value when I start processing a domain. I can't figure out how to Upsert/(insert/update) a time value for a unique domain however using TimescaleDB.

EX: I don’t want duplicate rows for ‘google.com’ in my table, which seems impossible since time is also a unique constraint.
Is there a way to get around this?

Ideally I want my rows to look like:

```<code>google.com - <time>
cnn.com - <time>
and NOT
google.com - <time 1>
google.com - <time 2>
cnn.com - <time 1>

</code>```
```<code>
Here’s my schema:
CREATE TABLE
  domain_rechecks (
    domain VARCHAR NOT NULL,
    requeue_at TIMESTAMP NOT NULL,
    requeued_at TIMESTAMP,
    UNIQUE(domain, requeue_at)
  );
SELECT
  create_hypertable (‘domain__rechecks’, ‘requeue_at’);

</code>```

Is there any way to do this using timescaledb? Or do I need to look for a different solution? Thanks!

Body:
I want to have rows in my table with unique domains (ex: google.com) with a time associated with each domain.

The domains should be unique, and I want to update the time value when I start processing a domain. I can't figure out how to Upsert/(insert/update) a time value for a unique domain however using TimescaleDB.

EX: I don’t want duplicate rows for ‘google.com’ in my table, which seems impossible since time is also a unique constraint.
Is there a way to get around this?

Ideally I want my rows to look like:

google.com - <time>
cnn.com - <time>
and NOT
google.com - <time 1>
google.com - <time 2>
cnn.com - <time 1>

Here’s my schema:
CREATE TABLE
  domain_rechecks (
    domain VARCHAR NOT NULL,
    requeue_at TIMESTAMP NOT NULL,
    requeued_at TIMESTAMP,
    UNIQUE(domain, requeue_at)
  );
SELECT
  create_hypertable (‘domain__rechecks’, ‘requeue_at’);

Is there any way to do this using timescaledb? Or do I need to look for a different solution? Thanks!


来源: stackexchange

问:
How to configure DB in a Flask app dynamicly?
I'm working on app, where user have to enter database connection parametrs by hands

So I've made an api here it is:

```<code>from flask_mysqldb import MySQL
from flask import Flask, request
import MySQLdb.cursors

app = Flask(__name__)

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

    return "Hello word"

# /get_tables
@app.route(f"/get_tables", methods=['GET'])
def get_tables():

    host = request.args.get('host', type=str)
    user = request.args.get('user', type=str)
    password = request.args.get('password', type=str)
    database = request.args.get('database', type=str)

    app.config['MYSQL_HOST'] = "localhost"
    app.config['MYSQL_USER'] = "root"
    app.config['MYSQL_PASSWORD'] = "password"
    app.config['MYSQL_DB'] = "restaurant"

    mysql = MySQL(app)

    cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    query = "SHOW TABLES"
    cursor.execute(query)
    records = cursor.fetchone()
    print(records)
    return records

</code>```

"hello" endpoint is working fine, but when run "get_tables" I recieve an error:

AssertionError: The setup method 'teardown_appcontext' can no longer be called on the application. It has already handled its first request, any changes will not be applied consistently. Make sure all imports, decorators, functions, etc. needed to set up the application are done before running it.

I also was trying to debug my api and found out that errorr ocures on a  mysql = MySQL(app) line

What can I do to solve this problem? or maybe it's better not to use api at all and just connect to DB from ui?

ContentLicense: CC BY-SA 4.0

Body:
I'm working on app, where user have to enter database connection parametrs by hands

So I've made an api here it is:

from flask_mysqldb import MySQL
from flask import Flask, request
import MySQLdb.cursors

app = Flask(__name__)

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

    return "Hello word"

# /get_tables
@app.route(f"/get_tables", methods=['GET'])
def get_tables():

    host = request.args.get('host', type=str)
    user = request.args.get('user', type=str)
    password = request.args.get('password', type=str)
    database = request.args.get('database', type=str)

    app.config['MYSQL_HOST'] = "localhost"
    app.config['MYSQL_USER'] = "root"
    app.config['MYSQL_PASSWORD'] = "password"
    app.config['MYSQL_DB'] = "restaurant"

    mysql = MySQL(app)

    cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    query = "SHOW TABLES"
    cursor.execute(query)
    records = cursor.fetchone()
    print(records)
    return records

"hello" endpoint is working fine, but when run "get_tables" I recieve an error:

AssertionError: The setup method 'teardown_appcontext' can no longer be called on the application. It has already handled its first request, any changes will not be applied consistently. Make sure all imports, decorators, functions, etc. needed to set up the application are done before running it.

I also was trying to debug my api and found out that errorr ocures on a  mysql = MySQL(app) line

What can I do to solve this problem? or maybe it's better not to use api at all and just connect to DB from ui?


问:
Android Studio ImageView and Bitmap
An activity has an icon to choose Image from Files.  After choosing the Image, The next activity page opens which has A button and an ImageView where the selected iimage should be displayed.

I can choose the Image but it does not show on ImageView.
I has tried Bitmap and it doesnt work. If I try to resize map and then run app, after choosing the image the app closes.

Below is the XML and Java of the activity

```<code>
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ShowPhotoActivity">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="196dp"
        android:layout_height="219dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.414"
        tools:srcCompat="@tools:sample/avatars" />

    <Button
        android:id="@+id/btnEdit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="EDIT PHOTO"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.773" />
</androidx.constraintlayout.widget.ConstraintLayout>

//Java of the Activity.

package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;

import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.util.Base64;
import android.widget.ImageView;
import java.io.File;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.net.Uri;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.io.File;

public class ShowPhotoActivity extends AppCompatActivity {
    ImageView myImage;
    Button btnEdit;
    String path = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_photo);
        myImage = (ImageView) findViewById(R.id.imageView);
        btnEdit = findViewById(R.id.btnEdit);
        path = getIntent().getExtras().getString("path");
        File imgFile = new File(path);
        if (imgFile.exists()) {
            Bitmap b = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
          //myImage.setImageBitmap(Bitmap.createScaledBitmap(b, 40, 40, false));

          myImage.setImageBitmap(b);

            btnEdit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(ShowPhotoActivity.this, EditPhotoActivity.class);
                    intent.putExtra("path", path);
                    startActivity(intent);
                }
            });
       }
    }

    public static Bitmap RotateBitmat(Bitmap source, float angle) {
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        return  Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
    }
}
</code>```

I need the selected Image to be shown in the ImageView and when I click the Edit button the Image should be passed to the next activity too.

Title: Android Studio ImageView and Bitmap

Body:
An activity has an icon to choose Image from Files.  After choosing the Image, The next activity page opens which has A button and an ImageView where the selected iimage should be displayed.

I can choose the Image but it does not show on ImageView.
I has tried Bitmap and it doesnt work. If I try to resize map and then run app, after choosing the image the app closes.

Below is the XML and Java of the activity

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ShowPhotoActivity">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="196dp"
        android:layout_height="219dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.414"
        tools:srcCompat="@tools:sample/avatars" />

    <Button
        android:id="@+id/btnEdit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="EDIT PHOTO"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.773" />
</androidx.constraintlayout.widget.ConstraintLayout>

//Java of the Activity.

package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;

import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.util.Base64;
import android.widget.ImageView;
import java.io.File;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.net.Uri;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.io.File;

public class ShowPhotoActivity extends AppCompatActivity {
    ImageView myImage;
    Button btnEdit;
    String path = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_photo);
        myImage = (ImageView) findViewById(R.id.imageView);
        btnEdit = findViewById(R.id.btnEdit);
        path = getIntent().getExtras().getString("path");
        File imgFile = new File(path);
        if (imgFile.exists()) {
            Bitmap b = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
          //myImage.setImageBitmap(Bitmap.createScaledBitmap(b, 40, 40, false));

          myImage.setImageBitmap(b);

            btnEdit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(ShowPhotoActivity.this, EditPhotoActivity.class);
                    intent.putExtra("path", path);
                    startActivity(intent);
                }
            });
       }
    }

    public static Bitmap RotateBitmat(Bitmap source, float angle) {
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        return  Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
    }
}

I need the selected Image to be shown in the ImageView and when I click the Edit button the Image should be passed to the next activity too.


问:
Error using Apache Ratis on android (files found with path 'javac.sh' from inputs)
I am trying to use Apache Ratis in my Android project(API 10). The dependency is setup as below and Gradle sync is fine as well.

```<code>implementation group: 'org.apache.ratis', name: 'ratis-server', version: '2.4.1'
implementation group: 'org.apache.ratis', name: 'ratis-grpc', version: '2.4.1'
</code>```

But, when I try to launch the app, the build fails with the below error. My googling didn't get me any solution. I am not sure what is the problem here and how to move on. Please help.

```<code>* What went wrong:
Execution failed for task ':app:mergeDebugJavaResource'.
> A failure occurred while executing com.android.build.gradle.internal.tasks.MergeJavaResWorkAction
   > 7 files found with path 'javac.sh' from inputs:
      - /Users/xxxxx/.gradle/caches/modules-2/files-2.1/org.apache.ratis/ratis-server/2.4.1/677eb97c26bcb5639b3ab5591bef4dc0d65494c2/ratis-server-2.4.1.jar
      - /Users/xxxxx/.gradle/caches/modules-2/files-2.1/org.apache.ratis/ratis-grpc/2.4.1/541c54e9a79f572933e2f1c383b2b64ac98b2d22/ratis-grpc-2.4.1.jar
      - /Users/xxxxx/.gradle/caches/modules-2/files-2.1/org.apache.ratis/ratis-server-api/2.4.1/e574ea1812f1edc7d0343531f4e664bb6902c37c/ratis-server-api-2.4.1.jar
      - /Users/xxxxx/.gradle/caches/modules-2/files-2.1/org.apache.ratis/ratis-client/2.4.1/6d573ec31e8747d55f4f2e0ec95169a319d1cece/ratis-client-2.4.1.jar
      - /Users/xxxxx/.gradle/caches/modules-2/files-2.1/org.apache.ratis/ratis-metrics/2.4.1/c838c833af481a663c4d4374d518cb233a04ceb4/ratis-metrics-2.4.1.jar
      - /Users/xxxxx/.gradle/caches/modules-2/files-2.1/org.apache.ratis/ratis-common/2.4.1/d43477d05b5d5add38037f3799b7cd353c7d6338/ratis-common-2.4.1.jar
      - /Users/xxxxx/.gradle/caches/modules-2/files-2.1/org.apache.ratis/ratis-proto/2.4.1/3755778d36159ea7218e65da9906b99a065beca1/ratis-proto-2.4.1.jar
     Adding a packagingOptions block may help, please refer to
     https://developer.android.com/reference/tools/gradle-api/7.3/com/android/build/api/dsl/ResourcesPackagingOptions
     for more information

</code>```

Body:
I am trying to use Apache Ratis in my Android project(API 10). The dependency is setup as below and Gradle sync is fine as well.

implementation group: 'org.apache.ratis', name: 'ratis-server', version: '2.4.1'
implementation group: 'org.apache.ratis', name: 'ratis-grpc', version: '2.4.1'

But, when I try to launch the app, the build fails with the below error. My googling didn't get me any solution. I am not sure what is the problem here and how to move on. Please help.

* What went wrong:
Execution failed for task ':app:mergeDebugJavaResource'.
> A failure occurred while executing com.android.build.gradle.internal.tasks.MergeJavaResWorkAction
   > 7 files found with path 'javac.sh' from inputs:
      - /Users/xxxxx/.gradle/caches/modules-2/files-2.1/org.apache.ratis/ratis-server/2.4.1/677eb97c26bcb5639b3ab5591bef4dc0d65494c2/ratis-server-2.4.1.jar
      - /Users/xxxxx/.gradle/caches/modules-2/files-2.1/org.apache.ratis/ratis-grpc/2.4.1/541c54e9a79f572933e2f1c383b2b64ac98b2d22/ratis-grpc-2.4.1.jar
      - /Users/xxxxx/.gradle/caches/modules-2/files-2.1/org.apache.ratis/ratis-server-api/2.4.1/e574ea1812f1edc7d0343531f4e664bb6902c37c/ratis-server-api-2.4.1.jar
      - /Users/xxxxx/.gradle/caches/modules-2/files-2.1/org.apache.ratis/ratis-client/2.4.1/6d573ec31e8747d55f4f2e0ec95169a319d1cece/ratis-client-2.4.1.jar
      - /Users/xxxxx/.gradle/caches/modules-2/files-2.1/org.apache.ratis/ratis-metrics/2.4.1/c838c833af481a663c4d4374d518cb233a04ceb4/ratis-metrics-2.4.1.jar
      - /Users/xxxxx/.gradle/caches/modules-2/files-2.1/org.apache.ratis/ratis-common/2.4.1/d43477d05b5d5add38037f3799b7cd353c7d6338/ratis-common-2.4.1.jar
      - /Users/xxxxx/.gradle/caches/modules-2/files-2.1/org.apache.ratis/ratis-proto/2.4.1/3755778d36159ea7218e65da9906b99a065beca1/ratis-proto-2.4.1.jar
     Adding a packagingOptions block may help, please refer to
     https://developer.android.com/reference/tools/gradle-api/7.3/com/android/build/api/dsl/ResourcesPackagingOptions
     for more information


问:
ValidationError at /admin/projects/project/add/ ['“self” is not a valid UUID.']
Gettin ValidationError at /admin/projects/project/add/
['“self” is not a valid UUID.']

My model.py

```<code>`class Project(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    # company=models.CharField(max_length=100)
    created_by=models.ForeignKey(User, on_delete=models.CASCADE)
    name=models.CharField(max_length=100)`
</code>```
```<code>

#`admin.py`
from django.contrib import admin
from . import models
# Register your models here.
admin.site.register(models.Project)`
</code>```

Body:
Gettin ValidationError at /admin/projects/project/add/
['“self” is not a valid UUID.']

My model.py

`class Project(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    # company=models.CharField(max_length=100)
    created_by=models.ForeignKey(User, on_delete=models.CASCADE)
    name=models.CharField(max_length=100)`

#`admin.py`
from django.contrib import admin
from . import models
# Register your models here.
admin.site.register(models.Project)`


问:
jspdf_autotable__WEBPACK_IMPORTED_MODULE_8__ is not a function
I have been created a library with jsPDF and JS autotable plugin on an Angular 13 app.
It works very well inside the example project that comes with the library.

component.ts

```<code>import jsPDF from 'jspdf';
import autoTable from 'jspdf-autotable';

exportPdf() {
        const doc = new jsPDF(this.pageOrientation, 'pt');
        autoTable(doc, {
            columns: this.exportableColumns,
            body: this.options.data
        });
        doc.save("exported_file.pdf");
    }
</code>```

template.html

```<code><p-button type="button" label="Export" (click)="exportPdf()"></p-button>
</code>```

Now, I'm trying to use the library as a dependency inside another project, but the following message error appear clicking the dependency button pdf generate.

Inside both projects

```<code>@angular/core: "~13.2.0",
jspdf: "^2.5.1",
jspdf-autotable: "^3.5.28"
</code>```

Could someone tell me what's going on? And if possible try to help me?
Thanks in advance!

Body:
I have been created a library with jsPDF and JS autotable plugin on an Angular 13 app.
It works very well inside the example project that comes with the library.

component.ts

import jsPDF from 'jspdf';
import autoTable from 'jspdf-autotable';

exportPdf() {
        const doc = new jsPDF(this.pageOrientation, 'pt');
        autoTable(doc, {
            columns: this.exportableColumns,
            body: this.options.data
        });
        doc.save("exported_file.pdf");
    }

template.html

Now, I'm trying to use the library as a dependency inside another project, but the following message error appear clicking the dependency button pdf generate.

Inside both projects

@angular/core: "~13.2.0",
jspdf: "^2.5.1",
jspdf-autotable: "^3.5.28"

Could someone tell me what's going on? And if possible try to help me?
Thanks in advance!


问:
Flask, SQLAlchemy: object is already attached to session
I'm trying to write an application where a user has to log in and afterwards can enlist for a shift.
The User and Entry classes represent the data model. Login is done via Flask-Login.

The user object is loaded from a database and will be attached to a new created entry. Whenever I try to store the new entry (i.e.

```<code>def insert_entry(day, user, isdayshift, comment):
</code>```

from database is called, i'll get the following error:

sqlalchemy.exc.InvalidRequestError: Object '<User at 0x7ff1ecc5e1d0>' is already attached to session '1' (this is '2')

main.py:

```<code>import locale
import logging
from datetime import date, datetime

import flask
import flask_login
from flask import Flask, render_template, request, flash, redirect, url_for
from flask_login import login_required, login_user, logout_user
from flask_sqlalchemy import SQLAlchemy

from calendartable import createtable, ServiceTable
from database import insert_entry
from database import load_user
from orm import User

logging.basicConfig(level=logging.DEBUG)
locale.setlocale(locale.LC_ALL, 'de_DE.utf8')

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://...'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

app.config.update(LOGIN_DISABLED=True)
app.secret_key = 'very secret key'  # Change this!
database = SQLAlchemy(app)
session = database.session

# prerequisites
d: date = date(day=1, month=11, year=2022)
user = load_user('')

login_manager = flask_login.LoginManager()
login_manager.init_app(app)
login_manager.login_view = "login"

@login_manager.user_loader
def user_loader(user_id):
    u: User = database.load_user(id)
    return u
</code>```

orm.py

```<code>from flask_login import UserMixin
from sqlalchemy import Column, Integer, String, DateTime, Boolean, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func

Base = declarative_base()

class Entry(Base):
    __tablename__ = 'entry'
    id = Column(Integer, primary_key=True)
    day = Column(DateTime(timezone=True), server_default=func.now())
    isdayshift = Column(Boolean, nullable=False, default=True)
    comment = Column(String(100), nullable=False)
    created_at = Column(DateTime(timezone=True), server_default=func.now())

    user_id = Column(Integer, ForeignKey('user.id'))
    user = relationship("User", back_populates="entry", cascade="save-update")

    def __init__(self, day, user, isdayshift, comment):
        self.day = day
        self.user = user
        self.isdayshift = isdayshift
        self.comment = comment

class User(Base, UserMixin):
    __tablename__ = 'user'
    id = Column(Integer, primary_key=True)
    lastname = Column(String(100), nullable=False)
    firstname = Column(String(100), nullable=False)
    email = Column(String(100), nullable=False, unique=True)
    password = Column(String(100), nullable=False)
    is_admin = Column(Boolean, nullable=False, default=False)
    created_at = Column(DateTime(timezone=True), server_default=func.now())

    entry = relationship("Entry", uselist=False, back_populates="user", cascade="merge")

    def __init__(self, lastname, firstname, email, password, is_admin):
        self.lastname = lastname
        self.firstname = firstname
        self.password = password
        self.email = email
        self.is_admin = is_admin

    def isadmin(self):
        return self.admin

    def is_active(self):
        return True

    def get_id(self):
        return self.id

    def is_authenticated(self):
        return True

    def is_anonymous(self):
        return False
</code>```

database.py

```<code>import logging

from sqlalchemy.ext.declarative import declarative_base

import main
from orm import User, Entry

logging.basicConfig(level=logging.DEBUG)

Base = declarative_base()

def load_user_by_id(user_id):
    u: User = main.session.query(User).filter_by(id == user_id).first()
    return u

def load_user(login):
    logging.debug("loading user from session: %s", main.session)
    u: User = main.session.query(User).filter_by(lastname='xxx').first()
    return u

def load_entry(date, isdayshift):
    # e: Entry = session.query(Entry).filter_by(day=date, isdayshift=isdayshift).first()
    return

def insert_entry(day, user, isdayshift, comment):
    logging.debug("storing entry from session: %s", main.session)
    eq1 = Entry(day, user, isdayshift, comment)
    main.session.add(eq1)
    main.session.commit()
</code>```

The session which was used to load the user is the same as the session used for storage.

DEBUG:root:loading user from session: <sqlalchemy.orm.scoping.scoped_session object at 0x7ff1ecd2cbb0>

DEBUG:root:storing entry from session: <sqlalchemy.orm.scoping.scoped_session object at 0x7ff1ecd2cbb0>

Body:
I'm trying to write an application where a user has to log in and afterwards can enlist for a shift.
The User and Entry classes represent the data model. Login is done via Flask-Login.

The user object is loaded from a database and will be attached to a new created entry. Whenever I try to store the new entry (i.e.

def insert_entry(day, user, isdayshift, comment):

from database is called, i'll get the following error:

sqlalchemy.exc.InvalidRequestError: Object '<User at 0x7ff1ecc5e1d0>' is already attached to session '1' (this is '2')

main.py:

import locale
import logging
from datetime import date, datetime

import flask
import flask_login
from flask import Flask, render_template, request, flash, redirect, url_for
from flask_login import login_required, login_user, logout_user
from flask_sqlalchemy import SQLAlchemy

from calendartable import createtable, ServiceTable
from database import insert_entry
from database import load_user
from orm import User

logging.basicConfig(level=logging.DEBUG)
locale.setlocale(locale.LC_ALL, 'de_DE.utf8')

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://...'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

app.config.update(LOGIN_DISABLED=True)
app.secret_key = 'very secret key'  # Change this!
database = SQLAlchemy(app)
session = database.session

# prerequisites
d: date = date(day=1, month=11, year=2022)
user = load_user('')

login_manager = flask_login.LoginManager()
login_manager.init_app(app)
login_manager.login_view = "login"

@login_manager.user_loader
def user_loader(user_id):
    u: User = database.load_user(id)
    return u

orm.py

from flask_login import UserMixin
from sqlalchemy import Column, Integer, String, DateTime, Boolean, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func

Base = declarative_base()

class Entry(Base):
    __tablename__ = 'entry'
    id = Column(Integer, primary_key=True)
    day = Column(DateTime(timezone=True), server_default=func.now())
    isdayshift = Column(Boolean, nullable=False, default=True)
    comment = Column(String(100), nullable=False)
    created_at = Column(DateTime(timezone=True), server_default=func.now())

    user_id = Column(Integer, ForeignKey('user.id'))
    user = relationship("User", back_populates="entry", cascade="save-update")

    def __init__(self, day, user, isdayshift, comment):
        self.day = day
        self.user = user
        self.isdayshift = isdayshift
        self.comment = comment

class User(Base, UserMixin):
    __tablename__ = 'user'
    id = Column(Integer, primary_key=True)
    lastname = Column(String(100), nullable=False)
    firstname = Column(String(100), nullable=False)
    email = Column(String(100), nullable=False, unique=True)
    password = Column(String(100), nullable=False)
    is_admin = Column(Boolean, nullable=False, default=False)
    created_at = Column(DateTime(timezone=True), server_default=func.now())

    entry = relationship("Entry", uselist=False, back_populates="user", cascade="merge")

    def __init__(self, lastname, firstname, email, password, is_admin):
        self.lastname = lastname
        self.firstname = firstname
        self.password = password
        self.email = email
        self.is_admin = is_admin

    def isadmin(self):
        return self.admin

    def is_active(self):
        return True

    def get_id(self):
        return self.id

    def is_authenticated(self):
        return True

    def is_anonymous(self):
        return False

database.py

import logging

from sqlalchemy.ext.declarative import declarative_base

import main
from orm import User, Entry

logging.basicConfig(level=logging.DEBUG)

Base = declarative_base()

def load_user_by_id(user_id):
    u: User = main.session.query(User).filter_by(id == user_id).first()
    return u

def load_user(login):
    logging.debug("loading user from session: %s", main.session)
    u: User = main.session.query(User).filter_by(lastname='xxx').first()
    return u

def load_entry(date, isdayshift):
    # e: Entry = session.query(Entry).filter_by(day=date, isdayshift=isdayshift).first()
    return

def insert_entry(day, user, isdayshift, comment):
    logging.debug("storing entry from session: %s", main.session)
    eq1 = Entry(day, user, isdayshift, comment)
    main.session.add(eq1)
    main.session.commit()

The session which was used to load the user is the same as the session used for storage.

DEBUG:root:loading user from session: <sqlalchemy.orm.scoping.scoped_session object at 0x7ff1ecd2cbb0>

DEBUG:root:storing entry from session: <sqlalchemy.orm.scoping.scoped_session object at 0x7ff1ecd2cbb0>


问:
vscode multi-command extension: how to combine workbench.action.terminal.runSelectedText + workbench.action.terminal.sendSequence?
In vscode, I'm trying to send a line selection to the terminal followed by a "\n" character.
I tried the extension multi-command with the following setup:

settings.json:

```<code>"multiCommand.commands": [
        {
            "command": "multiCommand.mycommand",
            "sequence": [
                "workbench.action.terminal.runSelectedText",
                {
                    "command": "workbench.action.terminal.sendSequence",
                    "args": {"text": "\n"}
                }
            ]
        }
    ]
</code>```

keybindings.json:

```<code>{
      "key": "ctrl+alt+i",
      "command": "extension.multiCommand.execute",
      "args": {"command": "multiCommand.mycommand"}
}
</code>```

But it only runs the first command in the sequence: "workbench.action.terminal.runSelectedText".

How can I fix this to run the entire sequence?

I already tried to add keybindings to the commands separately in the keybindings.json and it works:

```<code>{
        "key": "ctrl+alt+a",
        "command": "workbench.action.terminal.runSelectedText"
},
{
      "key": "ctrl+alt+s",
      "command": "workbench.action.terminal.sendSequence",
      "args": {
        "text": "\n"
      }
}
</code>```

So I thoght multi-command should work when defining a sequence with this two commands.

Body:
In vscode, I'm trying to send a line selection to the terminal followed by a "\n" character.
I tried the extension multi-command with the following setup:

settings.json:

"multiCommand.commands": [
        {
            "command": "multiCommand.mycommand",
            "sequence": [
                "workbench.action.terminal.runSelectedText",
                {
                    "command": "workbench.action.terminal.sendSequence",
                    "args": {"text": "\n"}
                }
            ]
        }
    ]

keybindings.json:

{
      "key": "ctrl+alt+i",
      "command": "extension.multiCommand.execute",
      "args": {"command": "multiCommand.mycommand"}
}

But it only runs the first command in the sequence: "workbench.action.terminal.runSelectedText".

How can I fix this to run the entire sequence?

I already tried to add keybindings to the commands separately in the keybindings.json and it works:

{
        "key": "ctrl+alt+a",
        "command": "workbench.action.terminal.runSelectedText"
},
{
      "key": "ctrl+alt+s",
      "command": "workbench.action.terminal.sendSequence",
      "args": {
        "text": "\n"
      }
}

So I thoght multi-command should work when defining a sequence with this two commands.


问:
GitLab Ci: Check if one variable is contained in another one
I tried to check if the content of one variable is part of another variable with:

```<code>  rules:
    - if: $DATABASES_LIST !~ /^.*$CI_COMMIT_REF_NAME.*$/
      when: always
</code>```

but this does not work. I guess this is due to gitlab not expanding the rightmost variable, but I am not sure (and I do not know what can be done about this).

Can somebody tell me how to change it?

Or this is too complex for a rule and I need to check it at the beginning of the ´script`?

Body:
I tried to check if the content of one variable is part of another variable with:

  rules:
    - if: $DATABASES_LIST !~ /^.*$CI_COMMIT_REF_NAME.*$/
      when: always

but this does not work. I guess this is due to gitlab not expanding the rightmost variable, but I am not sure (and I do not know what can be done about this).

Can somebody tell me how to change it?

Or this is too complex for a rule and I need to check it at the beginning of the ´script`?


问:
aspnetboilerplate: plugin with own dbcontext and UI
How to create a separate dbcontext and ui for each plugin created for aspnetboilerplate?

https://aspnetboilerplate.com/Pages/Documents/Plugin


问:
Wordpress Buffer HTML Cache
I'm writing a plugin that writes the HTML output to the file and loads the site from that file, next time. It works flawlessly. But I can't cache the code after the wp_footer hook. I tried the "shutdown" hook that works after the wp_footer hook but it returns null. I don't know why it is returning null. But I need a hook that runs after the wp_footer hook, where I can cache all the code from 0 to 100.

```<code><?php

$priority = 10;
add_action('template_redirect', function(){
    if(!is_admin() && !is_user_logged_in()){

        $cache_time = get_option('html_cache_time');
        if(empty($cache_time)){
            $cache_time = 60;
        }

        $current_url = get_site_url() . $_SERVER['REQUEST_URI'];

        if(filter_var($current_url, FILTER_SANITIZE_URL)){

            $parsed_url = parse_url($current_url);
            $url_path = isset($parsed_url['path']) ? $parsed_url['path'] : false;

            if(!empty($url_path)){

                $cached_url = NGY_CACHE_DIR . 'app/cached/' .  md5($url_path) . '.cache';

                define('NOGAY_CACHED_URL', $cached_url);
                $end_time = 60 * $cache_time;

                if(file_exists($cached_url)){
                    if(time() - $end_time < filemtime($cached_url)){
                        readfile($cached_url);
                        exit;
                    }else{
                        unlink($cached_url);
                    }
                }

            }
        }
        ob_start();
    }

}, $priority);

add_action('wp_footer', function(){
    if(!is_admin() && !is_user_logged_in()){

        $html = ob_get_clean();
        if(!file_exists(NOGAY_CACHED_URL)){
            echo $html;
        }

        $open_cached_file = fopen(NOGAY_CACHED_URL, 'w+');
        fwrite($open_cached_file, $html);
        fclose($open_cached_file);
        ob_end_flush();
    }
}, PHP_INT_MAX);
</code>```

I tried another Wordpress hooks. (shutdown)

Title: Wordpress Buffer HTML Cache

Body:
I'm writing a plugin that writes the HTML output to the file and loads the site from that file, next time. It works flawlessly. But I can't cache the code after the wp_footer hook. I tried the "shutdown" hook that works after the wp_footer hook but it returns null. I don't know why it is returning null. But I need a hook that runs after the wp_footer hook, where I can cache all the code from 0 to 100.

<?php

$priority = 10;
add_action('template_redirect', function(){
    if(!is_admin() && !is_user_logged_in()){

        $cache_time = get_option('html_cache_time');
        if(empty($cache_time)){
            $cache_time = 60;
        }

        $current_url = get_site_url() . $_SERVER['REQUEST_URI'];

        if(filter_var($current_url, FILTER_SANITIZE_URL)){

            $parsed_url = parse_url($current_url);
            $url_path = isset($parsed_url['path']) ? $parsed_url['path'] : false;

            if(!empty($url_path)){

                $cached_url = NGY_CACHE_DIR . 'app/cached/' .  md5($url_path) . '.cache';

                define('NOGAY_CACHED_URL', $cached_url);
                $end_time = 60 * $cache_time;

                if(file_exists($cached_url)){
                    if(time() - $end_time < filemtime($cached_url)){
                        readfile($cached_url);
                        exit;
                    }else{
                        unlink($cached_url);
                    }
                }

            }
        }
        ob_start();
    }

}, $priority);

add_action('wp_footer', function(){
    if(!is_admin() && !is_user_logged_in()){

        $html = ob_get_clean();
        if(!file_exists(NOGAY_CACHED_URL)){
            echo $html;
        }

        $open_cached_file = fopen(NOGAY_CACHED_URL, 'w+');
        fwrite($open_cached_file, $html);
        fclose($open_cached_file);
        ob_end_flush();
    }
}, PHP_INT_MAX);

I tried another Wordpress hooks. (shutdown)


问:
Why do I get an error when using the easyadmin search bar?
I don't understand why, only in my 'file' entity I can't use the search bar of easyadmin I have this error:

```<code>Class "string" does not exist
</code>```

trace:

```<code> (line 156)

                    /** @var \ReflectionNamedType|\ReflectionUnionType|null $idClassType */
                    $idClassType = (new \ReflectionProperty($entityFqcn, $propertyName))->getType();
                    if (null !== $idClassType) {
                        $idClassName = $idClassType->getName();
                        $isUlidProperty = (new \ReflectionClass($idClassName))->isSubclassOf(Ulid::class);
                        $isGuidProperty = (new \ReflectionClass($idClassName))->isSubclassOf(Uuid::class);
                    }
                }
                // this complex condition is needed to avoid issues on PostgreSQL databases
</code>```

Body:
I don't understand why, only in my 'file' entity I can't use the search bar of easyadmin I have this error:

Class "string" does not exist

trace:

 (line 156)

                    /** @var \ReflectionNamedType|\ReflectionUnionType|null $idClassType */
                    $idClassType = (new \ReflectionProperty($entityFqcn, $propertyName))->getType();
                    if (null !== $idClassType) {
                        $idClassName = $idClassType->getName();
                        $isUlidProperty = (new \ReflectionClass($idClassName))->isSubclassOf(Ulid::class);
                        $isGuidProperty = (new \ReflectionClass($idClassName))->isSubclassOf(Uuid::class);
                    }
                }
                // this complex condition is needed to avoid issues on PostgreSQL databases


问:
Can't convert .htaccess to nginx directives
in order to install Taskly crm, I'm trying to convert three simple directives by an .htaccess file to nginx vhosts directives without success.

I've installed Cloudpanel on my own vps server and when i add a website it comes with pre-configured vhosts, and this is the default file i have:

```<code>server {
  listen 8080;
  listen [::]:8080;
  server_name crm.mydomain.it;
  {{root}}

  try_files $uri $uri/ /index.php?$args;
  index index.php index.html;

  location ~ \.php$ {
    include fastcgi_params;
    fastcgi_intercept_errors on;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    try_files $uri =404;
    fastcgi_read_timeout 3600;
    fastcgi_send_timeout 3600;
    fastcgi_param HTTPS "on";
    fastcgi_param SERVER_PORT 443;
    fastcgi_pass 127.0.0.1:{{php_fpm_port}};
    fastcgi_param PHP_VALUE "{{php_settings}}";
  }

  if (-f $request_filename) {
    break;
  }
}

server {
  listen 80;
  listen [::]:80;
  listen 443 ssl http2;
  listen [::]:443 ssl http2;
  {{ssl_certificate_key}}
  {{ssl_certificate}}
  server_name crm.mydomain.it;
  {{root}}

  {{nginx_access_log}}
  {{nginx_error_log}}

  if ($scheme != "https") {
    rewrite ^ https://$host$uri permanent;
  }

  location ~ /.well-known {
    auth_basic off;
    allow all;
  }

  {{settings}}

  location / {
    {{varnish_proxy_pass}}
    proxy_set_header Host $http_host;
    proxy_set_header X-Forwarded-Host $http_host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_hide_header X-Varnish;
    proxy_redirect off;
    proxy_max_temp_file_size 0;
    proxy_connect_timeout      720;
    proxy_send_timeout         720;
    proxy_read_timeout         720;
    proxy_buffer_size          128k;
    proxy_buffers              4 256k;
    proxy_busy_buffers_size    256k;
    proxy_temp_file_write_size 256k;

  }

  location ~* ^.+\.(css|js|jpg|jpeg|gif|png|ico|gz|svg|svgz|ttf|otf|woff|woff2|eot|mp4|ogg|ogv|webm|webp|zip|swf|map)$ {
    add_header Access-Control-Allow-Origin "*";
    expires max;
    access_log off;
  }

  if (-f $request_filename) {
    break;
  }
}
</code>```

And i have those .htaccess rules to add:

```<code><IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Send Requests To Front Controller...
    RewriteCond %{REQUEST_URI} !(\.css|\.js|\.png|\.jpg|\.jpeg|\.gif|robots\.txt|\.ico|\.woff|\.woff2|.ttf|\.svg)$ [NC]
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]

    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_URI} !^/public/
    RewriteRule ^(css|assets|landing|storage|installer|js|custom)/(.*)$ public/$1/$2 [L,NC]
</IfModule>

</code>```

I translated those directives into this code with an online tool, and i tried to insert those lines where i supposed i should with success, as Cloudpanel if there is a error will not allow me to save the vhosts file, but it allowed me without problem. The problem is that adding those lines make my domain cause a loop redirect error.

Translated directives:

```<code># nginx configuration by winginx.com

autoindex off;

location ~* (\.css|\.js|\.png|\.jpg|\.jpeg|\.gif|robots\.txt|\.ico|\.woff|\.woff2|.ttf|\.svg)$ {
}

location ~ /public/ {
}

location / {
  if (!-e $request_filename){
    rewrite ^(.*)$ /%1 redirect;
  }
  if (!-e $request_filename){
    rewrite ^(.*)$ /index.php break;
  }
  if (!-e $request_filename){
    rewrite ^/(css|assets|landing|storage|installer|js|custom)/(.*)$ /public/$1/$2 break;
  }
}
</code>```

Body:
in order to install Taskly crm, I'm trying to convert three simple directives by an .htaccess file to nginx vhosts directives without success.

I've installed Cloudpanel on my own vps server and when i add a website it comes with pre-configured vhosts, and this is the default file i have:

server {
  listen 8080;
  listen [::]:8080;
  server_name crm.mydomain.it;
  {{root}}

  try_files $uri $uri/ /index.php?$args;
  index index.php index.html;

  location ~ \.php$ {
    include fastcgi_params;
    fastcgi_intercept_errors on;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    try_files $uri =404;
    fastcgi_read_timeout 3600;
    fastcgi_send_timeout 3600;
    fastcgi_param HTTPS "on";
    fastcgi_param SERVER_PORT 443;
    fastcgi_pass 127.0.0.1:{{php_fpm_port}};
    fastcgi_param PHP_VALUE "{{php_settings}}";
  }

  if (-f $request_filename) {
    break;
  }
}

server {
  listen 80;
  listen [::]:80;
  listen 443 ssl http2;
  listen [::]:443 ssl http2;
  {{ssl_certificate_key}}
  {{ssl_certificate}}
  server_name crm.mydomain.it;
  {{root}}

  {{nginx_access_log}}
  {{nginx_error_log}}

  if ($scheme != "https") {
    rewrite ^ https://$host$uri permanent;
  }

  location ~ /.well-known {
    auth_basic off;
    allow all;
  }

  {{settings}}

  location / {
    {{varnish_proxy_pass}}
    proxy_set_header Host $http_host;
    proxy_set_header X-Forwarded-Host $http_host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_hide_header X-Varnish;
    proxy_redirect off;
    proxy_max_temp_file_size 0;
    proxy_connect_timeout      720;
    proxy_send_timeout         720;
    proxy_read_timeout         720;
    proxy_buffer_size          128k;
    proxy_buffers              4 256k;
    proxy_busy_buffers_size    256k;
    proxy_temp_file_write_size 256k;

  }

  location ~* ^.+\.(css|js|jpg|jpeg|gif|png|ico|gz|svg|svgz|ttf|otf|woff|woff2|eot|mp4|ogg|ogv|webm|webp|zip|swf|map)$ {
    add_header Access-Control-Allow-Origin "*";
    expires max;
    access_log off;
  }

  if (-f $request_filename) {
    break;
  }
}

And i have those .htaccess rules to add:

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Send Requests To Front Controller...
    RewriteCond %{REQUEST_URI} !(\.css|\.js|\.png|\.jpg|\.jpeg|\.gif|robots\.txt|\.ico|\.woff|\.woff2|.ttf|\.svg)$ [NC]
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]

    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_URI} !^/public/
    RewriteRule ^(css|assets|landing|storage|installer|js|custom)/(.*)$ public/$1/$2 [L,NC]
</IfModule>

I translated those directives into this code with an online tool, and i tried to insert those lines where i supposed i should with success, as Cloudpanel if there is a error will not allow me to save the vhosts file, but it allowed me without problem. The problem is that adding those lines make my domain cause a loop redirect error.

Translated directives:

# nginx configuration by winginx.com

autoindex off;

location ~* (\.css|\.js|\.png|\.jpg|\.jpeg|\.gif|robots\.txt|\.ico|\.woff|\.woff2|.ttf|\.svg)$ {
}

location ~ /public/ {
}

location / {
  if (!-e $request_filename){
    rewrite ^(.*)$ /%1 redirect;
  }
  if (!-e $request_filename){
    rewrite ^(.*)$ /index.php break;
  }
  if (!-e $request_filename){
    rewrite ^/(css|assets|landing|storage|installer|js|custom)/(.*)$ /public/$1/$2 break;
  }
}


问:
I am using the delay function in C and its causing infinite loops
This allwos me to use time.h to add a delay function

```<code>void delay(int  seconds){

    // Converting time into milli_seconds

    int millsec = 1000 * seconds;

    // Storing start time

    clock_t start_time = clock();

    // looping till required time is not achieved
    while (clock() < start_time + millsec)
        ;
}
</code>```

but this line "while (clock() < start_time + millsec)" causes random loops for no reason sometimes. Usually happens when i use this global function.

```<code>int AskRound() {

    m=0;

    while (Runde!=1&&Runde!=2){

        if (m>0){   //Ab der ersten missinput wird folgendes Ausgegeben

            printf("\nEingabe nicht erkannt. Bitte entweder -1- oder -2- eingeben \n");

            delay(8000);

        }

        printf( "\n\nWollen Sie nochmal Spielen?\n"
                        "für Ja -1- Eingeben und für Nein -2- Eingeben:  ");

        scanf(  "%d",&Runde);   //Eingabe Neue Runde?

        delay(8000);

        m = 1.0;        //Missinput detection

    }

}
</code>```

At random times this global function keeps looping and when activaiting the slowmotion feature in my compiler it show that the line "while (clock() < start_time + millsec)" is looping.

Can someone explain?

Also since i added the delay function some culculations dont work properly. for exaple trying to multiply an int sometime outouts 0 for no vissible reason but idk if it has to do with this or at least i dont think.

Thanks

i tried using sleep function but my compiler doesnt include windows.h and i dont know how to add it to the library or if that is even possible. i tried unistd.h and the sleep function doesnt work either but my compyler findes the unistf.h library.

Body:
This allwos me to use time.h to add a delay function

void delay(int  seconds){

    // Converting time into milli_seconds

    int millsec = 1000 * seconds;

    // Storing start time

    clock_t start_time = clock();

    // looping till required time is not achieved
    while (clock() < start_time + millsec)
        ;
}

but this line "while (clock() < start_time + millsec)" causes random loops for no reason sometimes. Usually happens when i use this global function.

int AskRound() {

    m=0;

    while (Runde!=1&&Runde!=2){

        if (m>0){   //Ab der ersten missinput wird folgendes Ausgegeben

            printf("\nEingabe nicht erkannt. Bitte entweder -1- oder -2- eingeben \n");

            delay(8000);

        }

        printf( "\n\nWollen Sie nochmal Spielen?\n"
                        "für Ja -1- Eingeben und für Nein -2- Eingeben:  ");

        scanf(  "%d",&Runde);   //Eingabe Neue Runde?

        delay(8000);

        m = 1.0;        //Missinput detection

    }

}

At random times this global function keeps looping and when activaiting the slowmotion feature in my compiler it show that the line "while (clock() < start_time + millsec)" is looping.

Can someone explain?

Also since i added the delay function some culculations dont work properly. for exaple trying to multiply an int sometime outouts 0 for no vissible reason but idk if it has to do with this or at least i dont think.

Thanks

i tried using sleep function but my compiler doesnt include windows.h and i dont know how to add it to the library or if that is even possible. i tried unistd.h and the sleep function doesnt work either but my compyler findes the unistf.h library.


问:
How many decimals the `step` and `min` attributes can have on an html number input?
Designing a form with an input as a number, from its standard (namely : a default Ethereum ERC20 token) it can have up to 18 decimals (sometimes more for non default tokens). The html element to input it would turn like :

<input name="amount" type="number" min="0.000000000000000001" step="0.000000000000000001" />
```

It looks like this attributes are too low for the browser I'm using to take them into account and it disables the stepping features altogether (the up and down arrows are not reactive).

Through trial and errors on https://jsfiddle.net/g68t30o5/ I was able to determine it works as expected with 16 decimals (0.0000000000000001) for the Firefox browser.

I'm then wondering if this is a standard limit (nothing about it on https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/step) and/or if it happens to be different on various browsers ?

Body:
Designing a form with an input as a number, from its standard (namely : a default Ethereum ERC20 token) it can have up to 18 decimals (sometimes more for non default tokens). The html element to input it would turn like :

<input name="amount" type="number" min="0.000000000000000001" step="0.000000000000000001" />

It looks like this attributes are too low for the browser I'm using to take them into account and it disables the stepping features altogether (the up and down arrows are not reactive).

Through trial and errors on https://jsfiddle.net/g68t30o5/ I was able to determine it works as expected with 16 decimals (0.0000000000000001) for the Firefox browser.

I'm then wondering if this is a standard limit (nothing about it on https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/step) and/or if it happens to be different on various browsers ?


问:
Tailwind arbitrary classes not applying without server restart
I'm using tailwind in my React project. The issue I've come across is that I can't use tailwind arbitrary classes(e.g. p-[115px]) without restarting the server. Although I've added  mode: 'jit', to my tailwind.config.js but the issue still persists.
And the second thing is whenever I edit my code, it gets updated in the browser but I still have to refresh the page for inspecting my code and that gets annoying while debugging. Please suggest me solutions regarding these problems.

Note: I'm having "tailwindcss": "npm:@tailwindcss/postcss7-compat@^2.2.7" in my package.json.


问:
Must perspective be set on the parent element of `transform style: preserve-3d` element?

<!DOCTYPE html>

    <meta charset="UTF-8" />

front

back

right

left

top

bottom

```
<p>If the perspective is set on the<code>. scene</code> element, everything is ok, but I set the perspective on the <code>.cube</code>, as shown below. What's the difference?</p>
<p><img src="https://i.stack.imgur.com/X9LEK.png" alt="enter image description here" /></p>
<pre class="lang-css prettyprint-override"><code>   .scene {
        width: 200px;
        height: 200px;
        margin: 0 auto;
      }

      .cube {
        width: 100%;
        height: 100%;
        transition: all 3s;
        position: relative;
        transform-style: preserve-3d;
        transform-origin: center center -100px;
        perspective: 600px; //Move perspective from .scene to here
      }
</code>```

Body:
<!DOCTYPE html>

    <meta charset="UTF-8" />

front

back

right

left

top

bottom

If the perspective is set on the. scene element, everything is ok, but I set the perspective on the .cube, as shown below. What's the difference?

   .scene {
        width: 200px;
        height: 200px;
        margin: 0 auto;
      }

      .cube {
        width: 100%;
        height: 100%;
        transition: all 3s;
        position: relative;
        transform-style: preserve-3d;
        transform-origin: center center -100px;
        perspective: 600px; //Move perspective from .scene to here
      }


问:
what does the underscore mean in "mime_type, _ = mimetypes.guess_type(attachment_path)"
I'm having issues with getting the ADP file attached to the email and the email never comes through.

I started by learning about the modules and what is actually happening. I'm a complete noob, but I feel as though I have a basic understanding of most the code. The _ when googled means the last value and the issue is that tuple hadn't been called before in the code. Is this a placeholder?

```<code>  emails.send(message)
  attachment_path = "/tmp/cars.pdf"
  attachment_filename = os.path.basename(attachment_path)
  mime_type, _ = mimetypes.guess_type(attachment_path)
  mime_type, mime_subtype = mime_type.split('/', 1)
  message.add_attachment(ap.read(), maintype=mime_type, subtype=mime_subtype, filename=os.path.basename(attachment_path))
</code>```

I've restarted and the code up to this point looks like this

```<code>#!/usr/bin/env python3
import json
import mimetypes
import os
import locale
import sys
import reports
import emails
import smtplib

def load_data(filename):
  """Loads the contents of filename as a JSON file."""
  with open(filename) as json_file:
    data = json.load(json_file)
  return data

def format_car(car):
  """Given a car dictionary, returns a nicely formatted name."""
  return "{} {} ({})".format(
      car["car_make"], car["car_model"], car["car_year"])

def process_data(data):
  """Analyzes the data, looking for maximums.

  Returns a list of lines that summarize the information.
  """
  max_revenue = {"revenue": 0}
  max_sales = {"total_sales": 0}
  for item in data:
    # Calculate the revenue generated by this model (price * total_sales)
    # We need to convert the price from "$1234.56" to 1234.56
    item_price = locale.atof(item["price"].strip("$"))
    item_revenue = item["total_sales"] * item_price
    if item_revenue > max_revenue["revenue"]:
      item["revenue"] = item_revenue
      max_revenue = item
    # TODO: also handle max sales
    if item["total_sales"] > max_sales["total_sales"]:
        max_sales = item
    # TODO: also handle most popular car_year "The {car model} had the most sales: {total sales}"
    #most_popular_year = max(data, key=lambda x: x["total_sales"])

  summary = [
    "The {} generated the most revenue: ${}".format(
      format_car(max_revenue["car"]), max_revenue["revenue"]),
  ]

  return summary

def cars_dict_to_table(car_data):
  """Turns the data in car_data into a list of lists."""
  table_data = [["ID", "Car", "Price", "Total Sales"]]
  for item in car_data:
    table_data.append([item["id"], format_car(item["car"]), item["price"], item["total_sales"]])
  return table_data

def main(argv):
  """Process the JSON data and generate a full report out of it."""
  data = load_data("car_sales.json")
  summary = process_data(data)
  print(summary)

  # TODO: turn this into a PDF report
  car_data = cars_dict_to_table(data)
  reports.generate("/tmp/cars.pdf", "Sales summary for last month", "<br/>".join(summary), car_data)

  # TODO: send the PDF report as an email attachment
  message = emails.generate("automation@example.com", "student-04-9849759230b1@example.com", "Sales summary for last month", "\n".join(summary), "/tmp/cars.pdf")
  emails.send(message)
  attachment_path = "/tmp/cars.pdf"
  attachment_filename = os.path.basename(attachment_path)
  mime_type, _ = mimetypes.guess_type(attachment_path)
  mime_type, mime_subtype = mime_type.split('/', 1)
  message.add_attachment(ap.read(), maintype=mime_type, subtype=mime_subtype, filename=os.path.basename(attachment_path))

if __name__ == "__main__":
    main(sys.argv)
</code>```

I had tried different things, tried to let Git CoPilot hard carry with no success. I think I need to find a blog group or some community of coders that could flame me out of my ignorance.

Body:
I'm having issues with getting the ADP file attached to the email and the email never comes through.

I started by learning about the modules and what is actually happening. I'm a complete noob, but I feel as though I have a basic understanding of most the code. The _ when googled means the last value and the issue is that tuple hadn't been called before in the code. Is this a placeholder?

  emails.send(message)
  attachment_path = "/tmp/cars.pdf"
  attachment_filename = os.path.basename(attachment_path)
  mime_type, _ = mimetypes.guess_type(attachment_path)
  mime_type, mime_subtype = mime_type.split('/', 1)
  message.add_attachment(ap.read(), maintype=mime_type, subtype=mime_subtype, filename=os.path.basename(attachment_path))

I've restarted and the code up to this point looks like this

#!/usr/bin/env python3
import json
import mimetypes
import os
import locale
import sys
import reports
import emails
import smtplib

def load_data(filename):
  """Loads the contents of filename as a JSON file."""
  with open(filename) as json_file:
    data = json.load(json_file)
  return data

def format_car(car):
  """Given a car dictionary, returns a nicely formatted name."""
  return "{} {} ({})".format(
      car["car_make"], car["car_model"], car["car_year"])

def process_data(data):
  """Analyzes the data, looking for maximums.

  Returns a list of lines that summarize the information.
  """
  max_revenue = {"revenue": 0}
  max_sales = {"total_sales": 0}
  for item in data:
    # Calculate the revenue generated by this model (price * total_sales)
    # We need to convert the price from "$1234.56" to 1234.56
    item_price = locale.atof(item["price"].strip("$"))
    item_revenue = item["total_sales"] * item_price
    if item_revenue > max_revenue["revenue"]:
      item["revenue"] = item_revenue
      max_revenue = item
    # TODO: also handle max sales
    if item["total_sales"] > max_sales["total_sales"]:
        max_sales = item
    # TODO: also handle most popular car_year "The {car model} had the most sales: {total sales}"
    #most_popular_year = max(data, key=lambda x: x["total_sales"])

  summary = [
    "The {} generated the most revenue: ${}".format(
      format_car(max_revenue["car"]), max_revenue["revenue"]),
  ]

  return summary

def cars_dict_to_table(car_data):
  """Turns the data in car_data into a list of lists."""
  table_data = [["ID", "Car", "Price", "Total Sales"]]
  for item in car_data:
    table_data.append([item["id"], format_car(item["car"]), item["price"], item["total_sales"]])
  return table_data

def main(argv):
  """Process the JSON data and generate a full report out of it."""
  data = load_data("car_sales.json")
  summary = process_data(data)
  print(summary)

  # TODO: turn this into a PDF report
  car_data = cars_dict_to_table(data)
  reports.generate("/tmp/cars.pdf", "Sales summary for last month", "
".join(summary), car_data)

  # TODO: send the PDF report as an email attachment
  message = emails.generate("automation@example.com", "student-04-9849759230b1@example.com", "Sales summary for last month", "\n".join(summary), "/tmp/cars.pdf")
  emails.send(message)
  attachment_path = "/tmp/cars.pdf"
  attachment_filename = os.path.basename(attachment_path)
  mime_type, _ = mimetypes.guess_type(attachment_path)
  mime_type, mime_subtype = mime_type.split('/', 1)
  message.add_attachment(ap.read(), maintype=mime_type, subtype=mime_subtype, filename=os.path.basename(attachment_path))

if __name__ == "__main__":
    main(sys.argv)

I had tried different things, tried to let Git CoPilot hard carry with no success. I think I need to find a blog group or some community of coders that could flame me out of my ignorance.


问:
OpenAI not giving response because of invalid request
What is the error in this code ?? OpenAI not giving response because of invalid request

```<code>curl -XPOST -H "Content-type: application/json" -d 'What is the Capital of France ?' 'https://api.openai.com/v1/text/generations/'
</code>```

Hard time to get the success in this. Even I tried several solutions found on OpenAI , Google but does not work

```<code>public class OpenAI {
    private static final String API_URL = "https://api.openai.com/v1/text/generations";
    private static final String API_KEY = "MY_API_KEY";

    public static String generateText(String prompt) throws IOException {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(API_URL)
                .addHeader("Authorization", "Bearer " + API_KEY)
                .addHeader("Content-Type", "application/json")
                .post(okhttp3.RequestBody.create(okhttp3.MediaType.parse("application/json"), "{\"prompt\":\"" + prompt + "\",\"model\":\"text-davinci-002\",\"max_tokens\":2048}"))
                .build();
        Response response = client.newCall(request).execute();
        return response.body().string();
    }
}
</code>```

Body:
What is the error in this code ?? OpenAI not giving response because of invalid request

curl -XPOST -H "Content-type: application/json" -d 'What is the Capital of France ?' 'https://api.openai.com/v1/text/generations/'

Hard time to get the success in this. Even I tried several solutions found on OpenAI , Google but does not work

public class OpenAI {
    private static final String API_URL = "https://api.openai.com/v1/text/generations";
    private static final String API_KEY = "MY_API_KEY";

    public static String generateText(String prompt) throws IOException {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(API_URL)
                .addHeader("Authorization", "Bearer " + API_KEY)
                .addHeader("Content-Type", "application/json")
                .post(okhttp3.RequestBody.create(okhttp3.MediaType.parse("application/json"), "{\"prompt\":\"" + prompt + "\",\"model\":\"text-davinci-002\",\"max_tokens\":2048}"))
                .build();
        Response response = client.newCall(request).execute();
        return response.body().string();
    }
}


问:
How to draw curve line in React.js
I want to draw a curve line. I want o make a path. Is it possible to draw like a path in React.js?

Title: How to draw curve line in React.js


问:
AForge Genetic algorithms for solving expression
For example my expression is 2*x+y^2.
I have to use genetic algorithms to solve it with getting output closest to 0.

I was trying to define a population but I don't know how to start.
Population size is 20 for now, BinaryChromosome is 32, but what fitness function should be like? Is there a built in fitness solving my problem or I have to create new class for my own? Where to start? Thanks for the help in advance!


问:
Getting import error while loading CatBoostClassifier
installed catboost and ipywidgets still getting import error: cannot import name 'Iterable' from 'collections'</p>
```<code>from catboost import CatBoostClassifire
</code>```
```<code>---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
Cell In[1], line 14
     12 from sklearn.tree import DecisionTreeClassifier, ExtraTreeClassifier
     13 from sklearn.naive_bayes import GaussianNB
---> 14 from catboost import CatBoostClassifier
     16 from sklearn.feature_selection import chi2
     17 from sklearn.metrics import confusion_matrix, accuracy_score

File c:\Users\rahul\AppData\Local\Programs\Python\Python311\Lib\site-packages\catboost\__init__.py:1
----> 1 from .core import Pool, CatBoost, CatBoostClassifier, CatBoostRegressor, CatboostError, cv  # noqa
      2 try:
      3     from .widget import CatboostIpythonWidget  # noqa

File c:\Users\rahul\AppData\Local\Programs\Python\Python311\Lib\site-packages\catboost\core.py:4
      2 from six import iteritems, string_types
      3 import os.path
----> 4 from collections import Iterable, Sequence, Mapping, MutableMapping
      5 import warnings
      6 import numpy as np

ImportError: cannot import name 'Iterable' from 'collections' (c:\Users\rahul\AppData\Local\Programs\Python\Python311\Lib\collections\__init__.py)
</code>```

Body:
installed catboost and ipywidgets still getting import error: cannot import name 'Iterable' from 'collections'

from catboost import CatBoostClassifire

---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
Cell In[1], line 14
     12 from sklearn.tree import DecisionTreeClassifier, ExtraTreeClassifier
     13 from sklearn.naive_bayes import GaussianNB
---> 14 from catboost import CatBoostClassifier
     16 from sklearn.feature_selection import chi2
     17 from sklearn.metrics import confusion_matrix, accuracy_score

File c:\Users\rahul\AppData\Local\Programs\Python\Python311\Lib\site-packages\catboost\__init__.py:1
----> 1 from .core import Pool, CatBoost, CatBoostClassifier, CatBoostRegressor, CatboostError, cv  # noqa
      2 try:
      3     from .widget import CatboostIpythonWidget  # noqa

File c:\Users\rahul\AppData\Local\Programs\Python\Python311\Lib\site-packages\catboost\core.py:4
      2 from six import iteritems, string_types
      3 import os.path
----> 4 from collections import Iterable, Sequence, Mapping, MutableMapping
      5 import warnings
      6 import numpy as np

ImportError: cannot import name 'Iterable' from 'collections' (c:\Users\rahul\AppData\Local\Programs\Python\Python311\Lib\collections\__init__.py)


问:
Using smart pointer instead of raw pointer for Observer design pattern
I have an implementation for Observer design pattern where Observer stores a list of Subject and vice versa. So in case a Observer/Subject goes out of scope, the corresponding object is deleted in the destructor and no dangling reference remains stored.

Thing is raw pointers are rarely used in modern C++ and I'd want to replace them with a smart pointer.

My understanding is the utility shouldn't be taking ownership of the objects so std::weak_ptr makes more sense to me. Does that sound fair?

If so, changing the underlying data structure to hold weak_ptr of Subject would make sense, yes?

std::unordered_set<std::weak_ptr<Subject<T>>, std::hash<std::weak_ptr<Subject<T>>> _subjects;
```
<p>I am unsure of whether there may be some corner cases where storing <code>weak_ptr</code> in an <code>std::unordered_set</code> could cause problems.</p>
<p>Running into compile errors related to the hash but below is the link to the sample code with weak_ptr.</p>
<p>Code with weak_ptr (though it doesn't compile)</p>
<p>Original sample code with raw pointer (shown below)</p>
```template<typename T>
class Subject;

template<typename T>
class Observer
{
    std::set<Subject<T>*> _subjects;        // TODO: change to smart pointer

    public:
    virtual void update(T val) = 0;

    void addSubject(Subject<T>* subject)
    {
        printf ("[Observer] Adding Subject to observer - ");
        _subjects.insert(subject);
        std::cout << "number of Subjects = " << _subjects.size() << "\n\n";
    }

    void removeSubject(Subject<T>* subject)
    {
        printf ("[Observer] Removing Subject from observer - ");
        _subjects.erase(subject);
        std::cout << "number of Subjects = " << _subjects.size() << "\n";
    }

    size_t getNumberOfSubjects()
    {
        return _subjects.size();
    }

    void doesExist(Subject<T>* sub)
    {
        auto it = _subjects.find(sub);
        std::cout << "[Observer] Subject Exists = " << (it != _subjects.end()) << std::endl;
    }

    virtual ~Observer()
    {
        while (!_subjects.empty())
        {
            (*_subjects.begin())->detach(this);
        }
    }
};

template<typename T>
class Subject
{
    std::set<Observer<T>*> _observers;  // TODO: change to smart pointer

    protected:
    Subject() = default;

    public:
    void attach(Observer<T>* observer)
    {
        printf ("~~ [Subject] Attaching observer ~~\n");
        _observers.insert(observer);
        observer->addSubject(this);
    }

    void detach(Observer<T>* observer)
    {
        printf ("[Subject] Detaching observer ~ ");
        std::cout << "observers size = " << _observers.size() << "\n";
        _observers.erase(observer);
        observer->removeSubject(this);
    }

    void notify(const T& val)
    {
        for (auto& observer : _observers)
        {
            observer->update(val);
        }
    }

    size_t getNumberOfObservers()
    {
        return _observers.size();
    }

    virtual ~Subject()
    {
        printf ("\n~Subject\n");
        printf ("Observer size = %ld\n", _observers.size());
        for (auto& obs : _observers)
        {
            obs->removeSubject(this);
        }
    }
};

template<typename T>
class ConcreteSubject : public Subject<T>
{
    T _value;

    public:
    void set(const T& value)
    {
        _value = value;
        this->notify(value);
    }
};

template<typename T>
class ConcreteObserver : public Observer<T>
{
    public:
    void update(T value)
    {
        std::cout << "Observer Notified: " << value << "\n";
    }
};

int main()
{
    ConcreteObserver<int> obs;
    ConcreteSubject<int> sub;

    sub.attach(&obs);
    sub.set(5);

    printf ("\n~~> Before detaching:\nnumber of subjects in Observer = %ld ~~\n", obs.getNumberOfSubjects());
    printf ("number of observers in Subject = %ld\n\n", sub.getNumberOfObservers());

    sub.detach(&obs);
    printf ("\n~~> After detaching:\nnumber of subjects in Observer = %ld ~~\n", obs.getNumberOfSubjects());
    printf ("number of observers in Subject = %ld\n", sub.getNumberOfObservers());

    // subject no longer exists in observer
    obs.doesExist(&sub);
    return 0;
}
```

Body:
I have an implementation for Observer design pattern where Observer stores a list of Subject and vice versa. So in case a Observer/Subject goes out of scope, the corresponding object is deleted in the destructor and no dangling reference remains stored.

Thing is raw pointers are rarely used in modern C++ and I'd want to replace them with a smart pointer.

My understanding is the utility shouldn't be taking ownership of the objects so std::weak_ptr makes more sense to me. Does that sound fair?

If so, changing the underlying data structure to hold weak_ptr of Subject would make sense, yes?

std::unordered_set<std::weak_ptr<Subject<T>>, std::hash<std::weak_ptr<Subject<T>>> _subjects;

I am unsure of whether there may be some corner cases where storing weak_ptr in an std::unordered_set could cause problems.

Running into compile errors related to the hash but below is the link to the sample code with weak_ptr.

Code with weak_ptr (though it doesn't compile)

Original sample code with raw pointer (shown below)

template<typename T>
class Subject;

template<typename T>
class Observer
{
    std::set<Subject<T>*> _subjects;        // TODO: change to smart pointer

    public:
    virtual void update(T val) = 0;

    void addSubject(Subject<T>* subject)
    {
        printf ("[Observer] Adding Subject to observer - ");
        _subjects.insert(subject);
        std::cout << "number of Subjects = " << _subjects.size() << "\n\n";
    }

    void removeSubject(Subject<T>* subject)
    {
        printf ("[Observer] Removing Subject from observer - ");
        _subjects.erase(subject);
        std::cout << "number of Subjects = " << _subjects.size() << "\n";
    }

    size_t getNumberOfSubjects()
    {
        return _subjects.size();
    }

    void doesExist(Subject<T>* sub)
    {
        auto it = _subjects.find(sub);
        std::cout << "[Observer] Subject Exists = " << (it != _subjects.end()) << std::endl;
    }

    virtual ~Observer()
    {
        while (!_subjects.empty())
        {
            (*_subjects.begin())->detach(this);
        }
    }
};

template<typename T>
class Subject
{
    std::set<Observer<T>*> _observers;  // TODO: change to smart pointer

    protected:
    Subject() = default;

    public:
    void attach(Observer<T>* observer)
    {
        printf ("~~ [Subject] Attaching observer ~~\n");
        _observers.insert(observer);
        observer->addSubject(this);
    }

    void detach(Observer<T>* observer)
    {
        printf ("[Subject] Detaching observer ~ ");
        std::cout << "observers size = " << _observers.size() << "\n";
        _observers.erase(observer);
        observer->removeSubject(this);
    }

    void notify(const T& val)
    {
        for (auto& observer : _observers)
        {
            observer->update(val);
        }
    }

    size_t getNumberOfObservers()
    {
        return _observers.size();
    }

    virtual ~Subject()
    {
        printf ("\n~Subject\n");
        printf ("Observer size = %ld\n", _observers.size());
        for (auto& obs : _observers)
        {
            obs->removeSubject(this);
        }
    }
};

template<typename T>
class ConcreteSubject : public Subject<T>
{
    T _value;

    public:
    void set(const T& value)
    {
        _value = value;
        this->notify(value);
    }
};

template<typename T>
class ConcreteObserver : public Observer<T>
{
    public:
    void update(T value)
    {
        std::cout << "Observer Notified: " << value << "\n";
    }
};

int main()
{
    ConcreteObserver<int> obs;
    ConcreteSubject<int> sub;

    sub.attach(&obs);
    sub.set(5);

    printf ("\n~~> Before detaching:\nnumber of subjects in Observer = %ld ~~\n", obs.getNumberOfSubjects());
    printf ("number of observers in Subject = %ld\n\n", sub.getNumberOfObservers());

    sub.detach(&obs);
    printf ("\n~~> After detaching:\nnumber of subjects in Observer = %ld ~~\n", obs.getNumberOfSubjects());
    printf ("number of observers in Subject = %ld\n", sub.getNumberOfObservers());

    // subject no longer exists in observer
    obs.doesExist(&sub);
    return 0;
}


问:
How do I increment a count field automatically within a many to many intermediate table in django models?
So I have the following three models for creating an icecream (which consists of a flavour and the cone of the icecream):

from django.db import models

not_less_than_zero=MinValueValidator(0)

class Flavour(models.Model):
      name = models.CharField(max_length=255)
      price = models.DecimalField(
          max_digits=5,
          decimal_places=2,
          validators=([not_less_than_zero])
      )

class Icecream(models.Model):
      cone = models.ForeignKey(
          Cone,
          on_delete=models.PROTECT
      )
      scoops = models.ManyToManyField(
          Flavour,
          through='quickstart.IcecreamFlavour'
      )
      quantity = models.IntegerField(default=1, validators=([not_less_than_zero]))

class IcecreamFlavour(models.Model):
      icecream = models.ForeignKey(Icecream, on_delete=models.PROTECT)
      flavour = models.ForeignKey(Flavour, on_delete=models.PROTECT)
      count = models.IntegerField(blank=True, default=1, validators=([not_less_than_zero]))
```
<p>I would like for the <code>count</code> field in <code>IcecreamFlavour</code> to be updated automatically whenever a flavour is added to <code>Icecream</code> that already exists for that icecream. example in python shell:</p>
<pre class="lang-py prettyprint-override"><code>>>> from .models import Cone, Flavour, Icecream
>>>
>>> # defining some flavours in the database
>>> strawberry = Flavour.objects.create(name="Strawberry", price=0.75)
>>> chocolate = Flavour.objects.create(name="Chocolate", price=0.80)
>>>
>>> # for the purpose of this example, lets say there is already a predefined icecream in the database
>>> my_icecream = Icecream.objects.get(pk=1)
>>> my_icecream.scoops.add(chocolate)
>>> my_icecream.scoops.add(strawberry)
>>> my_icecream.scoops.count()  # beware! this is not the count field of IcecreamFlavour model
2
>>> # so far so good
>>> my_icecream.scoops.add(strawberry)
>>> my_icecream.scoops.count()
2
</code>```

So after seeing this I presumed that this was because there already exists an entry in the intermediate table IcecreamFlavour that connects the Flavour and Icecream models, therefore I added a count to the intermediate table to keep track of how many scoops of a single flavour are added to an icecream.

Unfortunately I have a hard time updating this count whenever a duplicate value is added for that Icecream.
I tried messing around with the m2m_changed signal and adding a callback to check what scoops already exists on the icecream, but unless I read the documentation wrong I see no way to check which flavour is added to the scoops of the icecream through this signal.

Basically this is what I would want to happen:

...
>>> from .models import IcecreamFlavour
>>> # let's say the id of the my_icecream variable is 4
>>> # and the id of the chocolate flavour is 2
>>> icecream_flavour = IcecreamFlavour.objects.get(icecream_id=4, flavour_id=2)
>>> icecream_flavour.count
1
>>> # at this point there is one chocolate scoop on my_icecream
>>> my_icecream.scoops.add(chocolate)
>>> icecream_flavour.count
2
...
```

After adding an icecream of the same flavour the count should be automatically updated for the icecream flavour.

Is there any way I can do this inside the models defined in Django, or do I actually need to write a custom trigger in the database to handle this behavior (which I would not prefer tbh)

It could be that I missed something really obvious, I just started learning django last week and I'm trying stuff out with some practice projects but I can't really find a solution in the docs for this particular problem, any help is greatly appreciated.
Thanks for reading in advance anyways :-).

Body:
So I have the following three models for creating an icecream (which consists of a flavour and the cone of the icecream):

from django.db import models

not_less_than_zero=MinValueValidator(0)

class Flavour(models.Model):
      name = models.CharField(max_length=255)
      price = models.DecimalField(
          max_digits=5,
          decimal_places=2,
          validators=([not_less_than_zero])
      )

class Icecream(models.Model):
      cone = models.ForeignKey(
          Cone,
          on_delete=models.PROTECT
      )
      scoops = models.ManyToManyField(
          Flavour,
          through='quickstart.IcecreamFlavour'
      )
      quantity = models.IntegerField(default=1, validators=([not_less_than_zero]))

class IcecreamFlavour(models.Model):
      icecream = models.ForeignKey(Icecream, on_delete=models.PROTECT)
      flavour = models.ForeignKey(Flavour, on_delete=models.PROTECT)
      count = models.IntegerField(blank=True, default=1, validators=([not_less_than_zero]))

I would like for the count field in IcecreamFlavour to be updated automatically whenever a flavour is added to Icecream that already exists for that icecream. example in python shell:

>>> from .models import Cone, Flavour, Icecream
>>>
>>> # defining some flavours in the database
>>> strawberry = Flavour.objects.create(name="Strawberry", price=0.75)
>>> chocolate = Flavour.objects.create(name="Chocolate", price=0.80)
>>>
>>> # for the purpose of this example, lets say there is already a predefined icecream in the database
>>> my_icecream = Icecream.objects.get(pk=1)
>>> my_icecream.scoops.add(chocolate)
>>> my_icecream.scoops.add(strawberry)
>>> my_icecream.scoops.count()  # beware! this is not the count field of IcecreamFlavour model
2
>>> # so far so good
>>> my_icecream.scoops.add(strawberry)
>>> my_icecream.scoops.count()
2

So after seeing this I presumed that this was because there already exists an entry in the intermediate table IcecreamFlavour that connects the Flavour and Icecream models, therefore I added a count to the intermediate table to keep track of how many scoops of a single flavour are added to an icecream.

Unfortunately I have a hard time updating this count whenever a duplicate value is added for that Icecream.
I tried messing around with the m2m_changed signal and adding a callback to check what scoops already exists on the icecream, but unless I read the documentation wrong I see no way to check which flavour is added to the scoops of the icecream through this signal.

Basically this is what I would want to happen:

...
>>> from .models import IcecreamFlavour
>>> # let's say the id of the my_icecream variable is 4
>>> # and the id of the chocolate flavour is 2
>>> icecream_flavour = IcecreamFlavour.objects.get(icecream_id=4, flavour_id=2)
>>> icecream_flavour.count
1
>>> # at this point there is one chocolate scoop on my_icecream
>>> my_icecream.scoops.add(chocolate)
>>> icecream_flavour.count
2
...

After adding an icecream of the same flavour the count should be automatically updated for the icecream flavour.

Is there any way I can do this inside the models defined in Django, or do I actually need to write a custom trigger in the database to handle this behavior (which I would not prefer tbh)

It could be that I missed something really obvious, I just started learning django last week and I'm trying stuff out with some practice projects but I can't really find a solution in the docs for this particular problem, any help is greatly appreciated.
Thanks for reading in advance anyways :-).


问:
pd.to_datetime() not working on a column with different date formats
I wrote a program where a dataframe is traversed & when any column with the name 'Date' is encountered, all the rows under that column are supposed to be converted to a 'datetime' object using 'pd.to_datetime' in the format mentioned. But this method is not working for me.

The 'Date' column in my dataset consists of dates in various formats & with different separators. Example: 26/04/2007, 01-15-1998, 2020-12-2. When I do debugging I get an error message for those dates that are not in the format specified.

Isn't the whole point of using the method a way to convert dates in any format to a datetime object & in the format specified?

My code:

```<code>from dateutil.parser import parse
import re
from datetime import datetime
import calendar

import pandas as pd

def date_fun(filepath):

   date_list=['Date', 'date', 'Dates', 'dates']

   for i in filepath.columns:

      for j in date_list:
          if i==j:
            filepath[i]=pd.to_datetime(filepath[i], format='%d-%m-%Y')

main_path = pd.read_csv('C:/Data_Cleansing/lockdown_us.csv')
fpath=main_path.copy()

date_fun(fpath)
</code>```

Error: time data '26-2016-09' does not match format '%d-%m-%Y' (match)

Where is the mistake in my code?

Body:
I wrote a program where a dataframe is traversed & when any column with the name 'Date' is encountered, all the rows under that column are supposed to be converted to a 'datetime' object using 'pd.to_datetime' in the format mentioned. But this method is not working for me.

The 'Date' column in my dataset consists of dates in various formats & with different separators. Example: 26/04/2007, 01-15-1998, 2020-12-2. When I do debugging I get an error message for those dates that are not in the format specified.

Isn't the whole point of using the method a way to convert dates in any format to a datetime object & in the format specified?

My code:

from dateutil.parser import parse
import re
from datetime import datetime
import calendar

import pandas as pd

def date_fun(filepath):

   date_list=['Date', 'date', 'Dates', 'dates']

   for i in filepath.columns:

      for j in date_list:
          if i==j:
            filepath[i]=pd.to_datetime(filepath[i], format='%d-%m-%Y')

main_path = pd.read_csv('C:/Data_Cleansing/lockdown_us.csv')
fpath=main_path.copy()

date_fun(fpath)

Error: time data '26-2016-09' does not match format '%d-%m-%Y' (match)

Where is the mistake in my code?


问:
How to extract a json entry without jq in bash if I know the start and end patterns?
I have a piece of json where I would like to extract a text entry string from:

```<code>{"choices":[{"text":" price for that\n\nSpend full price for that.","index":0,"logprobs":null}],"usage":{"prompt_tokens":13}}
</code>```

I know that the text always starts with "choices":[{"text": and ends with ,"index". Is there a way I can use native bash tools to extract whatever is in the middle? For the above, I would want to extract " price for that\n\nSpend full price for that." as the string. Thanks

Body:
I have a piece of json where I would like to extract a text entry string from:

{"choices":[{"text":" price for that\n\nSpend full price for that.","index":0,"logprobs":null}],"usage":{"prompt_tokens":13}}

I know that the text always starts with "choices":[{"text": and ends with ,"index". Is there a way I can use native bash tools to extract whatever is in the middle? For the above, I would want to extract " price for that\n\nSpend full price for that." as the string. Thanks


问:
Prisma data proxy npm script errors with 'DATABASE_URL' is not recognized as an internal or external command, operable program or batch file
After creating a Prisma data proxy by following this guide, I switched the DATABASE_URL to my proxy connection string in my .env

```<code>DATABASE_URL="prisma://..."
</code>```

I would like to migrate changes to my database. However, after reading this from Prisma on how to migrate changes with their proxy, I refactored my .env vars to include another variable that will be used in an NPM script whenever I wish to migrate some changes (the script essentially swaps the proxy string with the cloud-hosted DB string)

Refactored .env

```<code>DATABASE_URL="prisma://..."

MIGRATE_DATABASE_URL="mysql://..."
</code>```

Npm script inside package.json

```<code>{
  ...,
  "scripts": {
    "generate-client": "prisma generate --data-proxy",
    "migrate-deploy": "DATABASE_URL=\"$MIGRATE_DATABASE_URL\" prisma migrate deploy",
    "dev": "DATABASE_URL=\"$MIGRATE_DATABASE_URL\" prisma migrate dev",
  }
}
</code>```

The Problem: whenever I run npm run migrate-deploy, I recieve this error:
'DATABASE_URL' is not recognized as an internal or external command,
operable program or batch file.

Body:
After creating a Prisma data proxy by following this guide, I switched the DATABASE_URL to my proxy connection string in my .env

DATABASE_URL="prisma://..."

I would like to migrate changes to my database. However, after reading this from Prisma on how to migrate changes with their proxy, I refactored my .env vars to include another variable that will be used in an NPM script whenever I wish to migrate some changes (the script essentially swaps the proxy string with the cloud-hosted DB string)

Refactored .env

DATABASE_URL="prisma://..."

MIGRATE_DATABASE_URL="mysql://..."

Npm script inside package.json

{
  ...,
  "scripts": {
    "generate-client": "prisma generate --data-proxy",
    "migrate-deploy": "DATABASE_URL=\"$MIGRATE_DATABASE_URL\" prisma migrate deploy",
    "dev": "DATABASE_URL=\"$MIGRATE_DATABASE_URL\" prisma migrate dev",
  }
}

The Problem: whenever I run npm run migrate-deploy, I recieve this error:
'DATABASE_URL' is not recognized as an internal or external command,
operable program or batch file.


问:
A random pair of audio tags from an array are played when the user clicks a button. How to generate a new pair with a click of a different button? JS
I am making a website where the user can practise their recognition of musical intervals within a range of one octave.

Upon loading, the page randomly selects two notes (audio tags) from an array of 13. There is a large button on the page, that, when pressed, plays the two randomly selected notes.

After identifying the interval, the user should press submit to check their answer and they will be alerted if they are right or wrong.

My goal is that after pressing "submit", a new pair of randomly selected notes will be generated without having to refresh the page. However, I have so far only been able to achieve either always having the same pair of notes, or else having a new random pair of notes being generated every single time the user presses the big button, even if they have not submitted their answer yet.

Here is some of the code I have so far - I've tried to remove as much as possible not relevant to the problem.

intervalButton is the "big button".

```<code>const intervalButton = document.getElementById("quaver-button");
const notes = document.getElementsByTagName("audio");
const notesArray = Array.from(notes);
let randomNote = notesArray[Math.floor(Math.random() * notesArray.length)];
let randomNoteTwo = notesArray[Math.floor(Math.random() * notesArray.length)];
const submitButton = document.getElementById("submit");

intervalButton.addEventListener("click", function() {
    randomNote.play();
    setTimeout(function () {
        randomNoteTwo.play()
    }, 1000);
})

submitButton.addEventListener("click", function() {

    if (code for if user gets answer right) {
        alert("Correct message");
 } else {
        alert("Not correct message");
       }

    })

</code>```

So far I have tried removing my declarations for the variables holding the random notes, and then defining a function to get the random notes instead. I called this function in an event listener when the user clicks the big button, but of course this generates new random notes with every click.

I have also tried redeclaring the random notes in the submit button event listener listed above like so:

```<code>submitButton.addEventListener("click", function() {

    if (code for if user gets answer right) {
        alert("Correct message");
        let randomNote = notesArray[Math.floor(Math.random() * notesArray.length)];
        let randomNoteTwo = notesArray[Math.floor(Math.random() * notesArray.length)];
 } else {
        alert("Not correct message");
       }

    })
</code>```

This still gives me only the two initially generated random notes.

I have tried using my function that gets the random notes in this block too.

I have a fair idea that my problem has something to do with where I am declaring the variables, but so far I am really stuck with this.

Hope this question is acceptable - I got slated (fairly) for my last one but am brand spanking new to all this. Just a few weeks in with JS.

Body:
I am making a website where the user can practise their recognition of musical intervals within a range of one octave.

Upon loading, the page randomly selects two notes (audio tags) from an array of 13. There is a large button on the page, that, when pressed, plays the two randomly selected notes.

After identifying the interval, the user should press submit to check their answer and they will be alerted if they are right or wrong.

My goal is that after pressing "submit", a new pair of randomly selected notes will be generated without having to refresh the page. However, I have so far only been able to achieve either always having the same pair of notes, or else having a new random pair of notes being generated every single time the user presses the big button, even if they have not submitted their answer yet.

Here is some of the code I have so far - I've tried to remove as much as possible not relevant to the problem.

intervalButton is the "big button".

const intervalButton = document.getElementById("quaver-button");
const notes = document.getElementsByTagName("audio");
const notesArray = Array.from(notes);
let randomNote = notesArray[Math.floor(Math.random() * notesArray.length)];
let randomNoteTwo = notesArray[Math.floor(Math.random() * notesArray.length)];
const submitButton = document.getElementById("submit");

intervalButton.addEventListener("click", function() {
    randomNote.play();
    setTimeout(function () {
        randomNoteTwo.play()
    }, 1000);
})

submitButton.addEventListener("click", function() {

    if (code for if user gets answer right) {
        alert("Correct message");
 } else {
        alert("Not correct message");
       }

    })

So far I have tried removing my declarations for the variables holding the random notes, and then defining a function to get the random notes instead. I called this function in an event listener when the user clicks the big button, but of course this generates new random notes with every click.

I have also tried redeclaring the random notes in the submit button event listener listed above like so:

submitButton.addEventListener("click", function() {

    if (code for if user gets answer right) {
        alert("Correct message");
        let randomNote = notesArray[Math.floor(Math.random() * notesArray.length)];
        let randomNoteTwo = notesArray[Math.floor(Math.random() * notesArray.length)];
 } else {
        alert("Not correct message");
       }

    })

This still gives me only the two initially generated random notes.

I have tried using my function that gets the random notes in this block too.

I have a fair idea that my problem has something to do with where I am declaring the variables, but so far I am really stuck with this.

Hope this question is acceptable - I got slated (fairly) for my last one but am brand spanking new to all this. Just a few weeks in with JS.


问:
Close parent div when :after pseudo element is clicked using Javascript
I have a UI that has a couple of modals (open by default). I want to be able to close them when clicking a child element. There are then 2 separate links that can reopen the modals if they've been closed.

My close button uses a pseudo class like this .hgroup:after.

I haven't been able to get this to work, is it possible to trigger a click event on a before/after pseudo element? Or will I need to rework my markup to include a physical button or link?

Thanks in advance!

const finder = document.querySelector('.finder');
const closeBtn = document.querySelector('.hgroup:after');

closeBtn.addEventListener("click", function() {
    finder.classList.add('hidden');
});

const openAbout = document.querySelector('.desktop-icon__about');
const openGallery = document.querySelector('.desktop-icon__gallery');
const finderAbout = document.querySelector('.finder--about');
const finderGallery = document.querySelector('.finder--gallery');

openAbout.addEventListener("click", function() {
    finderAbout.classList.remove('hidden');
});

openGallery.addEventListener("click", function() {
    finderGallery.classList.remove('hidden');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.finder {
  background: #eee;
  height: 100px;
  margin-bottom: 12px;
  width: 200px;
}

finder.hidden {
  display: none;
}

.hgroup {
  display: flex;
  align-items: center;
  justify-content: space-between;
  position: relative;
  padding: 0 4px;
}

.hgroup:after {
  background: red;
  content: "";
  display: flex;
  height: 10px;
  cursor: pointer;
  width: 10px;
}

.desktop-icon {
  margin-right: 8px;
}</code>```

    Open About

    Open Gallery

About Box

Gallery Box

```

Body:
I have a UI that has a couple of modals (open by default). I want to be able to close them when clicking a child element. There are then 2 separate links that can reopen the modals if they've been closed.

My close button uses a pseudo class like this .hgroup:after.

I haven't been able to get this to work, is it possible to trigger a click event on a before/after pseudo element? Or will I need to rework my markup to include a physical button or link?

Thanks in advance!

const finder = document.querySelector('.finder');
const closeBtn = document.querySelector('.hgroup:after');

closeBtn.addEventListener("click", function() {
    finder.classList.add('hidden');
});

const openAbout = document.querySelector('.desktop-icon__about');
const openGallery = document.querySelector('.desktop-icon__gallery');
const finderAbout = document.querySelector('.finder--about');
const finderGallery = document.querySelector('.finder--gallery');

openAbout.addEventListener("click", function() {
    finderAbout.classList.remove('hidden');
});

openGallery.addEventListener("click", function() {
    finderGallery.classList.remove('hidden');
});

.finder {
  background: #eee;
  height: 100px;
  margin-bottom: 12px;
  width: 200px;
}

finder.hidden {
  display: none;
}

.hgroup {
  display: flex;
  align-items: center;
  justify-content: space-between;
  position: relative;
  padding: 0 4px;
}

.hgroup:after {
  background: red;
  content: "";
  display: flex;
  height: 10px;
  cursor: pointer;
  width: 10px;
}

.desktop-icon {
  margin-right: 8px;
}

    Open About

    Open Gallery

About Box

Gallery Box


问:
How do know, what is humanreadble result in Keras?
I have some train data, floats numbers (in some random order preferbly), which i turn into binary matrix using:
Y_train_enc = keras.utils.to_categorical(Y_train, number_classes)

My question is following, after I use model.predict to get result, (Which is supposed to be also number) I get matrix of  probalities. Now how I know what is the result, from this matrix? i.e. what is number that NN outputs?.

Also I don't understand if keras.utils.to_categorical() makes classes of floats for example if Y_train=[0,0.1,1] will be able to do it?