问:
Why laravel mix copy function does not work?
im tryng to make a copy of a js file that exist in node_modules to the public folder to try to use the javascript files on node_modules only when i need in specific parts of the system.

when i try to make a copy using mix.copy('node_modules/select2/dist/select2.min.js', 'public/vendor/js/'). the error i get is:

```<code>[webpack-cli] [Error: ENOENT: no such file or directory, lstat 'C:\laragon\www\project\node_modules\select2\dist\select2.min.js'] {
  errno: -4058,
  code: 'ENOENT',
  syscall: 'lstat',
  path: 'C:\\laragon\\www\\project\\node_modules\\select2\\dist\\select2.min.js'
}
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! @ development: `mix`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the @ development script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\OfficeUser\AppData\Roaming\npm-cache\_logs\2023-01-10T15_51_48_679Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! @ dev: `npm run development`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the @ dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\OfficeUser\AppData\Roaming\npm-cache\_logs\2023-01-10T15_51_48_721Z-debug.log

</code>```

What should i do now, is the file path incorrectly written?

Body:
im tryng to make a copy of a js file that exist in node_modules to the public folder to try to use the javascript files on node_modules only when i need in specific parts of the system.

when i try to make a copy using mix.copy('node_modules/select2/dist/select2.min.js', 'public/vendor/js/'). the error i get is:

[webpack-cli] [Error: ENOENT: no such file or directory, lstat 'C:\laragon\www\project\node_modules\select2\dist\select2.min.js'] {
  errno: -4058,
  code: 'ENOENT',
  syscall: 'lstat',
  path: 'C:\\laragon\\www\\project\\node_modules\\select2\\dist\\select2.min.js'
}
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! @ development: `mix`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the @ development script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\OfficeUser\AppData\Roaming\npm-cache\_logs\2023-01-10T15_51_48_679Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! @ dev: `npm run development`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the @ dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\OfficeUser\AppData\Roaming\npm-cache\_logs\2023-01-10T15_51_48_721Z-debug.log

What should i do now, is the file path incorrectly written?


来源: stackexchange

问:
Raspberry Pi 4: Keep the Physical Pin output remain HIGH until set to LOW
Looks like I just discovered something from the Raspberry Pi board. That is, command GPIO.output(led_pin,GPIO.HIGH) sets the output pin high only momentary. I originally thought it keeps the led_pin HIGH until I set it OFF. I was wrong. Again, I have to give time command to tell how long to keep it HIGH.

My question is, how to make the Pin output remain HIGH once set unless I set it again to LOW.

My code for keeping the Pin output HIGH for 5 seconds:

```<code>import RPi.GPIO as GPIO
import time

# To disable warning in the console
GPIO.setwarnings(False)

led_pin = 17
GPIO.setmode(GPIO.BCM)
GPIO.setup(led_pin,GPIO.OUT)

# Set the led Pin to HIGH
GPIO.output(led_pin,GPIO.HIGH)
# Keep led ON for 5 seconds
time.sleep(5)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Looks like I just discovered something from the Raspberry Pi board. That is, command GPIO.output(led_pin,GPIO.HIGH) sets the output pin high only momentary. I originally thought it keeps the led_pin HIGH until I set it OFF. I was wrong. Again, I have to give time command to tell how long to keep it HIGH.

My question is, how to make the Pin output remain HIGH once set unless I set it again to LOW.

My code for keeping the Pin output HIGH for 5 seconds:

import RPi.GPIO as GPIO
import time

# To disable warning in the console
GPIO.setwarnings(False)

led_pin = 17
GPIO.setmode(GPIO.BCM)
GPIO.setup(led_pin,GPIO.OUT)

# Set the led Pin to HIGH
GPIO.output(led_pin,GPIO.HIGH)
# Keep led ON for 5 seconds
time.sleep(5)


问:
Image Thumbnail and Title in bottom
Respectable Gurus
I am running website (https://urdunovelcollection.com/), I just want to convert books thumbnail just like using in gsmarena.com mobile thumbnail, I am not great in styling things, It will be great if someone share some html and css code here, Please help me to resolve my problem.

Title: Image Thumbnail and Title in bottom


问:
Getting BERT embeddings AFTER fine-tuning
I've been using this repo: https://github.com/google-research/bert

I know how to extract the pre-trained BERT embeddings. But I would like to get the embeddings after fine-tuning. I am assuming I need to save an object that's in the run_classifier.py file.


问:
FLUTTER: Execution failed for task ':flutter_plugin_android_lifecycle:generateDebugRFile'
I was trying to integrate google maps in my app. However, since I updated the minSdkVersion to 21. I am facing this problem.

My build.gradle

```<code>def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
    compileSdkVersion flutter.compileSdkVersion
    ndkVersion flutter.ndkVersion

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = '1.8'
    }

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "sarnyp.com.sarnyp"
        // You can update the following values to match your application needs.
        // For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-build-configuration.
        minSdkVersion 21
        targetSdkVersion flutter.targetSdkVersion
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
}

</code>```

The error I get on loop.

```<code>Launching lib/main.dart on Android SDK built for arm64 in debug mode...
Running Gradle task 'assembleDebug'...
Warning: Failed to parse host user

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':flutter_plugin_android_lifecycle:generateDebugRFile'.
> Could not resolve all files for configuration ':flutter_plugin_android_lifecycle:debugCompileClasspath'.
   > Could not resolve org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.5.30.
     Required by:
         project :flutter_plugin_android_lifecycle > org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.5.30

</code>```

Please help!

I tried to change http proxy settings, but it did no good. I even ran flutter clean, uninstalled and reinstalled both flutter and android studio, but it had no effects.

Body:
I was trying to integrate google maps in my app. However, since I updated the minSdkVersion to 21. I am facing this problem.

My build.gradle

def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
    compileSdkVersion flutter.compileSdkVersion
    ndkVersion flutter.ndkVersion

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = '1.8'
    }

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "sarnyp.com.sarnyp"
        // You can update the following values to match your application needs.
        // For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-build-configuration.
        minSdkVersion 21
        targetSdkVersion flutter.targetSdkVersion
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
}

The error I get on loop.

Launching lib/main.dart on Android SDK built for arm64 in debug mode...
Running Gradle task 'assembleDebug'...
Warning: Failed to parse host user

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':flutter_plugin_android_lifecycle:generateDebugRFile'.
> Could not resolve all files for configuration ':flutter_plugin_android_lifecycle:debugCompileClasspath'.
   > Could not resolve org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.5.30.
     Required by:
         project :flutter_plugin_android_lifecycle > org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.5.30

Please help!

I tried to change http proxy settings, but it did no good. I even ran flutter clean, uninstalled and reinstalled both flutter and android studio, but it had no effects.


问:
I tried to use maven in cmd, but I don't get the generated .jar file in the specified location
I used mvn clean package -DoutputDirectory=<my path>, but I don't get compiled .jar file in my listed output directory via command prompt, does anyone knows, how to fix it in the cmd?

Here's my debug configuration from Intellij IDEA Community:
https://i.imgur.com/KDnLYDV.png


问:
It is possible to show two sibling models into one's inline admin
I have one parent model, called Farmer, which has foreign key relationship with two child models namely, FarmerAdvisory and ImageDetail.
I want to show ImageDetail as an inline model to FarmerAdvisory in admin panel.

Is this possible?

FarmerAdvisory Models.py

```<code>class FarmerAdvisory(BaseModel):

STATUS_CHOICES = (
    ('OPEN', 'OPEN'),
    ('CLOSED', 'CLOSED')
)
id = models.AutoField(db_column='id', primary_key=True)
category = models.CharField(db_column='category', max_length=50, null=False, blank=False)
sub_category = models.CharField(db_column='sub_category', max_length=100, null=True, blank=True)
title = models.CharField(db_column='title', max_length=200, null=True, blank=True)
description = models.CharField(db_column='description', max_length=750, null=True, blank=True)
status = models.CharField(db_column='status', max_length=20, null=False, blank=False, default='OPEN',
                          choices=STATUS_CHOICES)
farmer_id = models.ForeignKey(Farmer, on_delete=models.CASCADE, null=True, db_column='farmer_id')
objects = models.Manager()

class Meta:
    managed = True
    db_table = 'farmer_advisory'
</code>```

ImageDetails Models.py

```<code>class ImageDetail(BaseModel):
id = models.AutoField(db_column='id', primary_key=True)
filename = models.CharField(db_column='filename', max_length=100)
ref_type = models.CharField(db_column='ref_type', max_length=20, choices=ImageRefType)
ref_sub_type = models.CharField(db_column='ref_sub_type', max_length=100, blank=True, null=True)
ref_id = models.IntegerField(db_column='ref_id', blank=True, null=True)
farmer_id = models.ForeignKey('Farmer', models.DO_NOTHING, db_column='farmer_id', blank=True, null=True)
objects = models.Manager()

class Meta:
    managed = True
    db_table = 'image_detail'
