问:
Value type "void*' can't be assigned to entity type char error in C
I am getting this value assignment error when trying to compile this code and I'm not sure what the problem is. It's just a simple little function to read a line of text and build a string from it.

It was very kindly noted in the comments that I should include the actual compiler output. Find it at the bottom.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *readLine(int size) {
char *str;
int ch;
int len = 0;
str = malloc(size);
if (str == NULL) {
    fprintf(stderr, "malloc error\n");
    exit(1);
}
while ((ch = getchar()) != EOF && (ch != '\n')) {
    str[len++] = ch;
    if (len == size) {
        size = size * 2;
        str = realloc(str, size);
        if(str == NULL) {
            fprintf(stderr, "realloc error\n");
            exit(1);
        }
    }
}
str[len] = '\0';
return str;
}

OUTPUT:
error : invalid conversion from ‘void*’ to ‘char*’ [-fpermissive]
error :   str = malloc(size);
</code>```

Body:
I am getting this value assignment error when trying to compile this code and I'm not sure what the problem is. It's just a simple little function to read a line of text and build a string from it.

It was very kindly noted in the comments that I should include the actual compiler output. Find it at the bottom.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *readLine(int size) {
char *str;
int ch;
int len = 0;
str = malloc(size);
if (str == NULL) {
    fprintf(stderr, "malloc error\n");
    exit(1);
}
while ((ch = getchar()) != EOF && (ch != '\n')) {
    str[len++] = ch;
    if (len == size) {
        size = size * 2;
        str = realloc(str, size);
        if(str == NULL) {
            fprintf(stderr, "realloc error\n");
            exit(1);
        }
    }
}
str[len] = '\0';
return str;
}

OUTPUT:
error : invalid conversion from ‘void*’ to ‘char*’ [-fpermissive]
error :   str = malloc(size);


来源: stackexchange

问:
How can i upload both $_POST and $_FILES at the same time? PHP
I am a student trying to figure out, how i can simultaneously upload an files (jpg, jpeg, png) along with sending an message through PHP?

Currently i have tried two things.

Making a single form in html, and trying to submit to the same .php file. While following two separate tutorials, combining them. (See picture)

Making two different forms, which i want to be submitted from the same html page, with the same ''submit''. Is this possible?

So far i think i figured out that it is not possible to use both $_POST and $_FILES from the same form, is this true?

Any ideas how to fix the original code i already have, and if not, what is the easiest way to do it.

**I am learning, so the easiest way is prefered :)
HTML
PHP

ContentLicense: CC BY-SA 4.0


问:
VSCode built-in SCSS formatter, can I set ignore a line / some lines to autoformat like what Prettier can?
My default VSCode setting will autoformat the my code below on save:

```<code>$btn-square: (
    "sm": 50px,
    "md": 100px,
    "lg": 150px,
    "xl": 200px
) !default;
</code>```

to like:

```<code>$btn-square: (
    "sm": 50px,
    "md": 100px,
    "lg": 150px,
    "xl": 200px) !default;
</code>```

I want VSCode to autoformat while saving as default, but want to keep some parts like above to skip/ignore autoformatting. Most documents/articles show how to use ignore comments for Pretier extension.

Is there a way to set comment to ingnore like Pretier for build-in SCSS autoformatter?

Body:
My default VSCode setting will autoformat the my code below on save:

$btn-square: (
    "sm": 50px,
    "md": 100px,
    "lg": 150px,
    "xl": 200px
) !default;

to like:

$btn-square: (
    "sm": 50px,
    "md": 100px,
    "lg": 150px,
    "xl": 200px) !default;

I want VSCode to autoformat while saving as default, but want to keep some parts like above to skip/ignore autoformatting. Most documents/articles show how to use ignore comments for Pretier extension.

Is there a way to set comment to ingnore like Pretier for build-in SCSS autoformatter?


问:
Swig typemap. Return Python enum object from C wrapper
As I found out swig cannot convert C++ enums to Python enums object, so I created py file with enum declarations.
For example I have enum in C++:

```<code>enum class Color
{
  red, green, blue
};
</code>```

and in py file:

```<code>from enum import Enum
class Color(Enum):
    red = 0
    green = 1
    blue = 2
</code>```

for in typemap i use something like this:

```<code>*$1 = (int) PyLong_AsLong(PyObject_GetAttr($input, PyString_FromString("value")));
</code>```

And it works fine (because int is valid type for C enum value). But for out typemap I have to create Python enum object and return it. I have no ideas what is the right way to do this.

Body:
As I found out swig cannot convert C++ enums to Python enums object, so I created py file with enum declarations.
For example I have enum in C++:

enum class Color
{
  red, green, blue
};

and in py file:

from enum import Enum
class Color(Enum):
    red = 0
    green = 1
    blue = 2

for in typemap i use something like this:

*$1 = (int) PyLong_AsLong(PyObject_GetAttr($input, PyString_FromString("value")));

And it works fine (because int is valid type for C enum value). But for out typemap I have to create Python enum object and return it. I have no ideas what is the right way to do this.


问:
iPhone app not recording "visits" using CLLocationManager delegate
I'm relatively new to Swift and self-taught, and I'm currently having issues with recording Visits using a swift app.

Relevant parts of AppDelegate:

```<code>import CoreLocation

class AppDelegate: NSObject, UIApplicationDelegate {

    let locationManager = LocationManager.shared

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {

        locationManager.startMonitoringLocationVisits()
        print("AppDelegate just ran")

        return true
    }
}
</code>```

Relevant parts of LocationManager:

```<code>import CoreLocation

class LocationManager : NSObject, ObservableObject, CLLocationManagerDelegate {

    static let shared = LocationManager()

    //New location manager
    var locationManager = CLLocationManager()

    //Seconds between location acquisitions in background
    var locationInterval = 120

    override init() {
        super.init()
        locationManager.delegate = self
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
        self.locationManager.activityType = .fitness
        self.locationManager.allowsBackgroundLocationUpdates = true
    }
}
</code>```
```<code>func locationManager(_ manager: CLLocationManager, didVisit visit: CLVisit) {

        print("received a visit")
        //Code that sends a notification every time a visit is recorded

        print("attempting to save visit")
        self.saveVisit(visit: visit)     //Code that saves details from the visit to CoreLocation
    }
</code>```
```<code>    public func startMonitoringLocationVisits() {
        locationManager.startMonitoringVisits()
    }
</code>```

The app compiles and runs fine on my device (iPhone 13 pro running iOS 16) but never records any visits. I've tried an example app I found online and that works correctly on my device, so it must be an issue with my code, but I can't figure out what. I also have a background refresh task recording location coordinates every few minutes in the same app that works correctly, and I'm hesitant to start radically changing location manager code to debug the Visits feature since I'm worried I would break the background task feature. Any advice or direction is appreciated!

Body:
I'm relatively new to Swift and self-taught, and I'm currently having issues with recording Visits using a swift app.

Relevant parts of AppDelegate:

import CoreLocation

class AppDelegate: NSObject, UIApplicationDelegate {

    let locationManager = LocationManager.shared

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {

        locationManager.startMonitoringLocationVisits()
        print("AppDelegate just ran")

        return true
    }
}

Relevant parts of LocationManager:

import CoreLocation

class LocationManager : NSObject, ObservableObject, CLLocationManagerDelegate {

    static let shared = LocationManager()

    //New location manager
    var locationManager = CLLocationManager()

    //Seconds between location acquisitions in background
    var locationInterval = 120

    override init() {
        super.init()
        locationManager.delegate = self
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
        self.locationManager.activityType = .fitness
        self.locationManager.allowsBackgroundLocationUpdates = true
    }
}

func locationManager(_ manager: CLLocationManager, didVisit visit: CLVisit) {

        print("received a visit")
        //Code that sends a notification every time a visit is recorded

        print("attempting to save visit")
        self.saveVisit(visit: visit)     //Code that saves details from the visit to CoreLocation
    }

    public func startMonitoringLocationVisits() {
        locationManager.startMonitoringVisits()
    }

The app compiles and runs fine on my device (iPhone 13 pro running iOS 16) but never records any visits. I've tried an example app I found online and that works correctly on my device, so it must be an issue with my code, but I can't figure out what. I also have a background refresh task recording location coordinates every few minutes in the same app that works correctly, and I'm hesitant to start radically changing location manager code to debug the Visits feature since I'm worried I would break the background task feature. Any advice or direction is appreciated!


问:
PIG - ExecException: ERROR 1070: Could not resolve testPyUDF.testFunc using imports
I am facing a basic issue of importing a python script into PIG. i'm just trying a simple script like this:

PIG script

```<code>REGISTER 'test.py' using jython as testPyUDF;
load_data = LOAD '$input_path' USING PigStorage(',') AS (row1);
resp = FOREACH load_data generate row1, testPyUDF.testFunc() as (test:CHARARRAY);
DUMP resp;
</code>```

test.py (Python UDF to import):

```<code>@outputSchema("test:chararray")
def testFunc():
    return "test"
</code>```

But this results in an error: ExecException: ERROR 1070: Could not resolve testPyUDF.testFunc using imports: [, org.apache.pig.builtin., org.apache.pig.impl.builtin., com.yahoo.yst.sds.ULT., org.apache.pig.piggybank.evaluation., org.apache.pig.piggybank.evaluation.datetime., org.apache.pig.piggybank.evaluation.decode., org.apache.pig.piggybank.evaluation.math., org.apache.pig.piggybank.evaluation.stats., org.apache.pig.piggybank.evaluation.string., org.apache.pig.piggybank.evaluation.util., org.apache.pig.piggybank.evaluation.util.apachelogparser., string., util., math., datetime., sequence., util., java.lang., org.apache.pig.builtin., org.apache.pig.impl.builtin.]

I even tried changing the python script path in REGISTER to HDFS path:

REGISTER 'hdfs:///user/xxx/......./test.py' using jython as testPyUDF;

and also absolute path on local..

REGISTER '/homes/user/..../test.py' using jython as testPyUDF;

No luck either way. What I am missing here?

Body:
I am facing a basic issue of importing a python script into PIG. i'm just trying a simple script like this:

PIG script

REGISTER 'test.py' using jython as testPyUDF;
load_data = LOAD '$input_path' USING PigStorage(',') AS (row1);
resp = FOREACH load_data generate row1, testPyUDF.testFunc() as (test:CHARARRAY);
DUMP resp;

test.py (Python UDF to import):

@outputSchema("test:chararray")
def testFunc():
    return "test"

But this results in an error: ExecException: ERROR 1070: Could not resolve testPyUDF.testFunc using imports: [, org.apache.pig.builtin., org.apache.pig.impl.builtin., com.yahoo.yst.sds.ULT., org.apache.pig.piggybank.evaluation., org.apache.pig.piggybank.evaluation.datetime., org.apache.pig.piggybank.evaluation.decode., org.apache.pig.piggybank.evaluation.math., org.apache.pig.piggybank.evaluation.stats., org.apache.pig.piggybank.evaluation.string., org.apache.pig.piggybank.evaluation.util., org.apache.pig.piggybank.evaluation.util.apachelogparser., string., util., math., datetime., sequence., util., java.lang., org.apache.pig.builtin., org.apache.pig.impl.builtin.]

I even tried changing the python script path in REGISTER to HDFS path:

REGISTER 'hdfs:///user/xxx/......./test.py' using jython as testPyUDF;

and also absolute path on local..

REGISTER '/homes/user/..../test.py' using jython as testPyUDF;

No luck either way. What I am missing here?


问:
Annotation processing got disabled, since it requires a 1.6 compliant JVM
I am using the most updated University Edition of Any Logic.
I created a data set in a Parameter Variation Experiment. In running the experiment I get the following error "Annotation processing got disabled, since it requires a 1.6 compliant JVM"

I dont know what is causing this error. Im sure Any Logic comes with the required Java

I set the program to display the results of 20 runs for a certain count variable. The program runs, but no output is being shown on the interface. Output is being shown to the console a long with the error message in the title. I am wondering if getting rid of the error will display output in the user interface.


问:
How to load items using react-window-infinite-loader with react-window FixedSizeGrid
I'm attempting to use react-window-infinite-loader with a FixedSizeGrid from react-window.

Before I start, I created a codesandbox with a minimal example which I'll reference in the question.

The issues I'm having are:

The grid doesn't seem to load all of the items in view. This is seen on initial load where the bottom two items on the first page are still in the loading state. This is strange because according to the docs, the infinite loader will load rows up until the threshold, which is 15 by default.

When scrolling, items near the end of the grid are not loaded in. In the example this can be seen by scrolling to the bottom and the seeing a batch of items in the loading state.

I think that my issues are due to using the infinite loader with a grid but following the example of the list. I think that part of the issue is the isItemLoaded function because the index I get from that doesn't seem to correspond with the index of the item, but I think it's the row?

In the end I'm not sure how to resolve these as the documentation I've seen has the infinite loader being used with a list component instead of a grid component.


问:
JBPM task assign manually
I am working with JBPM I want manager of group to decide which task will be executed by which user in process evey time it is executed.
Is it possible if yes please tell how?

I am a beginner so I read documentation about it but I find nothing about my problem I think task nomination can be used but I find nothing in documentation about it.

Title: JBPM task assign manually


问:
Unable to import module in aws lambda
Getting this error from my python script whenever I run a test

```<code>{
  "errorMessage": "Unable to import module 'lambda_function': No module named 'PIL'",
  "errorType": "Runtime.ImportModuleError",
  "stackTrace": []
}
</code>```

This code should take an input from an aws s3 bucket and transform it to a vangogh painting, then send it back to another s3 bucket.

```<code>import boto3
import os
import sys
import uuid
from PIL import Image
import PIL.Image

