问:
How do I bind and unbinddirectional for a StringProperty in a ComboBox javaFX?
This is how I unbindBiDirectional from a class FamilyMember that contains a string variable called 'txtName'. I unbind the old value and clear it, and then bind the new value.

Unbinding:

```<code>((TreeItem<FamilyMember>)oldValue).getValue().nameProperty().unbindBidirectional(txtName.textProperty());
txtName.clear();
</code>```

Binding:

```<code>txtName.setText(((TreeItem<FamilyMember>)newValue).getValue().nameProperty().getValue());
((TreeItem<FamilyMember>)newValue).getValue().nameProperty().bindBidirectional(txtName.textProperty());
</code>```

But im confused as to how to do this for a ComboBox. My ComboBox is for selecting a gender with 3 options as strings, (ComboBox), Male, Female and Other. How can I achieve the above using a ComboBox with String Property instead?

答:
Controller Class:

```<code>package sample;

import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;

import java.net.URL;
import java.util.Random;
import java.util.ResourceBundle;

public class Controller implements Initializable {

    @FXML
    private ComboBox<String> genderComboBox;
    @FXML
    private Label selectedGenderLabel;

    private Random random = new Random();

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        // Add items:
        genderComboBox.getItems().addAll("Male", "Female", "Other");

        // Bind selection of combo box to string property:
        selectedGenderLabel.textProperty().bind(genderComboBox.valueProperty());
    }

    @FXML
    public void handleUnbindBtnClick() {
        // Un-bind and clear:
        selectedGenderLabel.textProperty().unbind();
        selectedGenderLabel.setText("");
    }

    @FXML
    public void handleBindBtnClick() {
        // Make a random selection:
        genderComboBox.getSelectionModel().select(random.nextInt(3));

        // Re-bind:
        selectedGenderLabel.textProperty().bind(genderComboBox.valueProperty());
    }
}
</code>```

FXML file:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.ComboBox?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.VBox?>

<VBox xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Controller">
   <children>
      <ComboBox fx:id="genderComboBox" />

      <Button mnemonicParsing="false" onAction="#handleUnbindBtnClick" text="Unbind" />
      <Button mnemonicParsing="false" onAction="#handleBindBtnClick" text="Bind" />
   </children>
</VBox>
```

Body:
This is how I unbindBiDirectional from a class FamilyMember that contains a string variable called 'txtName'. I unbind the old value and clear it, and then bind the new value.

Unbinding:

((TreeItem<FamilyMember>)oldValue).getValue().nameProperty().unbindBidirectional(txtName.textProperty());
txtName.clear();

Binding:

txtName.setText(((TreeItem<FamilyMember>)newValue).getValue().nameProperty().getValue());
((TreeItem<FamilyMember>)newValue).getValue().nameProperty().bindBidirectional(txtName.textProperty());

But im confused as to how to do this for a ComboBox. My ComboBox is for selecting a gender with 3 options as strings, (ComboBox), Male, Female and Other. How can I achieve the above using a ComboBox with String Property instead?

Body:
Controller Class:

package sample;

import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;

import java.net.URL;
import java.util.Random;
import java.util.ResourceBundle;

public class Controller implements Initializable {

    @FXML
    private ComboBox<String> genderComboBox;
    @FXML
    private Label selectedGenderLabel;

    private Random random = new Random();

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        // Add items:
        genderComboBox.getItems().addAll("Male", "Female", "Other");

        // Bind selection of combo box to string property:
        selectedGenderLabel.textProperty().bind(genderComboBox.valueProperty());
    }

    @FXML
    public void handleUnbindBtnClick() {
        // Un-bind and clear:
        selectedGenderLabel.textProperty().unbind();
        selectedGenderLabel.setText("");
    }

    @FXML
    public void handleBindBtnClick() {
        // Make a random selection:
        genderComboBox.getSelectionModel().select(random.nextInt(3));

        // Re-bind:
        selectedGenderLabel.textProperty().bind(genderComboBox.valueProperty());
    }
}

FXML file:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.ComboBox?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.VBox?>

<VBox xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Controller">
   <children>
      <ComboBox fx:id="genderComboBox" />
      <Label text="Selected Gender:" />
      <Label fx:id="selectedGenderLabel" />
      <Button mnemonicParsing="false" onAction="#handleUnbindBtnClick" text="Unbind" />
      <Button mnemonicParsing="false" onAction="#handleBindBtnClick" text="Bind" />
   </children>
</VBox>


来源: stackexchange

问:
PyInstaller: FileNotFoundError when trying to run the distribution file
I'm helping out a friend who needs to transform some data in csvs, so I made a little python program called "csv_converter.py"- it takes a csv input file and csv output file and everything's peachy.

I want to be able to give them a file they can run on their machine (without necessarily needing python and pandas) so I'm trying PyInstaller.
In the directory with my python program I run: pyinstaller csv_converter.py

According to the docs, it'll make a 'dist' folder where "you find the bundled app you distribute to your users." It sounds like the key file to run will be: dist/csv_converter/csv_converter (clarification source: here), and then I can either send the whole csv_converter folder, or just the csv_converter file if I run the Pyinstaller command with the --onefile argument.

After running PyInstaller I see these directories created, but when I navigate to dist/csv_converter/ and try to run that important csv_converter file (before trying to send anything), it's giving the following error:

```<code>Dianes-MacBook-Pro:csv_converter dkaplan$ ./csv_converter -h
Traceback (most recent call last):
  File "site-packages/PyInstaller/loader/rthooks/pyi_rth__tkinter.py", line 30, in <module>
FileNotFoundError: Tcl data directory "/Users/dkaplan/PycharmProjects/chris_csv_converter/src/dist/csv_converter/tcl" not found.
[36637] Failed to execute script pyi_rth__tkinter
</code>```

So close, but so far!  Has anyone else had this issue or know a workaround?

答:
I heard back from the kind folks at PyInstaller, and this is a common one they see with tinter. I'm not sure where it was being pulled in from, but the workaround was to exclude it with this argument: --exclude-module=tkinter

I had chosen to use the --onefile argument (slower, but means I can send just one file), so the full command was: pyinstaller --onefile --exclude-module=tkinter csv_converter.py

Then:

I could go to the dist folder and do a test run with: ./csv_converter -h

then I send that csv_converter file to my friend and he'll be able to run it the same way (without needing python)

ContentLicense: CC BY-SA 4.0

Body:
I'm helping out a friend who needs to transform some data in csvs, so I made a little python program called "csv_converter.py"- it takes a csv input file and csv output file and everything's peachy.

I want to be able to give them a file they can run on their machine (without necessarily needing python and pandas) so I'm trying PyInstaller.
In the directory with my python program I run: pyinstaller csv_converter.py

According to the docs, it'll make a 'dist' folder where "you find the bundled app you distribute to your users." It sounds like the key file to run will be: dist/csv_converter/csv_converter (clarification source: here), and then I can either send the whole csv_converter folder, or just the csv_converter file if I run the Pyinstaller command with the --onefile argument.

After running PyInstaller I see these directories created, but when I navigate to dist/csv_converter/ and try to run that important csv_converter file (before trying to send anything), it's giving the following error:

Dianes-MacBook-Pro:csv_converter dkaplan$ ./csv_converter -h
Traceback (most recent call last):
  File "site-packages/PyInstaller/loader/rthooks/pyi_rth__tkinter.py", line 30, in <module>
FileNotFoundError: Tcl data directory "/Users/dkaplan/PycharmProjects/chris_csv_converter/src/dist/csv_converter/tcl" not found.
[36637] Failed to execute script pyi_rth__tkinter

So close, but so far!  Has anyone else had this issue or know a workaround?


问:
Save object only if condition
I am trying to add an easy condition on saving an object, but can't find where I should put it.

I have a space and a booking model. My space has a "minimum_days" column. What I want is that if the number of days of the booking is smaller  than the minimum_days of the space, the booking won't be saved and the form will be rendered again with errors.

For that, I have a very simple condition in my bookings controller :
if @booking.space.minimum_days > number_of_days

But I don't know what to do with it.

I've tried to put a "redirect_to" with a flash alert if the condition is met, but that does not work properly

I've also tried to add a "validate" in my model and create a method:

```<code>validates :must_respect_minimum_days

def must_respect_minimum_days
    if @booking.booking_type == "daily"
      number_of_days = @booking.end_time.to_date - @booking.start_time.to_date).to_i
      if @booking.space.minimum_days > number_of_days
        errors.add(:minimum_days, "You did not book enough days")
      end
    end
  end
</code>```

But it says @booking is nil.... I've also tried to replace @booking with my params, but I can't access the params in the model method. It tells me undefined local variable or method `params' for #<Booking:0x00007f8ec2b57e00>

What is the easiest way to do that ? That sounds easy but for some reason I can't make it work!

Thanks a lot

答:
Assuming the code you posted is located in the booking model, the object you should refer to is 'self'.

```<code>self.booking_type == "daily"
</code>```

Or

```<code>booking_type == "daily"
</code>```

Title: Save object only if condition

Body:
I am trying to add an easy condition on saving an object, but can't find where I should put it.

I have a space and a booking model. My space has a "minimum_days" column. What I want is that if the number of days of the booking is smaller  than the minimum_days of the space, the booking won't be saved and the form will be rendered again with errors.

For that, I have a very simple condition in my bookings controller :
if @booking.space.minimum_days > number_of_days

But I don't know what to do with it.

I've tried to put a "redirect_to" with a flash alert if the condition is met, but that does not work properly

I've also tried to add a "validate" in my model and create a method:

validates :must_respect_minimum_days

def must_respect_minimum_days
    if @booking.booking_type == "daily"
      number_of_days = @booking.end_time.to_date - @booking.start_time.to_date).to_i
      if @booking.space.minimum_days > number_of_days
        errors.add(:minimum_days, "You did not book enough days")
      end
    end
  end