</code>```

Body:
I have one parent model, called Farmer, which has foreign key relationship with two child models namely, FarmerAdvisory and ImageDetail.
I want to show ImageDetail as an inline model to FarmerAdvisory in admin panel.

Is this possible?

FarmerAdvisory Models.py

class FarmerAdvisory(BaseModel):

STATUS_CHOICES = (
    ('OPEN', 'OPEN'),
    ('CLOSED', 'CLOSED')
)
id = models.AutoField(db_column='id', primary_key=True)
category = models.CharField(db_column='category', max_length=50, null=False, blank=False)
sub_category = models.CharField(db_column='sub_category', max_length=100, null=True, blank=True)
title = models.CharField(db_column='title', max_length=200, null=True, blank=True)
description = models.CharField(db_column='description', max_length=750, null=True, blank=True)
status = models.CharField(db_column='status', max_length=20, null=False, blank=False, default='OPEN',
                          choices=STATUS_CHOICES)
farmer_id = models.ForeignKey(Farmer, on_delete=models.CASCADE, null=True, db_column='farmer_id')
objects = models.Manager()

class Meta:
    managed = True
    db_table = 'farmer_advisory'

ImageDetails Models.py

class ImageDetail(BaseModel):
id = models.AutoField(db_column='id', primary_key=True)
filename = models.CharField(db_column='filename', max_length=100)
ref_type = models.CharField(db_column='ref_type', max_length=20, choices=ImageRefType)
ref_sub_type = models.CharField(db_column='ref_sub_type', max_length=100, blank=True, null=True)
ref_id = models.IntegerField(db_column='ref_id', blank=True, null=True)
farmer_id = models.ForeignKey('Farmer', models.DO_NOTHING, db_column='farmer_id', blank=True, null=True)
objects = models.Manager()

class Meta:
    managed = True
    db_table = 'image_detail'


问:
Read thread is stopped for socket
The below log messages   indicate that the connection between my client and the server is being closed by the server since i am getting "Read thread is stopped for socket" from the Wireshark the  message indicates that the server is closing the connection after it has sent the final "ACK" message indeed , the server is sending a FIN,ACK after the client sends a Capabilities-Exchange message. This suggests that the server is properly receiving the client's message, but for some reason it is not responding with a message of its own and instead is closing the connection. the localhost is my laptop ,  below is the logs

```<code>2023-01-09 13:11:43,946 INFO DictionaryImpl - Mobicents Diameter Dictionary loaded in 188ms -- Vendors[10] Commands[52] Types[20] AVPs[510]

2023-01-09 13:11:44,044 INFO StackImpl - (-)(-)(-)(-)(-) Started Mobicents DIAMETER Stack v1.5.10.0-build639 (-)(-)(-)(-)(-)

2023-01-09 13:11:44,544 INFO StackCreator - Diameter CLIENT :: Adding Listener for [AppId [Vendor-Id:0; Auth-Application-Id:4; Acct-Application-Id:0]].

2023-01-09 13:11:44,547 INFO StackCreator - Diameter CLIENT :: Supporting 1 applications.

2023-01-09 13:11:45,152 INFO NetworkGuard - Open server socket ServerSocket[addr=/127.0.0.1,localport=8080]

2023-01-09 13:12:00,267 INFO TCPTransportClient - Read thread is stopped for socket [Socket[addr=10.10.10.113/10.10.203.113,port=3868,localport=60884]]
2023-01-09 13:12:00,267 INFO TCPTransportClient - Read thread is stopped for socket [Socket[addr=10.10.10.113/10.105.10.113,port=3868,localport=60884]]
2023-01-09 13:12:00,267 INFO TCPTransportClient - Read thread is stopped for socket [Socket[addr=10.10.10.113/10.105.10.113,port=3868,localport=60884]]
</code>```

do you have any idea please

I am expecting to connect to the server and send sendInitial request

Title: Read thread is stopped for socket

Body:
The below log messages   indicate that the connection between my client and the server is being closed by the server since i am getting "Read thread is stopped for socket" from the Wireshark the  message indicates that the server is closing the connection after it has sent the final "ACK" message indeed , the server is sending a FIN,ACK after the client sends a Capabilities-Exchange message. This suggests that the server is properly receiving the client's message, but for some reason it is not responding with a message of its own and instead is closing the connection. the localhost is my laptop ,  below is the logs

2023-01-09 13:11:43,946 INFO DictionaryImpl - Mobicents Diameter Dictionary loaded in 188ms -- Vendors[10] Commands[52] Types[20] AVPs[510]

2023-01-09 13:11:44,044 INFO StackImpl - (-)(-)(-)(-)(-) Started Mobicents DIAMETER Stack v1.5.10.0-build639 (-)(-)(-)(-)(-)

2023-01-09 13:11:44,544 INFO StackCreator - Diameter CLIENT :: Adding Listener for [AppId [Vendor-Id:0; Auth-Application-Id:4; Acct-Application-Id:0]].

2023-01-09 13:11:44,547 INFO StackCreator - Diameter CLIENT :: Supporting 1 applications.

2023-01-09 13:11:45,152 INFO NetworkGuard - Open server socket ServerSocket[addr=/127.0.0.1,localport=8080]

2023-01-09 13:12:00,267 INFO TCPTransportClient - Read thread is stopped for socket [Socket[addr=10.10.10.113/10.10.203.113,port=3868,localport=60884]]
2023-01-09 13:12:00,267 INFO TCPTransportClient - Read thread is stopped for socket [Socket[addr=10.10.10.113/10.105.10.113,port=3868,localport=60884]]
2023-01-09 13:12:00,267 INFO TCPTransportClient - Read thread is stopped for socket [Socket[addr=10.10.10.113/10.105.10.113,port=3868,localport=60884]]

do you have any idea please

I am expecting to connect to the server and send sendInitial request


问:
Local reverse video search
Problem: i have a small portion of a video and a screenshot.. and i know i should also have the full version of the video somewhere stored locally on my harddrive... somewhere between all those unorganised videos.

Is there a programme/tool that can scan this small portion/screenshot and then goes through all the videos on the harddrive to find the matching full video? or does anyone have any other ideas?

I thought this was something that already had an existing solution on the WWW.. but i have been searching for 2 hours now and can only find solutions for online content (youtube, google ect) and not for files i have stored locally.

Anyone that can help me out / point me in the right direction?

Title: Local reverse video search


问:
MySQL Query GROUP BY IN PERIODS OF 45 DAYS
I'm creating a MySQL query but a I have an issue with GROUP BY.
The idea is try to count the frequency of purchases in two different periods, from yesterday to 45 days ago (frequency_m), and from 46 days to 91 days ago (frequency_n), but it's not working properly. I think the issue is that in GROUP BY I have to group in periods of 45 days

The code is:

```<code>SELECT customerId,

        COUNT(CASE
            WHEN (TIMESTAMPDIFF(DAY, date, now()) > 1 AND TIMESTAMPDIFF(DAY,
                  date, now()) <= 46)
            THEN paymentId
            END) AS "Frequency_m",

        COUNT(CASE
            WHEN (TIMESTAMPDIFF(DAY, date, now()) > 46 AND TIMESTAMPDIFF(DAY,
                  date, now()) <= 91)
            THEN paymentId
            END) AS "Frequency_n"

  FROM payments
       WHERE date > ADDDATE(now(),-91)

       GROUP BY customerId, date
</code>```

Body:
I'm creating a MySQL query but a I have an issue with GROUP BY.
The idea is try to count the frequency of purchases in two different periods, from yesterday to 45 days ago (frequency_m), and from 46 days to 91 days ago (frequency_n), but it's not working properly. I think the issue is that in GROUP BY I have to group in periods of 45 days

The code is:

SELECT customerId,

        COUNT(CASE
            WHEN (TIMESTAMPDIFF(DAY, date, now()) > 1 AND TIMESTAMPDIFF(DAY,
                  date, now()) <= 46)
            THEN paymentId
            END) AS "Frequency_m",

        COUNT(CASE
            WHEN (TIMESTAMPDIFF(DAY, date, now()) > 46 AND TIMESTAMPDIFF(DAY,
                  date, now()) <= 91)
            THEN paymentId
            END) AS "Frequency_n"

  FROM payments
       WHERE date > ADDDATE(now(),-91)

       GROUP BY customerId, date


问:
Why the progress bar does not advance or move in shiny
I would like you to help me to understand why when I calculate the information in this shiny, the progress bar does not advance or go up indicating when it is still to finish the calculation done.

```<code>library(shiny)
library(shinydashboard)
library(shinythemes)
library(dplyr)
library(progressr)
library(lavaan)

#Example of data to load
df1 <- read.csv("https://raw.githubusercontent.com/jventural/Download/main/df1.csv", sep = ";")

#ui.r
ui <- fluidPage(
  #
  sidebarLayout(
    # Main panel ----------------
    sidebarPanel(
      sidebarMenu(
                   menuItem("Calculadora", tabName = "sect_a")

      )
    ),

    mainPanel(
        # Calculator ----------
        tabItem(
          tabName = "sect_a",
          tabsetPanel(
            id="tabA",
            type = "tabs",
            tabPanel("Calculando omega",
                     fileInput("datafile", "Choose CSV File", accept = ".csv"),

                     actionButton(inputId = "click1", "Calcular"),
                     fluidPage(
                       HTML("<b> Nota: </b> El nombre de los items debe ser: Item1, Item2... etc")
                     )
            ),
            tabPanel("Output", tableOutput("modifiedData")
            ))
        )

    )
  )
)

#server.r

server = function(input, output) {

  # Calculadora -----------
  result = eventReactive(list(input$datafile, input$click1),
                         {
                           req(input$click1)
                           raw_df <- read.csv(input$datafile$datapath, sep=";")

                           IC <-
                             MBESS::ci.reliability(data = raw_df %>% select(starts_with("Item")), N = nrow(raw_df), type = "categorical", interval.type = "perc", B = 10)

                         })

  output$modifiedData = renderTable({
    withProgress(message = 'Calculando',
                 detail = 'Espera un momento...', value = 0, {
                   result()
                 })
    result()

  })

}

