问:
How to design user profiles in Laravel?
For several days I have been tring to design users profiles.
The system assumes four types users: Medical Personal, Patient, Operator, Admin.
Medical Personal can branch into three sub types: Dcotor, Manual Doctor, Massager.

Each user type has own profile data. For example Doctor has information about education and experience.

As result I need to get users profiles depends user type for authenticated user.
So my realization is to create a separate table for each user types with corresponsing models and relations to the user model:

```<code>class MedicalPersonal extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

class Patient extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

   class Operator extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}
</code>```

And user model is:

```<code>public function medicalPersonal()
{
    return $this->hasOne(MedicalPersonal::class);
}

public function patient()
{
    return $this->hasOne(Patient::class);
}
</code>```

I defined column user_type inside user migration to know the user type.
First problem I have faced is patient can be medical personal. But I have only one column. The second is how to be with sub types? Then can be added in the feature. It means I have to extent models by relations each time.

I tried to intoduce the model roles/permission. But in this case I can not bind profiles data to each roles. Because each profile has own set of columns.

How to solve it?

Title: How to design user profiles in Laravel?

Body:
For several days I have been tring to design users profiles.
The system assumes four types users: Medical Personal, Patient, Operator, Admin.
Medical Personal can branch into three sub types: Dcotor, Manual Doctor, Massager.

Each user type has own profile data. For example Doctor has information about education and experience.

As result I need to get users profiles depends user type for authenticated user.
So my realization is to create a separate table for each user types with corresponsing models and relations to the user model:

class MedicalPersonal extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

class Patient extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

   class Operator extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

And user model is:

public function medicalPersonal()
{
    return $this->hasOne(MedicalPersonal::class);
}

public function patient()
{
    return $this->hasOne(Patient::class);
}

I defined column user_type inside user migration to know the user type.
First problem I have faced is patient can be medical personal. But I have only one column. The second is how to be with sub types? Then can be added in the feature. It means I have to extent models by relations each time.

I tried to intoduce the model roles/permission. But in this case I can not bind profiles data to each roles. Because each profile has own set of columns.

How to solve it?


来源: stackexchange

问:
Add Custom Cards in firebase dashboard based on custom events in firebase analytics
Firebase dashboard allows to add card in firebase dashboard but will this cards allow to plot custom data with custom events?

After hours of analysis to add charts via firebase options found was to have data-studio with google analytics & BigQuery & BigQuery is not appears to be on free tier.

Ask is to have custom graphs with custom events in firebase dashboard itself instead of data studio.

ContentLicense: CC BY-SA 4.0


问:
Vue Apexchart timeline: dataLabel still visible even items aren't visible in the chart (time has passed or not met)
vuejs
apexcharts

Hi, I have an issue and not sure if it was a bug or I have missed for some configuration. Currently I'm flowing the Timeline Charts here.  I have to enable for the label, and you can see when the time of a task have passed, or not met (by dragging the chart), but the label of hide item is still visible and be stacked with visible label

Issue example 1

Issue example 1

Any body got the same issues yet and how to resolve it? I don't think it's a bug because obiviously no one expected this behavior, right?

I have tried for most of the configuration in the dataLabels but nothing kind related to this. Feel free to drag the chart to see the issue clearly. The code is basically a demo from Apexchart demo, not modify much. You could easily download the original code here: https://apexcharts.com/vue-chart-demos/

Demo for the issue: jsfiddle.net/xhieu2206/quvzaxk9

P/s: after checking for a jsfiddle of the same usecase in React, it work normally without any configuration, so seem like it's a bug from Vue Apexchart team, please correct me if I was wrong (hopefully ...) ...

Demo in react: jsfiddle.net/xhieu2206/3fzb60ar/2/

Editted: the issue happened with react too:

demo: jsfiddle.net/xhieu2206/3fzb60ar/2

enter image description here


问:
Wrong path when dockerizing a Vue Php
I am pretty new to Docker, so in order to train it a bit i would like to fully dockerize my app. App consists of 3 main folders:

Folder - backend - where i have php backend of my app

Folder - frontend - where i have vue frontend of my app

File docker-compose.yml - nothing to add i guess :D

Folder - docker -> where i have folders with Dockerfiles for each system -> vue,php,nginx

Dockerfile for nginx:

```<code>FROM nginx:1.17.8-alpine

# Copy the public directory
COPY . /app/

# Copy the nginx config file
COPY ./docker/nginx/nginx.conf /etc/nginx/conf.d/default.conf
</code>```

Dockerfile for php:

```<code>FROM php:7.4.3-fpm-alpine3.11

RUN docker-php-ext-install pdo pdo_mysql

COPY ./sunday_league_backend/ /app

VOLUME ["/app"]
</code>```

And Dockerfile for vue:

```<code>FROM node:14.5.0-alpine

WORKDIR /sunday_league_frontend

# Install VueCLI
RUN npm install -g @vue/cli

# Copy project files
COPY . sunday_league_frontend

# Install dependencies
RUN npm install

# Expose the app port
EXPOSE 8080

# Start the app
CMD ["npm", "run", "serve"]
</code>```

The server and backend part of code are working great. However when i try to add frontend to it i`m getting errno error. It says that the path is wrong npm ERR! path /sunday_league_frontend/package.json

PS What i discovered by trying multiple configurations if i switch Dockerfile for vue like this:

```<code>FROM node:14.5.0-alpine

RUN mkdir -p /app
WORKDIR /app

# Install VueCLI
RUN npm install -g @vue/cli

# Copy project files
COPY . /app/

# Install dependencies
RUN npm install

# Expose the app port
EXPOSE 8080

# Start the app
CMD ["npm", "run", "serve"]
</code>```

And move all files from frontend file into main app folder, so it would be on same level as Folders for backend, docker and docker-compose.yml it will work just great. However it makes the architecture of files look terrible. What am i still missing :/
docker-compose file for better visualisation:

```<code>version: '3'
services:
  web:
    build:
      context: .
      dockerfile: docker/nginx/Dockerfile
    ports:
      - '8080:80'
    volumes:
      - .:/app/
    links:
      - php
      - vue

  php:
    build:
      context: .
      dockerfile: docker/php/Dockerfile
    volumes:
      - .:/app/

  vue:
    build:
      context: .
      dockerfile: docker/vue/Dockerfile
    ports:
      - '8081:8080'
    volumes:
      - .:/app/
</code>```

Title: Wrong path when dockerizing a Vue Php

Body:
I am pretty new to Docker, so in order to train it a bit i would like to fully dockerize my app. App consists of 3 main folders:

Folder - backend - where i have php backend of my app

Folder - frontend - where i have vue frontend of my app

File docker-compose.yml - nothing to add i guess :D

Folder - docker -> where i have folders with Dockerfiles for each system -> vue,php,nginx

Dockerfile for nginx:

FROM nginx:1.17.8-alpine

# Copy the public directory
COPY . /app/

# Copy the nginx config file
COPY ./docker/nginx/nginx.conf /etc/nginx/conf.d/default.conf

Dockerfile for php:

FROM php:7.4.3-fpm-alpine3.11

RUN docker-php-ext-install pdo pdo_mysql

COPY ./sunday_league_backend/ /app

VOLUME ["/app"]

And Dockerfile for vue:

FROM node:14.5.0-alpine

WORKDIR /sunday_league_frontend

# Install VueCLI
RUN npm install -g @vue/cli

# Copy project files
COPY . sunday_league_frontend

# Install dependencies
RUN npm install

# Expose the app port
EXPOSE 8080

# Start the app
CMD ["npm", "run", "serve"]

The server and backend part of code are working great. However when i try to add frontend to it i`m getting errno error. It says that the path is wrong npm ERR! path /sunday_league_frontend/package.json

PS What i discovered by trying multiple configurations if i switch Dockerfile for vue like this:

FROM node:14.5.0-alpine

RUN mkdir -p /app
WORKDIR /app

# Install VueCLI
RUN npm install -g @vue/cli

# Copy project files
COPY . /app/

# Install dependencies
RUN npm install

# Expose the app port
EXPOSE 8080

# Start the app
CMD ["npm", "run", "serve"]

And move all files from frontend file into main app folder, so it would be on same level as Folders for backend, docker and docker-compose.yml it will work just great. However it makes the architecture of files look terrible. What am i still missing :/
docker-compose file for better visualisation:

version: '3'
services:
  web:
    build:
      context: .
      dockerfile: docker/nginx/Dockerfile
    ports:
      - '8080:80'
    volumes:
      - .:/app/
    links:
      - php
      - vue

  php:
    build:
      context: .
      dockerfile: docker/php/Dockerfile
    volumes:
      - .:/app/

  vue:
    build:
      context: .
      dockerfile: docker/vue/Dockerfile
    ports:
      - '8081:8080'
    volumes:
      - .:/app/


问:
This is code is not removing a string from the firebase realtime database
This should delete the task from the database and I don't get any errors, it doesn't log further than -1. The HTML element gets deleted.

The code:

```<code>// Get the delete button
const deleteButton = taskElement.querySelector('.task-delete');

// Add click event listener to delete button
deleteButton.addEventListener('click', () => {
  console.log("-1")
  // Create a popup to confirm the deletion
  createPopup("Delete Task?", "Are you sure you want to delete this task?", "", "confirm", function(confirm) {
    console.log("0")
    if (confirm) {
      console.log("1")
      // Delete the task from the database
      console.log("2")
      tasksRef.orderByChild('task').equalTo(taskText).once('value').then((snapshot) => {
        console.log("3")
        snapshot.forEach((child) => {
          child.ref.delete();
          console.log("Deleted!")
        });
      });
      // Remove the task element from the page
      taskElement.remove();
    }
  });
});
</code>```

Body:
This should delete the task from the database and I don't get any errors, it doesn't log further than -1. The HTML element gets deleted.

The code:

// Get the delete button
const deleteButton = taskElement.querySelector('.task-delete');

// Add click event listener to delete button
deleteButton.addEventListener('click', () => {
  console.log("-1")
  // Create a popup to confirm the deletion
  createPopup("Delete Task?", "Are you sure you want to delete this task?", "", "confirm", function(confirm) {
    console.log("0")
    if (confirm) {
      console.log("1")
      // Delete the task from the database
      console.log("2")
      tasksRef.orderByChild('task').equalTo(taskText).once('value').then((snapshot) => {
        console.log("3")
        snapshot.forEach((child) => {
          child.ref.delete();
          console.log("Deleted!")
        });
      });
      // Remove the task element from the page
      taskElement.remove();
    }
  });
});


问:
Divi Builder CSS Media Queries are not working. Need Size of Element to stay the same
I am including two picture of the same section to illustrate what's happening on the website when I drag the screen to a smaller size. I am hoping to use the media queries to prevent such a thing from happening. Dragging the screen size smaller is changing the text and the size of the elements pictured. When I input the media queries into custom css, I see nothing change and my goal is to have the screen size look very similar across all screen sizes that use the website.

Before dragging screen to smaller size:
enter image description here

After dragging screen to smaller size:
enter image description here