But it says @booking is nil.... I've also tried to replace @booking with my params, but I can't access the params in the model method. It tells me undefined local variable or method `params' for #<Booking:0x00007f8ec2b57e00>

What is the easiest way to do that ? That sounds easy but for some reason I can't make it work!

Thanks a lot

Body:
Assuming the code you posted is located in the booking model, the object you should refer to is 'self'.

self.booking_type == "daily"

Or

booking_type == "daily"


问:
Compare two strings of ints in java
I have two Strings that contain numbers and I want to see if the second string contains the same numbers as the first String, whether they are in order or not. If it has any number repeating than report false. Is there anyway in java other than using .charAt() because its not working for number after 10? </p>

```<code>String one = "1 2 3 4 5 ";
String two = " 3 2 1 4 5 ";
String three = "3 2 1 4 4 ";
</code>```

答:
Try to parse the strings in int.

```<code>Integer.parseInt(One).intValue() == Integer.parseInt(two).intValue()
</code>```

I'm not sure what you're trying to do but my guess is that you'd better to use arrays.

ContentLicense: CC BY-SA 3.0

Title: Compare two strings of ints in java

Body:
I have two Strings that contain numbers and I want to see if the second string contains the same numbers as the first String, whether they are in order or not. If it has any number repeating than report false. Is there anyway in java other than using .charAt() because its not working for number after 10?

String one = "1 2 3 4 5 ";
String two = " 3 2 1 4 5 ";
String three = "3 2 1 4 4 ";

Body:
Try to parse the strings in int.

Integer.parseInt(One).intValue() == Integer.parseInt(two).intValue()

I'm not sure what you're trying to do but my guess is that you'd better to use arrays.


问:
Convert HTML5 canvas to image link
Hey so I have looked around and have been able to convert my canvas into an dataURL and download it using this function:

```<code>function downloadImage(data, filename = 'untitled.jpeg') {
    var a = document.createElement('a');
    a.href = data;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
}
</code>```

where

```<code>data = canvas.toDataURL("image/jpeg")
</code>```

but I didn't find any way to convert the canvas into an image link which I could share with other people around the globe. Maybe a post method has to be applied and how could it be? I can also use a node.js online server

答:
Assuming that data = canvas.toDataURL("image/jpeg"), you can specify a base64 link with the correct headers :

const canvas = document.querySelector('canvas')
const button = document.querySelector('button')
const ctx = canvas.getContext('2d')

canvas.width = window.innerWidth
canvas.height = window.innerHeight

ctx.fillStyle = 'red'
ctx.fillRect(50, 50, 100, 100)

button.addEventListener('click', () => {
  let data = canvas.toDataURL("image/jpeg");
  data = data.replace('data:image/jpeg;base64,', '')
  console.log(data)
  downloadImage(data);
})

function downloadImage(data, filename = 'untitled.jpeg') {
    const a = document.createElement('a');
    a.href = 'data:application/octet-stream;headers=Content-Disposition%3A%20attachment%3B%20filename=' + filename + ';base64,' + data;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button>Save</button>
<canvas></canvas></code>```

Source: HTML5 Canvas to PNG File

Title: Convert HTML5 canvas to image link

Body:
Hey so I have looked around and have been able to convert my canvas into an dataURL and download it using this function:

function downloadImage(data, filename = 'untitled.jpeg') {
    var a = document.createElement('a');
    a.href = data;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
}

where

data = canvas.toDataURL("image/jpeg")

but I didn't find any way to convert the canvas into an image link which I could share with other people around the globe. Maybe a post method has to be applied and how could it be? I can also use a node.js online server

Body:
Assuming that data = canvas.toDataURL("image/jpeg"), you can specify a base64 link with the correct headers :

const canvas = document.querySelector('canvas')
const button = document.querySelector('button')
const ctx = canvas.getContext('2d')

canvas.width = window.innerWidth
canvas.height = window.innerHeight

ctx.fillStyle = 'red'
ctx.fillRect(50, 50, 100, 100)

button.addEventListener('click', () => {
  let data = canvas.toDataURL("image/jpeg");
  data = data.replace('data:image/jpeg;base64,', '')
  console.log(data)
  downloadImage(data);
})

function downloadImage(data, filename = 'untitled.jpeg') {
    const a = document.createElement('a');
    a.href = 'data:application/octet-stream;headers=Content-Disposition%3A%20attachment%3B%20filename=' + filename + ';base64,' + data;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
}

<button>Save</button>
<canvas></canvas>

Source: HTML5 Canvas to PNG File


问:
spark.executor.cores Vs spark.executor.instance which one should I increase?
In order to parallelize spark jobs, both the number of cores and the number of executor instances can be increased. What is the trade-off here and how should one pick the actual values of both the configs?  </p>

答:
Advantages of increasing no. of cores over no. of executor are same
as advantages of multi threaded over multi processes.

No. of cores increase no. of threads for each executor and no. of
executors will increase no. of Java process(i.e. Over all Spark
executors on a cluster) .

If you are looking to perform multiple operations in parallel on same
Dataset/Dataframe then increase no .of cores per executor

But if you are looking to perform process large amount of
Dataset/Dataframe with relatively less parallelism then you can
partition your day on key column and Spark will process your data on
respective partition allocated executor.

I recommend that you read this blog post from Cloudera.

Bench marking you PySpark job by varying no. executors against no. of executor thread is the best way to come up with the right configuration for your application.


问:
New files on Visual Studio are marked as Miscellaneous
I added simple class file to the project and it marked as Miscellaneous.

Usually the following actions helped me in this case:

- Unload and Reload a projects

- Close solution, delete .vs file and reload solution

But it didn't help me now.

I used Build Loging tool to see what's wrong and I found the next error:

答:
The problem was in .csproj file for problem solution.

```<code><Import Project="..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.2.0.1\build\net46\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props" Condition="Exists('..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.2.0.1\build\net46\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props')" />
</code>```

I removed it and was loaded successfully.

Body:
The problem was in .csproj file for problem solution.

<Import Project="..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.2.0.1\build\net46\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props" Condition="Exists('..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.2.0.1\build\net46\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props')" />

I removed it and was loaded successfully.


问:
adminer in a kubernetes pod
I am trying to create a pod with both phpmyadmin and adminer in it. I have the Dockerfile created but I am not sure of the entrypoint needed.

Has anyone accomplished this before? I have everything figured out but the entrypoint...

```<code>FROM phpmyadmin/phpmyadmin

ENV MYSQL_DATABASE=${MYSQL_DATABASE}
ENV MYSQL_USER=${MYSQL_USERNAME}
ENV MYSQL_ROOT_PASSWORD=${MYSQL_PASSWORD}
ENV MYSQL_PORT=3381
ENV PMA_USER=${MYSQL_USER}
ENV PMA_PORT=3381
ENV PMA_PASSWORD=${MYSQL_PASSWORD}
ENV PMA_HOST=${MYSQL_HOST}

EXPOSE 8081
ENTRYPOINT [ "executable" ]

FROM adminer:4

ENV POSTGRES_DB=${POSTGRES_DATABASE}
ENV POSTGRES_USER=${POSTGRES_USER}
ENV POSTGRES_PASSWORD=${POSTGRES_PASSWORD}

EXPOSE 8082
ENTRYPOINT [ "?" ]
</code>```

------UPDATE 1 ----------
after read some comments I spilt my Dockerfiles and will create a yml file for the kube pod

```<code>FROM phpmyadmin/phpmyadmin

ENV MYSQL_DATABASE=${MYSQL_DATABASE}
ENV MYSQL_USER=${MYSQL_USERNAME}
ENV MYSQL_ROOT_PASSWORD=${MYSQL_PASSWORD}
ENV MYSQL_PORT=3381
ENV PMA_USER=${MYSQL_USER}
ENV PMA_PORT=3381
ENV PMA_PASSWORD=${MYSQL_PASSWORD}
ENV PMA_HOST=${MYSQL_HOST}

EXPOSE 8081
ENTRYPOINT [ "executable" ]
</code>```

container 2

```<code>FROM adminer:4

ENV POSTGRES_DB=${POSTGRES_DATABASE}
ENV POSTGRES_USER=${POSTGRES_USER}
ENV POSTGRES_PASSWORD=${POSTGRES_PASSWORD}

EXPOSE 8082
ENTRYPOINT [ "?" ]
</code>```

I am still not sure what the entrypoint script should be

答:
Since you are not modifying anything in the image, you don't need to create a custom docker image for this, you could simply run 2 deployments in kubernetes passing the environment variables using a Kubernetes Secret.

See this example of how to deploy both application on Kubernetes:

Create a Kubernetes secret with your connection details:

cat <<EOF >./kustomization.yaml
secretGenerator:
- name: database-conn
  literals:
  - MYSQL_DATABASE=${MYSQL_DATABASE}
  - MYSQL_USER=${MYSQL_USER}
  - MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD}
  - MYSQL_PORT=${MYSQL_PORT}
  - POSTGRES_DB=${POSTGRES_DB}
  - POSTGRES_USER=${POSTGRES_USER}
  - POSTGRES_PASSWORD=${POSTGRES_PASSWORD}
EOF
```

<p>Apply the generated file:</p>

<pre class="lang-sh prettyprint-override"><code>kubectl apply -k .
secret/database-conn-mm8ck2296m created
</code>```

Deploy phpMyAdmin and Adminer:

You need to create two deployment, the first for phpMyAdmin, and other to Adminer, using the secrets created above in the containers, for example:

Create a file called phpmyadmin-deploy.yml:

Note: Change the secret name from database-conn-mm8ck2296m to the generated name in the command above.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: phpmyadmin
spec:
  selector:
    matchLabels:
      app: phpmyadmin
  template:
    metadata:
      labels:
        app: phpmyadmin
    spec:
      containers:
      - name: phpmyadmin
        image: phpmyadmin/phpmyadmin
        env:
        - name: MYSQL_DATABASE
          valueFrom:
            secretKeyRef:
              name: database-conn-mm8ck2296m
              key: MYSQL_DATABASE
        - name: MYSQL_USER
          valueFrom:
            secretKeyRef:
              name: database-conn-mm8ck2296m
              key: MYSQL_USER
        - name: MYSQL_ROOT_PASSWORD
          valueFrom:
            secretKeyRef:
              name: database-conn-mm8ck2296m
              key: MYSQL_ROOT_PASSWORD
        - name: MYSQL_PORT
          valueFrom:
            secretKeyRef:
              name: database-conn-mm8ck2296m
              key: MYSQL_PORT
        - name: PMA_HOST
          value: mysql.host
        - name: PMA_USER
          valueFrom:
            secretKeyRef:
              name: database-conn-mm8ck2296m
              key: MYSQL_USER
        - name: PMA_PASSWORD
          valueFrom:
            secretKeyRef:
              name: database-conn-mm8ck2296m
              key: MYSQL_ROOT_PASSWORD
        - name: PMA_PORT
          valueFrom:
            secretKeyRef:
              name: database-conn-mm8ck2296m
              key: MYSQL_PORT
        ports:
        - name: http
          containerPort: 80
---
apiVersion: v1
kind: Service
metadata:
  name: phpmyadmin-svc
spec:
  selector:
    app: phpmyadmin
  ports:
    - protocol: TCP
      port: 80
      targetPort: 80
```

<p><strong>Adminer:</strong></p>

<p>Create other file named <code>adminer-deploy.yaml</code></p>

<pre class="lang-yaml prettyprint-override"><code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: adminer
spec:
  selector:
    matchLabels:
      app: adminer
  template:
    metadata:
      labels:
        app: adminer
    spec:
      containers:
      - name: adminer
        image: adminer:4
        env:
        - name: POSTGRES_DB
          valueFrom:
            secretKeyRef:
              name: database-conn-mm8ck2296m
              key: POSTGRES_DB
        - name: POSTGRES_USER
          valueFrom:
            secretKeyRef:
              name: database-conn-mm8ck2296m
              key: POSTGRES_USER
        - name: POSTGRES_PASSWORD
          valueFrom:
            secretKeyRef:
              name: database-conn-mm8ck2296m
              key: POSTGRES_PASSWORD
        ports:
        - name: http
          containerPort: 8080
---
apiVersion: v1
kind: Service
metadata:
  name: adminer-svc
spec:
  selector:
    app: adminer
  ports:
    - protocol: TCP
      port: 8080
      targetPort: 8080
</code>```