shinyApp(ui, server)
</code>```

I remain attentive to your suggestions

I am posting the codes so that you can see what I have been trying to do.

Body:
I would like you to help me to understand why when I calculate the information in this shiny, the progress bar does not advance or go up indicating when it is still to finish the calculation done.

library(shiny)
library(shinydashboard)
library(shinythemes)
library(dplyr)
library(progressr)
library(lavaan)

#Example of data to load
df1 <- read.csv("https://raw.githubusercontent.com/jventural/Download/main/df1.csv", sep = ";")

#ui.r
ui <- fluidPage(
  #
  sidebarLayout(
    # Main panel ----------------
    sidebarPanel(
      sidebarMenu(
                   menuItem("Calculadora", tabName = "sect_a")

      )
    ),

    mainPanel(
        # Calculator ----------
        tabItem(
          tabName = "sect_a",
          tabsetPanel(
            id="tabA",
            type = "tabs",
            tabPanel("Calculando omega",
                     fileInput("datafile", "Choose CSV File", accept = ".csv"),

                     actionButton(inputId = "click1", "Calcular"),
                     fluidPage(
                       HTML(" Nota:  El nombre de los items debe ser: Item1, Item2... etc")
                     )
            ),
            tabPanel("Output", tableOutput("modifiedData")
            ))
        )

    )
  )
)

#server.r

server = function(input, output) {

  # Calculadora -----------
  result = eventReactive(list(input$datafile, input$click1),
                         {
                           req(input$click1)
                           raw_df <- read.csv(input$datafile$datapath, sep=";")

                           IC <-
                             MBESS::ci.reliability(data = raw_df %>% select(starts_with("Item")), N = nrow(raw_df), type = "categorical", interval.type = "perc", B = 10)

                         })

  output$modifiedData = renderTable({
    withProgress(message = 'Calculando',
                 detail = 'Espera un momento...', value = 0, {
                   result()
                 })
    result()

  })

}

shinyApp(ui, server)

I remain attentive to your suggestions

I am posting the codes so that you can see what I have been trying to do.


问:
chart-js - npm install show version conflicts
after the clone of the latest 4.1.2 version of Chart.js I tried to set up the environment using
npm install the result is a version conflict

npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree

details see below.

from my understanding the rollup installation should work "^3.x.x" === ">=3.x.x" so 3.9.1 should fit (https://github.com/isaacs/node-semver "^3.3.0" === "3.3.0" <= V < 4.x.x)
rollup-7.0.2 will not fit ("^2.0.0" <= V <= "3.x.x" < 7.x.x)

If I do this using npm install --legacy-peer-deps the result is a deprecated package message-

npm WARN deprecated har-validator@5.1.5: this library is no longer supported

Details below.

It is ubuntu server 22.04LTS with nodes (incl. npm) from nodesource (node 18.12.1, npm 8.19.2).

Any hints are welcome.

I did

npm install

result:
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: chart.js@4.1.2
npm ERR! Found: rollup@3.9.1
npm ERR! node_modules/rollup
npm ERR!   dev rollup@"^3.3.0" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer rollup@"^2.0.0" from rollup-plugin-terser@7.0.2
npm ERR! node_modules/rollup-plugin-terser
npm ERR!   dev rollup-plugin-terser@"^7.0.2" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.

and
npm install --legacy-peer-deps


问:
Huobi swap linear get balance error #4002
when i run my code in huobi i get this error

TypeError: ('An error occured in get_balance_of_one_coin', ExchangeError('huobi {"status":"error","err_code":4002,"err_msg":"The merged cross and isolated margin account for USDT-M futures is unavailable.Please complete the query with linear-swap-api/v3/unified_account_info","ts":1673360055153}')


问:
How to trigger change in html select when using ref
React app with hooks.

```<code>const [regions, setRegions] = useState([]);
const [cities, setCities] = useState([]);
const regionRef = useRef(null);
const cityRef = useRef(null);

const citiesAndRegions = [
    {
        _id: 123, name: 'California', cities: [{id: 'abc', name: 'LA'},{id: 'efg', name: 'Hollywood'}]
    },
    {
        ,_id: 456, name: 'Florida', cities: [{id: 'hji', name: 'Miami'}]
    }
];

const regionChanged = async (id) => {
    const found = citiesAndRegions.find(el => el._id === id);
    setCities(found.cities);
}

useEffect(() => {
    const fetchRegions = async () => {
        const region_result = [{_id: 123, name: 'California',_id: 456, name: 'Florida'}];
        region_result.forEach(el => {
            el.value = el._id;
            el.label = el.name;
        });
        setRegions(region_result);
    }
    const setDefaultValues = async () => {
        const user = {name: 'Jack', region: 123, city: 'abc'};
        await fetchRegions();
        regionRef.current.value = user.region;
        await regionChanged(user.region);
        cityRef.current.value = user.city;
    }
    setDefaultValues().catch(console.error);
}, []);

return(
    <select ref={regionRef} onChange={e => regionChanged(e.target.value)}>
        {
            regions.map((opt, index) =>
                <option key={index} value={opt.value}>{opt.label}</option>
            )
        }
    </select>
    <select ref={cityRef}>
        {
            cities.map((opt, index) =>
                <option key={index} value={opt.id}>{opt.name}</option>
            )
        }
    </select>
);
</code>```

So in function useEffect I fetch first data about the user. Then all the regions. Then I set the reference for the region. After that, I trigger the change od the regions which implies fetching the cities. And at the end I set the current value for the city reference.

What happens is that all the regions are in the select box. And region "California" is selected. Moreover, in the city-select I see all the cities for the California region. However, the city with id "abc" (which is "LA") is not getting selected.
How do I trigger this change?

Body:
React app with hooks.

const [regions, setRegions] = useState([]);
const [cities, setCities] = useState([]);
const regionRef = useRef(null);
const cityRef = useRef(null);

const citiesAndRegions = [
    {
        _id: 123, name: 'California', cities: [{id: 'abc', name: 'LA'},{id: 'efg', name: 'Hollywood'}]
    },
    {
        ,_id: 456, name: 'Florida', cities: [{id: 'hji', name: 'Miami'}]
    }
];

const regionChanged = async (id) => {
    const found = citiesAndRegions.find(el => el._id === id);
    setCities(found.cities);
}

useEffect(() => {
    const fetchRegions = async () => {
        const region_result = [{_id: 123, name: 'California',_id: 456, name: 'Florida'}];
        region_result.forEach(el => {
            el.value = el._id;
            el.label = el.name;
        });
        setRegions(region_result);
    }
    const setDefaultValues = async () => {
        const user = {name: 'Jack', region: 123, city: 'abc'};
        await fetchRegions();
        regionRef.current.value = user.region;
        await regionChanged(user.region);
        cityRef.current.value = user.city;
    }
    setDefaultValues().catch(console.error);
}, []);

return(
    <select ref={regionRef} onChange={e => regionChanged(e.target.value)}>
        {
            regions.map((opt, index) =>
                <option key={index} value={opt.value}>{opt.label}</option>
            )
        }
    </select>
    <select ref={cityRef}>
        {
            cities.map((opt, index) =>
                <option key={index} value={opt.id}>{opt.name}</option>
            )
        }
    </select>
);

So in function useEffect I fetch first data about the user. Then all the regions. Then I set the reference for the region. After that, I trigger the change od the regions which implies fetching the cities. And at the end I set the current value for the city reference.

What happens is that all the regions are in the select box. And region "California" is selected. Moreover, in the city-select I see all the cities for the California region. However, the city with id "abc" (which is "LA") is not getting selected.
How do I trigger this change?


问:
exceCommand insertText inserting text twice when the text size is longer than specific character?
So I'm working on a chrome extension that inserts some texts in the twitter text field.

The following code works completely fine in chrome console,

```<code>document.getElementsByClassName("notranslate public-DraftEditor-content")[0].click();
document.execCommand('insertText', false, "A reply");
</code>```

But the same code for some reasons repeats itself while using through chrome extension after a button click, the text element repeats twice.

Even after that only the first part of text is editable, and the second part is not for some reasons. This issue never happens while using it through console. But sometimes the extension also work fine.

After some debugging I realized that the function is getting called only once which is fine, but when the tweet it's replying to is longer than a few words, the extension inserting text twice for some reasons, and when the parent tweet is 3-4 words, it works just fine.

Example
https://twitter.com/BuckyDroid/status/1612838966105112576

So something going on when using the execCommand function through extension. Any suggestion how can I fix it?

Body:
So I'm working on a chrome extension that inserts some texts in the twitter text field.

The following code works completely fine in chrome console,

document.getElementsByClassName("notranslate public-DraftEditor-content")[0].click();
document.execCommand('insertText', false, "A reply");

But the same code for some reasons repeats itself while using through chrome extension after a button click, the text element repeats twice.

Even after that only the first part of text is editable, and the second part is not for some reasons. This issue never happens while using it through console. But sometimes the extension also work fine.

After some debugging I realized that the function is getting called only once which is fine, but when the tweet it's replying to is longer than a few words, the extension inserting text twice for some reasons, and when the parent tweet is 3-4 words, it works just fine.

Example
https://twitter.com/BuckyDroid/status/1612838966105112576

So something going on when using the execCommand function through extension. Any suggestion how can I fix it?


问:
the first calculation with torch.einsum is much slower
When I run several calculations with torch.einsum in a row, the first one is always much slower than the following calculations.

The following code and plot illustrates the problem:

```<code>import torch as tor
from timeit import default_timer as timer

N = 1000
L = 10

time_arr = np.zeros(L)

for i in range(L):
    a = tor.randn(N, N).to("cuda:0") #3 random 1000x1000 matrices for each cycle
    b = tor.randn(N, N).to("cuda:0")
    c = tor.randn(N, N).to("cuda:0")

    time_start  = timer()
    tor.einsum("ij, kj",tor.einsum("ij, ja",  aa, ab), ac)
    time_end  = timer()

    time_arr[i] = time_end - time_start