s3_client = boto3.client('s3')

def vangogh_image(image_path, transformation_path):
    with Image.open(image_path).convert('RGB') as image:
        image.filter('VAN_GOGH')
        image.save(transformation_path)

def handler(event, context):
    for record in event['Records']:
        bucket = record['s3']['bucket']['name']
        key = record['s3']['object']['key']
        download_path = 'temp/{}{}'.format(uuid.uuid(), key)
        upload_filename = '/temp/vangogh-{}'.format(key)

        s3_client.download_file(bucket, key, download_path)
        vangogh_image(download_path, upload_filename)
        s3_client.upload_file(upload_filename, '{}-vangigh'.format(bucket), key)
</code>```

Title: Unable to import module in aws lambda

Body:
Getting this error from my python script whenever I run a test

{
  "errorMessage": "Unable to import module 'lambda_function': No module named 'PIL'",
  "errorType": "Runtime.ImportModuleError",
  "stackTrace": []
}

This code should take an input from an aws s3 bucket and transform it to a vangogh painting, then send it back to another s3 bucket.

import boto3
import os
import sys
import uuid
from PIL import Image
import PIL.Image

s3_client = boto3.client('s3')

def vangogh_image(image_path, transformation_path):
    with Image.open(image_path).convert('RGB') as image:
        image.filter('VAN_GOGH')
        image.save(transformation_path)

def handler(event, context):
    for record in event['Records']:
        bucket = record['s3']['bucket']['name']
        key = record['s3']['object']['key']
        download_path = 'temp/{}{}'.format(uuid.uuid(), key)
        upload_filename = '/temp/vangogh-{}'.format(key)

        s3_client.download_file(bucket, key, download_path)
        vangogh_image(download_path, upload_filename)
        s3_client.upload_file(upload_filename, '{}-vangigh'.format(bucket), key)


问:
I have a problem when using the chrome extension deepl in editorjs
I was using editorjs, but only when using the "header" and "pragraph" plugins,
I could not save.
After some research,
I found out that the problem occurs when using deepl as a chrome extension.

block «paragraph» skipped because saved data is invalid

I looked in the chrome developer tools and found that
The "deeplL" dev was inserted below the pure text

chrome developer tools

If I turn off the deepl extension, I can save successfully, but
Instead of making the application user do this
Is there any way to get editojs to function properly with the deepL extension on?


问:
NodeJS Express Server Failing to Launch on CPanel
I'm trying to upload my NodeJS express server to cdnapi.club through CPanel, It is using v16.17.1 and has DiscordJS, Express.

This is the error I am currently getting

```<code>Listening on port 3000
stderr:
/home/cdncraft/nodevenv/cdnapi.club/16/lib/node_modules/undici/lib/client.js:1184
        if (socket[kParser].timeoutType !== TIMEOUT_IDLE) {
                            ^

TypeError: Cannot read properties of undefined (reading 'timeoutType')
    at _resume (/home/cdncraft/nodevenv/cdnapi.club/16/lib/node_modules/undici/lib/client.js:1184:29)
    at resume (/home/cdncraft/nodevenv/cdnapi.club/16/lib/node_modules/undici/lib/client.js:1148:3)
    at connect (/home/cdncraft/nodevenv/cdnapi.club/16/lib/node_modules/undici/lib/client.js:1133:3)
</code>```

It starts listening to the actual port and then it crashes for some reason. I have been looking and trying to fix things for hours and haven't seen a fix. This is the index.js file for starting the server

```<code>const express = require('express');
const app = express();

const port = 3000
app.set('port', port)

const v1_path = "/api/v1"

app.listen(port, () => {
    console.log(`Listening on port ${port}`)
  })

app.get(`/`, (request, response) => {
    response.sendFile(__dirname + '/pages/index.html')
})
</code>```

This is the package.json https://pastes.dev/aUcTtdU0vX

Body:
I'm trying to upload my NodeJS express server to cdnapi.club through CPanel, It is using v16.17.1 and has DiscordJS, Express.

This is the error I am currently getting

Listening on port 3000
stderr:
/home/cdncraft/nodevenv/cdnapi.club/16/lib/node_modules/undici/lib/client.js:1184
        if (socket[kParser].timeoutType !== TIMEOUT_IDLE) {
                            ^

TypeError: Cannot read properties of undefined (reading 'timeoutType')
    at _resume (/home/cdncraft/nodevenv/cdnapi.club/16/lib/node_modules/undici/lib/client.js:1184:29)
    at resume (/home/cdncraft/nodevenv/cdnapi.club/16/lib/node_modules/undici/lib/client.js:1148:3)
    at connect (/home/cdncraft/nodevenv/cdnapi.club/16/lib/node_modules/undici/lib/client.js:1133:3)

It starts listening to the actual port and then it crashes for some reason. I have been looking and trying to fix things for hours and haven't seen a fix. This is the index.js file for starting the server

const express = require('express');
const app = express();

const port = 3000
app.set('port', port)

const v1_path = "/api/v1"

app.listen(port, () => {
    console.log(`Listening on port ${port}`)
  })

app.get(`/`, (request, response) => {
    response.sendFile(__dirname + '/pages/index.html')
})

This is the package.json https://pastes.dev/aUcTtdU0vX


问:
Why doesn't my file upload show up in my phoenix controller?
I’m attempting to upload a file to phoenix using JavaScript’s Fetch. The request looks as expected in the Chrome console, but I do not see any form data when I inspect the params or conn.body_params.

My client code looks like this:

```<code>        const formData = new FormData();

        formData.append("csvfile", file);

        this.fetch(this.resource, {
            method: 'POST',
            headers: new Headers({
                'Content-Type': 'multipart/form-data',
            }),
            body: file,
        })
</code>```

The request payload in the chrome console:

```<code>\------WebKitFormBoundarymsLCm9Lk39Yxssd0
 Content-Disposition: form-data; name="file"; filename="inventory.csv"
 Content-Type: text/csv

\------WebKitFormBoundarymsLCm9Lk39Yxssd0
 Content-Disposition: form-data; name="fileName"

inventory.csv
\------WebKitFormBoundarymsLCm9Lk39Yxssd0--
</code>```

Phoenix Controller (just trying to inspect the request)

```<code>  def upload(conn, params) do
    IO.inspect params
    IO.inspect conn.body_params
    json(conn, %{success: true})
  end
</code>```

I got an empty map for both inspect methods above.

In my controller, I have:

```<code>  plug Plug.Parsers,
    parsers: [:urlencoded, :multipart, :json],
    pass: ["*/*"],
    json_decoder: Jason
</code>```

config.exs

```<code>config :mime, :types, %{
  "text/csv" => ["csv", "CSV", "Csv"],
  "text/tab-separated-values" => ["tsv", "TSV"],
  "multipart/form-data" => ["multipart"]
}
</code>```

I feel like i’ve exhausted every forum, I could find on the topic. I know it’s something simple but it’s eluding me :slight_smile.

I expect the file to be available in the controller parameters but it is showing empty.

Body:
I’m attempting to upload a file to phoenix using JavaScript’s Fetch. The request looks as expected in the Chrome console, but I do not see any form data when I inspect the params or conn.body_params.

My client code looks like this:

        const formData = new FormData();

        formData.append("csvfile", file);

        this.fetch(this.resource, {
            method: 'POST',
            headers: new Headers({
                'Content-Type': 'multipart/form-data',
            }),
            body: file,
        })

The request payload in the chrome console:

\------WebKitFormBoundarymsLCm9Lk39Yxssd0
 Content-Disposition: form-data; name="file"; filename="inventory.csv"
 Content-Type: text/csv

\------WebKitFormBoundarymsLCm9Lk39Yxssd0
 Content-Disposition: form-data; name="fileName"

inventory.csv
\------WebKitFormBoundarymsLCm9Lk39Yxssd0--

Phoenix Controller (just trying to inspect the request)

  def upload(conn, params) do
    IO.inspect params
    IO.inspect conn.body_params
    json(conn, %{success: true})
  end

I got an empty map for both inspect methods above.

In my controller, I have:

  plug Plug.Parsers,
    parsers: [:urlencoded, :multipart, :json],
    pass: ["*/*"],
    json_decoder: Jason

config.exs

config :mime, :types, %{
  "text/csv" => ["csv", "CSV", "Csv"],
  "text/tab-separated-values" => ["tsv", "TSV"],
  "multipart/form-data" => ["multipart"]
}

I feel like i’ve exhausted every forum, I could find on the topic. I know it’s something simple but it’s eluding me :slight_smile.

I expect the file to be available in the controller parameters but it is showing empty.


问:
generate px.line graph (graph in web browser window). pytohn, pycharm, kmeans, graph, plotly
I have a working code that makes perfectly working graph with command plt.plot(df, cs.predict(df), 'o'). Its the right outpu but I need to make that graph in web browser window.(my teacher wants it that way). I got another code and it works with this:

```<code>fig = px.line(new_dataset2, x='time', y="value", title='coffee-machine wattage')
fig.show()
</code>```

Its a different .csv file but u get the idea, the graph looks like this:

the thing is it wont allow me to plot by px.line. Is there some way how to transform the plt.plot to plx.line?
I tried this:

```<code>fig = px.line(cs.predict(df), x='_time', y="_value", title='coffee-machine wattage',)
fig.show()
</code>```

but it throws an error

```<code>"Traceback (most recent call last):
  File "C:\Users\matus\PycharmProjects\fridge\cofeemashine-kmeans.py", line 28, in <module>
    fig = px.line(cs.predict(df), x='_time', y="_value", title='coffee-machine wattage',)
  File "C:\Users\matus\PycharmProjects\fridge\permut\lib\site-packages\plotly\express\_chart_types.py", line 264, in line
    return make_figure(args=locals(), constructor=go.Scatter)
  File "C:\Users\matus\PycharmProjects\fridge\permut\lib\site-packages\plotly\express\_core.py", line 1990, in make_figure
    args = build_dataframe(args, constructor)
  File "C:\Users\matus\PycharmProjects\fridge\permut\lib\site-packages\plotly\express\_core.py", line 1405, in build_dataframe
    df_output, wide_id_vars = process_args_into_dataframe(
  File "C:\Users\matus\PycharmProjects\fridge\permut\lib\site-packages\plotly\express\_core.py", line 1207, in process_args_into_dataframe
    raise ValueError(err_msg)
ValueError: Value of 'x' is not the name of a column in 'data_frame'. Expected one of [0] but received: _time

Process finished with exit code 1
"
</code>```

I will post my code, graph and part of my .csv file

```<code>import pandas as pd
from sklearn import cluster as cls
import matplotlib.pyplot as plt
import plotly.express as px

# Read the CSV file into a pandas DataFrame
df = pd.read_csv('coffee_machine_2022-11-22_09_22_influxdb_data.csv',header=0,usecols=['_time','_value'] )
print(df)
# Convert the _time column to a datetime type
df['_time'] = pd.to_datetime(df['_time'], format='%Y-%m-%dT%H:%M:%SZ')

# Set the index of the DataFrame to the _time column
df = df.set_index('_time')

# Print the resulting DataFrame
print(df)
# df.interpolate(method='linear') # not neccesary
cs = cls.KMeans(n_clusters=4)

cs.fit(df)
print(cs.predict([[1200]]))

plt.plot(df, cs.predict(df), 'o')
plt.show()

#below doesnt work
fig = px.line(cs.predict(df), x='_time', y="_value", title='coffee-machine wattage',)
fig.show()
</code>```

This is that working graph I need to change

part of my .csv file:

```<code>result,table,_start,_stop,_time,_value,_field,_measurement,device
,0,2022-10-23T08:22:04.124457277Z,2022-11-22T08:22:04.124457277Z,2022-10-24T12:12:35Z,44.61,power,shellies,Shelly_Kitchen-C_CoffeMachine/relay/0
,0,2022-10-23T08:22:04.124457277Z,2022-11-22T08:22:04.124457277Z,2022-10-24T12:12:40Z,17.33,power,shellies,Shelly_Kitchen-C_CoffeMachine/relay/0
,0,2022-10-23T08:22:04.124457277Z,2022-11-22T08:22:04.124457277Z,2022-10-24T12:12:45Z,41.2,power,shellies,Shelly_Kitchen-C_CoffeMachine/relay/0
,0,2022-10-23T08:22:04.124457277Z,2022-11-22T08:22:04.124457277Z,2022-10-24T12:12:51Z,33.49,power,shellies,Shelly_Kitchen-C_CoffeMachine/relay/0
,0,2022-10-23T08:22:04.124457277Z,2022-11-22T08:22:04.124457277Z,2022-10-24T12:12:56Z,55.68,power,shellies,Shelly_Kitchen-C_CoffeMachine/relay/0
,0,2022-10-23T08:22:04.124457277Z,2022-11-22T08:22:04.124457277Z,2022-10-24T12:12:57Z,55.68,power,shellies,Shelly_Kitchen-C_CoffeMachine/relay/0
,0,2022-10-23T08:22:04.124457277Z,2022-11-22T08:22:04.124457277Z,2022-10-24T12:13:02Z,25.92,power,shellies,Shelly_Kitchen-C_CoffeMachine/relay/0
,0,2022-10-23T08:22:04.124457277Z,2022-11-22T08:22:04.124457277Z,2022-10-24T12:13:08Z,5.71,power,shellies,Shelly_Kitchen-C_CoffeMachine/relay/0
,0,2022-10-23T08:22:04.124457277Z,2022-11-22T08:22:04.124457277Z,2022-10-24T12:13:14Z,553.75,power,shellies,Shelly_Kitchen-C_CoffeMachine/relay/0
,0,2022-10-23T08:22:04.124457277Z,2022-11-22T08:22:04.124457277Z,2022-10-24T12:13:19Z,5.71,power,shellies,Shelly_Kitchen-C_CoffeMachine/relay/0
,0,2022-10-23T08:22:04.124457277Z,2022-11-22T08:22:04.124457277Z,2022-10-24T12:13:24Z,8.95,power,shellies,Shelly_Kitchen-C_CoffeMachine/relay/0
,0,2022-10-23T08:22:04.124457277Z,2022-11-22T08:22:04.124457277Z,2022-10-24T12:13:26Z,5.69,power,shellies,Shelly_Kitchen-C_CoffeMachine/relay/0
,0,2022-10-23T08:22:04.124457277Z,2022-11-22T08:22:04.124457277Z,2022-10-24T12:13:30Z,5.63,power,shellies,Shelly_Kitchen-C_CoffeMachine/relay/0
</code>```

Body:
I have a working code that makes perfectly working graph with command plt.plot(df, cs.predict(df), 'o'). Its the right outpu but I need to make that graph in web browser window.(my teacher wants it that way). I got another code and it works with this:

fig = px.line(new_dataset2, x='time', y="value", title='coffee-machine wattage')
fig.show()

Its a different .csv file but u get the idea, the graph looks like this:

the thing is it wont allow me to plot by px.line. Is there some way how to transform the plt.plot to plx.line?
I tried this:

fig = px.line(cs.predict(df), x='_time', y="_value", title='coffee-machine wattage',)
fig.show()

but it throws an error

"Traceback (most recent call last):
  File "C:\Users\matus\PycharmProjects\fridge\cofeemashine-kmeans.py", line 28, in <module>
    fig = px.line(cs.predict(df), x='_time', y="_value", title='coffee-machine wattage',)
  File "C:\Users\matus\PycharmProjects\fridge\permut\lib\site-packages\plotly\express\_chart_types.py", line 264, in line
    return make_figure(args=locals(), constructor=go.Scatter)
  File "C:\Users\matus\PycharmProjects\fridge\permut\lib\site-packages\plotly\express\_core.py", line 1990, in make_figure
    args = build_dataframe(args, constructor)
  File "C:\Users\matus\PycharmProjects\fridge\permut\lib\site-packages\plotly\express\_core.py", line 1405, in build_dataframe
    df_output, wide_id_vars = process_args_into_dataframe(
  File "C:\Users\matus\PycharmProjects\fridge\permut\lib\site-packages\plotly\express\_core.py", line 1207, in process_args_into_dataframe
    raise ValueError(err_msg)
ValueError: Value of 'x' is not the name of a column in 'data_frame'. Expected one of [0] but received: _time

Process finished with exit code 1
"

I will post my code, graph and part of my .csv file

import pandas as pd
from sklearn import cluster as cls
import matplotlib.pyplot as plt
import plotly.express as px

# Read the CSV file into a pandas DataFrame
df = pd.read_csv('coffee_machine_2022-11-22_09_22_influxdb_data.csv',header=0,usecols=['_time','_value'] )
print(df)
# Convert the _time column to a datetime type
df['_time'] = pd.to_datetime(df['_time'], format='%Y-%m-%dT%H:%M:%SZ')

# Set the index of the DataFrame to the _time column
df = df.set_index('_time')

# Print the resulting DataFrame
print(df)
# df.interpolate(method='linear') # not neccesary
cs = cls.KMeans(n_clusters=4)

cs.fit(df)
print(cs.predict([[1200]]))

plt.plot(df, cs.predict(df), 'o')
plt.show()

#below doesnt work
fig = px.line(cs.predict(df), x='_time', y="_value", title='coffee-machine wattage',)
fig.show()

This is that working graph I need to change

part of my .csv file:

result,table,_start,_stop,_time,_value,_field,_measurement,device
,0,2022-10-23T08:22:04.124457277Z,2022-11-22T08:22:04.124457277Z,2022-10-24T12:12:35Z,44.61,power,shellies,Shelly_Kitchen-C_CoffeMachine/relay/0
,0,2022-10-23T08:22:04.124457277Z,2022-11-22T08:22:04.124457277Z,2022-10-24T12:12:40Z,17.33,power,shellies,Shelly_Kitchen-C_CoffeMachine/relay/0
,0,2022-10-23T08:22:04.124457277Z,2022-11-22T08:22:04.124457277Z,2022-10-24T12:12:45Z,41.2,power,shellies,Shelly_Kitchen-C_CoffeMachine/relay/0
,0,2022-10-23T08:22:04.124457277Z,2022-11-22T08:22:04.124457277Z,2022-10-24T12:12:51Z,33.49,power,shellies,Shelly_Kitchen-C_CoffeMachine/relay/0
,0,2022-10-23T08:22:04.124457277Z,2022-11-22T08:22:04.124457277Z,2022-10-24T12:12:56Z,55.68,power,shellies,Shelly_Kitchen-C_CoffeMachine/relay/0
,0,2022-10-23T08:22:04.124457277Z,2022-11-22T08:22:04.124457277Z,2022-10-24T12:12:57Z,55.68,power,shellies,Shelly_Kitchen-C_CoffeMachine/relay/0
,0,2022-10-23T08:22:04.124457277Z,2022-11-22T08:22:04.124457277Z,2022-10-24T12:13:02Z,25.92,power,shellies,Shelly_Kitchen-C_CoffeMachine/relay/0
,0,2022-10-23T08:22:04.124457277Z,2022-11-22T08:22:04.124457277Z,2022-10-24T12:13:08Z,5.71,power,shellies,Shelly_Kitchen-C_CoffeMachine/relay/0
,0,2022-10-23T08:22:04.124457277Z,2022-11-22T08:22:04.124457277Z,2022-10-24T12:13:14Z,553.75,power,shellies,Shelly_Kitchen-C_CoffeMachine/relay/0
,0,2022-10-23T08:22:04.124457277Z,2022-11-22T08:22:04.124457277Z,2022-10-24T12:13:19Z,5.71,power,shellies,Shelly_Kitchen-C_CoffeMachine/relay/0
,0,2022-10-23T08:22:04.124457277Z,2022-11-22T08:22:04.124457277Z,2022-10-24T12:13:24Z,8.95,power,shellies,Shelly_Kitchen-C_CoffeMachine/relay/0
,0,2022-10-23T08:22:04.124457277Z,2022-11-22T08:22:04.124457277Z,2022-10-24T12:13:26Z,5.69,power,shellies,Shelly_Kitchen-C_CoffeMachine/relay/0
,0,2022-10-23T08:22:04.124457277Z,2022-11-22T08:22:04.124457277Z,2022-10-24T12:13:30Z,5.63,power,shellies,Shelly_Kitchen-C_CoffeMachine/relay/0


问:
rtweet search_fullarchive returning duplicate Tweets
When using search_fullarchive, I am trying to pull n = 3000 tweets, but it returns a large list of 100 lists with data and 4 of these are empty lists, and the other 96 lists are data.frames of 34 rows and 38 columns. Upon further inspection, in each of the 96 lists, there are the same 34 Tweets and their information, meaning that instead of having information for (34 * 96 = ~3264 Tweets), I only have the information for 34 Tweets copied 96 times over in the large list. I have the Premium version of the Search Tweets API, and this call consumes 96 requests to the Twitter API.

The code I entered was

```<code>covid_data <- search_fullarchive(q="#covid19 -is:retweet has:geo", n = 3000, env_name = "researchpr", fromDate = "202202080000", toDate = "202205100000", token = twitter_token, parse = FALSE)
</code>```

I was expecting either 96 distinct lists of 34 rows, or 3000 distinct lists.

Body:
When using search_fullarchive, I am trying to pull n = 3000 tweets, but it returns a large list of 100 lists with data and 4 of these are empty lists, and the other 96 lists are data.frames of 34 rows and 38 columns. Upon further inspection, in each of the 96 lists, there are the same 34 Tweets and their information, meaning that instead of having information for (34 * 96 = ~3264 Tweets), I only have the information for 34 Tweets copied 96 times over in the large list. I have the Premium version of the Search Tweets API, and this call consumes 96 requests to the Twitter API.

The code I entered was

covid_data <- search_fullarchive(q="#covid19 -is:retweet has:geo", n = 3000, env_name = "researchpr", fromDate = "202202080000", toDate = "202205100000", token = twitter_token, parse = FALSE)

I was expecting either 96 distinct lists of 34 rows, or 3000 distinct lists.


问:
How do I select points in a Scatterplot and change their colour using mouse clicks and highlighting?
Currently I am working on a side project that will allow users to click points on scatter plots and change their colour. I'm trying to implement a method where users can highlight these points using the RectangleSelector in matplotlib but I've hit a brick wall.

I read through a solution posted here that works independently: Choosing a box of data points from a plot How can I get the same results with that solution? Thanks! Open to using other packages as well.

```<code>testdata=df2.to_numpy()

fig, ax = plt.subplots()
fig.set_size_inches(7.5, 8.25)
coll = ax.scatter(testdata[:,0], testdata[:,1], color=["black"]*len(testdata), picker = 5,s=[10]*len(testdata))

def on_pick(event):
    if event.mouseevent.button == 1:
        print (testdata[event.ind], "clicked")
        coll._facecolors[event.ind,:] = (1, 0, 0, 1)
        coll._edgecolors[event.ind,:] = (0, 0, 0, 1)
        fig.canvas.draw()
    elif event.mouseevent.button == 3:
        print (testdata[event.ind], "unclicked")
        coll._facecolors[event.ind,:] = (0, 0, 0, 1)
        coll._edgecolors[event.ind,:] = (0, 0, 0, 1)
        fig.canvas.draw()

fig.canvas.mpl_connect('pick_event', on_pick)

plt.show()
</code>```

Here's a snippet of my code. Right now I can change the colours of the scatterplot by using the Left click and Right clicks.

Body:
Currently I am working on a side project that will allow users to click points on scatter plots and change their colour. I'm trying to implement a method where users can highlight these points using the RectangleSelector in matplotlib but I've hit a brick wall.

I read through a solution posted here that works independently: Choosing a box of data points from a plot How can I get the same results with that solution? Thanks! Open to using other packages as well.

testdata=df2.to_numpy()

fig, ax = plt.subplots()
fig.set_size_inches(7.5, 8.25)
coll = ax.scatter(testdata[:,0], testdata[:,1], color=["black"]*len(testdata), picker = 5,s=[10]*len(testdata))

def on_pick(event):
    if event.mouseevent.button == 1:
        print (testdata[event.ind], "clicked")
        coll._facecolors[event.ind,:] = (1, 0, 0, 1)
        coll._edgecolors[event.ind,:] = (0, 0, 0, 1)
        fig.canvas.draw()
    elif event.mouseevent.button == 3:
        print (testdata[event.ind], "unclicked")
        coll._facecolors[event.ind,:] = (0, 0, 0, 1)
        coll._edgecolors[event.ind,:] = (0, 0, 0, 1)
        fig.canvas.draw()

fig.canvas.mpl_connect('pick_event', on_pick)

plt.show()

Here's a snippet of my code. Right now I can change the colours of the scatterplot by using the Left click and Right clicks.


问:
How to Get the Removed value in react select?
Sample

How to get the Remove value in multi react select


问:
How to enable Intel TSX in i7-7700 cpu?
I have this Intel i7-7700 CPU. lscpu shows it has Intel TSX feature.

```<code>flags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi
mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs
bts rep_good nopl xtopology nonstop_tsc aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx
est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer
aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch epb invpcid_single intel_pt ssbd ibrs ibpb stibp
kaiser tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms
invpcid rtm mpx rdseed adx smap clflushopt xsaveopt xsavec xgetbv1 dtherm ida arat pln pts hwp
hwp_notify hwp_act_window hwp_epp md_clear flush_l1d arch_capabilities
</code>```

However, I'm unable to use it. I was trying to run the test program from this repository https://github.com/blue9057/intel-tsx-sample. I check IA32_ARCH_CAPABILITIES with sudo rdmsr 0x10AH, and it returns 0xc04 which indicates bit 7 (TSX_CTRL) is 0. So there is no TSX support. I'm not an expert, I tried to change the MSR with sudo wrmsr 0x10ah 0xC84 and I get the following error,

```<code>wrmsr: CPU 0 cannot set MSR 0x0000010a to 0x0000000000000c84
</code>```

I also try to read IA32_TSX_CTRL with sudo rdmsr 0x122H and get the following error,

```<code>rdmsr: CPU 0 cannot read MSR 0x00000122
</code>```

I disable secure boot from BIOS

lscpu shows the microcode: 0xf0. I believe Intel disable this TSX feature with microde update. I'm not sure if this update is automatic or not. But as far I can remember I did not update any.

Not if this is relevent or not /usr/src/linux-headers-4.4.0-210/arch/x86/include/asm/msr-index.h files shows

```<code>#define MSR_IA32_TSX_CTRL               0x00000122
#define TSX_CTRL_RTM_DISABLE          BIT(0)  /* Disable RTM feature */
#define TSX_CTRL_CPUID_CLEAR          BIT(1)  /* Disable TSX enumeration */
</code>```

I also comment out #define TSX_CTRL_RTM_DISABLE and #define TSX_CTRL_CPUID_CLEAR but no luck.

I was wondering if there is any way I can enable this feature. I'm not sure If I provide enough information on this. Please let me know what other information will be helpful. I will add them. Or if you can point me in some directions that will be helpful.

OS version: Linux xxxx 4.4.0-210-generic x86_64

UPDATE

complete lscpu

```<code>xxx@xxx:~$ lscpu
Architecture:          x86_64
CPU op-mode(s):        32-bit, 64-bit
Byte Order:            Little Endian
CPU(s):                8
On-line CPU(s) list:   0-7
Thread(s) per core:    2
Core(s) per socket:    4
Socket(s):             1
NUMA node(s):          1
Vendor ID:             GenuineIntel
CPU family:            6
Model:                 158
Model name:            Intel(R) Core(TM) i7-7700 CPU @ 3.60GHz
Stepping:              9
CPU MHz:               900.000
CPU max MHz:           4200.0000
CPU min MHz:           800.0000
BogoMIPS:              7199.80
Virtualization:        VT-x
L1d cache:             32K
L1i cache:             32K
L2 cache:              256K
L3 cache:              8192K
NUMA node0 CPU(s):     0-7
Flags:                 fpu vme de pse tsc msr pae mce cx8 apic
sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse
sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art
arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc
aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2
ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe
popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm
3dnowprefetch epb invpcid_single intel_pt ssbd ibrs ibpb stibp
kaiser tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust
bmi1 hle avx2 smep bmi2 erms invpcid rtm mpx rdseed adx smap
clflushopt xsaveopt xsavec xgetbv1 dtherm ida arat pln pts hwp
hwp_notify hwp_act_window hwp_epp md_clear flush_l1d
arch_capabilities
</code>```

Kernel log shows,

```<code>$dmesg | grep "tsx=on"
[    0.000000] Command line: BOOT_IMAGE=/boot/vmlinuz-4.4.0-210-generic root=UUID=b528525a-2daa-4537-964e-106314e6a7bd ro quiet splash nokaslr tsx_async_abort=off tsx=on vt.handoff=7
[    0.000000] Kernel command line: BOOT_IMAGE=/boot/vmlinuz-4.4.0-210-generic root=UUID=b528525a-2daa-4537-964e-106314e6a7bd ro quiet splash nokaslr tsx_async_abort=off tsx=on vt.handoff=7

$dmesg | grep "TAA"
[    0.063012] TAA: Mitigation: Clear CPU buffers
[    0.209727] TAA CPU bug present and SMT on, data leak possible. See https://www.kernel.org/doc/html/latest/admin-guide/hw-vuln/tsx_async_abort.html for more details.
</code>```

Instead of using the example from the mentioned git repo, I was trying to run the following program,

```<code>#include <stdio.h>
#include <stdlib.h>
#include <immintrin.h>

int main(int argc, char *argv[]){
   volatile int result=-1;
   unsigned status;

   while(result != 1){
      if ((status = _xbegin()) == _XBEGIN_STARTED) {
         result=1;
         _xend();
      }else{
         printf("rtmCheck: Transaction failed\n");
         printf("Trying again ...\n");
         sleep(5);
      }
   }

   printf("rtmCheck : Result is %d\n", result);
   return 0;
}
</code>```

Makefile

```<code>CC=gcc
CFLAGS= -mrtm

rtmCheck: rtmCheck.o
    $(CC) $(CFLAGS) -o rtmCheck rtmCheck.o

clean:
    rm -f *.o rtmCheck
</code>```

output:

```<code>rtmCheck: Transaction failed
Trying again ...
rtmCheck: Transaction failed
Trying again ...
</code>```

Title: How to enable Intel TSX in i7-7700 cpu?

Body:
I have this Intel i7-7700 CPU. lscpu shows it has Intel TSX feature.

flags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi
mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs
bts rep_good nopl xtopology nonstop_tsc aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx
est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer
aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch epb invpcid_single intel_pt ssbd ibrs ibpb stibp
kaiser tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms
invpcid rtm mpx rdseed adx smap clflushopt xsaveopt xsavec xgetbv1 dtherm ida arat pln pts hwp
hwp_notify hwp_act_window hwp_epp md_clear flush_l1d arch_capabilities

However, I'm unable to use it. I was trying to run the test program from this repository https://github.com/blue9057/intel-tsx-sample. I check IA32_ARCH_CAPABILITIES with sudo rdmsr 0x10AH, and it returns 0xc04 which indicates bit 7 (TSX_CTRL) is 0. So there is no TSX support. I'm not an expert, I tried to change the MSR with sudo wrmsr 0x10ah 0xC84 and I get the following error,

wrmsr: CPU 0 cannot set MSR 0x0000010a to 0x0000000000000c84

I also try to read IA32_TSX_CTRL with sudo rdmsr 0x122H and get the following error,

rdmsr: CPU 0 cannot read MSR 0x00000122

I disable secure boot from BIOS

lscpu shows the microcode: 0xf0. I believe Intel disable this TSX feature with microde update. I'm not sure if this update is automatic or not. But as far I can remember I did not update any.

Not if this is relevent or not /usr/src/linux-headers-4.4.0-210/arch/x86/include/asm/msr-index.h files shows

#define MSR_IA32_TSX_CTRL               0x00000122
#define TSX_CTRL_RTM_DISABLE          BIT(0)  /* Disable RTM feature */
#define TSX_CTRL_CPUID_CLEAR          BIT(1)  /* Disable TSX enumeration */

I also comment out #define TSX_CTRL_RTM_DISABLE and #define TSX_CTRL_CPUID_CLEAR but no luck.

I was wondering if there is any way I can enable this feature. I'm not sure If I provide enough information on this. Please let me know what other information will be helpful. I will add them. Or if you can point me in some directions that will be helpful.

OS version: Linux xxxx 4.4.0-210-generic x86_64

UPDATE

complete lscpu

xxx@xxx:~$ lscpu
Architecture:          x86_64
CPU op-mode(s):        32-bit, 64-bit
Byte Order:            Little Endian
CPU(s):                8
On-line CPU(s) list:   0-7
Thread(s) per core:    2
Core(s) per socket:    4
Socket(s):             1
NUMA node(s):          1
Vendor ID:             GenuineIntel
CPU family:            6
Model:                 158
Model name:            Intel(R) Core(TM) i7-7700 CPU @ 3.60GHz
Stepping:              9
CPU MHz:               900.000
CPU max MHz:           4200.0000
CPU min MHz:           800.0000
BogoMIPS:              7199.80
Virtualization:        VT-x
L1d cache:             32K
L1i cache:             32K
L2 cache:              256K
L3 cache:              8192K
NUMA node0 CPU(s):     0-7
Flags:                 fpu vme de pse tsc msr pae mce cx8 apic
sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse
sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art
arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc
aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2
ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe
popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm
3dnowprefetch epb invpcid_single intel_pt ssbd ibrs ibpb stibp
kaiser tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust
bmi1 hle avx2 smep bmi2 erms invpcid rtm mpx rdseed adx smap
clflushopt xsaveopt xsavec xgetbv1 dtherm ida arat pln pts hwp
hwp_notify hwp_act_window hwp_epp md_clear flush_l1d
arch_capabilities

Kernel log shows,

$dmesg | grep "tsx=on"
[    0.000000] Command line: BOOT_IMAGE=/boot/vmlinuz-4.4.0-210-generic root=UUID=b528525a-2daa-4537-964e-106314e6a7bd ro quiet splash nokaslr tsx_async_abort=off tsx=on vt.handoff=7
[    0.000000] Kernel command line: BOOT_IMAGE=/boot/vmlinuz-4.4.0-210-generic root=UUID=b528525a-2daa-4537-964e-106314e6a7bd ro quiet splash nokaslr tsx_async_abort=off tsx=on vt.handoff=7

$dmesg | grep "TAA"
[    0.063012] TAA: Mitigation: Clear CPU buffers
[    0.209727] TAA CPU bug present and SMT on, data leak possible. See https://www.kernel.org/doc/html/latest/admin-guide/hw-vuln/tsx_async_abort.html for more details.

Instead of using the example from the mentioned git repo, I was trying to run the following program,

#include <stdio.h>
#include <stdlib.h>
#include <immintrin.h>

int main(int argc, char *argv[]){
   volatile int result=-1;
   unsigned status;

   while(result != 1){
      if ((status = _xbegin()) == _XBEGIN_STARTED) {
         result=1;
         _xend();
      }else{
         printf("rtmCheck: Transaction failed\n");
         printf("Trying again ...\n");
         sleep(5);
      }
   }

   printf("rtmCheck : Result is %d\n", result);
   return 0;
}

Makefile

CC=gcc
CFLAGS= -mrtm

rtmCheck: rtmCheck.o
    $(CC) $(CFLAGS) -o rtmCheck rtmCheck.o

clean:
    rm -f *.o rtmCheck

output:

rtmCheck: Transaction failed
Trying again ...
rtmCheck: Transaction failed
Trying again ...


问:
Possible to retrieve a httpOnly cookie with Supertest and send it back in the following request?
I am trying to access an endpoint on my Express server that has an http only cookie as part of the authentication dance to gain access.

Here we set the http only cookie:

```<code>res.cookie('jwt', refreshToken, { httpOnly: true, sameSite: 'none', secure: true, maxAge: 3 * 24 * 60 * 60 * 1000 });
            return res.send({ accessToken, role: userModel.role, profileId: userModel.profile });
</code>```

Here is my endpoint I am trying to integration test:

```<code>router.delete('/auth/delete/:id', basicAuth, checkAccountId, mentors.deleteMentorProfile);
</code>```

Inside basicAuth there is this: export const basicAuth = passport.authenticate('jwt', { session: false, failWithError: true });

What I think is required is that the httponly cookie is sent with the request to this endpoint. The line says passport.authenticate('jwt', ...) hence I must need the 'jwt' value to be there in a cookie.

And here is the code from my integration test:

```<code>const logInResponse = await api.post('/api/users/authenticate').send(userAcctCreationDetails);
            const jwtForTest = logInResponse.body.accessToken;
            const allMentors = await Mentor.find({});
            const testAccountMentorId = allMentors.find((mentor) => mentor.email === userToDelete.email)?._id.toString();
            // act
            const cookies = logInResponse.headers['set-cookie'][0];
            // console.log(cookies);
            const deletedProfileResponse = await api
                .delete('/api/mentor/auth/delete/' + testAccountMentorId)
                .set('Authorization', 'Bearer ' + jwtForTest)
                .set('jwt', cookies); // this fails!
</code>```

The line console.log(cookies) says some authentication credentials ending in   jwt=eyJhbGciOi...-2n21vxTNPOlS94-YeFhSN7o; Max-Age=259200; Path=/; Expires=Thu, 15 Dec 2022 01:26:24 GMT; HttpOnly; Secure; SameSite=None

My coworker tells me "httponly means the client can't access it" but can I at least send it back? How does a browser send it back if not via javascript?

Note I did google it and i found extreme scarcity of information about supertest and HTTP only cookies.

Body:
I am trying to access an endpoint on my Express server that has an http only cookie as part of the authentication dance to gain access.

Here we set the http only cookie:

res.cookie('jwt', refreshToken, { httpOnly: true, sameSite: 'none', secure: true, maxAge: 3 * 24 * 60 * 60 * 1000 });
            return res.send({ accessToken, role: userModel.role, profileId: userModel.profile });

Here is my endpoint I am trying to integration test:

router.delete('/auth/delete/:id', basicAuth, checkAccountId, mentors.deleteMentorProfile);

Inside basicAuth there is this: export const basicAuth = passport.authenticate('jwt', { session: false, failWithError: true });

What I think is required is that the httponly cookie is sent with the request to this endpoint. The line says passport.authenticate('jwt', ...) hence I must need the 'jwt' value to be there in a cookie.

And here is the code from my integration test:

const logInResponse = await api.post('/api/users/authenticate').send(userAcctCreationDetails);
            const jwtForTest = logInResponse.body.accessToken;
            const allMentors = await Mentor.find({});
            const testAccountMentorId = allMentors.find((mentor) => mentor.email === userToDelete.email)?._id.toString();
            // act
            const cookies = logInResponse.headers['set-cookie'][0];
            // console.log(cookies);
            const deletedProfileResponse = await api
                .delete('/api/mentor/auth/delete/' + testAccountMentorId)
                .set('Authorization', 'Bearer ' + jwtForTest)
                .set('jwt', cookies); // this fails!

The line console.log(cookies) says some authentication credentials ending in   jwt=eyJhbGciOi...-2n21vxTNPOlS94-YeFhSN7o; Max-Age=259200; Path=/; Expires=Thu, 15 Dec 2022 01:26:24 GMT; HttpOnly; Secure; SameSite=None

My coworker tells me "httponly means the client can't access it" but can I at least send it back? How does a browser send it back if not via javascript?

Note I did google it and i found extreme scarcity of information about supertest and HTTP only cookies.


问:
How to make a tkinter text element keep its selection after another element is selected
I am making a search function where the user can search for a string in their selection. The problem is, when another element is clicked on, the selection in the text element disapears.

If possible, I would like for the selection to remain after clicking on another element. I have tried to re-select the text using the .after() function, which didn't work.

Example:

import tkinter as tk

window = tk.Tk()

## Create a text element
text = tk.Text()
text.grid(sticky='NSWE')

## Create an entry element (example)
## When this element is clicked on, the selection in the text element disappears.
tk.Entry().grid(sticky='WE')

## Insert sample text
text.insert(1.0, 'Lorem ipsum dolor sit amet consectetur, adipisicing elit.')

window.mainloop()
```


问:
Scroll to reveal elements one by one
I'd like to have elements in an array be consecutively revealed as the user scrolls. I found some code from here which sort of does what I want, and modified it like this:

var unit = document.querySelectorAll("span");
var i = 0;
var currentID = 0;
var slideCount = unit.length;

document.addEventListener("scroll", (e) => {
  let scrolled =
    document.documentElement.scrollTop /
    (document.documentElement.scrollHeight -
      document.documentElement.clientHeight);

  unit.forEach(function (l, i) {
    if (i / unit.length < scrolled) {
      l.style.setProperty("--percentage", 1);
    } else {
      l.style.setProperty("--percentage", 0);
    }
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>:root {
  --percentage: 0;
}

#reveal span {
  opacity: var(--percentage);
}

body {
  height: 2000px;
}

#reveal {
  position: fixed;
  top: 0;
  left: 0;
}</code>```

  Scrolling
  should
  reveal
  elements
  one
  by
  one

```

I'm wondering how I can rework this code so it doesn't rely on the height of the body in order to operate. I'd like to eliminate all scrollbars (which is proving difficult on iOS).

Title: Scroll to reveal elements one by one

Body:
I'd like to have elements in an array be consecutively revealed as the user scrolls. I found some code from here which sort of does what I want, and modified it like this:

var unit = document.querySelectorAll("span");
var i = 0;
var currentID = 0;
var slideCount = unit.length;

document.addEventListener("scroll", (e) => {
  let scrolled =
    document.documentElement.scrollTop /
    (document.documentElement.scrollHeight -
      document.documentElement.clientHeight);

  unit.forEach(function (l, i) {
    if (i / unit.length < scrolled) {
      l.style.setProperty("--percentage", 1);
    } else {
      l.style.setProperty("--percentage", 0);
    }
  });
});

:root {
  --percentage: 0;
}

#reveal span {
  opacity: var(--percentage);
}

body {
  height: 2000px;
}

#reveal {
  position: fixed;
  top: 0;
  left: 0;
}

  Scrolling
  should
  reveal
  elements
  one
  by
  one

I'm wondering how I can rework this code so it doesn't rely on the height of the body in order to operate. I'd like to eliminate all scrollbars (which is proving difficult on iOS).


问:
Restoring an old database, need help installting plpythonu on windows
I haven't used postgres for a long time so I've forgotten much and probably much has changed. A database created in 2007 with postgres 9.1 involved plpythonu. When I restored it to postgres 15 using pgAdmin, the most common error was a complaint that plpythonu was not installed. This is on a windows pc.
I will need to install python. The way python would have been used originally would have been very very simple.

[1] Can I install a current version of python and not have compatibility issue?

[2] Is plpythonu still around, or do I need to use a replacement package? I read about plpython3u, but wasn't sure what it amounted to.

[3] could someone offer step by step for how to install plpythonu or whatever I should use on windows? I haven't used postgres for over a decade so I am a plain and simple novice.


问:
What is the specific issue with this function in C
```<code>#include <stdio.h>
#define N 5

int length(int b[]) {
    return sizeof(b)/sizeof(b[0]);
}
int main(void) {
    int a[N] = {1, 2, 3, 4 , 5};
    printf("%d\n", length(a));
}
</code>```

I've played around with this a bit and just wondering why it doesn't print the length of the array a. I know other ways to print the length, but I'm just wondering what the specific issue of this block of code is.

Body:
#include <stdio.h>
#define N 5

int length(int b[]) {
    return sizeof(b)/sizeof(b[0]);
}
int main(void) {
    int a[N] = {1, 2, 3, 4 , 5};
    printf("%d\n", length(a));
}

I've played around with this a bit and just wondering why it doesn't print the length of the array a. I know other ways to print the length, but I'm just wondering what the specific issue of this block of code is.


问:
Removing Blank Lines When Writing to Local File from Repository in Python
I have this code which takes lines of text from a github repository and writes it to a local text file. There is no separation between lines on the Github file - it's simply a list of words. When this gets written in the local file, there is an extra blank line between the others. For example,

Online shows:

lions

tigers

bears

The local text file writes:

lions

tigers

bears

How can I have it copy the text from the github file without extra lines?

```<code>url = 'https://raw.githubusercontent.com/listofmessages.txt'
Prompt = requests.get(url)

filehandle = open('helloworld.txt', 'w')
filehandle.write(Prompt.text)
filehandle.close()
</code>```

Body:
I have this code which takes lines of text from a github repository and writes it to a local text file. There is no separation between lines on the Github file - it's simply a list of words. When this gets written in the local file, there is an extra blank line between the others. For example,

Online shows:

lions

tigers

bears

The local text file writes:

lions

tigers

bears

How can I have it copy the text from the github file without extra lines?

url = 'https://raw.githubusercontent.com/listofmessages.txt'
Prompt = requests.get(url)

filehandle = open('helloworld.txt', 'w')
filehandle.write(Prompt.text)
filehandle.close()


问:
What is the best way to compare 2 records and find differences between each pair of properties?
I am using record from C# 9, for example

```<code>public record Receipt
{
    public string ClientName { get; init; } = "";

    public string ClientPhoneNumber { get; init; } = "";

    public List<OtherRecord> OtherInfo { get; init; } = new();
}
</code>```

and would like a function to compare 2 instances of that type and return a list of all values that are not identical on both sides (for auditing purpose).

I suppose it would use reflection so it can support any record type, without hardcoding the properties names?

Body:
I am using record from C# 9, for example

public record Receipt
{
    public string ClientName { get; init; } = "";

    public string ClientPhoneNumber { get; init; } = "";

    public List<OtherRecord> OtherInfo { get; init; } = new();
}

and would like a function to compare 2 instances of that type and return a list of all values that are not identical on both sides (for auditing purpose).

I suppose it would use reflection so it can support any record type, without hardcoding the properties names?


问:
Can't open some .csv file using read_csv()
I am writing a Python function to open two .csv files and make changes to the data inside. I am using pandas and pd.read_csv('text') to open the files. Everything works well and the function works for one .csv file. However, when I try it on a different smaller .csv file the file cannot even open.

This is part of the error I am getting when I try to open the .csv file.

```<code>Traceback (most recent call last):
  File "C:\Users\...\Downloads\test\test.py", line 3, in <module>
    df = pd.read_csv('data2.csv')
  File "C:\Users\...\AppData\Roaming\Python\Python311\site-packages\pandas\util\_decorators.py", line 211, in wrapper
    return func(*args, **kwargs)
  File "C:\Users\...\AppData\Roaming\Python\Python311\site-packages\pandas\util\_decorators.py", line 331, in wrapper
    return func(*args, **kwargs)
  File "C:\Users\...\AppData\Roaming\Python\Python311\site-packages\pandas\io\parsers\readers.py", line 950, in read_csv
    return _read(filepath_or_buffer, kwds)
  File "C:\Users\...\AppData\Roaming\Python\Python311\site-packages\pandas\io\parsers\readers.py", line 611, in _read
    return parser.read(nrows)
  File "C:\Users\...\AppData\Roaming\Python\Python311\site-packages\pandas\io\parsers\readers.py", line 1778, in read
    ) = self._engine.read(  # type: ignore[attr-defined]
  File "C:\Users\...\AppData\Roaming\Python\Python311\site-packages\pandas\io\parsers\c_parser_wrapper.py", line 230, in read
    chunks = self._reader.read_low_memory(nrows)
  File "pandas\_libs\parsers.pyx", line 808, in pandas._libs.parsers.TextReader.read_low_memory
  File "pandas\_libs\parsers.pyx", line 866, in pandas._libs.parsers.TextReader._read_rows
  File "pandas\_libs\parsers.pyx", line 852, in pandas._libs.parsers.TextReader._tokenize_rows
  File "pandas\_libs\parsers.pyx", line 1973, in pandas._libs.parsers.raise_parser_error
pandas.errors.ParserError: Error tokenizing data. C error: Expected 4 fields in line 8836, saw 5
</code>```

This is the code I am using to access the .csv files.

```<code>import pandas as pd

df = pd.read_csv('test.csv')
</code>```

All the files are in the correct folders and the file paths are all correct. Any help is appreciated, thanks

Body:
I am writing a Python function to open two .csv files and make changes to the data inside. I am using pandas and pd.read_csv('text') to open the files. Everything works well and the function works for one .csv file. However, when I try it on a different smaller .csv file the file cannot even open.

This is part of the error I am getting when I try to open the .csv file.

Traceback (most recent call last):
  File "C:\Users\...\Downloads\test\test.py", line 3, in <module>
    df = pd.read_csv('data2.csv')
  File "C:\Users\...\AppData\Roaming\Python\Python311\site-packages\pandas\util\_decorators.py", line 211, in wrapper
    return func(*args, **kwargs)
  File "C:\Users\...\AppData\Roaming\Python\Python311\site-packages\pandas\util\_decorators.py", line 331, in wrapper
    return func(*args, **kwargs)
  File "C:\Users\...\AppData\Roaming\Python\Python311\site-packages\pandas\io\parsers\readers.py", line 950, in read_csv
    return _read(filepath_or_buffer, kwds)
  File "C:\Users\...\AppData\Roaming\Python\Python311\site-packages\pandas\io\parsers\readers.py", line 611, in _read
    return parser.read(nrows)
  File "C:\Users\...\AppData\Roaming\Python\Python311\site-packages\pandas\io\parsers\readers.py", line 1778, in read
    ) = self._engine.read(  # type: ignore[attr-defined]
  File "C:\Users\...\AppData\Roaming\Python\Python311\site-packages\pandas\io\parsers\c_parser_wrapper.py", line 230, in read
    chunks = self._reader.read_low_memory(nrows)
  File "pandas\_libs\parsers.pyx", line 808, in pandas._libs.parsers.TextReader.read_low_memory
  File "pandas\_libs\parsers.pyx", line 866, in pandas._libs.parsers.TextReader._read_rows
  File "pandas\_libs\parsers.pyx", line 852, in pandas._libs.parsers.TextReader._tokenize_rows
  File "pandas\_libs\parsers.pyx", line 1973, in pandas._libs.parsers.raise_parser_error
pandas.errors.ParserError: Error tokenizing data. C error: Expected 4 fields in line 8836, saw 5

This is the code I am using to access the .csv files.

import pandas as pd

df = pd.read_csv('test.csv')

All the files are in the correct folders and the file paths are all correct. Any help is appreciated, thanks


问:
Shoryuken appears attempts to reprocess inflight SQS message
I currently have a rails 6 app using Shoryuken (5.2.3) with SQS to asynchronously handle user initiated image processing and uploading. Everything appears to be working as expected as far as the side effects of the job (which includes the Shoryuken::Worker) are considered. The Shoryuken logs (from using the command bundle exec shoryuken -q my-queue-name -R) generates some confusing output. The job has some puts statements for debugging, and while watching the initial run generate the expected sequence of puts statements, I start seeing output that would imply that the  job (the one still inflight) has been initiated again, before finishing or erroring out. This continues until the pool of threads have been exhausted, and this error is thrown.

```<code>ERROR: Processor failed: could not obtain a connection from the pool within 5.000 seconds (waited 5.000 seconds); all pooled connections were in use
</code>```

My concern is that this could block connections for users and negatively impact user experience or have unexpected consequences with partial job runs (despite the job being idempotent). I assume I might need to configure the retry settings but thats just a guess, and input on this would be helpful.

Body:
I currently have a rails 6 app using Shoryuken (5.2.3) with SQS to asynchronously handle user initiated image processing and uploading. Everything appears to be working as expected as far as the side effects of the job (which includes the Shoryuken::Worker) are considered. The Shoryuken logs (from using the command bundle exec shoryuken -q my-queue-name -R) generates some confusing output. The job has some puts statements for debugging, and while watching the initial run generate the expected sequence of puts statements, I start seeing output that would imply that the  job (the one still inflight) has been initiated again, before finishing or erroring out. This continues until the pool of threads have been exhausted, and this error is thrown.

ERROR: Processor failed: could not obtain a connection from the pool within 5.000 seconds (waited 5.000 seconds); all pooled connections were in use

My concern is that this could block connections for users and negatively impact user experience or have unexpected consequences with partial job runs (despite the job being idempotent). I assume I might need to configure the retry settings but thats just a guess, and input on this would be helpful.


问:
How do i do unit tests in python?
I have a simple program for traslating morse code back and forth as a school project and part of it is also writting unit tests. I ve tried for multiple hours but was not succesful at all

```<code>dictionary={'A':'.-', 'B':'-...',
            'C':'-.-.', 'D':'-..', 'E':'.','F':'..-.', 'G':'--.', 'H':'....',
            'I':'..', 'J':'.---', 'K':'-.-','L':'.-..', 'M':'--', 'N':'-.',
            'O':'---', 'P':'.--.', 'Q':'--.-','R':'.-.', 'S':'...', 'T':'-',
            'U':'..-', 'V':'...-', 'W':'.--','X':'-..-', 'Y':'-.--', 'Z':'--..'}

dictionary2={'.-':'A','-...':'B','-.-.':'C','-..':'D', '.':'E','..-.':'F','--.':'G','....':'H',
             '..':'I','.---':'J', '-.-':'K','.-..':'L', '--':'M', '-.':'N',
             '---':'O', '.--.':'P', '--.-':'Q','.-.':'R', '...':'S', '-':'T',
             '..-':'U', '...-':'V', '.--':'W','-..-':'X', '-.--':'Y', '--..':'Z', '':' '}

def coding(s):
    void=""
    for i in s: #indexing
        if i != ' ':
            void+=dictionary[i]+' '
        else:
            void +=' '

    print(void)

def decoding(s):
    void = ""
    splitstring=s.split("  ")

    splitstring = s.split(" ")#splitting by spaces
    #splitstring=splitstring.remove('')

    for i in splitstring: #indexing
        void += dictionary2[i]

    print(void)

def selection(f):
     f=int(input("1. Z ČEŠTINY DO MORSEOVKY || 2. Z MORESOVKY DO ČEŠTINY ")) # menu
     return f

c = 1
d = 0
while(c!="0"):
    d =selection(d)
    a=input("ZADEJ TEXT NA ŠIFROVÁNÍ: ")
    a=a.upper()

    startUp="" # not being used but program cant be ran without it for some reason

    if d==1: # translating to morse code
        coding(a)

    else: # translating from morse code
         decoding(a)

    c = input(("POKUD CHCTE PROGRAM UKONČIT, ZADEJTE 0 || PRO POKRAČOVÁNÍ ZADEJTE LIBOVOLNÝ ZNAK : "))
</code>```

this is what i ve tried:

```<code>import pytest
from example import coding
from example import decoding

def test_coding():
    assert coding('HELLO') == '.... . .-.. .-.. --- '
    assert coding('WORLD') == '.-- .-. .. -. ..-. '
    assert coding('HELLO WORLD') == '.... . .-.. .-.. ---  .-- .-. .. -. ..-. '

test_coding()

#To write unit tests for the decoding() function, we can test that it decodes strings correctly by comparing the output of the function with the expected result. For example:

def test_decoding():
    assert decoding('.... . .-.. .-.. --- ') == 'HELLO'
    assert decoding('.-- .-. .. -. ..-. ') == 'WORLD'
    assert decoding('.... . .-.. .-.. ---  .-- .-. .. -. ..-. ') == 'HELLO WORLD'

test_decoding()

</code>```

My teacher wants those tests to be ran with this command:

```<code>py.exe -m pytest --cov=. --cov-fail-under=66
</code>```

in command block, it has to reach at least 66% success rate.

thus far i ve always ended up with this result:

```<code>=========================================================================================================== test session starts ============================================================================================================
platform win32 -- Python 3.9.6, pytest-7.2.0, pluggy-1.0.0
rootdir: C:\Users\ash31\OneDrive\Plocha\AP1VS-final-project
plugins: cov-4.0.0
collected 0 items / 1 error

================================================================================================================== ERRORS ==================================================================================================================
_____________________________________________________________________________________________________ ERROR collecting example_test.py _____________________________________________________________________________________________________
example_test.py:1: in <module>
    from example import coding
example.py:51: in <module>
    d =selection(d)
example.py:43: in selection
    f=int(input("1. Z ČEŠTINY DO MORSEOVKY || 2. Z MORESOVKY DO ČEŠTINY ")) # menu
..\..\..\AppData\Local\Programs\Python\Python39\lib\site-packages\_pytest\capture.py:192: in read
    raise OSError(
E   OSError: pytest: reading from stdin while output is captured!  Consider using `-s`.
------------------------------------------------------------------------------------------------------------- Captured stdout --------------------------------------------------------------------------------------------------------------
1. Z ČEŠTINY DO MORSEOVKY || 2. Z MORESOVKY DO ČEŠTINY

----------- coverage: platform win32, python 3.9.6-final-0 -----------
Name              Stmts   Miss  Cover
-------------------------------------
example.py           32     22    31%
example_test.py      24     23     4%
-------------------------------------
TOTAL                56     45    20%

FAIL Required test coverage of 66% not reached. Total coverage: 19.64%
========================================================================================================= short test summary info ==========================================================================================================
ERROR example_test.py - OSError: pytest: reading from stdin while output is captured!  Consider using `-s`.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
============================================================================================================= 1 error in 0.46s =============================================================================================================
</code>```

Title: How do i do unit tests in python?

Body:
I have a simple program for traslating morse code back and forth as a school project and part of it is also writting unit tests. I ve tried for multiple hours but was not succesful at all

dictionary={'A':'.-', 'B':'-...',
            'C':'-.-.', 'D':'-..', 'E':'.','F':'..-.', 'G':'--.', 'H':'....',
            'I':'..', 'J':'.---', 'K':'-.-','L':'.-..', 'M':'--', 'N':'-.',
            'O':'---', 'P':'.--.', 'Q':'--.-','R':'.-.', 'S':'...', 'T':'-',
            'U':'..-', 'V':'...-', 'W':'.--','X':'-..-', 'Y':'-.--', 'Z':'--..'}

dictionary2={'.-':'A','-...':'B','-.-.':'C','-..':'D', '.':'E','..-.':'F','--.':'G','....':'H',
             '..':'I','.---':'J', '-.-':'K','.-..':'L', '--':'M', '-.':'N',
             '---':'O', '.--.':'P', '--.-':'Q','.-.':'R', '...':'S', '-':'T',
             '..-':'U', '...-':'V', '.--':'W','-..-':'X', '-.--':'Y', '--..':'Z', '':' '}

def coding(s):
    void=""
    for i in s: #indexing
        if i != ' ':
            void+=dictionary[i]+' '
        else:
            void +=' '

    print(void)

def decoding(s):
    void = ""
    splitstring=s.split("  ")

    splitstring = s.split(" ")#splitting by spaces
    #splitstring=splitstring.remove('')

    for i in splitstring: #indexing
        void += dictionary2[i]

    print(void)

def selection(f):
     f=int(input("1. Z ČEŠTINY DO MORSEOVKY || 2. Z MORESOVKY DO ČEŠTINY ")) # menu
     return f

c = 1
d = 0
while(c!="0"):
    d =selection(d)
    a=input("ZADEJ TEXT NA ŠIFROVÁNÍ: ")
    a=a.upper()

    startUp="" # not being used but program cant be ran without it for some reason

    if d==1: # translating to morse code
        coding(a)

    else: # translating from morse code
         decoding(a)

    c = input(("POKUD CHCTE PROGRAM UKONČIT, ZADEJTE 0 || PRO POKRAČOVÁNÍ ZADEJTE LIBOVOLNÝ ZNAK : "))

this is what i ve tried:

import pytest
from example import coding
from example import decoding

def test_coding():
    assert coding('HELLO') == '.... . .-.. .-.. --- '
    assert coding('WORLD') == '.-- .-. .. -. ..-. '
    assert coding('HELLO WORLD') == '.... . .-.. .-.. ---  .-- .-. .. -. ..-. '

test_coding()

#To write unit tests for the decoding() function, we can test that it decodes strings correctly by comparing the output of the function with the expected result. For example:

def test_decoding():
    assert decoding('.... . .-.. .-.. --- ') == 'HELLO'
    assert decoding('.-- .-. .. -. ..-. ') == 'WORLD'
    assert decoding('.... . .-.. .-.. ---  .-- .-. .. -. ..-. ') == 'HELLO WORLD'

test_decoding()

My teacher wants those tests to be ran with this command:

py.exe -m pytest --cov=. --cov-fail-under=66

in command block, it has to reach at least 66% success rate.

thus far i ve always ended up with this result:

=========================================================================================================== test session starts ============================================================================================================
platform win32 -- Python 3.9.6, pytest-7.2.0, pluggy-1.0.0
rootdir: C:\Users\ash31\OneDrive\Plocha\AP1VS-final-project
plugins: cov-4.0.0
collected 0 items / 1 error

================================================================================================================== ERRORS ==================================================================================================================
_____________________________________________________________________________________________________ ERROR collecting example_test.py _____________________________________________________________________________________________________
example_test.py:1: in <module>
    from example import coding
example.py:51: in <module>
    d =selection(d)
example.py:43: in selection
    f=int(input("1. Z ČEŠTINY DO MORSEOVKY || 2. Z MORESOVKY DO ČEŠTINY ")) # menu
..\..\..\AppData\Local\Programs\Python\Python39\lib\site-packages\_pytest\capture.py:192: in read
    raise OSError(
E   OSError: pytest: reading from stdin while output is captured!  Consider using `-s`.
------------------------------------------------------------------------------------------------------------- Captured stdout --------------------------------------------------------------------------------------------------------------
1. Z ČEŠTINY DO MORSEOVKY || 2. Z MORESOVKY DO ČEŠTINY

----------- coverage: platform win32, python 3.9.6-final-0 -----------
Name              Stmts   Miss  Cover
-------------------------------------
example.py           32     22    31%
example_test.py      24     23     4%
-------------------------------------
TOTAL                56     45    20%

FAIL Required test coverage of 66% not reached. Total coverage: 19.64%
========================================================================================================= short test summary info ==========================================================================================================
ERROR example_test.py - OSError: pytest: reading from stdin while output is captured!  Consider using `-s`.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
============================================================================================================= 1 error in 0.46s =============================================================================================================


问:
Power Automate Unattended Bot to sync OneDrive files
When using Unattended bots in Power Automate is there a way to sync OneDrive files?

Scenario: We are forced to use Power Automate Desktop to convert an excel online .xls file to .xlsx , however because it's an unattended bot, the file/changes are not visible to other users that the file has been shared with.

Resolution Tried: In Power Automate Desktop I attempted to use the Run Application action to force the sync, but it's not working for me.

Any other ideas?

Thanks


问:
Why do I keep getting an 'App not compatible with buildpack:' error when trying to deploy my django site to Heroku?
Here's the error:

Building on the Heroku-22 stack -----> Using buildpack: heroku/python -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure ! Push failed

I've been following YouTube tutorials. Nothing helps. I tried reading the Heroku docs. To no avail.

Please help.

Thank you!


问:
Intermittent timeout issues when communicating eks and rds
I would like to know the cause or solution of the timeout that occurs in EKS.
When communicating with other AWS resources, such as RDS or MSK, in the pod of EKS, a timeout  occurs intermittently.
There's not much traffic.
I am inquiring because it is a phenomenon that has not been found when using ECS or EC2, not EKS.

All resources are in the same vpc and connection is possible, but periodically times out.

RDS error log follows:
Cloud not receive data from client: Connection reset by peer

I referred to this link, but it didn't work.
https://aws.amazon.com/ko/premiumsupport/knowledge-center/rds-aurora-postgresql-connection-errors/

What am I doing wrong?


问:
Displaying a series of RGB array images in DirectX or Vulkan
Welcome.
I have the following problem. I have a function written in C++, and it returns an array of RGB pixels representing a single image. Each subsequent call to this function returns a new array representing the next frame of an animation. I want to display this animation frame by frame in a window, and I want this to be as fast as possible.

I have used GDI+ but have not been able to get satisfactory efficiency. I have therefore become interested in the DirectX and Vulkan libraries. Unfortunately for me, but at first glance, these libraries seem downright overwhelming to learn. Moreover, the tutorials I found focus on 3d graphics, which I don't need because, as I wrote earlier, I only want to display a series of RGB pixel arrays.

And this is where my question comes in.

Is there a boilerplate project on Github or anywhere else that I could use? If not, does anyone here know of a tutorial that, without going into learning 3D graphics, would help me to learn DirectX or Vulkan enough so that I could write the code I need myself?
Thank you in advance for your reply.


问:
Sendgrid emails ending in spam
Can someone point me to good article about what I can do to prevent my sendgrid emails from ending in spam? I’m using gmail.

I implemented an email drip campaign that ends up in the promotions folder or spam.

Title: Sendgrid emails ending in spam


问:
Issue with py- to-exe or cx_file or whatever. The code has several local submodules KIvymd+python
Good eve folks,
From the beggining I started with trying to use the pyinstaller based, auto-py-to-exe. I tryied every set of commands possible but It didn't work. The process of converting finishes but It returns tracebacks saying "Could not find a window provider" (error log in the picture below)
.

Basically the settings I made were: add every file which was in the main.py directory in the 'additional files' menu; I filled the 'advance settings->hidden modules' with the names of all the file employed on the project.

In the most I used kivy and kivymd modules. I dont think It's necessary to post the scripts here once It runs without errors.

I d appreciate a lot ya guys help!! I already surfed all around the web, besides having watched every youtube tutorials but auto-py-to-exe/pyinstaller keeps not working. At last I also d like to share a cx_freeze unsucesful approach, I headed to this alternative making a cx_freeze setup file to run with python 3.7:

```<code>import sys
from cx_Freeze import setup, Executable
from kivy.lang.builder import Builder
Builder.load_file('Mainwidget.kv')
Builder.load_file('Popups.kv')
from kivy.uix.popup import Popup
from kivymd.app import MDApp
from kivymd.uix.screen import MDScreen
from kivy.clock import Clock
from kivymd.uix.boxlayout import BoxLayout
from main_widget import Main_widget, ScanPopup, ModbusPopUp
from pyModbusTCP.client import ModbusClient
from kivy.core.window import Window
from threading import Thread
from time import sleep
from datetime import datetime
from kivy.uix.label import Label
import random
from kivymd.uix.snackbar import Snackbar
from kivy_garden.graph import LinePlot
from TimesSeriesGraph import TimeSeriesGraph
from bdhandle import BDHandle

base = None
if sys.platform == "win32":
    base = "Win32GUI"

executables = [
        Executable("main.py", base=base)
]

buildOptions = dict(
        packages = [],
        includes = ["kivy","kivymd","bdhandle","threading","main_widget","time","datetime","random","TimesSeriesGraph"],
        include_files = [],
        excludes = []
)

setup(
    name = "Refinery",
    version = "1.0",
    description = "Refinery supervisory",
    options = dict(build_exe = buildOptions),
    executables = executables
 )
</code>```

At the end of the day I dont know which way is the best whether using cx_freeze or pyinstaller. So far neither of them worked, and as an begginer app curious, I had never generated exes before.
Waiting for your answers with help and patience! Cya

Edit (PYINSTALLER CONFIG DRAWN FROM AUTO-PY-TO-RUN):

pyinstaller --noconfirm --onedir --console --add-data "C:/Users/User/source/repos/RefineryKVMD/bdhandle.py;." --add-data "C:/Users/User/source/repos/RefineryKVMD/main_widget.py;." --add-data "C:/Users/User/source/repos/RefineryKVMD/Mainwidget.kv;." --add-data "C:/Users/User/source/repos/RefineryKVMD/Popups.kv;." --add-data "C:/Users/User/source/repos/RefineryKVMD/Refinaria.png;." --add-data "C:/Users/User/source/repos/RefineryKVMD/requirements.txt;." --add-data "C:/Users/User/source/repos/RefineryKVMD/TimesSeriesGraph.py;." --add-data "C:/Users/User/source/repos/RefineryKVMD/Lib;Lib/" --add-data "C:/Users/User/source/repos/RefineryKVMD/Scripts;Scripts/" --add-data "C:/Users/User/source/repos/RefineryKVMD/venv;venv/" --hidden-import "kivy" --hidden-import "kivymd" --hidden-import "main_widget" --hidden-import "pyModbusTCP" --hidden-import "threading" --hidden-import "time" --hidden-import "datetime" --hidden-import "random" --hidden-import "TimesSeriesGraph" --hidden-import "bdhandle"  "C:/Users/User/source/repos/RefineryKVMD/main.py"

Body:
Good eve folks,
From the beggining I started with trying to use the pyinstaller based, auto-py-to-exe. I tryied every set of commands possible but It didn't work. The process of converting finishes but It returns tracebacks saying "Could not find a window provider" (error log in the picture below)
.

Basically the settings I made were: add every file which was in the main.py directory in the 'additional files' menu; I filled the 'advance settings->hidden modules' with the names of all the file employed on the project.

In the most I used kivy and kivymd modules. I dont think It's necessary to post the scripts here once It runs without errors.

I d appreciate a lot ya guys help!! I already surfed all around the web, besides having watched every youtube tutorials but auto-py-to-exe/pyinstaller keeps not working. At last I also d like to share a cx_freeze unsucesful approach, I headed to this alternative making a cx_freeze setup file to run with python 3.7:

import sys
from cx_Freeze import setup, Executable
from kivy.lang.builder import Builder
Builder.load_file('Mainwidget.kv')
Builder.load_file('Popups.kv')
from kivy.uix.popup import Popup
from kivymd.app import MDApp
from kivymd.uix.screen import MDScreen
from kivy.clock import Clock
from kivymd.uix.boxlayout import BoxLayout
from main_widget import Main_widget, ScanPopup, ModbusPopUp
from pyModbusTCP.client import ModbusClient
from kivy.core.window import Window
from threading import Thread
from time import sleep
from datetime import datetime
from kivy.uix.label import Label
import random
from kivymd.uix.snackbar import Snackbar
from kivy_garden.graph import LinePlot
from TimesSeriesGraph import TimeSeriesGraph
from bdhandle import BDHandle

base = None
if sys.platform == "win32":
    base = "Win32GUI"

executables = [
        Executable("main.py", base=base)
]

buildOptions = dict(
        packages = [],
        includes = ["kivy","kivymd","bdhandle","threading","main_widget","time","datetime","random","TimesSeriesGraph"],
        include_files = [],
        excludes = []
)

setup(
    name = "Refinery",
    version = "1.0",
    description = "Refinery supervisory",
    options = dict(build_exe = buildOptions),
    executables = executables
 )

At the end of the day I dont know which way is the best whether using cx_freeze or pyinstaller. So far neither of them worked, and as an begginer app curious, I had never generated exes before.
Waiting for your answers with help and patience! Cya

Edit (PYINSTALLER CONFIG DRAWN FROM AUTO-PY-TO-RUN):

pyinstaller --noconfirm --onedir --console --add-data "C:/Users/User/source/repos/RefineryKVMD/bdhandle.py;." --add-data "C:/Users/User/source/repos/RefineryKVMD/main_widget.py;." --add-data "C:/Users/User/source/repos/RefineryKVMD/Mainwidget.kv;." --add-data "C:/Users/User/source/repos/RefineryKVMD/Popups.kv;." --add-data "C:/Users/User/source/repos/RefineryKVMD/Refinaria.png;." --add-data "C:/Users/User/source/repos/RefineryKVMD/requirements.txt;." --add-data "C:/Users/User/source/repos/RefineryKVMD/TimesSeriesGraph.py;." --add-data "C:/Users/User/source/repos/RefineryKVMD/Lib;Lib/" --add-data "C:/Users/User/source/repos/RefineryKVMD/Scripts;Scripts/" --add-data "C:/Users/User/source/repos/RefineryKVMD/venv;venv/" --hidden-import "kivy" --hidden-import "kivymd" --hidden-import "main_widget" --hidden-import "pyModbusTCP" --hidden-import "threading" --hidden-import "time" --hidden-import "datetime" --hidden-import "random" --hidden-import "TimesSeriesGraph" --hidden-import "bdhandle"  "C:/Users/User/source/repos/RefineryKVMD/main.py"


问:
Angular Bootstrap import loads css but not JS
I have had lots of problems importing bootstrap using the npm modules.
I even tried updating my angular to v 15 to try fix the issue.

If I do not either include the assets manually or use an external CDN, the bootstrap routing and other functions stop working. Even explicitly including the ../node_modules/ ... files doesn't work. I tried following the different steps here: https://www.techiediaries.com/angular-bootstrap/ without success either.

package.json

  "@popperjs/core": "^2.11.6",
  "bootstrap": "^4.6.2",
  "jquery": "^3.6.0"
```
<h2>angular.json</h2>
<pre class="lang-json prettyprint-override"><code>...
  "projects": {
    "my-project": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "assets": [
              "src/images",
              "src/js",
              "src/css",
              "src/assets",
              "src/favicon.ico"
            ],
            "styles": [
              "src/styles.css",
              "./node_modules/cookieconsent/build/cookieconsent.min.css",
              "./node_modules/bootstrap/dist/css/bootstrap.min.css"
            ],
            "scripts": [
              "./node_modules/jquery/dist/jquery.min.js",
              "./node_modules/cookieconsent/build/cookieconsent.min.js",
              "./node_modules/popper.js/dist/popper.min.js",
              "./node_modules/bootstrap/dist/js/bootstrap.min.js"
            ]
...
</code>```

index.html

<!doctype html>

  <meta charset="utf-8">
  <title>MyProject</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

      <app-root></app-root>

```

Body:
I have had lots of problems importing bootstrap using the npm modules.
I even tried updating my angular to v 15 to try fix the issue.

If I do not either include the assets manually or use an external CDN, the bootstrap routing and other functions stop working. Even explicitly including the ../node_modules/ ... files doesn't work. I tried following the different steps here: https://www.techiediaries.com/angular-bootstrap/ without success either.

package.json

  "@popperjs/core": "^2.11.6",
  "bootstrap": "^4.6.2",
  "jquery": "^3.6.0"

angular.json

...
  "projects": {
    "my-project": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "assets": [
              "src/images",
              "src/js",
              "src/css",
              "src/assets",
              "src/favicon.ico"
            ],
            "styles": [
              "src/styles.css",
              "./node_modules/cookieconsent/build/cookieconsent.min.css",
              "./node_modules/bootstrap/dist/css/bootstrap.min.css"
            ],
            "scripts": [
              "./node_modules/jquery/dist/jquery.min.js",
              "./node_modules/cookieconsent/build/cookieconsent.min.js",
              "./node_modules/popper.js/dist/popper.min.js",
              "./node_modules/bootstrap/dist/js/bootstrap.min.js"
            ]
...

index.html

<!doctype html>

  <meta charset="utf-8">
  <title>MyProject</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

      <app-root></app-root>


问:
React - axios fetching empty array
I could not fetch the data using axios, despite fetching it succesfully through postman. Not sure why this is happening

Here's my function in react

import axios from "axios";

const url = "http://localhost:3001/tasks/";

const getDashboardData = async (setTasks) => {
  await axios.get(`${url}`, {
    uid: sessionStorage.getItem("uid")
  })
    .then((result) => {
      console.log(result.data);

      setTasks(result.data);
    })
    .catch((error) => {
      console.log(error);
    })
}
```
<p>Web app side</p>
```import React, { useContext, useEffect, useState } from 'react'
import { UserContext } from '../layout/Layout';
import { getDashboardData, handleCreate } from './DashboardScripts';

const Dashboard = () => {
  const {user, setUser} = useContext(UserContext);
  const [tasks, setTasks] = useState(null);

  useEffect(() => { getDashboardData(setTasks) }, []);

...
```
<p>Here's my server side code</p>
```// Returns all tasks
router.get("/", async (req, res) => {
  let uid = req.body.uid;
  await db.collection("users").doc(uid).collection("tasks").get()
    .then((querySnapshot) => {
      let tasksTemp = [];
      querySnapshot.forEach((doc) => {
        // doc.data() is never undefined for query doc snapshots
        tasksTemp.push([doc.id, doc.data()]);
      });
      res.status(200).send(tasksTemp);
    })
    .catch((error) => {
      res.status(400).send(error.message);
    });
})
```

Postman screenshot
Postman

I'm not sure whether I'm writing the Axios request properly, or whether I'm calling it the function wrongly from the web app. I tried different ways of writing the Axios request to no avail

Title: React - axios fetching empty array

Body:
I could not fetch the data using axios, despite fetching it succesfully through postman. Not sure why this is happening

Here's my function in react

import axios from "axios";

const url = "http://localhost:3001/tasks/";

const getDashboardData = async (setTasks) => {
  await axios.get(`${url}`, {
    uid: sessionStorage.getItem("uid")
  })
    .then((result) => {
      console.log(result.data);

      setTasks(result.data);
    })
    .catch((error) => {
      console.log(error);
    })
}

Web app side

import React, { useContext, useEffect, useState } from 'react'
import { UserContext } from '../layout/Layout';
import { getDashboardData, handleCreate } from './DashboardScripts';

const Dashboard = () => {
  const {user, setUser} = useContext(UserContext);
  const [tasks, setTasks] = useState(null);

  useEffect(() => { getDashboardData(setTasks) }, []);

...

Here's my server side code

// Returns all tasks
router.get("/", async (req, res) => {
  let uid = req.body.uid;
  await db.collection("users").doc(uid).collection("tasks").get()
    .then((querySnapshot) => {
      let tasksTemp = [];
      querySnapshot.forEach((doc) => {
        // doc.data() is never undefined for query doc snapshots
        tasksTemp.push([doc.id, doc.data()]);
      });
      res.status(200).send(tasksTemp);
    })
    .catch((error) => {
      res.status(400).send(error.message);
    });
})

Postman screenshot
Postman

I'm not sure whether I'm writing the Axios request properly, or whether I'm calling it the function wrongly from the web app. I tried different ways of writing the Axios request to no avail


问:
I need to know which app is this in image? It has functions ready to use
I want to know this image for any application? Or do you know a similar program?

any help will be appreciated.

I want to know this image for any application? Or do you know a similar program?


问:
Programming in QtSpim on macbook air
I'm trying to complete a programming assignment for my class with these instructions

Hints:  You will need qtSPIM installed and configured correctly in order to write these programs.  Only hand in SOURCE CODE.

MP4: This program should add the numbers 2, 5 and 7 and store the result in the C register.
MP5:   Hand in your assembly language program MP5_YourFullName.asm here on Blackboard.    Enter your name as an ASCII hex string in the .DATA section of your program.  Create a loop and output 1 character at a time in the loop.  Hint:  NULL terminate your string, use that as a conditional to check for end of string.
MP6:   Hand in your assembly language program MP6_YourFullName.asm here on Blackboard.     Encode your ASCII name from MP5 so it's not readable if you look at the data section of your program in the qtSPIM hex editor.  Your program should loop through each character in your name and output the correct letter to the console.  Hint:  Go character by character, do not print the entire string in a single statement (if you do, you are not following instructions).  Hint:  bitwise operators are your friend.

I was following a tutorial on how to use QtSpim, and they suggested the best starting place is to load your own "helloworld.s" file. However, when I tried to load the file in, I saw the rainbow wheel and everything on my laptop froze. Please help!

I tried to load a simple .s file and never received any sort of output.

Title: Programming in QtSpim on macbook air