Deploy the yaml files with kubectl apply -f *-deploy.yaml, after some seconds type kubectl get pods && kubectl get svc to verify if everything is ok.

Note: Both services will be created as ClusterIP, it means that it will be only accessible internally. If you are using a cloud provider, you can use service type LoadBalancer to get an external ip. Or you can use kubectl port-forward (see here) command to access your service from your computer.

Access application using port-forward:

phpMyadmin:

```<code># This command will map the port 8080 from your localhost to phpMyadmin application:
kubectl port-forward svc/phpmyadmin-svc 8080:80
</code>```

Adminer

```<code># This command will map the port 8181 from your localhost to Adminer application:
kubectl port-forward svc/adminer-svc 8181:8080
</code>```

And try to access:

http://localhost:8080 <= phpMyAdmin
http://localhost:8181 <= Adminer

References:

Kubernetes Secrets

Kubernetes Environment variables

Kubernetes port forward

Title: adminer in a kubernetes pod

Body:
I am trying to create a pod with both phpmyadmin and adminer in it. I have the Dockerfile created but I am not sure of the entrypoint needed.

Has anyone accomplished this before? I have everything figured out but the entrypoint...

FROM phpmyadmin/phpmyadmin

ENV MYSQL_DATABASE=${MYSQL_DATABASE}
ENV MYSQL_USER=${MYSQL_USERNAME}
ENV MYSQL_ROOT_PASSWORD=${MYSQL_PASSWORD}
ENV MYSQL_PORT=3381
ENV PMA_USER=${MYSQL_USER}
ENV PMA_PORT=3381
ENV PMA_PASSWORD=${MYSQL_PASSWORD}
ENV PMA_HOST=${MYSQL_HOST}

EXPOSE 8081
ENTRYPOINT [ "executable" ]

FROM adminer:4

ENV POSTGRES_DB=${POSTGRES_DATABASE}
ENV POSTGRES_USER=${POSTGRES_USER}
ENV POSTGRES_PASSWORD=${POSTGRES_PASSWORD}

EXPOSE 8082
ENTRYPOINT [ "?" ]

------UPDATE 1 ----------
after read some comments I spilt my Dockerfiles and will create a yml file for the kube pod

FROM phpmyadmin/phpmyadmin

ENV MYSQL_DATABASE=${MYSQL_DATABASE}
ENV MYSQL_USER=${MYSQL_USERNAME}
ENV MYSQL_ROOT_PASSWORD=${MYSQL_PASSWORD}
ENV MYSQL_PORT=3381
ENV PMA_USER=${MYSQL_USER}
ENV PMA_PORT=3381
ENV PMA_PASSWORD=${MYSQL_PASSWORD}
ENV PMA_HOST=${MYSQL_HOST}

EXPOSE 8081
ENTRYPOINT [ "executable" ]

container 2

FROM adminer:4

ENV POSTGRES_DB=${POSTGRES_DATABASE}
ENV POSTGRES_USER=${POSTGRES_USER}
ENV POSTGRES_PASSWORD=${POSTGRES_PASSWORD}

EXPOSE 8082
ENTRYPOINT [ "?" ]

I am still not sure what the entrypoint script should be

Body:
Since you are not modifying anything in the image, you don't need to create a custom docker image for this, you could simply run 2 deployments in kubernetes passing the environment variables using a Kubernetes Secret.

See this example of how to deploy both application on Kubernetes:

Create a Kubernetes secret with your connection details:

cat <<EOF >./kustomization.yaml
secretGenerator:
- name: database-conn
  literals:
  - MYSQL_DATABASE=${MYSQL_DATABASE}
  - MYSQL_USER=${MYSQL_USER}
  - MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD}
  - MYSQL_PORT=${MYSQL_PORT}
  - POSTGRES_DB=${POSTGRES_DB}
  - POSTGRES_USER=${POSTGRES_USER}
  - POSTGRES_PASSWORD=${POSTGRES_PASSWORD}
EOF

Apply the generated file:

kubectl apply -k .
secret/database-conn-mm8ck2296m created

Deploy phpMyAdmin and Adminer:

You need to create two deployment, the first for phpMyAdmin, and other to Adminer, using the secrets created above in the containers, for example:

Create a file called phpmyadmin-deploy.yml:

Note: Change the secret name from database-conn-mm8ck2296m to the generated name in the command above.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: phpmyadmin
spec:
  selector:
    matchLabels:
      app: phpmyadmin
  template:
    metadata:
      labels:
        app: phpmyadmin
    spec:
      containers:
      - name: phpmyadmin
        image: phpmyadmin/phpmyadmin
        env:
        - name: MYSQL_DATABASE
          valueFrom:
            secretKeyRef:
              name: database-conn-mm8ck2296m
              key: MYSQL_DATABASE
        - name: MYSQL_USER
          valueFrom:
            secretKeyRef:
              name: database-conn-mm8ck2296m
              key: MYSQL_USER
        - name: MYSQL_ROOT_PASSWORD
          valueFrom:
            secretKeyRef:
              name: database-conn-mm8ck2296m
              key: MYSQL_ROOT_PASSWORD
        - name: MYSQL_PORT
          valueFrom:
            secretKeyRef:
              name: database-conn-mm8ck2296m
              key: MYSQL_PORT
        - name: PMA_HOST
          value: mysql.host
        - name: PMA_USER
          valueFrom:
            secretKeyRef:
              name: database-conn-mm8ck2296m
              key: MYSQL_USER
        - name: PMA_PASSWORD
          valueFrom:
            secretKeyRef:
              name: database-conn-mm8ck2296m
              key: MYSQL_ROOT_PASSWORD
        - name: PMA_PORT
          valueFrom:
            secretKeyRef:
              name: database-conn-mm8ck2296m
              key: MYSQL_PORT
        ports:
        - name: http
          containerPort: 80
---
apiVersion: v1
kind: Service
metadata:
  name: phpmyadmin-svc
spec:
  selector:
    app: phpmyadmin
  ports:
    - protocol: TCP
      port: 80
      targetPort: 80

Adminer:

Create other file named adminer-deploy.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: adminer
spec:
  selector:
    matchLabels:
      app: adminer
  template:
    metadata:
      labels:
        app: adminer
    spec:
      containers:
      - name: adminer
        image: adminer:4
        env:
        - name: POSTGRES_DB
          valueFrom:
            secretKeyRef:
              name: database-conn-mm8ck2296m
              key: POSTGRES_DB
        - name: POSTGRES_USER
          valueFrom:
            secretKeyRef:
              name: database-conn-mm8ck2296m
              key: POSTGRES_USER
        - name: POSTGRES_PASSWORD
          valueFrom:
            secretKeyRef:
              name: database-conn-mm8ck2296m
              key: POSTGRES_PASSWORD
        ports:
        - name: http
          containerPort: 8080
---
apiVersion: v1
kind: Service
metadata:
  name: adminer-svc
spec:
  selector:
    app: adminer
  ports:
    - protocol: TCP
      port: 8080
      targetPort: 8080

Deploy the yaml files with kubectl apply -f *-deploy.yaml, after some seconds type kubectl get pods && kubectl get svc to verify if everything is ok.

Note: Both services will be created as ClusterIP, it means that it will be only accessible internally. If you are using a cloud provider, you can use service type LoadBalancer to get an external ip. Or you can use kubectl port-forward (see here) command to access your service from your computer.

Access application using port-forward:

phpMyadmin:

# This command will map the port 8080 from your localhost to phpMyadmin application:
kubectl port-forward svc/phpmyadmin-svc 8080:80

Adminer

# This command will map the port 8181 from your localhost to Adminer application:
kubectl port-forward svc/adminer-svc 8181:8080

And try to access:

http://localhost:8080 <= phpMyAdmin
http://localhost:8181 <= Adminer

References:

Kubernetes Secrets

Kubernetes Environment variables

Kubernetes port forward


问:
Minecraft PE(json) command
Why is this command not working? How can I fix it? I watched all the videos and none of them could explain.

/give @p gold_ingot 1 0 {"display":[{Name:"help"}]}

答: It was updated and it is now /give @p gold_ingot{"display":[{Name:"texthere"}]}

Title: Minecraft PE(json) command


问:
PHP 2 actions from a single Button
I am wondering how to get 2 actions in PHP from a single Button.
Attached here is an screenshot of the page:

I have the following code:
For the Submit button

```<code><form method='POST'>
   <div class="form-group">
   <input type="text" name="s_amount" style='width:20%;' required>
   <input type="submit"  class="btn btn-primary" name="submit" value="Submit" />
    </div>
</form>
<?php
 $s_amount = $_POST['s_amount'];
 echo $s_amount;
?>

</code>```

AND for the Submit Code button

```<code>    <button id="submitcode"type="button" class="btn btn-default">Submit Code</button>
    ```.../...```

</code>```

When the Submit code is pressed, this executes the following script

```<code><script>
    $(document).ready(function(){
        $("#submitcode").on("click", function(){
            ocpu.seturl("https://public.opencpu.org/ocpu/library/base/R")
            //arguments
            var mysnippet = new ocpu.Snippet("V_CT="+$('[name="CT"]:radio:checked').val()+"\r V_TP="+$('[name="LENGTH"]:radio:checked').val()+$('#input2').val());
            //perform the request
            var req = ocpu.call("identity", {
                "x" : mysnippet
            }, function(session){
                session.getObject(function(data) {
                //data is the object returned by the R function
                $("#output").text(data);
            });
            });
        })
        });
    </script>
</code>```

What I would like to have is a single button, which not only gets the value next to the first submit button (here 12, see attached pciture) but also executes the script.

Many thanks !

答:
Could finally do it very easily using js.

```<code><input type="text" id="VTP" value="0">

</code>```

and get the value in the javascript form

```<code>document.getElementById("VTP").value
</code>```

@ nikhil borikar: Thanks but it did not work

Title: PHP 2 actions from a single Button

Body:
I am wondering how to get 2 actions in PHP from a single Button.
Attached here is an screenshot of the page:

I have the following code:
For the Submit button

<form method='POST'>

   <input type="text" name="s_amount" style='width:20%;' required>
   <input type="submit"  class="btn btn-primary" name="submit" value="Submit" />

</form>
<?php
 $s_amount = $_POST['s_amount'];
 echo $s_amount;
?>

AND for the Submit Code button

    <button id="submitcode"type="button" class="btn btn-default">Submit Code</button>

.../...

When the Submit code is pressed, this executes the following script

What I would like to have is a single button, which not only gets the value next to the first submit button (here 12, see attached pciture) but also executes the script.

Many thanks !

Body:
Could finally do it very easily using js.

<input type="text" id="VTP" value="0">

and get the value in the javascript form

document.getElementById("VTP").value

@ nikhil borikar: Thanks but it did not work


问:
IllegalStateException Subscription to topics, partitions and pattern are mutually exclusive
Need to fetch messages from a Kafka topic, from a particular offset

Stuck cause of IllegalStateException exception at assign()

If I do not use assign() , then the consumer does not perform seek, as that being a Lazy operation

Actual purpose: Need to iterate messages at topic from a pre-decided offset till end. This pre-decided offset is calculated at markOffset()