</code>```

Plot of the different times for each cylce of the loop

Body:
When I run several calculations with torch.einsum in a row, the first one is always much slower than the following calculations.

The following code and plot illustrates the problem:

import torch as tor
from timeit import default_timer as timer

N = 1000
L = 10

time_arr = np.zeros(L)

for i in range(L):
    a = tor.randn(N, N).to("cuda:0") #3 random 1000x1000 matrices for each cycle
    b = tor.randn(N, N).to("cuda:0")
    c = tor.randn(N, N).to("cuda:0")

    time_start  = timer()
    tor.einsum("ij, kj",tor.einsum("ij, ja",  aa, ab), ac)
    time_end  = timer()

    time_arr[i] = time_end - time_start

Plot of the different times for each cylce of the loop


问:
Passing secure parameter to PowerShell DSC script from Bicep template
I am using a Bicep template to deploy a virtual machine with a PowerShell DSC script that adds a Log Analytics workspace to the Log Analytics agent. The script uses a secure parameter (workspaceKey1) which is defined in the template and pulled from a key vault. When running the script, I'm getting the following error:

" Performing the operation "Set-TargetResource" on target "Executing the SetScript with the user supplied credential"."},
PowerShell DSC resource MSFT_ScriptResource  failed to execute Set-TargetResource functionality with error message: Value does not fall within the expected range."

A simplified version of the script is below.

```<code>Configuration MmaMultihoming

{

    Param (
        [string] $workspaceId1,
        [System.Management.Automation.PSCredential] $workspaceKey1,
    )

    Import-DscResource -ModuleName PSDesiredStateConfiguration;
    Import-DscResource -ModuleName xPSDesiredStateConfiguration;

    [System.Management.Automation.PSCredential]$workspaceKey1 = New-Object System.Management.Automation.PSCredential ($workspaceKey1.userName, $workspaceKey1.password)

    Node localhost {

        Script ConfigureWorkspace
        {
            SetScript =
            {
                $workspaceId = $Using:workspaceId1;
                $workspaceKey = $Using:workspaceKey1;
                $mma = New-Object -ComObject 'AgentConfigManager.MgmtSvcCfg';
                $mma.AddCloudWorkspace($workspaceId, $workspaceKey);
                $mma.ReloadConfiguration();
            }

            TestScript = { Test-Path "HKLM:\SYSTEM\ControlSet001\Services\HealthService\Parameters\Service Connector Services\Log Analytics - $($Using:workspaceId)"}
            GetScript = { @{ Result = (Get-ChildItem "HKLM:\SYSTEM\ControlSet001\Services\HealthService\Parameters\Service Connector Services")} }
        }
    }
}

</code>```

The Bicep code is below:

```<code>
param keyvaultName string = 'keyvault'
param kvResourceGroup string = 'keyvault-rg'
param workspaceId1 string
@secure()
param workspaceKey1 string = kv.getSecret('workspaceKey1')

resource kv 'Microsoft.KeyVault/vaults@2022-07-01' existing = {
  name: keyvaultName
  scope: resourceGroup(kvResourceGroup )
}

resource DSC_LogAnalytics 'Microsoft.Compute/virtualMachines/extensions@2022-08-01' = {
  parent: vm1
  name: 'Microsoft.Powershell.DSC'
  location: location
  properties: {
    publisher: 'Microsoft.PowerShell'
    type: 'DSC'
    typeHandlerVersion: '2.77'
    autoUpgradeMinorVersion: true
    settings: {
      wmfVersion: 'latest'
      configuration: {
        url: dscScript
        script: 'dsc.ps1'
        function: 'MmaMultihoming'
      }
      configurationArguments: {
        workspaceId1: workspaceId1
      }
      privacy: {
        datacollection: 'enable'
      }
      advancedOptions: {
        forcePullAndApply: false

      }
    }
    protectedSettings: {
      configurationArguments: {
        workspaceKey1: {
          userName: 'donotuse'
          password: workspaceKey1
        }

    }
    configurationUrlSasToken: SaaStoken
    }

  }

}

</code>```

I am really quite stuck so would appreciate any ideas people can give.

Thanks!

Body:
I am using a Bicep template to deploy a virtual machine with a PowerShell DSC script that adds a Log Analytics workspace to the Log Analytics agent. The script uses a secure parameter (workspaceKey1) which is defined in the template and pulled from a key vault. When running the script, I'm getting the following error:

" Performing the operation "Set-TargetResource" on target "Executing the SetScript with the user supplied credential"."},
PowerShell DSC resource MSFT_ScriptResource  failed to execute Set-TargetResource functionality with error message: Value does not fall within the expected range."

A simplified version of the script is below.

Configuration MmaMultihoming

{

    Param (
        [string] $workspaceId1,
        [System.Management.Automation.PSCredential] $workspaceKey1,
    )

    Import-DscResource -ModuleName PSDesiredStateConfiguration;
    Import-DscResource -ModuleName xPSDesiredStateConfiguration;

    [System.Management.Automation.PSCredential]$workspaceKey1 = New-Object System.Management.Automation.PSCredential ($workspaceKey1.userName, $workspaceKey1.password)

    Node localhost {

        Script ConfigureWorkspace
        {
            SetScript =
            {
                $workspaceId = $Using:workspaceId1;
                $workspaceKey = $Using:workspaceKey1;
                $mma = New-Object -ComObject 'AgentConfigManager.MgmtSvcCfg';
                $mma.AddCloudWorkspace($workspaceId, $workspaceKey);
                $mma.ReloadConfiguration();
            }

            TestScript = { Test-Path "HKLM:\SYSTEM\ControlSet001\Services\HealthService\Parameters\Service Connector Services\Log Analytics - $($Using:workspaceId)"}
            GetScript = { @{ Result = (Get-ChildItem "HKLM:\SYSTEM\ControlSet001\Services\HealthService\Parameters\Service Connector Services")} }
        }
    }
}

The Bicep code is below:

param keyvaultName string = 'keyvault'
param kvResourceGroup string = 'keyvault-rg'
param workspaceId1 string
@secure()
param workspaceKey1 string = kv.getSecret('workspaceKey1')

resource kv 'Microsoft.KeyVault/vaults@2022-07-01' existing = {
  name: keyvaultName
  scope: resourceGroup(kvResourceGroup )
}

resource DSC_LogAnalytics 'Microsoft.Compute/virtualMachines/extensions@2022-08-01' = {
  parent: vm1
  name: 'Microsoft.Powershell.DSC'
  location: location
  properties: {
    publisher: 'Microsoft.PowerShell'
    type: 'DSC'
    typeHandlerVersion: '2.77'
    autoUpgradeMinorVersion: true
    settings: {
      wmfVersion: 'latest'
      configuration: {
        url: dscScript
        script: 'dsc.ps1'
        function: 'MmaMultihoming'
      }
      configurationArguments: {
        workspaceId1: workspaceId1
      }
      privacy: {
        datacollection: 'enable'
      }
      advancedOptions: {
        forcePullAndApply: false

      }
    }
    protectedSettings: {
      configurationArguments: {
        workspaceKey1: {
          userName: 'donotuse'
          password: workspaceKey1
        }

    }
    configurationUrlSasToken: SaaStoken
    }

  }

}

I am really quite stuck so would appreciate any ideas people can give.

Thanks!


问:
XML serialization includes 'xmlns=' want this omitted
I'm logging xml object by serializing the object, I've looked at several presented solutions from here and the result is that for sub elements I still get the xmlns=.  This caused an issue with the vendor I'm working with as they claimed this was the reason for a failure i was experiencing (it was not). But for future consideration I want to log the xml data we are sending exactly as the Connected service does, without the xmlns=.

This is how the Object is defined (WSDL auto gened code)

```<code>  [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.8.4084.0")]
  [System.SerializableAttribute()]
  [System.Diagnostics.DebuggerStepThroughAttribute()]
  [System.ComponentModel.DesignerCategoryAttribute("code")]
  [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://stamps.com/xml/namespace/2021/01/swsim/SwsimV111")]
  public partial class Address : object, System.ComponentModel.INotifyPropertyChanged
  {

    private string fullNameField;

    public Address()
    {
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Order = 0)]
    public string FullName
    {
      get
      {
        return this.fullNameField;
      }
      set
      {
        this.fullNameField = value;
        this.RaisePropertyChanged("FullName");
      }
    }
  }
</code>```

This is the routine I'm using to serialize:

```<code>   public static string SerializeObject<T>(T dataObject)
    {
      if (dataObject == null) return string.Empty;

      XmlWriterSettings settings = new XmlWriterSettings
      {
        OmitXmlDeclaration = true,
        Indent = true,
        NewLineHandling = NewLineHandling.None,
        NewLineOnAttributes = false,
      };

      XmlAttributes xmlAttributes = new XmlAttributes { Xmlns = false };

      var xmlAttributeOverrides = new XmlAttributeOverrides();
      xmlAttributeOverrides.Add(dataObject.GetType(), xmlAttributes);

      try
      {
        XmlSerializerNamespaces emptyNS = new XmlSerializerNamespaces(new[] { new XmlQualifiedName(string.Empty, string.Empty) });
        using (StringWriter xmlWriter = new StringWriter())
        {
          using (XmlWriter writer = XmlWriter.Create(xmlWriter, settings))
          {
            var serializer = new XmlSerializer(typeof(T), xmlAttributeOverrides);
            serializer.Serialize(xmlWriter, dataObject, emptyNS);
            return xmlWriter.ToString();
          }
        }
      }
      catch (Exception)
      {
        return string.Empty;
      }
    }

  }