```<code>/*For browser/screen widths less than 768px*/
@media screen and (max-width: 1440px) {
    .container {
        max-width: 75%;
    }
    .content {
        width: 50%;
    }
}

@media only screen and (min-height: 900px){
    .container {
        max-width: 75%;
    }
    .content {
        width: 50%;
    }
}

@media only screen and (min-width: 900px) and (orientation: portrait) {
    .container {
        max-width: 75%;
    }
    .content {
        width: 50%;
    }
}

@media only screen and (min-width: 1440px) and (orientation: landscape){
    .container {
        max-width: 75%;
    }
    .content {
        width: 50%;
    }
}

I've tried multiple css media query styles and I have not seen any changes to any pages of the website. Please help me to assess what I am doing wrong. I am exploring all options to make this website responsive. The divi builder only provides three options, desktop, tablet and mobile for screen sizing. I need more screens recognised which is why I am using custom css for this project. I have noticed especially on macbook air that the screen size is having multiple issues accommodating the size of elements on each page. Some images are cutoff on pages and some are turning into different weird sizes that were not intended to do so.

Thanks in advance!
</code>```

Body:
I am including two picture of the same section to illustrate what's happening on the website when I drag the screen to a smaller size. I am hoping to use the media queries to prevent such a thing from happening. Dragging the screen size smaller is changing the text and the size of the elements pictured. When I input the media queries into custom css, I see nothing change and my goal is to have the screen size look very similar across all screen sizes that use the website.

Before dragging screen to smaller size:
enter image description here

After dragging screen to smaller size:
enter image description here

/*For browser/screen widths less than 768px*/
@media screen and (max-width: 1440px) {
    .container {
        max-width: 75%;
    }
    .content {
        width: 50%;
    }
}

@media only screen and (min-height: 900px){
    .container {
        max-width: 75%;
    }
    .content {
        width: 50%;
    }
}

@media only screen and (min-width: 900px) and (orientation: portrait) {
    .container {
        max-width: 75%;
    }
    .content {
        width: 50%;
    }
}

@media only screen and (min-width: 1440px) and (orientation: landscape){
    .container {
        max-width: 75%;
    }
    .content {
        width: 50%;
    }
}

I've tried multiple css media query styles and I have not seen any changes to any pages of the website. Please help me to assess what I am doing wrong. I am exploring all options to make this website responsive. The divi builder only provides three options, desktop, tablet and mobile for screen sizing. I need more screens recognised which is why I am using custom css for this project. I have noticed especially on macbook air that the screen size is having multiple issues accommodating the size of elements on each page. Some images are cutoff on pages and some are turning into different weird sizes that were not intended to do so.

Thanks in advance!


问:
javascript indexof issue
I have the following code on datatables

```<code>var colData = table.column(0).data({
    order: 'index'
}).toArray();
var pos;

for (var j = 0; j < csv.length; j++) {
    pos = colData.indexOf(csv[j][PKField]);

    console.log(pos)
    if (pos === -1) {
        // it exists, so we need to add to update list
        // toUpdate.push(csv[j]);
        // toUpdateIds.push(pos);
        console.log("ID found: "+ csv[j][PKField]);
        delete colData.splice(pos);
        continue;
    } else {
        // doesn't exist, so add to create list
        console.log("New ID to import "+ csv[j][PKField]);
        toCreate.push(csv[j]);
    }
...
}
</code>```

I have a csv with 4 rows. 3 entries exists in the database. The 4th is new.
When I import the csv I get the below results

```<code>POS: -1 ID found: 1371
POS: -1 ID found: 1450
POS: -1 ID found: 1485
POS: -1 ID found: 99999
</code>```

What is wrong with the IF statement and the last row (99999) cannot be inserted on the table?

Title: javascript indexof issue

Body:
I have the following code on datatables

var colData = table.column(0).data({
    order: 'index'
}).toArray();
var pos;

for (var j = 0; j < csv.length; j++) {
    pos = colData.indexOf(csv[j][PKField]);

    console.log(pos)
    if (pos === -1) {
        // it exists, so we need to add to update list
        // toUpdate.push(csv[j]);
        // toUpdateIds.push(pos);
        console.log("ID found: "+ csv[j][PKField]);
        delete colData.splice(pos);
        continue;
    } else {
        // doesn't exist, so add to create list
        console.log("New ID to import "+ csv[j][PKField]);
        toCreate.push(csv[j]);
    }
...
}

I have a csv with 4 rows. 3 entries exists in the database. The 4th is new.
When I import the csv I get the below results

POS: -1 ID found: 1371
POS: -1 ID found: 1450
POS: -1 ID found: 1485
POS: -1 ID found: 99999

What is wrong with the IF statement and the last row (99999) cannot be inserted on the table?


问:
How to sign correctly a Powershell script for AllSigned ExecutionPolicy?
We have an application where we use several PowerShell scripts. We received a complain regarding about they aren't signed and unable to run them if they have the strictest Execution Policy - AllSigned.

I signed with our certificate issued by well-known issuer via signtool as we do it for dlls and exe app but even after that there is an issue if I try running the script I'm getting warning:

Do you want to run software from this untrusted publisher?