```<code>static void fetchMessagesFromMarkedOffset() {
    Consumer<Long, String> consumer = ConsumerCreator.createConsumer();
    consumer.assign(set); // <---- Exception at this place
    map.forEach((k,v) -> {
        consumer.seek(k, v-3);
    });
    ConsumerRecords<Long, String> consumerRecords = consumer.poll(100);
    consumerRecords.forEach(record -> {
        System.out.println("Record Key " + record.key());
        System.out.println("Record value " + record.value());
        System.out.println("Record partition " + record.partition());
        System.out.println("Record offset " + record.offset());
    });
    consumer.close();
}
</code>```

Rest of concerned code involved

```<code>public static Set<TopicPartition> set;
public static Map<TopicPartition, Long> map;

static void markOffset() {
    Consumer<Long, String> consumer = ConsumerCreator.createConsumer();
    consumer.poll(100);
    set = consumer.assignment();
    map = consumer.endOffsets(set);
    System.out.println("Topic  Partitions: " + set);
    System.out.println("End Offsets: " + map);
}
</code>```

Consumer Creation

```<code>private Consumer createConsumer(String topicName) {
    final Properties props = new Properties();
    props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
    props.put(ConsumerConfig.GROUP_ID_CONFIG, "capacity-service-application");
    props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, LongDeserializer.class.getName());
    props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
    props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
    props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest");

    final Consumer consumer = new KafkaConsumer(props);
    consumer.subscribe(Collections.singletonList(topicName));
    return consumer;
}
</code>```

Exception

```<code>Exception in thread "main" java.lang.IllegalStateException: Subscription to topics, partitions and pattern are mutually exclusive
at org.apache.kafka.clients.consumer.internals.SubscriptionState.setSubscriptionType(SubscriptionState.java:104)
at org.apache.kafka.clients.consumer.internals.SubscriptionState.assignFromUser(SubscriptionState.java:157)
at org.apache.kafka.clients.consumer.KafkaConsumer.assign(KafkaConsumer.java:1064)
at com.gaurav.kafka.App.fetchMessagesFromMarkedOffset(App.java:44)
at com.gaurav.kafka.App.main(App.java:30)
</code>```

答:
You can't mixed manual and automatic partition assignment.
You should use KafkaConsumer::subscribe or KafkaConsumer::assign but not both.

If after calling KafkaConsumer::subscribe you want to switch to manual approach you should first call KafkaConsumer::unsubscribe.

According to https://kafka.apache.org/10/javadoc/org/apache/kafka/clients/consumer/KafkaConsumer.html

Note that it isn't possible to mix manual partition assignment (i.e. using assign) with dynamic partition assignment through topic subscription (i.e. using subscribe).

Body:
Need to fetch messages from a Kafka topic, from a particular offset

Stuck cause of IllegalStateException exception at assign()

If I do not use assign() , then the consumer does not perform seek, as that being a Lazy operation

Actual purpose: Need to iterate messages at topic from a pre-decided offset till end. This pre-decided offset is calculated at markOffset()

static void fetchMessagesFromMarkedOffset() {
    Consumer<Long, String> consumer = ConsumerCreator.createConsumer();
    consumer.assign(set); // <---- Exception at this place
    map.forEach((k,v) -> {
        consumer.seek(k, v-3);
    });
    ConsumerRecords<Long, String> consumerRecords = consumer.poll(100);
    consumerRecords.forEach(record -> {
        System.out.println("Record Key " + record.key());
        System.out.println("Record value " + record.value());
        System.out.println("Record partition " + record.partition());
        System.out.println("Record offset " + record.offset());
    });
    consumer.close();
}

Rest of concerned code involved

public static Set<TopicPartition> set;
public static Map<TopicPartition, Long> map;

static void markOffset() {
    Consumer<Long, String> consumer = ConsumerCreator.createConsumer();
    consumer.poll(100);
    set = consumer.assignment();
    map = consumer.endOffsets(set);
    System.out.println("Topic  Partitions: " + set);
    System.out.println("End Offsets: " + map);
}

Consumer Creation

private Consumer createConsumer(String topicName) {
    final Properties props = new Properties();
    props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
    props.put(ConsumerConfig.GROUP_ID_CONFIG, "capacity-service-application");
    props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, LongDeserializer.class.getName());
    props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
    props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
    props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest");

    final Consumer consumer = new KafkaConsumer(props);
    consumer.subscribe(Collections.singletonList(topicName));
    return consumer;
}

Exception

Exception in thread "main" java.lang.IllegalStateException: Subscription to topics, partitions and pattern are mutually exclusive
at org.apache.kafka.clients.consumer.internals.SubscriptionState.setSubscriptionType(SubscriptionState.java:104)
at org.apache.kafka.clients.consumer.internals.SubscriptionState.assignFromUser(SubscriptionState.java:157)
at org.apache.kafka.clients.consumer.KafkaConsumer.assign(KafkaConsumer.java:1064)
at com.gaurav.kafka.App.fetchMessagesFromMarkedOffset(App.java:44)
at com.gaurav.kafka.App.main(App.java:30)


问:
the other 2 Pythagorean triplets for a given number
so I was recently trying out a question and wrote some code but I couldn't manage to pass more than 3 test cases out of 5.
the ques is: Given a number N (denoting one of the legs of the triangle), Print its Pythagoras pair in increasing order if they exist. Otherwise, print "-1".

Input Format
A single integer N

Constraints
N <= 10^9

Output Format
Two numbers X and Y denoting the rest of the numbers of the Pythagorean triplet in increasing order.

Sample Input
3
Sample Output
4 5

My Solution:

```<code>   #include<iostream>
    #include<cmath>
    using namespace std;
    int main() {
        int n;
        cin>>n;
        if(n>=0 && n<=2){
            cout<<"-1"<<endl;
            }
        else if (n%2==0){
            cout<<pow((n/2),2)-1<<" "<<pow((n/2),2)+1<<endl;
        }
        else if (n%2==1){
            cout<< 2*((n-1)/2)*((n+1)/2) <<" "<<pow((n+1)/2,2) + pow((n-1)/2,2)<<endl;
        }

        else{
            cout<<"-1"<<endl;
        }
        return 0;
    }
</code>```

can someone suggest what am i missing in this ?

答:
There are some issues you could address.