</code>```

And finally this is the output:

```<code><?xml version="1.0" encoding="utf-16"?>
<CleanseAddressRequest>
  <Authenticator>Removed</Authenticator>
  <Address>
    <FullName xmlns="http://stamps.com/xml/namespace/2021/01/swsim/SwsimV111">Test 103</FullName>
    <PhoneNumber xmlns="http://stamps.com/xml/namespace/2021/01/swsim/SwsimV111" />
    <FullAddress xmlns="http://stamps.com/xml/namespace/2021/01/swsim/SwsimV111">
103 Linda Lane
Media PA    19063</FullAddress>
  </Address>
</CleanseAddressRequest>
</code>```

Based on my efforts with the vendor I want to be able to use output like:

```<code><?xml version="1.0" encoding="utf-16"?>
<CleanseAddressRequest>
  <Authenticator>Removed</Authenticator>
  <Address>
    <FullName>Test 103</FullName>
    <PhoneNumber />
    <FullAddress>
103 Linda Lane
Media PA    19063</FullAddress>
  </Address>
</CleanseAddressRequest>
</code>```

The work around I used to resolve my issue was to manually edit the XML, not what is useful for future maintainers of the code base.

How can I programmatically remove the extraneous xmlns=?

Edited for spelling error.

Body:
I'm logging xml object by serializing the object, I've looked at several presented solutions from here and the result is that for sub elements I still get the xmlns=.  This caused an issue with the vendor I'm working with as they claimed this was the reason for a failure i was experiencing (it was not). But for future consideration I want to log the xml data we are sending exactly as the Connected service does, without the xmlns=.

This is how the Object is defined (WSDL auto gened code)

  [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.8.4084.0")]
  [System.SerializableAttribute()]
  [System.Diagnostics.DebuggerStepThroughAttribute()]
  [System.ComponentModel.DesignerCategoryAttribute("code")]
  [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://stamps.com/xml/namespace/2021/01/swsim/SwsimV111")]
  public partial class Address : object, System.ComponentModel.INotifyPropertyChanged
  {

    private string fullNameField;

    public Address()
    {
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Order = 0)]
    public string FullName
    {
      get
      {
        return this.fullNameField;
      }
      set
      {
        this.fullNameField = value;
        this.RaisePropertyChanged("FullName");
      }
    }
  }

This is the routine I'm using to serialize:

   public static string SerializeObject<T>(T dataObject)
    {
      if (dataObject == null) return string.Empty;

      XmlWriterSettings settings = new XmlWriterSettings
      {
        OmitXmlDeclaration = true,
        Indent = true,
        NewLineHandling = NewLineHandling.None,
        NewLineOnAttributes = false,
      };

      XmlAttributes xmlAttributes = new XmlAttributes { Xmlns = false };

      var xmlAttributeOverrides = new XmlAttributeOverrides();
      xmlAttributeOverrides.Add(dataObject.GetType(), xmlAttributes);

      try
      {
        XmlSerializerNamespaces emptyNS = new XmlSerializerNamespaces(new[] { new XmlQualifiedName(string.Empty, string.Empty) });
        using (StringWriter xmlWriter = new StringWriter())
        {
          using (XmlWriter writer = XmlWriter.Create(xmlWriter, settings))
          {
            var serializer = new XmlSerializer(typeof(T), xmlAttributeOverrides);
            serializer.Serialize(xmlWriter, dataObject, emptyNS);
            return xmlWriter.ToString();
          }
        }
      }
      catch (Exception)
      {
        return string.Empty;
      }
    }

  }

And finally this is the output:

<?xml version="1.0" encoding="utf-16"?>
<CleanseAddressRequest>
  <Authenticator>Removed</Authenticator>
  <Address>
    <FullName xmlns="http://stamps.com/xml/namespace/2021/01/swsim/SwsimV111">Test 103</FullName>
    <PhoneNumber xmlns="http://stamps.com/xml/namespace/2021/01/swsim/SwsimV111" />
    <FullAddress xmlns="http://stamps.com/xml/namespace/2021/01/swsim/SwsimV111">
103 Linda Lane
Media PA    19063</FullAddress>
  </Address>
</CleanseAddressRequest>

Based on my efforts with the vendor I want to be able to use output like:

<?xml version="1.0" encoding="utf-16"?>
<CleanseAddressRequest>
  <Authenticator>Removed</Authenticator>
  <Address>
    <FullName>Test 103</FullName>
    <PhoneNumber />
    <FullAddress>
103 Linda Lane
Media PA    19063</FullAddress>
  </Address>
</CleanseAddressRequest>

The work around I used to resolve my issue was to manually edit the XML, not what is useful for future maintainers of the code base.

How can I programmatically remove the extraneous xmlns=?

Edited for spelling error.


问:
Change authentification error message text
I've followed the guide error-handling for handling back an error to the users from the setCredentials method. However, even when using the provided example method to throw an error to the user, I still get the generic error on all my reports:
This is the default code I used for setting up the setCredentials function looker-studio auth connector.

```<code>function setCredentials(request) {
    try {
    Logger.log('setCredentials/try');
    var creds = request.userPass;
    var username = creds.username;
    var password = creds.password;
    var validCreds = validateCredentials(username, password).validCreds;
    if (!validCreds) {
      return {
        errorCode: 'INVALID_CREDENTIALS'
      };
    };
    var userProperties = PropertiesService.getUserProperties();
    userProperties.setProperty('connector.username', username);
    userProperties.setProperty('connector.password', password);
    return {
      errorCode: 'NONE'
    };
  } catch(e) {
    Logger.log('setCredentials/catch');
    DataStudioApp.createCommunityConnector()
      .newUserError()
      .setDebugText('Error setting credentials. Exception details: ' + e)
      .setText('I want to show a custom error message')
      .throwException();
  }
}
</code>```

This is the toast message I want to change

I tried to throw an error before returning INVALID_CREDENTIALS so it falls in the catch. However, I don't see changes in the text.

```<code>function setCredentials(request) {
    try {
    Logger.log('setCredentials/try');
    var creds = request.userPass;
    var username = creds.username;
    var password = creds.password;
    var validCreds = validateCredentials(username, password).validCreds;
    if (!validCreds) {
      throw new Error('Only to fall to the catch');
    };
    var userProperties = PropertiesService.getUserProperties();
    userProperties.setProperty('connector.username', username);
    userProperties.setProperty('connector.password', password);
    return {
      errorCode: 'NONE'
    };
  } catch(e) {
    Logger.log('setCredentials/catch');
    throw new Error('This message appears but it doesn't overwritte the default message');
  }
}
</code>```

(I have admin set to true)
If I throw again a new Error in the catch before the DataStudioApp newUserError I can see that 2 error toasts appear. A default one and mine, however this is not the intended result. What I want is to edit the default error message and I don't know if it's possible.

Body:
I've followed the guide error-handling for handling back an error to the users from the setCredentials method. However, even when using the provided example method to throw an error to the user, I still get the generic error on all my reports:
This is the default code I used for setting up the setCredentials function looker-studio auth connector.

function setCredentials(request) {
    try {
    Logger.log('setCredentials/try');
    var creds = request.userPass;
    var username = creds.username;
    var password = creds.password;
    var validCreds = validateCredentials(username, password).validCreds;
    if (!validCreds) {
      return {
        errorCode: 'INVALID_CREDENTIALS'
      };
    };
    var userProperties = PropertiesService.getUserProperties();
    userProperties.setProperty('connector.username', username);
    userProperties.setProperty('connector.password', password);
    return {
      errorCode: 'NONE'
    };
  } catch(e) {
    Logger.log('setCredentials/catch');
    DataStudioApp.createCommunityConnector()
      .newUserError()
      .setDebugText('Error setting credentials. Exception details: ' + e)
      .setText('I want to show a custom error message')
      .throwException();
  }
}

This is the toast message I want to change

I tried to throw an error before returning INVALID_CREDENTIALS so it falls in the catch. However, I don't see changes in the text.

function setCredentials(request) {
    try {
    Logger.log('setCredentials/try');
    var creds = request.userPass;
    var username = creds.username;
    var password = creds.password;
    var validCreds = validateCredentials(username, password).validCreds;
    if (!validCreds) {
      throw new Error('Only to fall to the catch');
    };
    var userProperties = PropertiesService.getUserProperties();
    userProperties.setProperty('connector.username', username);
    userProperties.setProperty('connector.password', password);
    return {
      errorCode: 'NONE'
    };
  } catch(e) {
    Logger.log('setCredentials/catch');
    throw new Error('This message appears but it doesn't overwritte the default message');
  }
}

(I have admin set to true)
If I throw again a new Error in the catch before the DataStudioApp newUserError I can see that 2 error toasts appear. A default one and mine, however this is not the intended result. What I want is to edit the default error message and I don't know if it's possible.


问:
How to plot the probability densities of a signal ( signal detection) with threshold decision ? [Matlab]
I will first write the problem :

A binary system of communication with equiprobable messages, in which we have two signals s0 = -1 V for '0' logic and s1 = 1V for '1' logic . The received signal is Y(t) = s(t) + N(t) . The noise N(t) has  normal probability densities N( 0, 0.25), which means mean = 0, deviation = 0.25 . The  threshold  of decision is -0.15.

a) plot a graphic in matlab for the transmitted signal for the chanel that uses the sequence of symbols [1010001101]

b) plot a graphic for the probability densities of the signal Y(t), the threshold decision  ( has to show up in the  plot , I will attach a photo to show ) and the space/intervals of decision ( s0 and s1). (matlab)

First of all  I will attach for a) and b) a photo to show an example of it is required .

For a) :

For b) :

Now my problem is that I don't know how to plot  the probability densities of signal Y(t) together with  the threshold decision and space/intervals of decision like in the photo that I have attached above( photo b) ) . The same problem I have with plotting the transmitted signal at a) . Now I have managed to draw a graphic on my notebook for a) but I don't know how to implement that ( I will attach a photo).
Also,  for b) the threshold decision is noted in the photo with the greek letter gamma and is the pink vertical line .

For b) this is what I have tried :

```<code>
% Generate some example data
mu1 = -0.5; sigma1 = 0.7; mu2 = 0.8; sigma2 = 0.5;
x = linspace(-8, 8, 500);
y1 = normpdf(x, mu1, sigma1);
y2 = normpdf(x, mu2, sigma2);

% Plot it
figure; plot(x, [y1; y2])
hold on

% Detect intersection between curves; choose threshold so you get the whole
% intersection (0.0001 should do unless your sigmas are very large)
ind = y1 .* y2 > 0.0001;
% Find the minimum values in range
minVals = min([y1(ind); y2(ind)]);

if ~isempty(minVals)
    area(x(ind), minVals)
end
</code>```

And this is a photo with the plot :

The problem is that I don't know how to adapt it for my case .

For a) this is what I have tried :

But I don't know how to implement this in matlab .

I would very much appreciate any help ! Thank you !

Body:
I will first write the problem :

A binary system of communication with equiprobable messages, in which we have two signals s0 = -1 V for '0' logic and s1 = 1V for '1' logic . The received signal is Y(t) = s(t) + N(t) . The noise N(t) has  normal probability densities N( 0, 0.25), which means mean = 0, deviation = 0.25 . The  threshold  of decision is -0.15.

a) plot a graphic in matlab for the transmitted signal for the chanel that uses the sequence of symbols [1010001101]

b) plot a graphic for the probability densities of the signal Y(t), the threshold decision  ( has to show up in the  plot , I will attach a photo to show ) and the space/intervals of decision ( s0 and s1). (matlab)

First of all  I will attach for a) and b) a photo to show an example of it is required .

For a) :

For b) :

Now my problem is that I don't know how to plot  the probability densities of signal Y(t) together with  the threshold decision and space/intervals of decision like in the photo that I have attached above( photo b) ) . The same problem I have with plotting the transmitted signal at a) . Now I have managed to draw a graphic on my notebook for a) but I don't know how to implement that ( I will attach a photo).
Also,  for b) the threshold decision is noted in the photo with the greek letter gamma and is the pink vertical line .

For b) this is what I have tried :

% Generate some example data
mu1 = -0.5; sigma1 = 0.7; mu2 = 0.8; sigma2 = 0.5;
x = linspace(-8, 8, 500);
y1 = normpdf(x, mu1, sigma1);
y2 = normpdf(x, mu2, sigma2);

% Plot it
figure; plot(x, [y1; y2])
hold on

% Detect intersection between curves; choose threshold so you get the whole
% intersection (0.0001 should do unless your sigmas are very large)
ind = y1 .* y2 > 0.0001;
% Find the minimum values in range
minVals = min([y1(ind); y2(ind)]);

if ~isempty(minVals)
    area(x(ind), minVals)
end

And this is a photo with the plot :

The problem is that I don't know how to adapt it for my case .

For a) this is what I have tried :

But I don't know how to implement this in matlab .

I would very much appreciate any help ! Thank you !


问:
How to ensure a function avoids copying a returned value in C++17
I've always avoided returning objects by value, due to copy-elision being an optimization with observable side-effects... but I've read that C++17 has added a way to ensure returned objects never call their copy constructor and destructor!  Is there anything special I need to do in order to trigger this new behavior reliably?

I don't fully understand the rules around it, and it sounds easy to accidentally write a function that triggers the "old" behavior; I want to avoid that at all costs if possible. Generating a compiler error if the compiler lacks this guarantee, (or more realistically, if I mess it up) would grant me peace.

Is there any kind of boilerplate or habit, when coding my class or function, that'd let me absolutely avoid the pre-C++17 behavior?


问:
How to configure ExcelReaderFactory to solve problem of Encoding in c#?
I use ExcelDataReader.DataSet nuggetPackage

```<code>var reader = ExcelReaderFactory.CreateReader(stream);
 var conf = new ExcelDataSetConfiguration
                {

                    UseColumnDataType = true,

                    FilterSheet = (tableReader, sheetIndex) => true,

                    ConfigureDataTable = (tableReader) => new ExcelDataTableConfiguration()
                    {
                        EmptyColumnNamePrefix = "Column",
                        UseHeaderRow = false,
                        }
                    }
                };
                var dataSet = reader.AsDataSet(conf);