It's signed by a certificate issued by know CA (Sectigo). Only how can I get rid of this warning is to add the certificate to Trusted Publishers. It's not good for customers to do those steps (but maybe it's necessary security step). Note: With the same certificate, we sign exe app and it works fine and Windows doesn't complain. (Look like PowerShell policies are stricter.)

Is it possible somehow avoid getting this warning on a customer side without manually adding our certificate into Trusted Publishers? Looks to me that it is not possible.

What I've found out so far:

I've searched across internet and it looks like there is no solution for that. Even if I used  PowerShell script signed by Microsoft Corporation I get the same warning unless I add to the Trusted Publishers folder.

Also e.g. HP directly recommends to add the certificate manually to the cert store.

In a documenation about execution policies is written in AllSigned section: Prompts you before running scripts from publishers that you haven't yet classified as trusted or untrusted.

From those all information, I got it as there is no way how to avoid getting this warning on a customer side without adding to the cert store. I want just to assure myself I'm right.


问:
I want to be able to find something where I could give a string and it will take it apart character by character
I want to be able to more easily spell out words in an expanded format. I want it like the Python code:</p>
```<code>import time

word = input()
for i in range(len(word)):
  print(word[i])
  time.sleep(1)
</code>```

Body:
I want to be able to more easily spell out words in an expanded format. I want it like the Python code:

import time

word = input()
for i in range(len(word)):
  print(word[i])
  time.sleep(1)


问:
NodeJS sub-projects installation
I have a large project that contains multiple sub-modules, many of which are optional. And I have each sub-module sitting in its own folder with local package.json.

I'm trying to figure out the best way to create an integral package.json that would be able to run npm install on a specific subset of those modules.

Question

Is there a more civilized approach these days than just running npm install from every sub-module folder? I want to be able to halt the integral installation when it fails for one module, and hopefully do it on a declarative level within package.json, rather than implementing such logic myself. Plus, I want postinstall-s run on each package (if present), and then one of the integration package.

Other than that, maybe there is a better way today to manage such projects? I'm open to any suggestions!

Title: NodeJS sub-projects installation


问:
encountering an error while running the simulation for SlottedFama in Unet IDE
I'm trying to run a Slotted FAMA simulation in UNET, but I'm getting a MissingPropertyException when I try to create an instance of the SlottedFama class. When I run the code BenchmarkedScenario1Sim.groovy or any other sample simulation script in the Unet IDE I get this error message:

```<code>"groovy.lang.MissingPropertyException: No such property: containers for class: org.arl.fjage.DiscreteEventSimulator
Possible solutions: containers
groovy.lang.MissingPropertyException: No such property: containers for class: org.arl.fjage.DiscreteEventSimulator
Possible solutions: containers
BUG! exception in phase 'semantic analysis' in source unit 'C:\Users\syedm\Documents\unet-3.4.0\bin\S-FAMA\BenchmarkedScenario1Sim.groovy' The lookup for SlottedFama caused a failed compilation. There should not have been any compilation from this call."
</code>```

The link to the code is https://github.com/org-arl/unet-contrib/blob/master/contrib/S-FAMA/BenchmarkedScenario1Sim.groovy

It looks like there is a problem with the line 107---> def macAgent = new SlottedFama(), which is causing a MissingPropertyException. This error message suggests that the SlottedFama class is not available or is not being imported correctly. Similarly if I am trying to import a class from any other script for my other code in the IDE, I am not able to do it. Maybe I am not doing it the right way.

I am using java version
openjdk version "1.8.0_352"
OpenJDK Runtime Environment (Temurin)(build 1.8.0_352-b08)
OpenJDK 64-Bit Server VM (Temurin)(build 25.352-b08, mixed mode)

and UNET version 3.4.0 and I've imported the necessary classes and dependencies. I'm not sure what's causing this error or how to fix it. Can anyone help me troubleshoot this issue and get my simulation running? Any guidance or suggestions would be much appreciated. Thank you!

Regards,
Murtaza

I tried importing the SlottedFama.groovy script, but the error still persists.

Body:
I'm trying to run a Slotted FAMA simulation in UNET, but I'm getting a MissingPropertyException when I try to create an instance of the SlottedFama class. When I run the code BenchmarkedScenario1Sim.groovy or any other sample simulation script in the Unet IDE I get this error message:

"groovy.lang.MissingPropertyException: No such property: containers for class: org.arl.fjage.DiscreteEventSimulator
Possible solutions: containers
groovy.lang.MissingPropertyException: No such property: containers for class: org.arl.fjage.DiscreteEventSimulator
Possible solutions: containers
BUG! exception in phase 'semantic analysis' in source unit 'C:\Users\syedm\Documents\unet-3.4.0\bin\S-FAMA\BenchmarkedScenario1Sim.groovy' The lookup for SlottedFama caused a failed compilation. There should not have been any compilation from this call."

The link to the code is https://github.com/org-arl/unet-contrib/blob/master/contrib/S-FAMA/BenchmarkedScenario1Sim.groovy

It looks like there is a problem with the line 107---> def macAgent = new SlottedFama(), which is causing a MissingPropertyException. This error message suggests that the SlottedFama class is not available or is not being imported correctly. Similarly if I am trying to import a class from any other script for my other code in the IDE, I am not able to do it. Maybe I am not doing it the right way.

I am using java version
openjdk version "1.8.0_352"
OpenJDK Runtime Environment (Temurin)(build 1.8.0_352-b08)
OpenJDK 64-Bit Server VM (Temurin)(build 25.352-b08, mixed mode)

and UNET version 3.4.0 and I've imported the necessary classes and dependencies. I'm not sure what's causing this error or how to fix it. Can anyone help me troubleshoot this issue and get my simulation running? Any guidance or suggestions would be much appreciated. Thank you!

Regards,
Murtaza

I tried importing the SlottedFama.groovy script, but the error still persists.


问:
How to do a light mode, dark mode theme in next.js for Full-calendar
I have 1 variable indicates applications mode. How should I add to styling for Full-calendar with condition, I don’t want to use Bootstrap 5 because I already used Tailwind, is there any suggestion?  Thanks!

I cannot think of anyway to do this, as there are no condition in global.css and I can’t simply create a class with condition to overwrite previous style in Full-calendar ( I don’t know how to create css that impact other class than itself other than global.css, since every styling need className={Style.[classname]} and that doesn’t impact Full-calendar components)


问:
DockerFile commands to put ssh keys in Docker Container to access the Git Repo used for Spring boot Config Server
I have a spring boot config server which is fetching config files from a remote private GitHub repository using ssh. The service works perfectly when running in local but when I run the service through docker, it runs but unfortunately couldn't fetch the config repo and the reason is I am not able to correctly set up ssh in the docker container.

Here's my application property files -

```<code>server:
  port: 8888
spring:
  application:
    name: configserver
  cloud:
    config:
      server:
        git:
          uri: something_url
          ignoreLocalSshSettings: false
          passphrase: phassphrase
          defaultLabel: master
</code>```

Here's so far what I have tried with my docker file -

```<code>FROM openjdk:11
ARG SSH_PRIVATE_KEY
RUN mkdir ~/.ssh/
RUN echo "${SSH_PRIVATE_KEY}" > ~/.ssh/id_ecdsa
RUN chmod 600 ~/.ssh/id_ecdsa
RUN ssh-keyscan github.com >> ~/.ssh/known_hosts
RUN bash -c 'echo -e "Host *\n\tIdentifyFile ~/.ssh/id_ecdsa" >> ~/.ssh/config >> ~/.ssh/config'
ARG JAR_FILE=build/libs/*.jar
COPY ${JAR_FILE} config-server.jar
ENTRYPOINT ["java", "-jar", "/config-server.jar"]
</code>```

I am using the following command to create the image -

docker build --build-arg SSH_PRIVATE_KEY="$(cat ~/.ssh/id_ecdsa)"  -t config-server .

The container starts perfectly but as soon as I run the eureka server container it throws the error saying AUTH FAILS

Body:
I have a spring boot config server which is fetching config files from a remote private GitHub repository using ssh. The service works perfectly when running in local but when I run the service through docker, it runs but unfortunately couldn't fetch the config repo and the reason is I am not able to correctly set up ssh in the docker container.

Here's my application property files -

server:
  port: 8888
spring:
  application:
    name: configserver
  cloud:
    config:
      server:
        git:
          uri: something_url
          ignoreLocalSshSettings: false
          passphrase: phassphrase
          defaultLabel: master

Here's so far what I have tried with my docker file -

FROM openjdk:11
ARG SSH_PRIVATE_KEY
RUN mkdir ~/.ssh/
RUN echo "${SSH_PRIVATE_KEY}" > ~/.ssh/id_ecdsa
RUN chmod 600 ~/.ssh/id_ecdsa
RUN ssh-keyscan github.com >> ~/.ssh/known_hosts
RUN bash -c 'echo -e "Host *\n\tIdentifyFile ~/.ssh/id_ecdsa" >> ~/.ssh/config >> ~/.ssh/config'
ARG JAR_FILE=build/libs/*.jar
COPY ${JAR_FILE} config-server.jar
ENTRYPOINT ["java", "-jar", "/config-server.jar"]

I am using the following command to create the image -

docker build --build-arg SSH_PRIVATE_KEY="$(cat ~/.ssh/id_ecdsa)"  -t config-server .

The container starts perfectly but as soon as I run the eureka server container it throws the error saying AUTH FAILS


问:
Pulling Data from a PHP file into a PHP file [Wordpress]
EDIT: I did it. I was able to pull in the data, but not sure if this is the right method, but it is working.

I added this to my template file and it works:

 include(locate_template('template-parts/data/lemon/data-lemon.php'));

Saw it from this posting: How can I pass a variable from functions.php to the template file in WordPress?

So I have a client that does not want a page builder or Gutenberg, but wants to be able to change the data when needed. This person is not tech savvy, so giving them access to files is not a good idea.

So I thought about using markdown files or even variables. I could have a template, then pull the variables from another template. This way they can change the data but have no access to the file structure.

Here is what I have:

```<code><!-- Variable for Data -->
<?php locate_template( 'template-parts/data/lemon/data-lemon.php', true ); ?>

<!-- Hero Section -->
<section id="hero" class="flex flex-col md:flex-row gap-4">

    <div id="col-left" class="basis-2/5">
        <h3>
            <?php echo $heroSubtitle; ?>
        </h3>
        <h1>
            <?php echo $heroTitle; ?>
        </h1>
        <p>
            <?php echo $heroDescription; ?>
        </p>
        <div id="button-wrapper" class="flex flex-row gap-2">
            <button class="bg-yellow-500 text-white px-4 h-[40px]">
                <a href="/" class="text-gray-900 hover:text-white active:text-white">Buy Lemon</a>
            </button>
            <button class="bg-white border-solid border-grey-100 border-2 px-2 h-[40px]">
                <a href="/">
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 14" width="24" height="24">
                        <path fill="none" d="M0 0h24v24H0z"/>
                        <path d="M16.004 9.414l-8.607 8.607-1.414-1.414L14.589 8H7.004V6h11v11h-2V9.414z"/>
                    </svg>
                </a>
            </button>
        </div>
    </div>
    <div id="col-right" class="basis-3/5">
        <figure>
            <img src="<?php echo get_stylesheet_directory_uri(); ?>\assets\img\progessive-img.png" alt="" title="" />
        </figure>
    </div>
</section>

</code>```

Then ... I have the variable or data file like this [This is inside the data-lemon.php file]:

```<code><?php
    // Variable for the lemon page
    $heroSubtitle = 'Meet Lemon';
    $heroTitle = 'Build a better site for your business.';
    $heroDescription = '[short description here] blorem blipsum dolor sit bamat minim mollit non deserunt ullamco lorem ipsum.';
?>

</code>```

As you can see in the example I have tried "locate_template()", but I have also tried "get_template_parts" with no luck.

"get_template_parts" works great for getting oher blocks of data into the template file, but not when it comes to variables.

Any idea of what I am doing wrong or if this is even possible.

Cheers

Body:
EDIT: I did it. I was able to pull in the data, but not sure if this is the right method, but it is working.

I added this to my template file and it works:

 include(locate_template('template-parts/data/lemon/data-lemon.php'));

Saw it from this posting: How can I pass a variable from functions.php to the template file in WordPress?

So I have a client that does not want a page builder or Gutenberg, but wants to be able to change the data when needed. This person is not tech savvy, so giving them access to files is not a good idea.

So I thought about using markdown files or even variables. I could have a template, then pull the variables from another template. This way they can change the data but have no access to the file structure.

Here is what I have:

<?php locate_template( 'template-parts/data/lemon/data-lemon.php', true ); ?>

            <?php echo $heroSubtitle; ?>

            <?php echo $heroTitle; ?>

            <?php echo $heroDescription; ?>

            <button class="bg-yellow-500 text-white px-4 h-[40px]">
                Buy Lemon
            </button>
            <button class="bg-white border-solid border-grey-100 border-2 px-2 h-[40px]">

                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 14" width="24" height="24">
                        <path fill="none" d="M0 0h24v24H0z"/>
                        <path d="M16.004 9.414l-8.607 8.607-1.414-1.414L14.589 8H7.004V6h11v11h-2V9.414z"/>
                    </svg>

            </button>

            <img src="<?php echo get_stylesheet_directory_uri(); ?>\assets\img\progessive-img.png" alt="" title="" />

Then ... I have the variable or data file like this [This is inside the data-lemon.php file]:

<?php
    // Variable for the lemon page
    $heroSubtitle = 'Meet Lemon';
    $heroTitle = 'Build a better site for your business.';
    $heroDescription = '[short description here] blorem blipsum dolor sit bamat minim mollit non deserunt ullamco lorem ipsum.';
?>

As you can see in the example I have tried "locate_template()", but I have also tried "get_template_parts" with no luck.

"get_template_parts" works great for getting oher blocks of data into the template file, but not when it comes to variables.

Any idea of what I am doing wrong or if this is even possible.

Cheers


问:
flutter markdown extension
I want to detect and do something when there is a message that starts with the @ sign. How do I do this with the extension set feature?
I added a new class and extended it</p>
```<code>    return Bubble(
      style: BubbleStyle(
        radius: const Radius.circular(4),
        elevation: 1,
        color: Theme.of(context).scaffoldBackgroundColor,
        margin: const BubbleEdges.only(bottom: 4.0, top: 4.0),
      ),
      child: Container(
        constraints: const BoxConstraints(minWidth: 0.0, maxWidth: 240),
        child: MarkdownBody(
          extensionSet: md.ExtensionSet(
            md.ExtensionSet.gitHubFlavored.blockSyntaxes,
            [X(), ...md.ExtensionSet.gitHubFlavored.inlineSyntaxes],
          ),
          onTapLink: (text, href, title) {
            launchUrlString(href ?? text);
            print(text);
            print(href);
            print(title);
          },
          data: body,
        ),
      ),
    );
  }
}

class X extends md.InlineSyntax {
  X() : super("/(^|\s)@\w+/g");

  @override
  bool onMatch(md.InlineParser parser, Match match) {
    print("eşleşti");
    return true;
  }
}
</code>```

Title: flutter markdown extension

Body:
I want to detect and do something when there is a message that starts with the @ sign. How do I do this with the extension set feature?
I added a new class and extended it

    return Bubble(
      style: BubbleStyle(
        radius: const Radius.circular(4),
        elevation: 1,
        color: Theme.of(context).scaffoldBackgroundColor,
        margin: const BubbleEdges.only(bottom: 4.0, top: 4.0),
      ),
      child: Container(
        constraints: const BoxConstraints(minWidth: 0.0, maxWidth: 240),
        child: MarkdownBody(
          extensionSet: md.ExtensionSet(
            md.ExtensionSet.gitHubFlavored.blockSyntaxes,
            [X(), ...md.ExtensionSet.gitHubFlavored.inlineSyntaxes],
          ),
          onTapLink: (text, href, title) {
            launchUrlString(href ?? text);
            print(text);
            print(href);
            print(title);
          },
          data: body,
        ),
      ),
    );
  }
}

class X extends md.InlineSyntax {
  X() : super("/(^|\s)@\w+/g");

  @override
  bool onMatch(md.InlineParser parser, Match match) {
    print("eşleşti");
    return true;
  }
}


问:
Problem mounting a component programatically in a Laravel 9 Vue 2.6 application
I am having trouble in programmatically adding (mounting) a child component in a parent component.

I have a parent component (createPost) on a page. When the page loads, it includes an instance of a child component (createInteraction). The page contains three buttons (Interaction, Appointment and Task) and on clicking these buttons, I what to add the corresponding child component (e.g. createInteraction) on the page in a division with an ID 'postsDiv'. In the click event of the button, I have the following code:

```<code>const ComponentCtor = Vue.extend(createInteraction);
                        const ComponentInstance = new ComponentCtor({
                                propsData : {
                                    interactionIndex : 1,
                                    postsCount:this.postsCount,
                                    encrypted_client_id: this.encrypted_client_id,
                                    encrypted_parent_post_id: this.encrypted_parent_post_id,
                                    clientInteractionData: this.clientInteractionData,
                                    hasUserWriteAccess: this.hasUserWriteAccess,
                                }

                            }
                        );
   // Results in error: app.js:105442 [Vue warn]: Error in render: "TypeError: Cannot read properties of undefined (reading 'component')"
   ComponentInstance.$mount('#postsDiv');
   // ComponentInstance.$mount();
</code>```

I get the error when I try to mount the component instance (and no error while creating the component instance).

Any suggestion, how to correctly mount the component?

Body:
I am having trouble in programmatically adding (mounting) a child component in a parent component.

I have a parent component (createPost) on a page. When the page loads, it includes an instance of a child component (createInteraction). The page contains three buttons (Interaction, Appointment and Task) and on clicking these buttons, I what to add the corresponding child component (e.g. createInteraction) on the page in a division with an ID 'postsDiv'. In the click event of the button, I have the following code:

const ComponentCtor = Vue.extend(createInteraction);
                        const ComponentInstance = new ComponentCtor({
                                propsData : {
                                    interactionIndex : 1,
                                    postsCount:this.postsCount,
                                    encrypted_client_id: this.encrypted_client_id,
                                    encrypted_parent_post_id: this.encrypted_parent_post_id,
                                    clientInteractionData: this.clientInteractionData,
                                    hasUserWriteAccess: this.hasUserWriteAccess,
                                }

                            }
                        );
   // Results in error: app.js:105442 [Vue warn]: Error in render: "TypeError: Cannot read properties of undefined (reading 'component')"
   ComponentInstance.$mount('#postsDiv');
   // ComponentInstance.$mount();

I get the error when I try to mount the component instance (and no error while creating the component instance).

Any suggestion, how to correctly mount the component?


问:
how to cancel an in-app test purchase on android? in billing version 5.0 version
i'm using test account but i'm not sure about that it's working fine. how to test cancel scenario in-app billing in android kotlin

in-app purchases subscription step in billing version 5. android kotlin


问:
Sum of sines and cosines from DFT
I have a signal and want to reconstruct it from its spectrum as a sum of sines and/or cosines. I am aware of the inverse FFT but I want to reconstruct the signal in this way.

An example would look like this:

sig = np.array([1, 5, -3, 0.7, 3.1, -5, -0.5, 3.2, -2.3, -1.1, 3, 0.3, -2.05, 2.1, 3.05, -2.3])

fft = np.fft.rfft(sig)
mag = np.abs(fft) * 2 / sig.size
phase = np.angle(fft)

x = np.arange(sig.size)
reconstructed = list()
for x_i in x:
    val = 0
    for i, (m, p) in enumerate(zip(mag, phase)):
        val += ...  # what's the correct form?
    reconstructed.append(val)
```

What's the correct code to write in the next-to-last line?

Title: Sum of sines and cosines from DFT

Body:
I have a signal and want to reconstruct it from its spectrum as a sum of sines and/or cosines. I am aware of the inverse FFT but I want to reconstruct the signal in this way.

An example would look like this:

sig = np.array([1, 5, -3, 0.7, 3.1, -5, -0.5, 3.2, -2.3, -1.1, 3, 0.3, -2.05, 2.1, 3.05, -2.3])

fft = np.fft.rfft(sig)
mag = np.abs(fft) * 2 / sig.size
phase = np.angle(fft)

x = np.arange(sig.size)
reconstructed = list()
for x_i in x:
    val = 0
    for i, (m, p) in enumerate(zip(mag, phase)):
        val += ...  # what's the correct form?
    reconstructed.append(val)

What's the correct code to write in the next-to-last line?


问:
No connection could made because the target machine actively refused it

How can I fix this message? A message appears when downloading


问:
Datadog metric formulas in statuspage
We wanted to add few availability metrics to Statuspage via datadog. I was following https://support.atlassian.com/statuspage/docs/add-a-datadog-metric/ but this shows allowing individual metric.

How do i use datadog to show availability e.g. using a datadog formula as below in statuspage
availability = 100-(100*errors/count)

Title: Datadog metric formulas in statuspage


问:
ga:Goal13Completions only shows 0.0 OR 77.0 values on Google Analytics Query API Call using Python
I'm running this python code, calling the Google Analytics API using my secrets.json and token.json to get the values.

Goal13 should have entire values, ranging from 0 to infinity, but it seems that the API is showing me the "1.0" conversions into "77.0" and I don't have idea why.

So, it basicaly shows me even 0 or 77, and this should not be the case.

This is the code I'm running:

goal13_report = {'metrics':'ga:goal13Completions',
         'dimensions':'ga:date,ga:dimension2,ga:dimension14',
         'start_index': 1,
         'max_results': 100000,
         'start_date':'2019-01-01',
         'end_date':'2022-12-29',
         'unsampled': False,
         'ids':'ga:xxxxxxxxx'
         }
conversions_g13 = ga.get_report(**goal13_report)
df = conversions_g13.to_data_frame()
df
```

The dataframe that results from that query, notice the last column

I tried using as little dimensions as possible but the problem still persists. Whenever I check the results on Google Analytics native web dashboards, results are ok. Even the SuperMetrics query I call on GoogleSheets show me perfect results

I'm expecting to get the same results as SuperMetrics, as it has no sampling.

Body:
I'm running this python code, calling the Google Analytics API using my secrets.json and token.json to get the values.

Goal13 should have entire values, ranging from 0 to infinity, but it seems that the API is showing me the "1.0" conversions into "77.0" and I don't have idea why.

So, it basicaly shows me even 0 or 77, and this should not be the case.

This is the code I'm running:

goal13_report = {'metrics':'ga:goal13Completions',
         'dimensions':'ga:date,ga:dimension2,ga:dimension14',
         'start_index': 1,
         'max_results': 100000,
         'start_date':'2019-01-01',
         'end_date':'2022-12-29',
         'unsampled': False,
         'ids':'ga:xxxxxxxxx'
         }
conversions_g13 = ga.get_report(**goal13_report)
df = conversions_g13.to_data_frame()
df

The dataframe that results from that query, notice the last column

I tried using as little dimensions as possible but the problem still persists. Whenever I check the results on Google Analytics native web dashboards, results are ok. Even the SuperMetrics query I call on GoogleSheets show me perfect results

I'm expecting to get the same results as SuperMetrics, as it has no sampling.


问:
why do I have to add a higher folder when opening a file in python when debugging?
I have a directory tree similar to this:

```<code>my_application
    my_component
        process_config.py
        process_config.yaml
    runner.py
</code>```

I launch python runner.py and it calls a class inside process_config.py that reads the yaml file like this:

```<code>with open(
   os.path.join("my_component", "process_config.yaml"), "r"
) as proces_config_defaults_source:
</code>```

And it works fine when y run python runner.py, but it can't locate the file when I run the file from the debugger. I have to use this option for it to work:

```<code>with open(
    os.path.join("my_application", "my_component", "process_config.yaml"), "r"
) as proces_config_defaults_source:
</code>```

How can I make the debugger to work the same as a python run?

Body:
I have a directory tree similar to this:

my_application
    my_component
        process_config.py
        process_config.yaml
    runner.py

I launch python runner.py and it calls a class inside process_config.py that reads the yaml file like this:

with open(
   os.path.join("my_component", "process_config.yaml"), "r"
) as proces_config_defaults_source:

And it works fine when y run python runner.py, but it can't locate the file when I run the file from the debugger. I have to use this option for it to work:

with open(
    os.path.join("my_application", "my_component", "process_config.yaml"), "r"
) as proces_config_defaults_source:

How can I make the debugger to work the same as a python run?


问:
using proxy with selenium webdriver firefox in python not working
I would like to make a program that modifies my ip when I go to consult a site with selenium, I use webdriver firefox, unfortunately the site that I use for my tests returns my ip and not the ip that I indicated in the options, could you tell me the error please.

The program launches and the firefox page opens (I don't use headless for the test), but it's my ip that is returned and not the one from the specified proxy.
here is my program

```<code>from selenium import webdriver

options = webdriver.FirefoxOptions()
proxy = f'{"137.74.65.101"}:{"80"}'

options.add_argument(f'--proxy-server={proxy}')

driver = webdriver.Firefox(options=options)

driver.get('https://httpbin.org/ip')
</code>```

Body:
I would like to make a program that modifies my ip when I go to consult a site with selenium, I use webdriver firefox, unfortunately the site that I use for my tests returns my ip and not the ip that I indicated in the options, could you tell me the error please.

The program launches and the firefox page opens (I don't use headless for the test), but it's my ip that is returned and not the one from the specified proxy.
here is my program

from selenium import webdriver

options = webdriver.FirefoxOptions()
proxy = f'{"137.74.65.101"}:{"80"}'

options.add_argument(f'--proxy-server={proxy}')

driver = webdriver.Firefox(options=options)

driver.get('https://httpbin.org/ip')


问:
Byte Array mapping of a column in Entity class throwing Error
In My entity class "asset_docs" i am using photos_byte as column name defined in postgress sql defined as "photos_byte" as bytea . But whenever i am trying to use JPA framework to save someobject it throws the below error :

o.h.e.j.s.SqlExceptionHelper             : ERROR: column "photos_byte" of relation "asset_docs" does not exist

```<code>   @Id
   @Basic(optional = false)
   @Column(name = "id")
   @GeneratedValue(strategy=GenerationType.IDENTITY)
   private Long id;
   @Column(name = "created_at")
   @Temporal(TemporalType.DATE)
   private Date createdAt;
   @Lob
   @Column(name="photos_byte", columnDefinition="bytea")
   private byte[] photosByte;
</code>```

Whats wrong here ?

Body:
In My entity class "asset_docs" i am using photos_byte as column name defined in postgress sql defined as "photos_byte" as bytea . But whenever i am trying to use JPA framework to save someobject it throws the below error :

o.h.e.j.s.SqlExceptionHelper             : ERROR: column "photos_byte" of relation "asset_docs" does not exist

   @Id
   @Basic(optional = false)
   @Column(name = "id")
   @GeneratedValue(strategy=GenerationType.IDENTITY)
   private Long id;
   @Column(name = "created_at")
   @Temporal(TemporalType.DATE)
   private Date createdAt;
   @Lob
   @Column(name="photos_byte", columnDefinition="bytea")
   private byte[] photosByte;

Whats wrong here ?


问:
Find if there's a close enough node to the end node (Python)
```<code>def explorer(visited, graph, node, N, M, K):
    if ((node[0]-N)**2+(node[1]-M)**2)**(1/2) <= K:
        return True
    if node not in visited:
        visited.append(node)
        for element in graph:
            if ((node[0]-element[0])**2+(node[1]-element[1])**2)**(1/2) <= K:
                if ((element[0]-N)**2+abs(element[1]-M)**2)**(1/2)<=K:
                        visited.append(element)
                        return True
                return explorer(visited, graph, element, N, M, K)
</code>```

I'm using the aforementioned function over a list of nodes, which I know has a path from [0,0] to [N, M]. But the function returns None.

Body:
def explorer(visited, graph, node, N, M, K):
    if ((node[0]-N)**2+(node[1]-M)**2)**(1/2) <= K:
        return True
    if node not in visited:
        visited.append(node)
        for element in graph:
            if ((node[0]-element[0])**2+(node[1]-element[1])**2)**(1/2) <= K:
                if ((element[0]-N)**2+abs(element[1]-M)**2)**(1/2)<=K:
                        visited.append(element)
                        return True
                return explorer(visited, graph, element, N, M, K)

I'm using the aforementioned function over a list of nodes, which I know has a path from [0,0] to [N, M]. But the function returns None.


问:
All of a sudden Ctrl+Click on a link in the output of the integrated terminal, opens file in a new instance of vscode
All of a sudden Ctrl+Click on a link in the output of the integrated terminal, opens file in a new instance of vscode. This was not happening some time back. How to troubleshoot and fix this?</p>


问:
Getting data from supabase in nuxt 3 middleware
```<code>const client = useSupabaseClient()

  useAsyncData('profiles', async () => {
    const { data } = await client.from('profiles').select('id, username, description').eq('user_id', user.value.id).single()

    return data
  }).then(resp => {
    if (resp.data.value.username == null) {
      navigateTo('/createprofile')
    } else {
      store.username = resp.data.value.username
    }
  })
</code>```

I have this piece of code inside of a middleware and it works, but it gives two errors

```<code>[nitro] [dev] [unhandledRejection] Error: nuxt instance unavailable
[Vue warn]: onServerPrefetch is called when there is no active component instance to be associated with. Lifecycle injection APIs can only be used during execution of setup(). If you are using async setup(), make sure to register lifecycle hooks before the first await statement.
</code>```

I am using NuxtSupabase if that wasn't clear

This is middleware for fetching user's profile data and if that profile does not exist then redirect them to profile creation

What I am wondering is how I do this without getting the errors

Body:
const client = useSupabaseClient()

  useAsyncData('profiles', async () => {
    const { data } = await client.from('profiles').select('id, username, description').eq('user_id', user.value.id).single()

    return data
  }).then(resp => {
    if (resp.data.value.username == null) {
      navigateTo('/createprofile')
    } else {
      store.username = resp.data.value.username
    }
  })

I have this piece of code inside of a middleware and it works, but it gives two errors

[nitro] [dev] [unhandledRejection] Error: nuxt instance unavailable
[Vue warn]: onServerPrefetch is called when there is no active component instance to be associated with. Lifecycle injection APIs can only be used during execution of setup(). If you are using async setup(), make sure to register lifecycle hooks before the first await statement.

I am using NuxtSupabase if that wasn't clear

This is middleware for fetching user's profile data and if that profile does not exist then redirect them to profile creation

What I am wondering is how I do this without getting the errors


问:
How to upload videos to aws using dynamic path in node js
I am having a list of 2 videos in a folder which I upload to AWS from my local directory when I call uploadDir function.

The videos are named dynamically to the path of their already existing file, because am re-uploading to replace the same file in the existing directory on aws

Example.

Video 1 name is:   https://myBucketName.s3.amazonaws.com/Movies/video/comedy/93dcf22e84918d0efcb90ba2/Tom-41560712aa0f84f49ed130f2/Home Alone.mp4

Video 2 name is:
https://myBucketName.s3.amazonaws.com/Movies/video/action/26wjf31g64918d0efcb90bw6/Ben-71560712aa0f84f49ed130f4/Mission Impossible.mp4

But because I can't save a filename with special characters I then replace the video name with special characters in my folder directory using the function below

```<code>var str1 = videoName.replace(':','X');
  var str2 = str1.replace(/[&\/\\#,<>{}]/g,'Q');
</code>```

So I replaced all the ':' with 'X', and replaced all the '/' with 'Q'

So now the video name in my directory I want to upload back to AWS is looking like this

Replaced Video 1 name is: httpsXQQmyBucketName.s3.amazonaws.comQMoviesQvideoQcomedyQ93dcf22e84918d0efcb90ba2QTom-41560712aa0f84f49ed130f2QHome Alone.mp4

Replaced Video 2 name is: httpsXQQmyBucketName.s3.amazonaws.comQMoviesQvideoQactionQ26wjf31g64918d0efcb90bw6QBen-71560712aa0f84f49ed130f4QMission Impossible.mp4

So now I want to upload the videos back to their AWS path, which is originally the video name.

So for me to achieve this I believe I must first replace the original special characters, So all the 'X' will be ':', and all the 'Q' will be '/'

And the next step is for me to upload to the video name path.

How can I achieve this.

I already have a function uploading the videos to Aws bucket, but not to the directly I want the videos to be.

This is the code uploading the videos to Aws

```<code>var AWS = require('aws-sdk');
var path = require("path");
var fs = require('fs');

const uploadDir = function(s3Path, bucketName) {

    let s3 = new AWS.S3();

    function walkSync(currentDirPath, callback) {
        fs.readdirSync(currentDirPath).forEach(function (name) {
            var filePath = path.join(currentDirPath, name);
            var stat = fs.statSync(filePath);
            if (stat.isFile()) {
                callback(filePath, stat);
            } else if (stat.isDirectory()) {
                walkSync(filePath, callback);
            }
        });
    }

    walkSync(s3Path, function(filePath, stat) {
        let bucketPath = filePath.substring(s3Path.length+1);
        let params = {Bucket: bucketName, Key: bucketPath, Body: fs.readFileSync(filePath) };
        s3.putObject(params, function(err, data) {
            if (err) {
                console.log(err)
            } else {
                console.log('Successfully uploaded '+ bucketPath +' to ' + bucketName);
            }
        });

    });
};
</code>```

```<code>uploadDir(path.resolve('path-containing-videos'), 'bucket-name');
</code>```

Body:
I am having a list of 2 videos in a folder which I upload to AWS from my local directory when I call uploadDir function.

The videos are named dynamically to the path of their already existing file, because am re-uploading to replace the same file in the existing directory on aws

Example.

Video 1 name is:   https://myBucketName.s3.amazonaws.com/Movies/video/comedy/93dcf22e84918d0efcb90ba2/Tom-41560712aa0f84f49ed130f2/Home Alone.mp4

Video 2 name is:
https://myBucketName.s3.amazonaws.com/Movies/video/action/26wjf31g64918d0efcb90bw6/Ben-71560712aa0f84f49ed130f4/Mission Impossible.mp4

But because I can't save a filename with special characters I then replace the video name with special characters in my folder directory using the function below

var str1 = videoName.replace(':','X');
  var str2 = str1.replace(/[&\/\\#,<>{}]/g,'Q');

So I replaced all the ':' with 'X', and replaced all the '/' with 'Q'

So now the video name in my directory I want to upload back to AWS is looking like this

Replaced Video 1 name is: httpsXQQmyBucketName.s3.amazonaws.comQMoviesQvideoQcomedyQ93dcf22e84918d0efcb90ba2QTom-41560712aa0f84f49ed130f2QHome Alone.mp4

Replaced Video 2 name is: httpsXQQmyBucketName.s3.amazonaws.comQMoviesQvideoQactionQ26wjf31g64918d0efcb90bw6QBen-71560712aa0f84f49ed130f4QMission Impossible.mp4

So now I want to upload the videos back to their AWS path, which is originally the video name.

So for me to achieve this I believe I must first replace the original special characters, So all the 'X' will be ':', and all the 'Q' will be '/'

And the next step is for me to upload to the video name path.

How can I achieve this.

I already have a function uploading the videos to Aws bucket, but not to the directly I want the videos to be.

This is the code uploading the videos to Aws

var AWS = require('aws-sdk');
var path = require("path");
var fs = require('fs');

const uploadDir = function(s3Path, bucketName) {

    let s3 = new AWS.S3();

    function walkSync(currentDirPath, callback) {
        fs.readdirSync(currentDirPath).forEach(function (name) {
            var filePath = path.join(currentDirPath, name);
            var stat = fs.statSync(filePath);
            if (stat.isFile()) {
                callback(filePath, stat);
            } else if (stat.isDirectory()) {
                walkSync(filePath, callback);
            }
        });
    }

    walkSync(s3Path, function(filePath, stat) {
        let bucketPath = filePath.substring(s3Path.length+1);
        let params = {Bucket: bucketName, Key: bucketPath, Body: fs.readFileSync(filePath) };
        s3.putObject(params, function(err, data) {
            if (err) {
                console.log(err)
            } else {
                console.log('Successfully uploaded '+ bucketPath +' to ' + bucketName);
            }
        });

    });
};

uploadDir(path.resolve('path-containing-videos'), 'bucket-name');


问:
Why loss is not decreasing in a Siamese BERT-Network training (Entity matching task)
I'm trying to finetune a model for an entity matching task (kind of a sentence similarity task).

The idea is that if I give as input two sentences the model should output if they represent the same entity or not. I'm interested in the products' domain.

So for example:

sentences_left = ('logitech harmony 890 advanced universal remote control h890', 'sony silver digital voice recorder icdb600')
sentences_right = ('logitech harmony 890 advanced universal remote hdtv , tv , dvd player ( s ) , lighting , audio system 100 ft universal remote 966193-0403', 'canon black ef 70-300mm f/4 -5.6 is usm telephoto zoom lens 0345b002')
```
<p>The output should be 1 for the first left-right pair of sentences and 0 for the second.</p>
<p>I want to test two approaches. The first is a <em>sequence classification</em> setup. So I take a pair of sentences, concat them with a [SEP] token in-between, encode it and feed it to BERT.</p>
<p><img src="https://i.stack.imgur.com/k0cQg.png" alt="This is the idea" /></p>
<p>This approach kind of work, but I wanted to explore a second one that, in theory, should work too.</p>
<p>In few words, using mpnet as pre-trained language model I'm trying to implement this setup:</p>
<p><img src="https://i.stack.imgur.com/S3zVP.png" alt="Siamese BERT from the Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks paper" /></p>
<p>This is taken from the paper Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks. The idea is to compute not only a single embedding as before, but two separate embeddings for each of the sentences. Then concatenate the embeddings and feeds them to a <em>softmax classifier</em>.</p>
<p>After lots of struggles I'm still unable to make it work, since the loss has no intention of decreasing. It starts at 0.25 and never goes up neither down.</p>
<p>I'm using the <em>Abt-Buy</em>, <em>Amazon-Google</em> and <em>Walmart-Amazon</em> datasets.</p>
<p>This is my model:</p>
<pre class="lang-py prettyprint-override"><code>
class FinalClassifier(nn.Module):

    def __init__(self, pos_neg=None, frozen=False):

        super(FinalClassifier, self).__init__()

        use_cuda = torch.cuda.is_available()
        self.device = torch.device("cuda" if use_cuda else "cpu")

        self.encoder = AutoModel.from_pretrained(
'all-mpnet-base-v2')

        if frozen:
          for param in self.encoder.parameters():
            param.requires_grad = False
        self.tokenizer = AutoTokenizer.from_pretrained(
'all-mpnet-base-v2')

        if pos_neg:
          self.criterion = BCEWithLogitsLoss(pos_weight=torch.Tensor([pos_neg]))

        self.linear = nn.Linear(3*768, 1)
        self.relu = nn.ReLu()

    def forward(self, texts_left, texts_right, labels=None):
       encoded_inputs_left = self.tokenizer(texts_left, padding='max_length',
                                        truncation=True, return_tensors='pt')
       encoded_inputs_left = encoded_inputs_left.to(self.device)

       output_left = self.encoder(**encoded_inputs_left)
       output_left = _mean_pooling(output_left, encoded_inputs_left['attention_mask'])
       # output_left = F.normalize(output_left, p=2, dim=1)

       encoded_inputs_right = self.tokenizer(texts_right, padding='max_length',
                                        truncation=True, return_tensors='pt')
       encoded_inputs_right = encoded_inputs_right.to(self.device)

       output_right = self.encoder(**encoded_inputs_right)
       output_right = _mean_pooling(output_right, encoded_inputs_right['attention_mask'])
       # output_right = F.normalize(output_right, p=2, dim=1)

       # Look at sBERT paper (u, v, |u-v|)
       pooled_output = torch.cat((output_left, output_right, torch.abs(output_left - output_right)), -1)

      linear_output = self.linear(pooled_output)
      relu_output = self.relu(linear_output)

      labels = labels.to(self.device)
      loss = self.criterion(linear_output.view(-1), labels.float())

      return (loss, relu_output)

</code>```

Here's the Dataset

class FinalDataset(torch.utils.data.Dataset):

    def __init__(self, df):

        self.labels = [int(label) for label in df['label']]
        self.examples = df

    def classes(self):
        return self.labels

    def __len__(self):
        return len(self.labels)

    def __getitem__(self, idx):
        examples = self.examples.iloc[idx]
        text_left = examples['text_left']
        text_right = examples['text_right']
        label = np.array(self.labels[idx])
        return text_left, text_right, label

```
<p>and finally the training loop</p>
<pre class="lang-py prettyprint-override"><code>
def train(model, train, val, learning_rate=1e-6, epochs=5, batch_size=8):
  train_dataloader = torch.utils.data.DataLoader(train, batch_size=8, shuffle=True)
  val_dataloader = torch.utils.data.DataLoader(val, batch_size=8)

  use_cuda = torch.cuda.is_available()
  device = torch.device("cuda" if use_cuda else "cpu")

  optimizer = Adam(model.parameters(), lr= learning_rate)

  if use_cuda:
    model = model.cuda()

  for epoch_num in range(epochs):
    total_loss_train = 0
    tmp_loss = 0
    step = 0

    model.train()
    for i, data in enumerate(tqdm(train_dataloader)):
      left_batch, right_batch, labels = data

      (batch_loss, _) = model(left_batch, right_batch, labels)

      total_loss_train += batch_loss
      tmp_loss += batch_loss

      model.zero_grad()
      batch_loss.backward()
      optimizer.step()

      # every 100 mini-batches
      if i % 100 == 99:
        print(f' Loss/train at epoch {epoch_num+1} (batch {i}): {tmp_loss/500}')
        writer.add_scalar('Loss/train',
                          tmp_loss / 100,
                          epoch_num * len(train_dataloader) + i)
        tmp_loss = 0

    total_loss_val = 0
    predictions = None
    total_labels = None
    step = 0

    model.eval()
    with torch.no_grad():

      for i, data in enumerate(val_dataloader):
        left_batch, right_batch, labels = data
        (batch_loss, linear_output) = model(left_batch, right_batch, labels)

        labels = labels.detach().cpu().numpy()
        linear_output = linear_output.detach().cpu().numpy()
        if predictions is None:
          predictions = np.where(linear_output>0.5, 1, 0)
          total_labels = labels
        else:
          predictions = np.append(predictions, np.where(linear_output>0.5, 1, 0), axis=0)
          total_labels = np.append(total_labels, labels, axis=0)

        total_loss_val += batch_loss.item()
        tmp_loss += batch_loss.item()

        # every 100 mini-batches
        if i % 100 == 99:
          print(f' Loss/val at epoch {epoch_num+1} (batch {i}): {tmp_loss/500}')
          writer.add_scalar('Loss/val',
                            tmp_loss / 100,
                            epoch_num * len(val_dataloader) + i)
          writer.add_scalar('F1/val',
                            f1_score(y_true=total_labels.flatten()[step:i], y_pred=predictions.flatten()[step:i]),
                            epoch_num * len(val_dataloader) + i)
          tmp_loss = 0
          step += 100

    f1 = f1_score(y_true=total_labels.flatten(), y_pred=predictions.flatten())
    report = classification_report(total_labels, predictions, zero_division=0)

    # plot all the pr curves
    for i in range(len([0, 1])):
      add_pr_curve_tensorboard(i, predictions.flatten(), total_labels.flatten())

    for name, p in model.named_parameters():
      writer.add_histogram(name, p, bins='auto')

    print(
        f'Epochs: {epoch_num + 1} | Train Loss: {total_loss_train / len(train): .3f} \
        | Val Loss: {total_loss_val / len(val): .3f} \
        | Val F1: {f1: .3f}')

    tqdm.write(report)

writer = SummaryWriter(log_dir=tensorboard_path)

EPOCHS = 5

LR = 1e-6
train_pos_neg_ratio = 9

model = FinalClassifier(train_pos_neg_ratio, frozen=False)
train_data, val_data = FinalDataset(df_train), FinalDataset(df_dev)

train(model, train_data, val_data, LR, EPOCHS)
writer.flush()
writer.close()

</code>```

The issue is that the loss does NOT decrease, and the F1 accuracy as a result. I tried to normalize the outputs, add a dropout layer, analized the dataset to be sure that the problem wasn't there but now I ran out of ideas. An help would be extremely valuable.

Body:
I'm trying to finetune a model for an entity matching task (kind of a sentence similarity task).

The idea is that if I give as input two sentences the model should output if they represent the same entity or not. I'm interested in the products' domain.

So for example:

sentences_left = ('logitech harmony 890 advanced universal remote control h890', 'sony silver digital voice recorder icdb600')
sentences_right = ('logitech harmony 890 advanced universal remote hdtv , tv , dvd player ( s ) , lighting , audio system 100 ft universal remote 966193-0403', 'canon black ef 70-300mm f/4 -5.6 is usm telephoto zoom lens 0345b002')

The output should be 1 for the first left-right pair of sentences and 0 for the second.

I want to test two approaches. The first is a sequence classification setup. So I take a pair of sentences, concat them with a [SEP] token in-between, encode it and feed it to BERT.

This approach kind of work, but I wanted to explore a second one that, in theory, should work too.

In few words, using mpnet as pre-trained language model I'm trying to implement this setup:

This is taken from the paper Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks. The idea is to compute not only a single embedding as before, but two separate embeddings for each of the sentences. Then concatenate the embeddings and feeds them to a softmax classifier.

After lots of struggles I'm still unable to make it work, since the loss has no intention of decreasing. It starts at 0.25 and never goes up neither down.

I'm using the Abt-Buy, Amazon-Google and Walmart-Amazon datasets.

This is my model:

class FinalClassifier(nn.Module):

    def __init__(self, pos_neg=None, frozen=False):

        super(FinalClassifier, self).__init__()

        use_cuda = torch.cuda.is_available()
        self.device = torch.device("cuda" if use_cuda else "cpu")

        self.encoder = AutoModel.from_pretrained(
'all-mpnet-base-v2')

        if frozen:
          for param in self.encoder.parameters():
            param.requires_grad = False
        self.tokenizer = AutoTokenizer.from_pretrained(
'all-mpnet-base-v2')

        if pos_neg:
          self.criterion = BCEWithLogitsLoss(pos_weight=torch.Tensor([pos_neg]))

        self.linear = nn.Linear(3*768, 1)
        self.relu = nn.ReLu()

    def forward(self, texts_left, texts_right, labels=None):
       encoded_inputs_left = self.tokenizer(texts_left, padding='max_length',
                                        truncation=True, return_tensors='pt')
       encoded_inputs_left = encoded_inputs_left.to(self.device)

       output_left = self.encoder(**encoded_inputs_left)
       output_left = _mean_pooling(output_left, encoded_inputs_left['attention_mask'])
       # output_left = F.normalize(output_left, p=2, dim=1)

       encoded_inputs_right = self.tokenizer(texts_right, padding='max_length',
                                        truncation=True, return_tensors='pt')
       encoded_inputs_right = encoded_inputs_right.to(self.device)

       output_right = self.encoder(**encoded_inputs_right)
       output_right = _mean_pooling(output_right, encoded_inputs_right['attention_mask'])
       # output_right = F.normalize(output_right, p=2, dim=1)

       # Look at sBERT paper (u, v, |u-v|)
       pooled_output = torch.cat((output_left, output_right, torch.abs(output_left - output_right)), -1)

      linear_output = self.linear(pooled_output)
      relu_output = self.relu(linear_output)

      labels = labels.to(self.device)
      loss = self.criterion(linear_output.view(-1), labels.float())

      return (loss, relu_output)

Here's the Dataset

class FinalDataset(torch.utils.data.Dataset):

    def __init__(self, df):

        self.labels = [int(label) for label in df['label']]
        self.examples = df

    def classes(self):
        return self.labels

    def __len__(self):
        return len(self.labels)

    def __getitem__(self, idx):
        examples = self.examples.iloc[idx]
        text_left = examples['text_left']
        text_right = examples['text_right']
        label = np.array(self.labels[idx])
        return text_left, text_right, label

and finally the training loop

def train(model, train, val, learning_rate=1e-6, epochs=5, batch_size=8):
  train_dataloader = torch.utils.data.DataLoader(train, batch_size=8, shuffle=True)
  val_dataloader = torch.utils.data.DataLoader(val, batch_size=8)

  use_cuda = torch.cuda.is_available()
  device = torch.device("cuda" if use_cuda else "cpu")

  optimizer = Adam(model.parameters(), lr= learning_rate)

  if use_cuda:
    model = model.cuda()

  for epoch_num in range(epochs):
    total_loss_train = 0
    tmp_loss = 0
    step = 0

    model.train()
    for i, data in enumerate(tqdm(train_dataloader)):
      left_batch, right_batch, labels = data

      (batch_loss, _) = model(left_batch, right_batch, labels)

      total_loss_train += batch_loss
      tmp_loss += batch_loss

      model.zero_grad()
      batch_loss.backward()
      optimizer.step()

      # every 100 mini-batches
      if i % 100 == 99:
        print(f' Loss/train at epoch {epoch_num+1} (batch {i}): {tmp_loss/500}')
        writer.add_scalar('Loss/train',
                          tmp_loss / 100,
                          epoch_num * len(train_dataloader) + i)
        tmp_loss = 0

    total_loss_val = 0
    predictions = None
    total_labels = None
    step = 0

    model.eval()
    with torch.no_grad():

      for i, data in enumerate(val_dataloader):
        left_batch, right_batch, labels = data
        (batch_loss, linear_output) = model(left_batch, right_batch, labels)

        labels = labels.detach().cpu().numpy()
        linear_output = linear_output.detach().cpu().numpy()
        if predictions is None:
          predictions = np.where(linear_output>0.5, 1, 0)
          total_labels = labels
        else:
          predictions = np.append(predictions, np.where(linear_output>0.5, 1, 0), axis=0)
          total_labels = np.append(total_labels, labels, axis=0)

        total_loss_val += batch_loss.item()
        tmp_loss += batch_loss.item()

        # every 100 mini-batches
        if i % 100 == 99:
          print(f' Loss/val at epoch {epoch_num+1} (batch {i}): {tmp_loss/500}')
          writer.add_scalar('Loss/val',
                            tmp_loss / 100,
                            epoch_num * len(val_dataloader) + i)
          writer.add_scalar('F1/val',
                            f1_score(y_true=total_labels.flatten()[step:i], y_pred=predictions.flatten()[step:i]),
                            epoch_num * len(val_dataloader) + i)
          tmp_loss = 0
          step += 100

    f1 = f1_score(y_true=total_labels.flatten(), y_pred=predictions.flatten())
    report = classification_report(total_labels, predictions, zero_division=0)

    # plot all the pr curves
    for i in range(len([0, 1])):
      add_pr_curve_tensorboard(i, predictions.flatten(), total_labels.flatten())

    for name, p in model.named_parameters():
      writer.add_histogram(name, p, bins='auto')

    print(
        f'Epochs: {epoch_num + 1} | Train Loss: {total_loss_train / len(train): .3f} \
        | Val Loss: {total_loss_val / len(val): .3f} \
        | Val F1: {f1: .3f}')

    tqdm.write(report)

writer = SummaryWriter(log_dir=tensorboard_path)

EPOCHS = 5

LR = 1e-6
train_pos_neg_ratio = 9

model = FinalClassifier(train_pos_neg_ratio, frozen=False)
train_data, val_data = FinalDataset(df_train), FinalDataset(df_dev)

train(model, train_data, val_data, LR, EPOCHS)
writer.flush()
writer.close()

The issue is that the loss does NOT decrease, and the F1 accuracy as a result. I tried to normalize the outputs, add a dropout layer, analized the dataset to be sure that the problem wasn't there but now I ran out of ideas. An help would be extremely valuable.


问:
Problem with Authlogic and RSpec
I'm writing a simple Survey application using Authlogic gem. When I did testing using rails built in test tools everything worked well but now with Rspec I'm getting following error : This error is coming when it tries to run the command require "authlogic/testcase" from spec_helper.rb

```<code>/home/gunanka/.rvm/gems/ruby-1.9.2-p290/gems/activesupport-3.0.10/lib/active_support/dependencies.rb:239:in `require': no such file to load -- authlogic/testcase (LoadError)
from /home/gunanka/.rvm/gems/ruby-1.9.2-p290/gems/activesupport-3.0.10/lib/active_support/dependencies.rb:239:in `block in require'
from /home/gunanka/.rvm/gems/ruby-1.9.2-p290/gems/activesupport-3.0.10/lib/active_support/dependencies.rb:227:in `load_dependency'
from /home/gunanka/.rvm/gems/ruby-1.9.2-p290/gems/activesupport-3.0.10/lib/active_support/dependencies.rb:239:in `require'
from /home/gunanka/survey/spec/spec_helper.rb:8:in `<top (required)>'
from /home/gunanka/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
from /home/gunanka/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
from /home/gunanka/survey/spec/controllers/users_controller_spec.rb:1:in `<top (required)>'
from /home/gunanka/.rvm/gems/ruby-1.9.2-p290/gems/rspec-core-2.6.4/lib/rspec/core/configuration.rb:419:in `load'
from /home/gunanka/.rvm/gems/ruby-1.9.2-p290/gems/rspec-core-2.6.4/lib/rspec/core/configuration.rb:419:in `block in load_spec_files'
from /home/gunanka/.rvm/gems/ruby-1.9.2-p290/gems/rspec-core-2.6.4/lib/rspec/core/configuration.rb:419:in `map'
from /home/gunanka/.rvm/gems/ruby-1.9.2-p290/gems/rspec-core-2.6.4/lib/rspec/core/configuration.rb:419:in `load_spec_files'
from /home/gunanka/.rvm/gems/ruby-1.9.2-p290/gems/rspec-core-2.6.4/lib/rspec/core/command_line.rb:18:in `run'
from /home/gunanka/.rvm/gems/ruby-1.9.2-p290/gems/rspec-core-2.6.4/lib/rspec/core/runner.rb:80:in `run_in_process'
from /home/gunanka/.rvm/gems/ruby-1.9.2-p290/gems/rspec-core-2.6.4/lib/rspec/core/runner.rb:69:in `run'
from /home/gunanka/.rvm/gems/ruby-1.9.2-p290/gems/rspec-core-2.6.4/lib/rspec/core/runner.rb:11:in `block in autorun'
</code>```

It is trying to fetch authlogic/testcase from activesupport/dependencies instead of authlogic. Please can anyone suggest where I'm going wrong.
Versions:
ruby -1.9.2
rails - 3.0.10
authlogic - 3.0.3
rspec -2.6.0

Thanks in advance

ContentLicense: CC BY-SA 3.0

Title: Problem with Authlogic and RSpec

Body:
I'm writing a simple Survey application using Authlogic gem. When I did testing using rails built in test tools everything worked well but now with Rspec I'm getting following error : This error is coming when it tries to run the command require "authlogic/testcase" from spec_helper.rb

/home/gunanka/.rvm/gems/ruby-1.9.2-p290/gems/activesupport-3.0.10/lib/active_support/dependencies.rb:239:in `require': no such file to load -- authlogic/testcase (LoadError)
from /home/gunanka/.rvm/gems/ruby-1.9.2-p290/gems/activesupport-3.0.10/lib/active_support/dependencies.rb:239:in `block in require'
from /home/gunanka/.rvm/gems/ruby-1.9.2-p290/gems/activesupport-3.0.10/lib/active_support/dependencies.rb:227:in `load_dependency'
from /home/gunanka/.rvm/gems/ruby-1.9.2-p290/gems/activesupport-3.0.10/lib/active_support/dependencies.rb:239:in `require'
from /home/gunanka/survey/spec/spec_helper.rb:8:in `<top (required)>'
from /home/gunanka/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
from /home/gunanka/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
from /home/gunanka/survey/spec/controllers/users_controller_spec.rb:1:in `<top (required)>'
from /home/gunanka/.rvm/gems/ruby-1.9.2-p290/gems/rspec-core-2.6.4/lib/rspec/core/configuration.rb:419:in `load'
from /home/gunanka/.rvm/gems/ruby-1.9.2-p290/gems/rspec-core-2.6.4/lib/rspec/core/configuration.rb:419:in `block in load_spec_files'
from /home/gunanka/.rvm/gems/ruby-1.9.2-p290/gems/rspec-core-2.6.4/lib/rspec/core/configuration.rb:419:in `map'
from /home/gunanka/.rvm/gems/ruby-1.9.2-p290/gems/rspec-core-2.6.4/lib/rspec/core/configuration.rb:419:in `load_spec_files'
from /home/gunanka/.rvm/gems/ruby-1.9.2-p290/gems/rspec-core-2.6.4/lib/rspec/core/command_line.rb:18:in `run'
from /home/gunanka/.rvm/gems/ruby-1.9.2-p290/gems/rspec-core-2.6.4/lib/rspec/core/runner.rb:80:in `run_in_process'
from /home/gunanka/.rvm/gems/ruby-1.9.2-p290/gems/rspec-core-2.6.4/lib/rspec/core/runner.rb:69:in `run'
from /home/gunanka/.rvm/gems/ruby-1.9.2-p290/gems/rspec-core-2.6.4/lib/rspec/core/runner.rb:11:in `block in autorun'

It is trying to fetch authlogic/testcase from activesupport/dependencies instead of authlogic. Please can anyone suggest where I'm going wrong.
Versions:
ruby -1.9.2
rails - 3.0.10
authlogic - 3.0.3
rspec -2.6.0

Thanks in advance


问:
tkinter PhotoImage object has no attribute 'read'
```<code>from tkinter import *
import tkinter as tk
from PIL import ImageTk, Image
from tkinter import ttk
import kalkulasi

#making the window
root = Tk()
root.title('Estimasi Perjalanan Kereta Rute Tangerang-Depok')
root.minsize(400,400)
root.geometry('650x700')

#define image
image = Image.open('petafix.png')

#define image as bg
bg = ImageTk.PhotoImage(image)

# create canvas
main_canvas = Canvas(root, width=650, height=700)
main_canvas.pack(fill='both', expand=True)

# set img in canvas
main_canvas.create_image(325, 300, image=bg)

# add "Selamat Datang!" text
main_canvas.create_text(325, 25, text="Selamat Datang!", font=('Helvetica', 25))

# making resize "HITUNG" button image
hitung_button = Image.open('button.jpg')
hitung_button_resized = hitung_button.resize((75, 30), Image.ANTIALIAS)
new_hitung_button = ImageTk.PhotoImage(hitung_button_resized)
label_hitung_button = Label(root, image= new_hitung_button, border= 0, anchor='center')
label_hitung_button.pack()

# reposition the "hitung" button
button = Button(root, image= new_hitung_button, border= 0, highlightthickness= 0,)
button_window = main_canvas.create_window(300, 670, anchor='nw', window=button)

# making resizer function
def resizer(event):
    global bg1, resized_bg, new_bg
    # open the image
    bg1 = Image.open('petafix.png)
    # Resize the image
    resized_bg = bg1.resize((event.width, event.height), Image.ANTIALIAS)
    # define image again as new bg
    new_bg = ImageTk.PhotoImage(resized_bg)
    # add new bg back to the canvas
    main_canvas.create_image(325, 300, image=new_bg)

root.bind('<Configure>', resizer)

root.mainloop()

</code>```

I'm trying to make my GUI window's dynamic, but there is an error i can't figured out that when i run the program, the program want to run but it still not dynamic and in the terminal, there is an error says AttributeError: 'PhotoImage' object has no attribute 'read'.

Body:
from tkinter import *
import tkinter as tk
from PIL import ImageTk, Image
from tkinter import ttk
import kalkulasi

#making the window
root = Tk()
root.title('Estimasi Perjalanan Kereta Rute Tangerang-Depok')
root.minsize(400,400)
root.geometry('650x700')

#define image
image = Image.open('petafix.png')

#define image as bg
bg = ImageTk.PhotoImage(image)

# create canvas
main_canvas = Canvas(root, width=650, height=700)
main_canvas.pack(fill='both', expand=True)

# set img in canvas
main_canvas.create_image(325, 300, image=bg)

# add "Selamat Datang!" text
main_canvas.create_text(325, 25, text="Selamat Datang!", font=('Helvetica', 25))

# making resize "HITUNG" button image
hitung_button = Image.open('button.jpg')
hitung_button_resized = hitung_button.resize((75, 30), Image.ANTIALIAS)
new_hitung_button = ImageTk.PhotoImage(hitung_button_resized)
label_hitung_button = Label(root, image= new_hitung_button, border= 0, anchor='center')
label_hitung_button.pack()

# reposition the "hitung" button
button = Button(root, image= new_hitung_button, border= 0, highlightthickness= 0,)
button_window = main_canvas.create_window(300, 670, anchor='nw', window=button)

# making resizer function
def resizer(event):
    global bg1, resized_bg, new_bg
    # open the image
    bg1 = Image.open('petafix.png)
    # Resize the image
    resized_bg = bg1.resize((event.width, event.height), Image.ANTIALIAS)
    # define image again as new bg
    new_bg = ImageTk.PhotoImage(resized_bg)
    # add new bg back to the canvas
    main_canvas.create_image(325, 300, image=new_bg)

root.bind('<Configure>', resizer)

root.mainloop()

I'm trying to make my GUI window's dynamic, but there is an error i can't figured out that when i run the program, the program want to run but it still not dynamic and in the terminal, there is an error says AttributeError: 'PhotoImage' object has no attribute 'read'.


问:
Initialising char array of length smaller than required doesn't gives error
When I declare a char array of length 2 and then input a string of length greater than 2, it doesn't give an error and outputs the whole string. Does that mean extra size is allocated dynamically?

Sample code:

```<code>char arr[2];
cin >> arr;
cout << arr << endl;
</code>```

Input = "Hey"

Output = "Hey"

Body:
When I declare a char array of length 2 and then input a string of length greater than 2, it doesn't give an error and outputs the whole string. Does that mean extra size is allocated dynamically?

Sample code:

char arr[2];
cin >> arr;
cout << arr << endl;

Input = "Hey"

Output = "Hey"


问:
How to check EVA data that has errors
I have to manipulate data which has information like title, short description and long description all in multi-language.

The short and long description does not follow any rules. I would like to harmonize them in order to be well referenced on search engines and above all to avoid repetitions on my files.
I am using the ‘Translatable behavior extension for Doctrine 2’ bundle
So I use this class:

```<code>Class Fiche {
#[ORM\Id]
    #[ORM\GeneratedValue(strategy: 'IDENTITY')]
    #[ORM\Column]
    private ?int $id = null;
/**
     * Used locale to override Translation listener`s locale
     * this is not a mapped field of entity metadata, just a simple property
     */
    #[Gedmo\Locale]
    private $locale;

    #[ORM\Column(type: Types::TEXT, nullable: true)]
    #[Gedmo\Translatable]
    private ?string $descriptionCourte = null;

    #[ORM\Column(type: Types::TEXT, nullable: true)]
    #[Gedmo\Translatable]
    private ?string $descriptionLongue = null;
[…]
</code>```

In the ddlfile example ddlfile, 'url1' to 'url6' represent 6 objects that I need to rebuild.

The short and long description content can be repeated, be absent (one or the other or both) etc…
So I also have to set the shortDescription and longDescription fields of the file table for the lang ‘fr’ otherwise, for the other languages, I have to add them to the ext_translations table (for the translations bundle).

I can have short or long descriptions, both or none of the 2 represented [url2/data2, url3/data3, url4, url1/data1]

I need to check that the short description is not equal (removing the last 3 characters as I potentially have '...' at the end) to the long description, represented as [url1/data1]. There are short descriptions totally different from the long description (with or without translation) and those I want to keep

I can have the short description (shortcut) 200 characters same as the long description, but the short description can have translations (lang) that the long description did not represent [url6/data6, url7/data7] .

I therefore want to retrieve the maximum information (short or long description both or none) (example for No. 3 retrieve the long description) but keep the translations of the short description if the description does not have any.

I hope to be precise and especially sorry I use a translator

Title: How to check EVA data that has errors

Body:
I have to manipulate data which has information like title, short description and long description all in multi-language.

The short and long description does not follow any rules. I would like to harmonize them in order to be well referenced on search engines and above all to avoid repetitions on my files.
I am using the ‘Translatable behavior extension for Doctrine 2’ bundle
So I use this class:

Class Fiche {
#[ORM\Id]
    #[ORM\GeneratedValue(strategy: 'IDENTITY')]
    #[ORM\Column]
    private ?int $id = null;
/**
     * Used locale to override Translation listener`s locale
     * this is not a mapped field of entity metadata, just a simple property
     */
    #[Gedmo\Locale]
    private $locale;

    #[ORM\Column(type: Types::TEXT, nullable: true)]
    #[Gedmo\Translatable]
    private ?string $descriptionCourte = null;

    #[ORM\Column(type: Types::TEXT, nullable: true)]
    #[Gedmo\Translatable]
    private ?string $descriptionLongue = null;
[…]

In the ddlfile example ddlfile, 'url1' to 'url6' represent 6 objects that I need to rebuild.

The short and long description content can be repeated, be absent (one or the other or both) etc…
So I also have to set the shortDescription and longDescription fields of the file table for the lang ‘fr’ otherwise, for the other languages, I have to add them to the ext_translations table (for the translations bundle).

I can have short or long descriptions, both or none of the 2 represented [url2/data2, url3/data3, url4, url1/data1]

I need to check that the short description is not equal (removing the last 3 characters as I potentially have '...' at the end) to the long description, represented as [url1/data1]. There are short descriptions totally different from the long description (with or without translation) and those I want to keep

I can have the short description (shortcut) 200 characters same as the long description, but the short description can have translations (lang) that the long description did not represent [url6/data6, url7/data7] .

I therefore want to retrieve the maximum information (short or long description both or none) (example for No. 3 retrieve the long description) but keep the translations of the short description if the description does not have any.

I hope to be precise and especially sorry I use a translator


问:
laravel 9 auth dropdown menu don't show
I am using laravel 9 UI auth.
When login in and I click the user name,
it should show a dropdown menu let me logout,
but the dropdown menu don't show

and it works properly in mobile (responsive) view

createPopper.js:110 Popper: CSS "margin" styles cannot be used to apply padding between the popper and its reference element or boundary. To replicate margin, use the offset modifier, as well as the padding option in the preventOverflow and flip modifiers.

```<code>setOptions @ createPopper.js:110
createPopper4 @ createPopper.js:215
_createPopper @ dropdown.js:240
show @ dropdown.js:138
toggle @ dropdown.js:120
(anonymous) @ dropdown.js:445
handler @ event-handler.js:118
</code>```

'''''''

```<code><!-- Right Side Of Navbar -->
          <ul class="navbar-nav ms-auto ">
              <!-- Authentication Links -->
              @guest
                  @if (Route::has('login'))
                      <li class="nav-item">
                          <a class="nav-link" href="{{ route('login') }}">{{ __('Login') }}</a>
                      </li>
                  @endif

                  @if (Route::has('register'))
                      <li class="nav-item">
                          <a class="nav-link" href="{{ route('register') }}">{{ __('Register') }}</a>
                      </li>
                  @endif
              @else
                  <li class="nav-item dropdown ">
                      <a id="navbarDropdown" class="nav-link dropdown-toggle " href="#" role="button" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre>
                          {{ Auth::user()->name }}
                      </a>

                      <div class="dropdown-menu dropdown-menu-ende background-color-blues " aria-labelledby="navbarDropdown">

                        {{--                    --}}
                          <a class="dropdown-item" href="{{ route('logout') }}"
                             onclick="event.preventDefault();
                                           document.getElementById('logout-form').submit();">
                              {{ __('Logout') }}
                          </a>

                          <form id="logout-form" action="{{ route('logout') }}" method="POST" class="d-none">
                              @csrf
                          </form>
                      </div>
                  </li>
              @endguest
          </ul>
</code>```

''''''''''

I tried adding class    margin:0     ,
in different places but it doesn't work

Title: laravel 9 auth dropdown menu don't show

Body:
I am using laravel 9 UI auth.
When login in and I click the user name,
it should show a dropdown menu let me logout,
but the dropdown menu don't show

and it works properly in mobile (responsive) view

createPopper.js:110 Popper: CSS "margin" styles cannot be used to apply padding between the popper and its reference element or boundary. To replicate margin, use the offset modifier, as well as the padding option in the preventOverflow and flip modifiers.

setOptions @ createPopper.js:110
createPopper4 @ createPopper.js:215
_createPopper @ dropdown.js:240
show @ dropdown.js:138
toggle @ dropdown.js:120
(anonymous) @ dropdown.js:445
handler @ event-handler.js:118

'''''''

              @guest
                  @if (Route::has('login'))

                          {{ __('Login') }}

                  @endif

                  @if (Route::has('register'))

                          {{ __('Register') }}

                  @endif
              @else

                          {{ Auth::user()->name }}

                        {{--                    --}}

                              {{ __('Logout') }}

                          <form id="logout-form" action="{{ route('logout') }}" method="POST" class="d-none">
                              @csrf
                          </form>

              @endguest

''''''''''

I tried adding class    margin:0     ,
in different places but it doesn't work


问:
how i can get the single call when we upload the folder using dropzone js
how i can get the single call when we upload the  folder using dropzone js.

Problem is it show the progress bar for each single call  i want a one single progress bar total upload progress bar.

My code is

```<code><script>
Dropzone.options.fileUploader3 = {
            chunking: true,
            chunkSize: 10000000,
            forceChunking: true,
            retryChunks: true,
            retryChunksLimit: 3,
            clickable: false,
            parallelUploads: 1000, // does not support more than 1!
            timeout: 120000,
            dictDefaultMessage: "Create Folder",
            complete:function(file) {
            },
            totaluploadprogress: function(progress) {
            //console.log("progress==>"+progress);
               $(".progress-track").show();
               $(".progress-bar").width(progress + '%');
               $(".progress-bar").text(progress.toFixed(2) + '%');
            },
            addedfile:function() {
                 console.log("A file has been added");
            },
            maxFilesize: 10000000000,
            acceptedFiles : "",
            init: function () {

                this.on("sending", function (file, xhr, formData) {

                    var values = {};

                    if($("#fileUploader3").serializeArray()){
                        console.log("createfolder==>"+$("#fileUploader3").serializeArray());
                        $.each($("#fileUploader3").serializeArray(), function (i, field) {
                            values[field.name] = field.value;
                        });

                        //Value Retrieval Function
                        var getValue = function (valueName) {
                        return values[valueName];
                        };

                        //Retrieve the Values
                        var upload_type = getValue("upload_type");

                    }

                    console.log("upload_type_fileUploader3==>==>"+upload_type);

                    if(upload_type == 'createfolderfile'){
                       let _path = (file.fullPath) ? file.fullPath : file.name;
                       document.getElementById("fullpath").value = _path;

                    let _path1 = (file.fullPath) ? file.fullPath : file.name;
                    // Code For Upload Folder only
                    <?php
                     $ii = 3399;
                       foreach ($folders as $key => $value){
                            if ($value == 'trash') {  unset($folders[$key]); }
                            if ($value == 'shared') {  unset($folders[$key]); }
                        }
                      foreach ($folders as $f) {
                     ?>
                        if(document.getElementById("fullpath"+<?php echo $ii ?>)){
                           document.getElementById("fullpath"+<?php echo $ii ?>).value =_path1;
                        }
                    <?php
                      flush();
                      $ii++;
                    }
                    ?>
                    }
                    if(upload_type == 'createfolder'){
                        let _path = (file.fullPath) ? file.fullPath : file.name;
                       document.getElementById("fullpath1").value = _path;
                    }

                    if(upload_type == 'recentfile'){
                        let _path = (file.fullPath) ? file.fullPath : file.name;
                       document.getElementById("fullpath2").value = _path;
                    }

                    xhr.ontimeout = (function() {
                        toast('Error: Server Timeout');
                    });
                }).on("success", function (res, responseText) {
                    $(".progress-track").hide();
                    var jsonResponse = JSON.parse(res.xhr.response);
                    if(res.status == 'success'){
                       // Path Return Back to Same Folder Path after Drop Folder
                       let _pfolderpath= jsonResponse.p;
                       if(_pfolderpath != ''){
                           var scroll = $('.file-scroll').scrollTop();
                           $("#content_div").load("https://rosnyc.com/admin/filemanager/load_recentfiles.php?p="+_pfolderpath,function(){
                            Dropzone.discover();
                            $('.file-scroll').scrollTop(scroll);
                              $('#home_storage_data').hide();
                          })
                         $("#right-side-content_div").load("https://rosnyc.com/admin/filemanager/rightside.php?p="+_pfolderpath,function(){
                          // Update Right Side Content
                        });
                       }
                       else {
                        var scroll = $('.file-scroll').scrollTop();
                        $("#content_div").load("https://rosnyc.com/admin/filemanager/load_recentfiles.php",function(){
                           Dropzone.discover();
                           $('.file-scroll').scrollTop(scroll);
                         })
                        $("#right-side-content_div").load("https://rosnyc.com/admin/filemanager/rightside.php",function(){
                          // Update Right Side Content
                          Dropzone.discover();
                        });
                      //let _response = JSON.parse(res.xhr.response);
                      //console.log('Upload Status >> ', res.status);
                    }
                      //toast('Upload Successfully');

                      $("#toast-message").html('Upload Successfully');
                $("#basic-primary-trigger").trigger('click');

                    }
                    if(res.status == "error") {
                        toast(_response.info);
                    }
                 }).on("error", function(file, response) {
                    toast(response);
                });

            }
        }
  </script>
</code>```