The chained ifs should be modified (as noted in the comments, the last cout<<"-1"<<endl; is never reached) and could be simplified (if a number is not even, it's odd).

The code reads int values, but the constraints state that the number could be as big as 109. A long int is guaranteed to be able to store such value.

To square the values, a call to std::pow(..., 2); is used. Since C++11, if any argument has integral type, it is cast to double and the return value is also of type double. This may introduce rounding errors that an integral calculation (with an integral type having a big enough size) wouldn't have. Note that, given the constraints, (0.5 * 109)2 = 2.5 * 1017 which is bigger than 253 + 1 (~9 * 1015), the first integer number not exactly representable by an IEE 754 double.

The posted algorithm finds a triple, but a number may appear in many of them. E.g. given 20 as input, the posted code outputs

99 101

Other possible triples beeing (20, 21, 29) or (20, 15, 25).

That said, a possible implementation could be the following

```<code>#include <iostream>

long long int square(long int x)
{
    return static_cast<long long int>(x) * x;
}

int main()
{
    long int n;
    while (std::cin >> n) {
        if( n <= 2 ) {
            std::cout << "-1\n";
        }
        else {
            if ( n % 2 == 0 ) {
                long long int q = square(n / 2);
                std::cout << (q - 1) << " " << (q + 1) << '\n';
            }
            else {
                long long int q = square(n);
                std::cout << (q - 1)/2 << " " << (q + 1)/2 << '\n';
            }
        }
    }
}
</code>```

Body:
so I was recently trying out a question and wrote some code but I couldn't manage to pass more than 3 test cases out of 5.
the ques is: Given a number N (denoting one of the legs of the triangle), Print its Pythagoras pair in increasing order if they exist. Otherwise, print "-1".

Input Format
A single integer N

Constraints
N <= 10^9

Output Format
Two numbers X and Y denoting the rest of the numbers of the Pythagorean triplet in increasing order.

Sample Input
3
Sample Output
4 5

My Solution:

   #include<iostream>
    #include<cmath>
    using namespace std;
    int main() {
        int n;
        cin>>n;
        if(n>=0 && n<=2){
            cout<<"-1"<<endl;
            }
        else if (n%2==0){
            cout<<pow((n/2),2)-1<<" "<<pow((n/2),2)+1<<endl;
        }
        else if (n%2==1){
            cout<< 2*((n-1)/2)*((n+1)/2) <<" "<<pow((n+1)/2,2) + pow((n-1)/2,2)<<endl;
        }

        else{
            cout<<"-1"<<endl;
        }
        return 0;
    }

can someone suggest what am i missing in this ?

Body:
There are some issues you could address.

The chained ifs should be modified (as noted in the comments, the last cout<<"-1"<<endl; is never reached) and could be simplified (if a number is not even, it's odd).

The code reads int values, but the constraints state that the number could be as big as 109. A long int is guaranteed to be able to store such value.

To square the values, a call to std::pow(..., 2); is used. Since C++11, if any argument has integral type, it is cast to double and the return value is also of type double. This may introduce rounding errors that an integral calculation (with an integral type having a big enough size) wouldn't have. Note that, given the constraints, (0.5 * 109)2 = 2.5 * 1017 which is bigger than 253 + 1 (~9 * 1015), the first integer number not exactly representable by an IEE 754 double.

The posted algorithm finds a triple, but a number may appear in many of them. E.g. given 20 as input, the posted code outputs

99 101

Other possible triples beeing (20, 21, 29) or (20, 15, 25).

That said, a possible implementation could be the following

#include <iostream>

long long int square(long int x)
{
    return static_cast<long long int>(x) * x;
}

int main()
{
    long int n;
    while (std::cin >> n) {
        if( n <= 2 ) {
            std::cout << "-1\n";
        }
        else {
            if ( n % 2 == 0 ) {
                long long int q = square(n / 2);
                std::cout << (q - 1) << " " << (q + 1) << '\n';
            }
            else {
                long long int q = square(n);
                std::cout << (q - 1)/2 << " " << (q + 1)/2 << '\n';
            }
        }
    }
}


问:
Connection of PostgreSQL database with corda
How to connect PostgreSQL database using pg admin to corda instead of H2 database ?

What are the changes to be done in node.conf file before the nodes are up ?

答:
As mentioned in the comments, all you need is adding the followings node.conf file after you have generated your node.

```<code>dataSourceProperties = {
    dataSourceClassName = "org.postgresql.ds.PGSimpleDataSource"
    dataSource.url = "jdbc:postgresql://[HOST]:[PORT]/postgres"
    dataSource.user = [USER]
    dataSource.password = [PASSWORD]
}

database = {
    transactionIsolationLevel = READ_COMMITTED
}
</code>```

And please remember to wrap all the string values with double quotes (eg. "Username", "Password")

Body:
As mentioned in the comments, all you need is adding the followings node.conf file after you have generated your node.

dataSourceProperties = {
    dataSourceClassName = "org.postgresql.ds.PGSimpleDataSource"
    dataSource.url = "jdbc:postgresql://[HOST]:[PORT]/postgres"
    dataSource.user = [USER]
    dataSource.password = [PASSWORD]
}

database = {
    transactionIsolationLevel = READ_COMMITTED
}

And please remember to wrap all the string values with double quotes (eg. "Username", "Password")


问:
llength not returning correct list size
I have a list which has the elements below.

```<code>test = {a[1] b[60] c[25] c[36]}
</code>```

I am checking the length of test as below:

```<code>set result [llength ($test)]
</code>```

This is giving me the error below:

```<code>list element in braces followed by ")" instead of space
</code>```

What could be the issue?

Thanks in advance.

答:
You might need to review the basics of Tcl syntax

Don't put parenthesis around the argument to llength.

```<code>set x {test = {a[1] b[60] c[25] c[36]}}
set result [llength $x]
</code>```

In future questions, it is better to post an entire program that can be
executed so that your error can be reproduced easily.

Title: llength not returning correct list size

Body:
I have a list which has the elements below.

test = {a[1] b[60] c[25] c[36]}

I am checking the length of test as below:

set result [llength ($test)]

This is giving me the error below:

list element in braces followed by ")" instead of space

What could be the issue?

Thanks in advance.

Body:
You might need to review the basics of Tcl syntax

Don't put parenthesis around the argument to llength.

set x {test = {a[1] b[60] c[25] c[36]}}
set result [llength $x]

In future questions, it is better to post an entire program that can be
executed so that your error can be reproduced easily.


问:
How to achieve this when I hover an flex item?
I have searched all over stack overflow but I am unable to find any clue and I am struck here. I used flex container and child items in my code to some extent but I couldn't move beyond that. Thing is when we hover a child item, a new child item need to be created as shown in the expected result. Should we need to use pseudo element or any other flex properties to achieve this. Thanks much in advance.

My code:

https://jsfiddle.net/k2qr398u/1/

My result

https://imgur.com/kRHNHuu

Expected result:

https://imgur.com/2B6CkYF

/**CSS**/

body {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: sans-serif;
  background-color: #400017;
}

.img-css {
  width: 50px;
  height: 50px;
}

.main-heading {
  display: block;
  text-align: center;
  color: #fc065d;
  margin-bottom: 70px;
}

.img-js {
  width: 50px;
  height: 50px;
}

.container {
  display: flex;
  justify-content: space-around;
  align-items: center;
  flex-wrap: wrap;
  border: 3px solid #360310;
  max-width: 610px;
  height: 310px;
  text-align: center;
  margin: 0 auto;
  flex-direction: row;
  /* transform: translate(-50%,-50%); */
}

.col {
  width: 130px;
  height: 100px;
  margin: 0 auto;
  border: 3px solid #5e0a1f;
  padding-top: 44px;
  padding-left: 26px;
  padding-right: 26px;
  color: #fff;
  background-color: #010001;
  border-radius: 30px;
  z-index: 20;
  /* position: relative; */
}

.col p {
  font-size: 16px;
  font-weight: bold;
}

.col-2 p {
  position: relative;
  top: 55px;
  text-align: center;
  font-weight: bold;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!--**HTML**-->

<body>

  <div class="container">
    <div class="col col-1">
      <img src="images/css.svg" alt="CSS logo" class="img-css">
      <br>
      <p>I am</p>
    </div>

    <div class="col col-2">

      <p class="my-name">Sri</p>

    </div>

    <div class="col col-3">
      <img src="images/javascript.svg" alt="JS logo" class="img-js">
      <p>Developer
      </p>
    </div>

  </div>
</body></code>```

P.S: Sorry if this question sounds very silly or dumb, I am a beginner trying to learn web dev skillsets.

答:
The idea is:

Overlay some content over main content.

On hover reveal it :)

.card {
  width: 150px;
  height: 80px;
  border: 1px solid #999;
  background: #ccc;
  border-radius: 8px;
  position: relative;
  margin: 20% auto;
}

.card:hover > .o-top {
  top: -80px;
  background: #f00;
}

.card:hover > .o-bottom {
  bottom: -80px;
}

.o-top {
  top: 0;
  transition: top 1.5s, background 2s;
}

.o-bottom {
  bottom: 0;
  transition: bottom 1.5s, background 2s;
}

.card-overlay {
  position: absolute;
  height: 100%;
  width: 100%;
  background: #333;
  pointer-events: none;
  color: #fff;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="card">
  <div class="card-overlay o-top">TOP OVERLAY</div>
  <div class="card-overlay o-bottom">BOTTOM OVERLAY</div>
  <H3>INTERNAL CONTENT</H3>
</div></code>```

Body:
I have searched all over stack overflow but I am unable to find any clue and I am struck here. I used flex container and child items in my code to some extent but I couldn't move beyond that. Thing is when we hover a child item, a new child item need to be created as shown in the expected result. Should we need to use pseudo element or any other flex properties to achieve this. Thanks much in advance.

My code:

https://jsfiddle.net/k2qr398u/1/

My result

https://imgur.com/kRHNHuu

Expected result:

https://imgur.com/2B6CkYF

/**CSS**/

body {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: sans-serif;
  background-color: #400017;
}

.img-css {
  width: 50px;
  height: 50px;
}

.main-heading {
  display: block;
  text-align: center;
  color: #fc065d;
  margin-bottom: 70px;
}

.img-js {
  width: 50px;
  height: 50px;
}

.container {
  display: flex;
  justify-content: space-around;
  align-items: center;
  flex-wrap: wrap;
  border: 3px solid #360310;
  max-width: 610px;
  height: 310px;
  text-align: center;
  margin: 0 auto;
  flex-direction: row;
  /* transform: translate(-50%,-50%); */
}

.col {
  width: 130px;
  height: 100px;
  margin: 0 auto;
  border: 3px solid #5e0a1f;
  padding-top: 44px;
  padding-left: 26px;
  padding-right: 26px;
  color: #fff;
  background-color: #010001;
  border-radius: 30px;
  z-index: 20;
  /* position: relative; */
}

.col p {
  font-size: 16px;
  font-weight: bold;
}

.col-2 p {
  position: relative;
  top: 55px;
  text-align: center;
  font-weight: bold;
}

I am

Sri

Developer

P.S: Sorry if this question sounds very silly or dumb, I am a beginner trying to learn web dev skillsets.

Body:
The idea is:

Overlay some content over main content.

On hover reveal it :)

.card {
  width: 150px;
  height: 80px;
  border: 1px solid #999;
  background: #ccc;
  border-radius: 8px;
  position: relative;
  margin: 20% auto;
}

.card:hover > .o-top {
  top: -80px;
  background: #f00;
}

.card:hover > .o-bottom {
  bottom: -80px;
}

.o-top {
  top: 0;
  transition: top 1.5s, background 2s;
}

.o-bottom {
  bottom: 0;
  transition: bottom 1.5s, background 2s;
}

.card-overlay {
  position: absolute;
  height: 100%;
  width: 100%;
  background: #333;
  pointer-events: none;
  color: #fff;
}

<div class="card">
  <div class="card-overlay o-top">TOP OVERLAY</div>
  <div class="card-overlay o-bottom">BOTTOM OVERLAY</div>
  <H3>INTERNAL CONTENT</H3>
</div>


问:
How to run post build commands in meson?
How can I do in meson to run a command after building a target?
Eg. I have an executable:

```<code>executable('target.elf', 'source1.c', 'source2.c')
</code>```

And after target.elf built I want to execute a command (eg. chmod -x target.elf) on it.

I tried custom_target(), but that requires an output. I don't have new output, I just have target.elf. I tried run_command() but I didn't know how to execute it after the building.

答:
executable now has an argument install_mode (added 0.47.0) to specify the file mode in symbolic format and optionally the owner/uid and group/gid for the installed files.

I just noticed that yasushi-shoji has provided this answer already.

Body:
How can I do in meson to run a command after building a target?
Eg. I have an executable:

executable('target.elf', 'source1.c', 'source2.c')

And after target.elf built I want to execute a command (eg. chmod -x target.elf) on it.

I tried custom_target(), but that requires an output. I don't have new output, I just have target.elf. I tried run_command() but I didn't know how to execute it after the building.


问:
How to query object with contains specific key in array in Graphql
I have object to query:

```<code>query demo {
   demo {
     name # string
     words # array of strings
   }
}
</code>```

I am sending this query to API, property words is array of strings.

I would like to query all object which contains hello in words (array of strings) property.

It is possible on client side using for example @include ?

And how?

答:
The @skip and @include directives are used to explicitly skip or include a particular field based on the provided if argument. They are normally used in conjunction with variables, so that the same document can be used to effectively generate queries with different selection sets (sets of fields) based on the provided variable.

For example, you can write a single query like this

```<code>query demo($includeName: Boolean!) {
   demo {
     name @include(if: $includeName)
     words
   }
}
</code>```

and just pass in a different value for includeName instead of writing two separate queries:

```<code>query demoWithName {
   demo {
     name
     words
   }
}

query demoWithoutName {
   demo {
     words
   }
}
</code>```

GraphQL provides built-in mechanism for specifying which fields to return like fragments and the @skip and @include directives. It does not, however, have any built-in mechanism for filtering (or, for that matter, sorting, pagination, etc.). The server has to implement a way to filter fields by adding the appropriate arguments to fields and changing the field resolution logic to account for the values of those arguments.

Body:
I have object to query:

query demo {
   demo {
     name # string
     words # array of strings
   }
}

I am sending this query to API, property words is array of strings.

I would like to query all object which contains hello in words (array of strings) property.

It is possible on client side using for example @include ?

And how?

Body:
The @skip and @include directives are used to explicitly skip or include a particular field based on the provided if argument. They are normally used in conjunction with variables, so that the same document can be used to effectively generate queries with different selection sets (sets of fields) based on the provided variable.

For example, you can write a single query like this

query demo($includeName: Boolean!) {
   demo {
     name @include(if: $includeName)
     words
   }
}

and just pass in a different value for includeName instead of writing two separate queries:

query demoWithName {
   demo {
     name
     words
   }
}

query demoWithoutName {
   demo {
     words
   }
}

GraphQL provides built-in mechanism for specifying which fields to return like fragments and the @skip and @include directives. It does not, however, have any built-in mechanism for filtering (or, for that matter, sorting, pagination, etc.). The server has to implement a way to filter fields by adding the appropriate arguments to fields and changing the field resolution logic to account for the values of those arguments.


问:
Trying to get to the popup window (sign up) form after clicking on 'sign up' button using cypress
I am navigating to this website https://www.twitch.tv/ and to register a new user.

I am performing those steps:

navigating to the page.

clicking on sign up button

moving to popup and clicking on log in

then a sign up pop up window comes up.

I am trying to get this window but my application does not recognize the page and I am getting an error. please mind the image attached:

this is my code:

```<code>describe('RegisterTwitchTv', function() {
  it('Register New User', function() {
    cy.visit('')
    cy.title().should('eq', 'Twitch')
    cy.get('button[data-a-target="signup-button"]').click()
    // cy.on('window:confirm', ($alertElement) => {
    // expect($alertElement).to.equal('Log in')
    // }).click
    cy.contains('Log in').click()
    cy.window().then((win) => {
      cy.get('button[class~="tw-pd-x-1"]').click()
    })
  })
})
</code>```

but my code does not recognize the new window which is the one I want to handle.

答:
Unfortunately accessing new windows via Cypress is not possible in its current version.

I would be a good practice to test this functionality using two isolated tests:

```<code>describe('RegisterTwitchTv', () => {
    // Check the popup is opened
    it('Register New User popup is opened', () => {
        cy.visit('', {
            onBeforeLoad(win) {
                cy.stub(win, 'open');
            }
        });
        cy.title().should('eq', 'Twitch')
        cy.get('button[data-a-target="signup-button"]').click();
        cy.contains('Log in').click();
        cy.window()
            .its('open')
            .should('be.called');
     });

     // Check the login works
     it('Register New User2 login', () => {
         cy.visit('/login?popup=true');
         cy.get('button[class~="tw-pd-x-1"]').click()
         cy.get('#signup-username').type('test@test.com');
         ...
         ...
     });
});
</code>```

Body:
I am navigating to this website https://www.twitch.tv/ and to register a new user.

I am performing those steps:

navigating to the page.

clicking on sign up button

moving to popup and clicking on log in

then a sign up pop up window comes up.

I am trying to get this window but my application does not recognize the page and I am getting an error. please mind the image attached:

this is my code:

describe('RegisterTwitchTv', function() {
  it('Register New User', function() {
    cy.visit('')
    cy.title().should('eq', 'Twitch')
    cy.get('button[data-a-target="signup-button"]').click()
    // cy.on('window:confirm', ($alertElement) => {
    // expect($alertElement).to.equal('Log in')
    // }).click
    cy.contains('Log in').click()
    cy.window().then((win) => {
      cy.get('button[class~="tw-pd-x-1"]').click()
    })
  })
})

but my code does not recognize the new window which is the one I want to handle.

Body:
Unfortunately accessing new windows via Cypress is not possible in its current version.

I would be a good practice to test this functionality using two isolated tests:

describe('RegisterTwitchTv', () => {
    // Check the popup is opened
    it('Register New User popup is opened', () => {
        cy.visit('', {
            onBeforeLoad(win) {
                cy.stub(win, 'open');
            }
        });
        cy.title().should('eq', 'Twitch')
        cy.get('button[data-a-target="signup-button"]').click();
        cy.contains('Log in').click();
        cy.window()
            .its('open')
            .should('be.called');
     });

     // Check the login works
     it('Register New User2 login', () => {
         cy.visit('/login?popup=true');
         cy.get('button[class~="tw-pd-x-1"]').click()
         cy.get('#signup-username').type('test@test.com');
         ...
         ...
     });
});


问:
How create one query?
One author has many books. There are many authors with books in the database.
It is required to get the latest books of authors. In one query.</p>

```<code>class Autor(models.Model):
    name = models.Charfield()

class Book(models.Model):
    name = models.Charfield()
    author = models.ForegnKey("Autors", models.CASCADE)
    created_at = models.DatetimeField(auto_now_add=True)

# its a many queries
last_books = []
for author in Autor.objects.all():
    last_book = Book.object.filter(autor=autor).latest("created_at")
    last_books.append(last_book)
# need one query
</code>```

答:
You can simply use Subquery:

```<code>from django.db.models import Subquery, OuterRef

books = Book.objects.filter(author=OuterRef('pk'))
authors = Author.objects.annotate(book=Subquery(books.order_by('-created').values('name')[:1]))
</code>```

Title: How create one query?

Body:
One author has many books. There are many authors with books in the database.
It is required to get the latest books of authors. In one query.

class Autor(models.Model):
    name = models.Charfield()

class Book(models.Model):
    name = models.Charfield()
    author = models.ForegnKey("Autors", models.CASCADE)
    created_at = models.DatetimeField(auto_now_add=True)

# its a many queries
last_books = []
for author in Autor.objects.all():
    last_book = Book.object.filter(autor=autor).latest("created_at")
    last_books.append(last_book)
# need one query

Body:
You can simply use Subquery:

from django.db.models import Subquery, OuterRef

books = Book.objects.filter(author=OuterRef('pk'))
authors = Author.objects.annotate(book=Subquery(books.order_by('-created').values('name')[:1]))


问:
Xamarin Android Native bindings Java.Lang.NoClassDefFoundError: 'Failed resolution of: [Lkotlin/reflect/KProperty;'
I'm binding Stripe's android library in Xamarin.Android.
I succeeded in creating the binding project and building it finally after a lot of error resolutions.
Now, when I want to use the library I finally built in my project, I get this error without any additional information:

Java.Lang.NoClassDefFoundError: 'Failed resolution of: [Lkotlin/reflect/KProperty;'

I added the .aar library in my android project and set the build property to Androidaarlibrary, and referenced the binding project directly from the .dll created, but nothing worked. I tried everything I could find but nothing worked.

I have added the dependencies found in the kotlin library, as you can see below:

Here is what I added as dependencies in the xamarin binding project:

I really don't know what else to try, can someone help please ?

答:
if you bind .aar or .jar file contain kotlin source code, you need install Xamarin.Kotlin.StdLib on your xamarin project via nuget, plz install this Link on your project and then build your project, maybe this way work for you.

even you can send your .aar file to my email address, and i can bind for you, or test .dll file on my project.


问:
No function is getting called inside firebase get function
I am trying to write login code, but this firebase get function is refraining me to do so. I am unable to call any function (except alert), within this get function. Navigating to another component also does not work here. I know I have to use async/await keywords but I dont know how to. Can someone please help me with this?
Pasting the code below.</p>

```<code>navigate() {
    alert("Aya");
}
 login() {
    const { uname } = this.state;
    const { password } = this.state;
    var userid = "";
    var data;
    if (uname && password) {
        firebase
            .auth()
            .signInWithEmailAndPassword(uname, password)
            .then(async user => {
                userid = await firebase.auth().currentUser.uid;
               await db.collection("Users").doc(userid)
                    .get()
                    .then(function (doc) {
                        if (doc.exists) {
                            data = doc.data();
                            alert(JSON.stringify(data.role));
                            if (data.role === "Company Admin") {
                                logged = true;
                                alert("Yahoo");
                                this.navigate();
                            }
                            else {
                                logged = false;
                            }
                        } else {
                            // doc.data() will be undefined in this case
                            console.log("No such document!");
                        }
                    }).catch(function (error) {
                        console.log("Error getting document:", error);
                    });
             })
            .catch(error => {
                alert(error);
                this.setState({ error });
            });
        if (logged) {
            alert(logged);
        }
        else {
            alert("Nope");
        }
    }
    else {
        alert("Enter all fields data");
    }
}
</code>```

答:
Don't use normal function, you are going to lose the context of this. The this in the callback function is not pointing to your class. So this.navigate() line of code won't work

.then(function (doc) {
```

<p>As a solution, <strong>Use arrow function</strong>. </p>

<pre class="lang-js prettyprint-override"><code>...
.then((doc) => {
...
</code>```

Body:
I am trying to write login code, but this firebase get function is refraining me to do so. I am unable to call any function (except alert), within this get function. Navigating to another component also does not work here. I know I have to use async/await keywords but I dont know how to. Can someone please help me with this?
Pasting the code below.

navigate() {
    alert("Aya");
}
 login() {
    const { uname } = this.state;
    const { password } = this.state;
    var userid = "";
    var data;
    if (uname && password) {
        firebase
            .auth()
            .signInWithEmailAndPassword(uname, password)
            .then(async user => {
                userid = await firebase.auth().currentUser.uid;
               await db.collection("Users").doc(userid)
                    .get()
                    .then(function (doc) {
                        if (doc.exists) {
                            data = doc.data();
                            alert(JSON.stringify(data.role));
                            if (data.role === "Company Admin") {
                                logged = true;
                                alert("Yahoo");
                                this.navigate();
                            }
                            else {
                                logged = false;
                            }
                        } else {
                            // doc.data() will be undefined in this case
                            console.log("No such document!");
                        }
                    }).catch(function (error) {
                        console.log("Error getting document:", error);
                    });
             })
            .catch(error => {
                alert(error);
                this.setState({ error });
            });
        if (logged) {
            alert(logged);
        }
        else {
            alert("Nope");
        }
    }
    else {
        alert("Enter all fields data");
    }
}

Body:
Don't use normal function, you are going to lose the context of this. The this in the callback function is not pointing to your class. So this.navigate() line of code won't work

.then(function (doc) {

As a solution, Use arrow function.

...
.then((doc) => {
...


问:
How to change plotting order with multiple geoms and a factor in ggplot2
I'm trying to make a plot with a line and two ribbons for each of three factor levels (factor named block). This is my call to ggplot2:

```<code>ggplot(df, aes(x = x, y = y, fill = block, color = block)) +
  geom_ribbon(aes(ymin = llb, ymax = uub), alpha = .1, color = NA) +
  geom_ribbon(aes(ymin = lb, ymax = ub), alpha = .5, color = NA) +
  geom_line(size = 2)
</code>```

This is what I get:
graph
a better example added in later edit

As you can see in the picture, this is the order of plotting:

Light red ribbon

Light blue ribbon

Light green ribbon

Dark red ribbon

Dark blue ribbon

Dark green ribbon

Red line

Blue line

Green line

This is ugly. I want to plot the line and two ribbons for the first factor level first, then all of those for the second level, and then the third. Or, more explicitly, plot in this order:

Light red ribbon

Dark red ribbon

Red line

Light blue ribbon

Blue line

Dark blue ribbon

Light green ribbon

Dark green ribbon

Green line

Any ideas on doing so without subsetting the data by factor and manually calling the geoms three times? Perhaps an easy way to group three geoms into a new geom?

Thanks!

答:
When the fill color is determined automatically, it is assigned based on the level of the factor.

Consider a density plot of the following sample data:

```<code>set.seed(3)
data <- data.frame(factor = rep(LETTERS[1:3],each = 50),
                   value = c(rnorm(n = 50, mean = 5, sd = 4),
                             rnorm(n = 50, mean = 10, sd = 4),
                             rnorm(n = 50, mean = 15, sd = 4)))

library(ggplot)
ggplot(data, aes(x = value, fill = factor)) +
  geom_density(color = NA)
</code>```

If we add a call to scale_fill_manual and provide values, we can reverse the order of the colors:

```<code>ggplot(data, aes(x = value, fill = factor)) +
  geom_density(color = NA) +
  scale_fill_manual(values = c("#619CFF","#00BA38","#F8766D"))
</code>```

If we combine this with factor re-ordering, with factor(x, levels = y) we can also change the factor that is plotted on top:

```<code>ggplot(data, aes(x = value, fill = factor(factor, levels = c("C","B","A")))) +
  geom_density(color = NA) + labs(fill = "factor") +
  scale_fill_manual(values = c("#619CFF","#00BA38","#F8766D")) +
  guides(fill = guide_legend(reverse = TRUE))
</code>```

Body:
I'm trying to make a plot with a line and two ribbons for each of three factor levels (factor named block). This is my call to ggplot2:

ggplot(df, aes(x = x, y = y, fill = block, color = block)) +
  geom_ribbon(aes(ymin = llb, ymax = uub), alpha = .1, color = NA) +
  geom_ribbon(aes(ymin = lb, ymax = ub), alpha = .5, color = NA) +
  geom_line(size = 2)

This is what I get:
graph
a better example added in later edit

As you can see in the picture, this is the order of plotting:

Light red ribbon

Light blue ribbon

Light green ribbon

Dark red ribbon

Dark blue ribbon

Dark green ribbon

Red line

Blue line

Green line

This is ugly. I want to plot the line and two ribbons for the first factor level first, then all of those for the second level, and then the third. Or, more explicitly, plot in this order:

Light red ribbon

Dark red ribbon

Red line

Light blue ribbon

Blue line

Dark blue ribbon

Light green ribbon

Dark green ribbon

Green line

Any ideas on doing so without subsetting the data by factor and manually calling the geoms three times? Perhaps an easy way to group three geoms into a new geom?

Thanks!

Body:
When the fill color is determined automatically, it is assigned based on the level of the factor.

Consider a density plot of the following sample data:

set.seed(3)
data <- data.frame(factor = rep(LETTERS[1:3],each = 50),
                   value = c(rnorm(n = 50, mean = 5, sd = 4),
                             rnorm(n = 50, mean = 10, sd = 4),
                             rnorm(n = 50, mean = 15, sd = 4)))

library(ggplot)
ggplot(data, aes(x = value, fill = factor)) +
  geom_density(color = NA)

If we add a call to scale_fill_manual and provide values, we can reverse the order of the colors:

ggplot(data, aes(x = value, fill = factor)) +
  geom_density(color = NA) +
  scale_fill_manual(values = c("#619CFF","#00BA38","#F8766D"))

If we combine this with factor re-ordering, with factor(x, levels = y) we can also change the factor that is plotted on top:

ggplot(data, aes(x = value, fill = factor(factor, levels = c("C","B","A")))) +
  geom_density(color = NA) + labs(fill = "factor") +
  scale_fill_manual(values = c("#619CFF","#00BA38","#F8766D")) +
  guides(fill = guide_legend(reverse = TRUE))


问:
Serializable isolation level - does it block read?
I have read that serializable isolation level blocks only: insert, update, delete but NOT read.

I have run in one window:

```<code>SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;

UPDATE [dbo].[Categories]
SET name = 'aaa'
WHERE categoryid = 4;

-- without commit
</code>```

And in the second window:

```<code>SELECT TOP (1000) [CategoryId]
      ,[Name]
  FROM [dbo].[Categories]
</code>```

And the above query is waiting for the end of the first query. So does serialization isolation level block also read?

答: Yes it blocks reads.  Your transaction is not committed, so you can still do a rollback.  That means the data you have updated should not be read by any other process before you commit.</p>

Body:
I have read that serializable isolation level blocks only: insert, update, delete but NOT read.

I have run in one window:

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;

UPDATE [dbo].[Categories]
SET name = 'aaa'
WHERE categoryid = 4;

-- without commit

And in the second window:

SELECT TOP (1000) [CategoryId]
      ,[Name]
  FROM [dbo].[Categories]

And the above query is waiting for the end of the first query. So does serialization isolation level block also read?


问:
Function not call when button click
i have create a UIBUtton

```<code>editButton = [[UIButton alloc]initWithFrame:CGRectMake(width, -4, 30, 30)];
        [editButton setImage:[UIImage imageNamed:@"DeleteButton.jpg"] forState:UIControlStateNormal];
        [editButton addTarget:self action:@selector(deleteObjectViewImage:) forControlEvents:UIControlEventTouchUpInside];
        editButton.hidden = YES;
        [editButton setTag:tag];
        [backView addSubview:editButton];
</code>```

But control not jump to its definition where i check if button give its tag value on click or not.

-

```<code>(void)deleteObjectViewImage
{

    NSInteger index = editButton.tag;
    editButton.hidden = YES;
}
</code>```

Can anyone tell me why it not work please.

答:
Use this line instead of line in your code (colon removed after function name),</p>

```<code> [editButton addTarget:self action:@selector(deleteObjectViewImage) forControlEvents:UIControlEventTouchUpInside];
</code>```

Title: Function not call when button click

Body:
i have create a UIBUtton

editButton = [[UIButton alloc]initWithFrame:CGRectMake(width, -4, 30, 30)];
        [editButton setImage:[UIImage imageNamed:@"DeleteButton.jpg"] forState:UIControlStateNormal];
        [editButton addTarget:self action:@selector(deleteObjectViewImage:) forControlEvents:UIControlEventTouchUpInside];
        editButton.hidden = YES;
        [editButton setTag:tag];
        [backView addSubview:editButton];

But control not jump to its definition where i check if button give its tag value on click or not.

-

(void)deleteObjectViewImage
{

    NSInteger index = editButton.tag;
    editButton.hidden = YES;
}

Can anyone tell me why it not work please.

Body:
Use this line instead of line in your code (colon removed after function name),

 [editButton addTarget:self action:@selector(deleteObjectViewImage) forControlEvents:UIControlEventTouchUpInside];


问:
How to point bookstack (Laravel) application's public folder on a mydomain.com/bookstack
Hi I am trying to host bookstack application which is basically a larvel application on a shared hosting, After uploading database dump from local and uploading all the files to public_html/bookstack folder.

Now I am able to visit the webapp at https://example.com/bookstack/public , but I want to host the site at example.com/bookstack only and don't want the "public" in url.

I have two questions,

1) How to achieve it using .htaccess file?

2) Inside the .env file there is an option

```<code># Application URL
# Remove the hash below and set a URL if using BookStack behind
# a proxy, if using a third-party authentication option.
# This must be the root URL that you want to host BookStack on.
# All URL's in BookStack will be generated using this value.

#APP_URL=https://example.com
</code>```

So if here I put APP_URL as https://example.com/bookstack , and remove the comment,  its first giving "403 Forbidden - You don't have permission to access this resource." error and if I visit to https://example.com/bookstack/public it works fine.

Update : So I found this subdirectory setup page in bookstack documentation but it only describe how to setup if I have access of apache, which is not possible in case of shared hosting

答:
Move the .htaccess file in /public to root.

Rename server.php file in root to index.php.

Body:
Hi I am trying to host bookstack application which is basically a larvel application on a shared hosting, After uploading database dump from local and uploading all the files to public_html/bookstack folder.

Now I am able to visit the webapp at https://example.com/bookstack/public , but I want to host the site at example.com/bookstack only and don't want the "public" in url.

I have two questions,

1) How to achieve it using .htaccess file?

2) Inside the .env file there is an option

# Application URL
# Remove the hash below and set a URL if using BookStack behind
# a proxy, if using a third-party authentication option.
# This must be the root URL that you want to host BookStack on.
# All URL's in BookStack will be generated using this value.

#APP_URL=https://example.com

So if here I put APP_URL as https://example.com/bookstack , and remove the comment,  its first giving "403 Forbidden - You don't have permission to access this resource." error and if I visit to https://example.com/bookstack/public it works fine.

Update : So I found this subdirectory setup page in bookstack documentation but it only describe how to setup if I have access of apache, which is not possible in case of shared hosting


问:
What is the difference between "long", "long long", "long int", and "long long int" in C++?
I am transitioning from Java to C++ and have some questions about the long data type. In Java, to hold an integer greater than 232, you would simply write long x;. However, in C++, it seems that long is both a data type and a modifier.

There seems to be several ways to use long:

```<code>long x;
long long x;
long int x;
long long int x;
</code>```

Also, it seems there are things such as:

```<code>long double x;
</code>```

and so on.

What is the difference between all of these various data types, and do they all have the same purpose?

答:
While in Java a long is always 64 bits, in C++ this depends on computer architecture and operating system. For example, a long is 64 bits on Linux and 32 bits on Windows (this was done to keep backwards-compatability, allowing 32-bit programs to compile on 64-bit Windows without any changes). long int is a synonym for long.

Later on, long long was introduced to mean "long (64 bits) on Windows for real this time". long long int is a synonym for this.

It is considered good C++ style to avoid short, int, long etc. and instead use:

```<code>std::int8_t   # exactly  8 bits
std::int16_t  # exactly 16 bits
std::int32_t  # exactly 32 bits
std::int64_t  # exactly 64 bits

std::size_t   # can hold all possible object sizes, used for indexing
</code>```

You can use these int*_t types by including the <cstdint> header. size_t is in <stdlib.h>.

Body:
I am transitioning from Java to C++ and have some questions about the long data type. In Java, to hold an integer greater than 232, you would simply write long x;. However, in C++, it seems that long is both a data type and a modifier.

There seems to be several ways to use long:

long x;
long long x;
long int x;
long long int x;

Also, it seems there are things such as:

long double x;

and so on.

What is the difference between all of these various data types, and do they all have the same purpose?

Body:
While in Java a long is always 64 bits, in C++ this depends on computer architecture and operating system. For example, a long is 64 bits on Linux and 32 bits on Windows (this was done to keep backwards-compatability, allowing 32-bit programs to compile on 64-bit Windows without any changes). long int is a synonym for long.

Later on, long long was introduced to mean "long (64 bits) on Windows for real this time". long long int is a synonym for this.

It is considered good C++ style to avoid short, int, long etc. and instead use:

std::int8_t   # exactly  8 bits
std::int16_t  # exactly 16 bits
std::int32_t  # exactly 32 bits
std::int64_t  # exactly 64 bits

std::size_t   # can hold all possible object sizes, used for indexing

You can use these int*_t types by including the <cstdint> header. size_t is in <stdlib.h>.


问:
missing SIGINT from script?
I am experiencing very strange behaviour when I attempt to send SIGINT from a bash script:

```<code>#!/bin/bash
./executable 6 &
PID=$!
sleep 2
kill -s SIGINT $PID
sleep 2
if wait $PID; then
    echo "FAILURE"
else
    echo "SUCCESS"
fi
</code>```

to an executable compiled from C++ code (g++ source.spp --std=c++11 -o executable) that has no signal handler set:

```<code>#include <iostream>
#include <chrono>
#include <thread>
int main(int argc, char* argv[])
{
    std::this_thread::sleep_for(std::chrono::seconds(std::atoi(argv[1])));
    std::cout << std::endl << "FINISHED" << std::endl;
}
</code>```

The process does not get terminated (I get "FAILURE", then "FINISHED").

This works completely as expected, when I:

send SIGINT from command line to background process

press CTRL-C when process is in foreground

set default signal handler explicitly: signal(SIGINT, SIG_DFL);

I can reproduce it on different distros with different compilers (for example, Ubuntu 20.04 with Bash 5.0.16, GCC 9.3.0). Ideally I would like to understand what is going on, but for a time being I would be happy with a workaround that does not require changes to an executable.

答:
@MohithReddy thank you! Your hint has led me to an answer that explains why it happening (process started in a background from a script has SIG_IGN for SIGINT and SIGQUIT): https://unix.stackexchange.com/questions/478563/sleep-wait-and-ctrlc-propagation/478697#478697

Now I only need to find a workaround that would let me run an executable with SIGINT set to SIG_DFL by default.

Title: missing SIGINT from script?

Body:
I am experiencing very strange behaviour when I attempt to send SIGINT from a bash script:

#!/bin/bash
./executable 6 &
PID=$!
sleep 2
kill -s SIGINT $PID
sleep 2
if wait $PID; then
    echo "FAILURE"
else
    echo "SUCCESS"
fi

to an executable compiled from C++ code (g++ source.spp --std=c++11 -o executable) that has no signal handler set:

#include <iostream>
#include <chrono>
#include <thread>
int main(int argc, char* argv[])
{
    std::this_thread::sleep_for(std::chrono::seconds(std::atoi(argv[1])));
    std::cout << std::endl << "FINISHED" << std::endl;
}

The process does not get terminated (I get "FAILURE", then "FINISHED").

This works completely as expected, when I:

send SIGINT from command line to background process

press CTRL-C when process is in foreground

set default signal handler explicitly: signal(SIGINT, SIG_DFL);

I can reproduce it on different distros with different compilers (for example, Ubuntu 20.04 with Bash 5.0.16, GCC 9.3.0). Ideally I would like to understand what is going on, but for a time being I would be happy with a workaround that does not require changes to an executable.


问:
Passing props from parent to child returns undefined in React
I am learning React and I am building a simple app to experiment with props. I have an input field that searches the database based on the user input and I want to display the results in a different component that loads after the search and is a child to the Search component. When I pass the data from the Search component to the SearchResultsPage Component I get that Cannot read property 'map' of undefined and I don't know why, how can I pass the data properly via props?
Here is my Search component:

```<code>import React, { Component } from "react";
import Spinner from '../../components/Spinner/Spinner.jsx';
import SearchResultsPage from '../SearchResultsPage/SearchResultsPage.jsx';
import { Link } from 'react-router-dom';
import axios from "axios";

class Search extends Component {
    constructor(props) {
        super(props);

        this.state = {
            searchResults: [],
            isLoading: false,
            isSearchStringFound: true
        }
    }

    getSearchQuery = (event) => {
        const SEARCH_RESULTS_ENDPOINT = process.env.REACT_APP_SEARCH_ENDPOINT;

        const searchString = document.querySelector(".search-input").value;

        if (event.keyCode === 13) {
            this.setState({ ...this.state, isLoading: true });
            axios.post(SEARCH_RESULTS_ENDPOINT, {
                searchString: searchString,

            }).then(response => {
                this.setState({ ...this.state, searchResults: response.data });

                if (response.data.length === 0) {
                    this.setState({ ...this.state, isSearchStringFound: false });
                }

                else if (response.data.length > 0) {
                    this.setState({ ...this.state, isSearchStringFound: true });
                }

                this.setState({ ...this.state, isLoading: false });
                window.location.href = "/blog/searchResults"
            });
        }
    };

    render() {
        if (this.state.isLoading) {
            return <Spinner />
        }
        return (

            <div>
                <input
                    type="text"
                    placeholder="Search"
                    className="search-input"
                    onKeyDown={(e) => this.getSearchQuery(e)}

                />
                <div>
                    <SearchResultsPage
                        searchResults={this.state.searchResults}
                        isSearchStringFound={this.state.isSearchStringFound}
                    />
                </div>
            </div>
        );
    }
}

export default Search;
</code>```

and my ResultsPage component:

```<code>import React, { Component } from 'react';
import { Link } from 'react-router-dom';

import Footer from '../Footer/Footer.jsx';
import CustomHeader from '../CustomHeader/CustomHeader.jsx';
let title = 'Blog'

class SearchResultsPage extends Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (
            <div>
                <CustomHeader
                    title={title}
                />
                <div>
                    {this.props.isSearchStringFound === false ? <div className="no-results-found">No results were found</div> : this.props.searchResults.map(result => (
                        <div key={result._id} >
                            <img src={result.picture} alt="avatar" />
                            <div >
                                <div>
                                    <h2>{result.title}</h2>
                                    <p>{result.date}</p>
                                    <p>{result.postContent}</p>
                                    <Link to={`/post/${result._id}`} className="read-more-btn">
                                        <button className="read-more-btn">Read more</button>
                                    </Link>
                                </div>
                            </div>
                        </div>
                    ))}
                </div>
                <Footer />
            </div>
        )
    }
};

export default SearchResultsPage;
</code>```

答:
You aren't updating the state correctly. State updates inside event handlers are batched and are asynchronous which is why the state isn't correctly updated causing the error in child component

Also spreading this.state with this.setState isn't needed and you shouldn't be needed to redirect after axios call as the component is already rendered

You can update your state with a single setState invocation like

```<code> axios.post(SEARCH_RESULTS_ENDPOINT, {
            searchString: searchString,

        }).then(response => {
            const data = response.data;
            let isSearchStringFound;

            if (response.data.length === 0) {
                isSearchStringFound= false;
            }

            else if (response.data.length > 0) {
                isSearchStringFound = true;
            }

            this.setState({ isSearchStringFound, searchResults: data, isLoading: false });
        });
</code>```

Body:
I am learning React and I am building a simple app to experiment with props. I have an input field that searches the database based on the user input and I want to display the results in a different component that loads after the search and is a child to the Search component. When I pass the data from the Search component to the SearchResultsPage Component I get that Cannot read property 'map' of undefined and I don't know why, how can I pass the data properly via props?
Here is my Search component:

import React, { Component } from "react";
import Spinner from '../../components/Spinner/Spinner.jsx';
import SearchResultsPage from '../SearchResultsPage/SearchResultsPage.jsx';
import { Link } from 'react-router-dom';
import axios from "axios";

class Search extends Component {
    constructor(props) {
        super(props);

        this.state = {
            searchResults: [],
            isLoading: false,
            isSearchStringFound: true
        }
    }

    getSearchQuery = (event) => {
        const SEARCH_RESULTS_ENDPOINT = process.env.REACT_APP_SEARCH_ENDPOINT;

        const searchString = document.querySelector(".search-input").value;

        if (event.keyCode === 13) {
            this.setState({ ...this.state, isLoading: true });
            axios.post(SEARCH_RESULTS_ENDPOINT, {
                searchString: searchString,

            }).then(response => {
                this.setState({ ...this.state, searchResults: response.data });

                if (response.data.length === 0) {
                    this.setState({ ...this.state, isSearchStringFound: false });
                }

                else if (response.data.length > 0) {
                    this.setState({ ...this.state, isSearchStringFound: true });
                }

                this.setState({ ...this.state, isLoading: false });
                window.location.href = "/blog/searchResults"
            });
        }
    };

    render() {
        if (this.state.isLoading) {
            return <Spinner />
        }
        return (

                <input
                    type="text"
                    placeholder="Search"
                    className="search-input"
                    onKeyDown={(e) => this.getSearchQuery(e)}

                />

                    <SearchResultsPage
                        searchResults={this.state.searchResults}
                        isSearchStringFound={this.state.isSearchStringFound}
                    />

        );
    }
}

export default Search;

and my ResultsPage component:

import React, { Component } from 'react';
import { Link } from 'react-router-dom';

import Footer from '../Footer/Footer.jsx';
import CustomHeader from '../CustomHeader/CustomHeader.jsx';
let title = 'Blog'

class SearchResultsPage extends Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (

                <CustomHeader
                    title={title}
                />

                    {this.props.isSearchStringFound === false ?
No results were found
 : this.props.searchResults.map(result => (

{result.title}

{result.date}

{result.postContent}

                                    <Link to={`/post/${result._id}`} className="read-more-btn">
                                        <button className="read-more-btn">Read more</button>
                                    </Link>

                    ))}

        )
    }
};

export default SearchResultsPage;

Body:
You aren't updating the state correctly. State updates inside event handlers are batched and are asynchronous which is why the state isn't correctly updated causing the error in child component

Also spreading this.state with this.setState isn't needed and you shouldn't be needed to redirect after axios call as the component is already rendered

You can update your state with a single setState invocation like

 axios.post(SEARCH_RESULTS_ENDPOINT, {
            searchString: searchString,

        }).then(response => {
            const data = response.data;
            let isSearchStringFound;

            if (response.data.length === 0) {
                isSearchStringFound= false;
            }

            else if (response.data.length > 0) {
                isSearchStringFound = true;
            }

            this.setState({ isSearchStringFound, searchResults: data, isLoading: false });
        });


问:
Is it possible to create a Calendar object like Tue Mar 03 13:43:00 (without time zone)?
I have a requirement of sending the calendar object with time zone, like Tue Mar 03 13:43:00. I know that Calendar object always return with Tue Mar 03 13:43:00 CST 2009, so how can I create it without the time zone?

答:
It's not possible to have a Calendar object without a TimeZone. Really, that doesn't make any sense - Calendar seeks to represent "a specific instant in time" - how can you represent an instance in time without knowing what TimeZone the time you are representing is in?

So, there's a few things to consider:

You say you need to pass this Calendar to some other component - does that API care what TimeZone the Calendars are in? Will that API ignore the TimeZone setting, use it to calculate a time difference against it's own local timezone, etc.?

Are you aware that you can easily change the TimeZone of a Calendar instance?

```<code>Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getDefault()); // returns default TimeZone for your system
cal.setTimeZone(TimeZone.getTimeZone("EST")); // Eastern Standard Time
cal.setTimeZone(TimeZone.getTimeZone("Asia/Kolkota"); // UTC+5:30
</code>```

Javadocs on Calendar, TimeZone.

OwnerDisplayName: kamal

LastEditorDisplayName: mmyers

ContentLicense: CC BY-SA 2.5

Body:
It's not possible to have a Calendar object without a TimeZone. Really, that doesn't make any sense - Calendar seeks to represent "a specific instant in time" - how can you represent an instance in time without knowing what TimeZone the time you are representing is in?

So, there's a few things to consider:

You say you need to pass this Calendar to some other component - does that API care what TimeZone the Calendars are in? Will that API ignore the TimeZone setting, use it to calculate a time difference against it's own local timezone, etc.?

Are you aware that you can easily change the TimeZone of a Calendar instance?

Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getDefault()); // returns default TimeZone for your system
cal.setTimeZone(TimeZone.getTimeZone("EST")); // Eastern Standard Time
cal.setTimeZone(TimeZone.getTimeZone("Asia/Kolkota"); // UTC+5:30

Javadocs on Calendar, TimeZone.

OwnerDisplayName: matt b


问:
Compare two strings of ints in java
I have two Strings that contain numbers and I want to see if the second string contains the same numbers as the first String, whether they are in order or not. If it has any number repeating than report false. Is there anyway in java other than using .charAt() because its not working for number after 10? </p>

```<code>String one = "1 2 3 4 5 ";
String two = " 3 2 1 4 5 ";
String three = "3 2 1 4 4 ";
</code>```

答: You could tokenize/split the strings based on the spaces, then loop through the resulting tokens which would be the numbers themselves.</p>

Title: Compare two strings of ints in java

Body:
I have two Strings that contain numbers and I want to see if the second string contains the same numbers as the first String, whether they are in order or not. If it has any number repeating than report false. Is there anyway in java other than using .charAt() because its not working for number after 10?

String one = "1 2 3 4 5 ";
String two = " 3 2 1 4 5 ";
String three = "3 2 1 4 4 ";