</code>```

I have the data in the dataset but some characters became ? (é => ?, ç => ?)

i try to use ExcelReaderConfiguration but i didn't find how to use dataset with this.

```<code>var readerConf = ExcelReaderFactory.CreateReader(stream, new ExcelReaderConfiguration()
                {
                    FallbackEncoding = Encoding.GetEncoding(1252),
                    AutodetectSeparators = new char[] { ',', ';', '\t', '|', '#' },
                    LeaveOpen = false,
                    AnalyzeInitialCsvRows = 0,
                });
</code>```

Body:
I use ExcelDataReader.DataSet nuggetPackage

var reader = ExcelReaderFactory.CreateReader(stream);
 var conf = new ExcelDataSetConfiguration
                {

                    UseColumnDataType = true,

                    FilterSheet = (tableReader, sheetIndex) => true,

                    ConfigureDataTable = (tableReader) => new ExcelDataTableConfiguration()
                    {
                        EmptyColumnNamePrefix = "Column",
                        UseHeaderRow = false,
                        }
                    }
                };
                var dataSet = reader.AsDataSet(conf);

I have the data in the dataset but some characters became ? (é => ?, ç => ?)

i try to use ExcelReaderConfiguration but i didn't find how to use dataset with this.

var readerConf = ExcelReaderFactory.CreateReader(stream, new ExcelReaderConfiguration()
                {
                    FallbackEncoding = Encoding.GetEncoding(1252),
                    AutodetectSeparators = new char[] { ',', ';', '\t', '|', '#' },
                    LeaveOpen = false,
                    AnalyzeInitialCsvRows = 0,
                });


问:
Why my anchors implementation is not working?
This is the url I'm working with

https://example.com/#/main?name=Denzel%20and%20Dakota%20Reunite!%20Here%E2%80%99s%20Everything%20You%20Need%20To%20Know%20About%20%E2%80%98The%20Equalizer%203%E2%80%99&uri=https:%2F%2Fqa1-cue-webservice.misitemgr.com%2Fwebservice%2Fescenic%2Fcontent%2F24907540&mimetype=x-ece%2Fstory

This is the code:

.overlay {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.7);
  transition: opacity 500ms;
  visibility: hidden;
  opacity: 0;
  z-index: 3;
}

.overlay:target {
  visibility: visible;
  opacity: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <div>
    Copy to keywords
  </div>

  <div id="popup1" class="overlay">
    <div class="popup">
      ×
      <iframe id="cnx_frame" style="border: none" src="https://elements.connatix.com/extension?h={"library":{"mediaId":"2afc6334-ecdc-4cdb-94da-c6ef7a4fce39","mediaIdList":null,"playerId":"42ff15a0-ee43-42a6-abfe-2b0957ed9e22"},"playlists":{"mediaId":null,"mediaIdList":["2c6d7e20-8b96-4ebf-b9eb-d89a72a5a10e","a072194d-4eb3-4238-855a-eb6e69352f03"],"playerId":"8b034f64-513c-4987-b16f-42d6008f7feb"}}"></iframe>
    </div>
  </div>
</div></code>```

No sure if the issue is related with the "#" present in the url: https://example.com/#/main? ...

When I click on the link, I'm been redirected to https://example.com/#popup1

Just to try, I manually change the url adding the anchor but no results:

https://example.com/#/main?name=Denzel%20and%20Dakota%20Reunite!%20Here%E2%80%99s%20Everything%20You%20Need%20To%20Know%20About%20%E2%80%98The%20Equalizer%203%E2%80%99&uri=https:%2F%2Fqa1-cue-webservice.misitemgr.com%2Fwebservice%2Fescenic%2Fcontent%2F24907540&mimetype=x-ece%2Fstory#popup1

Any advice or alternative to anchors links ?

Body:
This is the url I'm working with

https://example.com/#/main?name=Denzel%20and%20Dakota%20Reunite!%20Here%E2%80%99s%20Everything%20You%20Need%20To%20Know%20About%20%E2%80%98The%20Equalizer%203%E2%80%99&uri=https:%2F%2Fqa1-cue-webservice.misitemgr.com%2Fwebservice%2Fescenic%2Fcontent%2F24907540&mimetype=x-ece%2Fstory

This is the code:

.overlay {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.7);
  transition: opacity 500ms;
  visibility: hidden;
  opacity: 0;
  z-index: 3;
}

.overlay:target {
  visibility: visible;
  opacity: 1;
}

    Copy to keywords

      ×

No sure if the issue is related with the "#" present in the url: https://example.com/#/main? ...

When I click on the link, I'm been redirected to https://example.com/#popup1

Just to try, I manually change the url adding the anchor but no results:

https://example.com/#/main?name=Denzel%20and%20Dakota%20Reunite!%20Here%E2%80%99s%20Everything%20You%20Need%20To%20Know%20About%20%E2%80%98The%20Equalizer%203%E2%80%99&uri=https:%2F%2Fqa1-cue-webservice.misitemgr.com%2Fwebservice%2Fescenic%2Fcontent%2F24907540&mimetype=x-ece%2Fstory#popup1

Any advice or alternative to anchors links ?


问:
vscode shows no function documentation for some functions on hover
I guess vscode is supposed to show the full function documentation in the docstring on hovering over it. At least that is what it does for many functions. However, for some functions it only shows the function with all arguments. For example, the first link shows an example where the full docstring is displayed and the second link an example where it isnt. Both functions are from the same package, so this really does not make any sense to me. Does anyone know if there is a fix or if this is a bug that somehow has to be fixed by vscode or something?


问:
Imbalance dataset and Tree-base regressors
I have an imbalanced dataset and need to balance it to predict the target with tree-based regressors like DecisionTreeRegressor.

To balance, I found solutions like using:

Square Root Transformation

Log Transformation

Box-Cox Transformation

However, I can't use methods 2 and 3 because I have too many 0 in the y array and I get errors like:

RuntimeWarning: divide by zero encountered in the log

So far, I can only use the square root transform method:

```<code>transformati='square_root'
y_train_transformed = np.sqrt(y_train)
reg = DecisionTreeRegressor().fit(X_train, y_train_transformed)
# create predictions on the test set
preds = reg.predict(X_test)
# transform back
preds = preds **2
 # get mse and r2
r2 = r2_score(y_test, preds)
mse = mean_squared_error(y_test, preds)
# store in results dict
results_dict[transformation] = [r2, mse]
</code>```

But when I compare this result with the result I get from the regression without any changes, I see that this method does not work well for me.:

```<code>transformat='no transformation'
reg = DecisionTreeRegressor().fit(X_train, y_train)
# create predictions on test set
preds = reg.predict(X_test)
 # get mse and r2
r2 = r2_score(y_test, preds)
mse = mean_squared_error(y_test, preds)
# store in results dict
results_dict[transformation] = [r2, mse]
</code>```

The final results:

```<code>import pandas as pd
 df_results = pd.DataFrame.from_dict(results_dict, orient="index", columns=["R2-Score", "MSE"])
  df_results
</code>```

Since I didn't get a better answer when I tried to balance the dataset with this solution, I keep looking for other solutions and I find that there is a SMOTE library for regression in Python, but I can't find a nice example to know how I can use it.

So far, I only find this example:

```<code>## load libraries
import smogn
import pandas

## load data
housing = pandas.read_csv(

## http://jse.amstat.org/v19n3/decock.pdf
"https://raw.githubusercontent.com/nickkunz/smogn/master/data/housing.csv")

## conduct smogn
housing_smogn = smogn.smoter(

    data = housing,
    y = "SalePrice"
)
</code>```

https://github.com/nickkunz/smogn

But it is still not clear to me how to use this method:

```<code>import smogn
smogn = smogn.smoter(
    # I am not sure if it is correct?
    data = X_train,
    y = y_train
)

reg = DecisionTreeRegressor().fit(smogn[data], smogn[y]) # I do not know what should I put here?
</code>```

Can someone explain to me how to use this method?

Also, knowing that I have a lot of 0 values in my dataset, are there any other methods I can use to balance the dataset?

Body:
I have an imbalanced dataset and need to balance it to predict the target with tree-based regressors like DecisionTreeRegressor.

To balance, I found solutions like using:

Square Root Transformation

Log Transformation

Box-Cox Transformation

However, I can't use methods 2 and 3 because I have too many 0 in the y array and I get errors like:

RuntimeWarning: divide by zero encountered in the log

So far, I can only use the square root transform method:

transformati='square_root'
y_train_transformed = np.sqrt(y_train)
reg = DecisionTreeRegressor().fit(X_train, y_train_transformed)
# create predictions on the test set
preds = reg.predict(X_test)
# transform back
preds = preds **2
 # get mse and r2
r2 = r2_score(y_test, preds)
mse = mean_squared_error(y_test, preds)
# store in results dict
results_dict[transformation] = [r2, mse]

But when I compare this result with the result I get from the regression without any changes, I see that this method does not work well for me.:

transformat='no transformation'
reg = DecisionTreeRegressor().fit(X_train, y_train)
# create predictions on test set
preds = reg.predict(X_test)
 # get mse and r2
r2 = r2_score(y_test, preds)
mse = mean_squared_error(y_test, preds)
# store in results dict
results_dict[transformation] = [r2, mse]

The final results:

import pandas as pd
 df_results = pd.DataFrame.from_dict(results_dict, orient="index", columns=["R2-Score", "MSE"])
  df_results

Since I didn't get a better answer when I tried to balance the dataset with this solution, I keep looking for other solutions and I find that there is a SMOTE library for regression in Python, but I can't find a nice example to know how I can use it.

So far, I only find this example:

## load libraries
import smogn
import pandas

## load data
housing = pandas.read_csv(

## http://jse.amstat.org/v19n3/decock.pdf
"https://raw.githubusercontent.com/nickkunz/smogn/master/data/housing.csv")

## conduct smogn
housing_smogn = smogn.smoter(

    data = housing,
    y = "SalePrice"
)

https://github.com/nickkunz/smogn

But it is still not clear to me how to use this method:

import smogn
smogn = smogn.smoter(
    # I am not sure if it is correct?
    data = X_train,
    y = y_train
)

reg = DecisionTreeRegressor().fit(smogn[data], smogn[y]) # I do not know what should I put here?

Can someone explain to me how to use this method?

Also, knowing that I have a lot of 0 values in my dataset, are there any other methods I can use to balance the dataset?


问:
Mock Inherited method only
My repository is derived from a Class and an interface.

I want to mock the inherited method from the class, see the code here:

```<code>public interface IPersonRepository: ICommonRepository<PersonEntity>
{
    PersonEntity GetPersonDetailById(string Id);
}

public class PersonRepository: CommonRepository<PersonEntity>, IPersonRepository
{
   public PersonRepository(DatabaseContext context, ILogger logger) : base(context, logger){}

   public PersonEntity GetPersonDetailById(string Id)
   {
     DataTable records = GetAllById(Id); // Who to Mock this method only
   }
}
</code>```

And Here is my unit test code

```<code>public Mock<ILogger> mockLogger = new Mock<ILogger>();
public DbContextOptions<DatabaseContext> options =
    new DbContextOptionsBuilder<DatabaseContext>()
           .UseInMemoryDatabase(databaseName: "DB_InMemory")
           .Options;

public Mock<PersonRepository> personRepo =
    new Mock<PersonRepository>(context, mockLogger.Object);
personRepo.CallBase = true;
personRepo.Setup(m => m.GetAllById(It.IsAny<string>>()))
            .Returns(new System.Data.DataTable());
// Above line gives an error, see the error at the end
var response = personRepo.Object.GetPersonDetailById("1234");
Assert.NotNull(response);
</code>```

Here is the error:

Non-overridable members (here: CommonRepository.GetAllById) may not be used in setup / verification expressions

Any suggestion or way to mock it?

Title: Mock Inherited method only

Body:
My repository is derived from a Class and an interface.

I want to mock the inherited method from the class, see the code here:

public interface IPersonRepository: ICommonRepository<PersonEntity>
{
    PersonEntity GetPersonDetailById(string Id);
}

public class PersonRepository: CommonRepository<PersonEntity>, IPersonRepository
{
   public PersonRepository(DatabaseContext context, ILogger logger) : base(context, logger){}

   public PersonEntity GetPersonDetailById(string Id)
   {
     DataTable records = GetAllById(Id); // Who to Mock this method only
   }
}

And Here is my unit test code

public Mock<ILogger> mockLogger = new Mock<ILogger>();
public DbContextOptions<DatabaseContext> options =
    new DbContextOptionsBuilder<DatabaseContext>()
           .UseInMemoryDatabase(databaseName: "DB_InMemory")
           .Options;

public Mock<PersonRepository> personRepo =
    new Mock<PersonRepository>(context, mockLogger.Object);
personRepo.CallBase = true;
personRepo.Setup(m => m.GetAllById(It.IsAny<string>>()))
            .Returns(new System.Data.DataTable());
// Above line gives an error, see the error at the end
var response = personRepo.Object.GetPersonDetailById("1234");
Assert.NotNull(response);

Here is the error:

Non-overridable members (here: CommonRepository.GetAllById) may not be used in setup / verification expressions

Any suggestion or way to mock it?


问:
Why the changes I made in the Django model not being reflected in the html form?

I have a field named 'amount' of type Floatfield.

I changed it to DecimalField and ran makemigrations and migrate commands and it successfully generated 0002_alter_expense_amount.py file.

This change is  reflected in the database.

But in the html form when I try to add new amount It's showing this message.
When I tried the same from the admin panel it was successful

What should I do to make the html form accept the decimal value? Is there anything I'm missing?

models.py

```<code>from django.db import models
from django.contrib.auth.models import User
from django.utils.timezone import now

class Expense(models.Model):
    amount = models.DecimalField(decimal_places=2, max_digits=10)
    date = models.DateField(default=now)
    description = models.TextField()
    owner = models.ForeignKey(to=User, on_delete=models.CASCADE)
    category = models.CharField(max_length=255)

    def __str__(self):
        return self.category

    class Meta:
        ordering = ['-date']

class Category(models.Model):
    name = models.CharField(max_length=255)

    class Meta:
        verbose_name_plural = 'Categories'

    def __str__(self):
        return self.name
</code>```

views.py

```<code>@login_required(login_url="/authentication/login")
def add_expenses(request):
    categories = Category.objects.all()
    context = {
        'categories': categories,
        'values': request.POST
    }
    if request.method == 'POST':
        amount = request.POST['amount']
        description = request.POST['description']
        date = request.POST['expense_date']
        category = request.POST['category']

        Expense.objects.create(owner=request.user, amount=amount, date=date, category=category, description=description)
        messages.success(request, 'Expense saved successfully')
        return redirect('expenses')
    else:
        return render(request, 'expenses/add-expenses.html', context)
</code>```

html form

```<code>    <form action="{% url 'add-expenses' %}" method="post">
        {% include 'partials/messages.html' %}
        {% csrf_token %}
        <div class="form-group mb-3">
            <label for="">Categories</label>
            <select class="form-control form-control" name="category" required>
                {% for category in categories%}
                <option name="category" value="{{category.name}}">
                    {{category.name}}
                </option>
                {% endfor %}
            </select>
        </div>
        <div class="form-group mb-3">
            <label for="">Amount</label>
            <input type="number" class="form-control form-control-sm" name="amount" required />
        </div>
        <div class="form-group mb-3">
            <label for="">Description</label>
            <input type="text" class="form-control form-control-sm" name="description" value="{{values.description}}">
        </div>
        <div class="form-group mb-3">
            <label for="">Date</label>
            <div class="d-grid gap-2 col-3">
                <input type="date" class="form-control form-control-sm" name="expense_date" required>
            </div>
        </div>
        <div class="d-grid gap-2 col-3">
            <input type="submit" value="Add" class="btn btn-outline-dark" />
        </div>
    </form>
</code>```

Body:
I have a field named 'amount' of type Floatfield.

I changed it to DecimalField and ran makemigrations and migrate commands and it successfully generated 0002_alter_expense_amount.py file.

This change is  reflected in the database.

But in the html form when I try to add new amount It's showing this message.
When I tried the same from the admin panel it was successful

What should I do to make the html form accept the decimal value? Is there anything I'm missing?

models.py

from django.db import models
from django.contrib.auth.models import User
from django.utils.timezone import now

class Expense(models.Model):
    amount = models.DecimalField(decimal_places=2, max_digits=10)
    date = models.DateField(default=now)
    description = models.TextField()
    owner = models.ForeignKey(to=User, on_delete=models.CASCADE)
    category = models.CharField(max_length=255)

    def __str__(self):
        return self.category

    class Meta:
        ordering = ['-date']

class Category(models.Model):
    name = models.CharField(max_length=255)

    class Meta:
        verbose_name_plural = 'Categories'

    def __str__(self):
        return self.name

views.py

@login_required(login_url="/authentication/login")
def add_expenses(request):
    categories = Category.objects.all()
    context = {
        'categories': categories,
        'values': request.POST
    }
    if request.method == 'POST':
        amount = request.POST['amount']
        description = request.POST['description']
        date = request.POST['expense_date']
        category = request.POST['category']

        Expense.objects.create(owner=request.user, amount=amount, date=date, category=category, description=description)
        messages.success(request, 'Expense saved successfully')
        return redirect('expenses')
    else:
        return render(request, 'expenses/add-expenses.html', context)

html form

    <form action="{% url 'add-expenses' %}" method="post">
        {% include 'partials/messages.html' %}
        {% csrf_token %}

            Categories
            <select class="form-control form-control" name="category" required>
                {% for category in categories%}
                <option name="category" value="{{category.name}}">
                    {{category.name}}
                </option>
                {% endfor %}
            </select>

            Amount
            <input type="number" class="form-control form-control-sm" name="amount" required />

            Description
            <input type="text" class="form-control form-control-sm" name="description" value="{{values.description}}">

            Date

                <input type="date" class="form-control form-control-sm" name="expense_date" required>

            <input type="submit" value="Add" class="btn btn-outline-dark" />

    </form>


问:
Python can't locate module files from other directory
I have a project structured as follow:

```<code>project\
   __init__.py
   gui\
      __init__.py
      gui_file_one.py
      gui_file_two.py
   logic\
      __init__.py
      logic_file_one.py
      logic_file_two.py
</code>```

Let's say that in a gui_file_one.py I need to import class A that is located in a logic_file_one.py. When I try to do from logic.logic_file_one import A I get a ModuleNotFoundError: No module named 'logic'. How do I overcome this? How should this class be imported?

Body:
I have a project structured as follow:

project\
   __init__.py
   gui\
      __init__.py
      gui_file_one.py
      gui_file_two.py
   logic\
      __init__.py
      logic_file_one.py
      logic_file_two.py

Let's say that in a gui_file_one.py I need to import class A that is located in a logic_file_one.py. When I try to do from logic.logic_file_one import A I get a ModuleNotFoundError: No module named 'logic'. How do I overcome this? How should this class be imported?


问:
How to use a 256x64 OLED Display with STM32 via SPI
I'm working on a proyect with a display with a resolution of 256x64 SPI interface, but i can't find any information about it.

Has anyone worked on this type of display?

This is the display that I'm working on https://www.mouser.cl/ProductDetail/Newhaven-Display/NHD-2.8-25664UCB2?qs=EQmeiuRlVUTjbx5MVlv5%2Fw%3D%3D

I've found the µGUI library, but I'm really new in this kind of proyect, so i don't understand the documentation about it.


问:
question about `updatePostbackConversionValue` method
I read below link for updatePostbackConversionValue method.
https://developer.apple.com/documentation/storekit/skadnetwork/4097267-updatepostbackconversionvalue

But I want to know, does completionHandler of updatePostbackConversionValue called even if Apple’s privacy threshold for minimum install counts doesn't meet(In other words does completionHandler called even for NULL Conversion Values)?
I ask this because If it is called, I can use this as a way for tracking install counts via Ads in iOS 15.4+


问:
How to Exclude rows in one table by using conditions
I want to exclude rows where linenumber is equal to linkedlineno and type should be ES and SE and two rows number should be equal . And where the linkedlineno NULL should appear in results.

```<code>| Name |Linenumber|Linkedlineno|Type |  Number|
________ ________   ___________  ____ ________
|Apple|   2            3          ES     9999
|Apple|   3            2          SE     9999
|Apple|   5            NULL       ES     9999
|Apple|   6            NULL       ES     9999
|Apple|   7            NULL       ES     9999
|Apple|   8            NULL       ES     9999
</code>```

Don't use only linked is null  need other

When I tried excluding those two rows but where Type NULL rows are not appearing.

```<code>Select *
from H1
where Type in('ES','SE') and
      linenumber in (select * from H1 linkedlineno) and
      Number in (select * from H1 Number )
</code>```

Body:
I want to exclude rows where linenumber is equal to linkedlineno and type should be ES and SE and two rows number should be equal . And where the linkedlineno NULL should appear in results.

| Name |Linenumber|Linkedlineno|Type |  Number|
________ ________   ___________  ____ ________
|Apple|   2            3          ES     9999
|Apple|   3            2          SE     9999
|Apple|   5            NULL       ES     9999
|Apple|   6            NULL       ES     9999
|Apple|   7            NULL       ES     9999
|Apple|   8            NULL       ES     9999

Don't use only linked is null  need other

When I tried excluding those two rows but where Type NULL rows are not appearing.

Select *
from H1
where Type in('ES','SE') and
      linenumber in (select * from H1 linkedlineno) and
      Number in (select * from H1 Number )


问:
While looping to create a password protection function using Jupyter Notebook
Using Eric Pimpler's book Programing ArcGIS Pro with Python I am on Exercise 9: For and While Loops and have an issue trying to execute a code regarding a simple password and protection function.
The current modules installed are arcpy and os.
Example of code is below.

```<code>password = ' '
while password != 'password':
print("What is the password?")
password = input()
print('Yes, the password is ' + password + '. You may enter.')
</code>```

What is the password?

TypeError                                 Traceback (most recent call last)
In  [229]:
Line 4:     password = input()

TypeError: 'str' object is not callable

I tried to open another notebook and retype the code, it work initially, but failed after I copied and pasted the code back to my working notebook for the exercises. Sometimes I receive an * next to the cell and nothing happens I cant even cancel the kernel. Again I am running Jupyter from with ArcGIS Pro.

Body:
Using Eric Pimpler's book Programing ArcGIS Pro with Python I am on Exercise 9: For and While Loops and have an issue trying to execute a code regarding a simple password and protection function.
The current modules installed are arcpy and os.
Example of code is below.

password = ' '
while password != 'password':
print("What is the password?")
password = input()
print('Yes, the password is ' + password + '. You may enter.')

What is the password?

TypeError                                 Traceback (most recent call last)
In  [229]:
Line 4:     password = input()

TypeError: 'str' object is not callable

I tried to open another notebook and retype the code, it work initially, but failed after I copied and pasted the code back to my working notebook for the exercises. Sometimes I receive an * next to the cell and nothing happens I cant even cancel the kernel. Again I am running Jupyter from with ArcGIS Pro.


问:
Andoid FCM message show RTL
I am sending FCM messages using php curl with the legacy http protocol.
https://firebase.google.com/docs/cloud-messaging/http-server-ref

I am successfully using the title_loc_key and title_loc_args fields along with the following resource strings in my android app.

```<code><string name="fcm_msg_title">%1$s</string>
<string name="fcm_msg_body">%1$s</string>
</code>```

But whatever method I use in the resource strings to make it appear RTL, it does not work.

I tried to use html with dir="rtl" and also style="direction:rtl".

I tried to use the different combinations of unicode characters as described here:
https://stackoverflow.com/a/10989502/8507634

But nothing works and the text is still showing as LTR.

Does any one know of something that can help.

Title: Andoid FCM message show RTL

Body:
I am sending FCM messages using php curl with the legacy http protocol.
https://firebase.google.com/docs/cloud-messaging/http-server-ref

I am successfully using the title_loc_key and title_loc_args fields along with the following resource strings in my android app.

<string name="fcm_msg_title">%1$s</string>
<string name="fcm_msg_body">%1$s</string>

But whatever method I use in the resource strings to make it appear RTL, it does not work.

I tried to use html with dir="rtl" and also style="direction:rtl".

I tried to use the different combinations of unicode characters as described here:
https://stackoverflow.com/a/10989502/8507634

But nothing works and the text is still showing as LTR.

Does any one know of something that can help.