问:
java.io.IOException: Unexpected response code for CONNECT: 400
I am using Okhttp client to get the OAuth 2.0 token based on a Rest API.

When I deploy it over Weblogic 12c its showing the error java.io.IOException: Unexpected response code for CONNECT: 400

I have tried to change the implementation and header method methods in different styles might be my request is failing because I am providing wrong credentials but nothing changed.

Can anybody suggest what I am doing wrong in my code?

Client Code

```<code>public String Post (String url, String json) throws IOException {

        Response response = null;
        try {

        logger.info("FMS WEBSERVICE LOG >>> Posting method...");

        RequestBody body = RequestBody.create(JSON, json);

        logger.info("FMS WEBSERVICE LOG >>> body: " + body);

        Request request = new Request.Builder().url(url).post(body).build();

        logger.info("FMS WEBSERVICE LOG >>> request: " + request);
        response = client.newCall(request).execute();

        logger.info("FMS WEBSERVICE LOG >>> returning: " + response.toString());

        }
        catch (Exception e) {
            logger.info("FMS WEBSERVICE LOG >>> exception in WebServiceClient: " + e);
        }

        return response.body().string();

    }

@GET
    @Path("/fundTransfer")
    @Produces(javax.ws.rs.core.MediaType.APPLICATION_JSON)
    public String soapCaller() throws IOException, JSONException  {

        logger.info("FMS WEBSERVICE LOG >>> Inside the client method");

        String json = new StringBuilder()
                .append("{")
                .append("\"grant_type\":\"client_credentials\",")
                .append("\"client_id\":\"0146b9a4-7e99-4c83-8e9e-6049cfec55da\",")
                .append("\"client_secret\":\"nY3oL5xQ3bJ8yT3nC1nV5bY4mY6eW7yP1nY6dS6rQ2nE5iR0rM\",")
                .append("\"scope\":\"ABLApis\"")
                .append("}").toString();

        logger.info("FMS WEBSERVICE LOG >>> JSON >>> " + json.toString());

        String response = Post("https://221.120.211.69:443/abl-api/uat/oauth2/token", json);

        logger.info("FMS WEBSERVICE LOG >>> response >>> " + response);

        return response;

    }
</code>```

I am using postman to hit the GET Request with this URL: http:///FMS_WEB_SERVICES/fmsServices/fundTransfer

答:
CONNECT is the HTTP method OkHttp uses to build an HTTPS connection through a proxy server. It uses either the proxy server configured in your OkHttpClient, or the one the JVM prefers via its ProxySelector feature.

A 400 response from CONNECT implies the proxy doesn't like the CONNECT request. You probably need to disable the proxy altogether (pass Proxy.NO_PROXY to OkHttpClient.Builder) or fix it to accept this call.

Body:
I am using Okhttp client to get the OAuth 2.0 token based on a Rest API.

When I deploy it over Weblogic 12c its showing the error java.io.IOException: Unexpected response code for CONNECT: 400

I have tried to change the implementation and header method methods in different styles might be my request is failing because I am providing wrong credentials but nothing changed.

Can anybody suggest what I am doing wrong in my code?

Client Code

public String Post (String url, String json) throws IOException {

        Response response = null;
        try {

        logger.info("FMS WEBSERVICE LOG >>> Posting method...");

        RequestBody body = RequestBody.create(JSON, json);

        logger.info("FMS WEBSERVICE LOG >>> body: " + body);

        Request request = new Request.Builder().url(url).post(body).build();

        logger.info("FMS WEBSERVICE LOG >>> request: " + request);
        response = client.newCall(request).execute();

        logger.info("FMS WEBSERVICE LOG >>> returning: " + response.toString());

        }
        catch (Exception e) {
            logger.info("FMS WEBSERVICE LOG >>> exception in WebServiceClient: " + e);
        }

        return response.body().string();

    }

@GET
    @Path("/fundTransfer")
    @Produces(javax.ws.rs.core.MediaType.APPLICATION_JSON)
    public String soapCaller() throws IOException, JSONException  {

        logger.info("FMS WEBSERVICE LOG >>> Inside the client method");

        String json = new StringBuilder()
                .append("{")
                .append("\"grant_type\":\"client_credentials\",")
                .append("\"client_id\":\"0146b9a4-7e99-4c83-8e9e-6049cfec55da\",")
                .append("\"client_secret\":\"nY3oL5xQ3bJ8yT3nC1nV5bY4mY6eW7yP1nY6dS6rQ2nE5iR0rM\",")
                .append("\"scope\":\"ABLApis\"")
                .append("}").toString();

        logger.info("FMS WEBSERVICE LOG >>> JSON >>> " + json.toString());

        String response = Post("https://221.120.211.69:443/abl-api/uat/oauth2/token", json);

        logger.info("FMS WEBSERVICE LOG >>> response >>> " + response);

        return response;

    }

I am using postman to hit the GET Request with this URL: http:///FMS_WEB_SERVICES/fmsServices/fundTransfer


来源: stackexchange

问:
Text goes out of screen in recycler view item
I have an item.xml being used in a recycler view, but the text goes out of the screen. I tried to rely on this answer,

You can avoid all of this by giving each textview a width of match_parent and an appropriate layout_weight.

but I find it confusing as I'm not sure where the

```<code>width="0"
</code>```

should be implemented.

My item.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/productLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginBottom="@dimen/product_recycler_view_margin">

    <ImageView
        android:id="@+id/photoIV"
        android:layout_width="@dimen/product_image_size"
        android:layout_height="@dimen/product_image_size"
        android:scaleType="centerCrop"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="@dimen/product_image_size"
        android:orientation="vertical"
        android:gravity="top"
        android:layout_marginStart="@dimen/product_details_margin_left"
        app:layout_constraintStart_toEndOf="@+id/photoIV"
        app:layout_constraintTop_toTopOf="@id/photoIV">

        <TextView
            android:id="@+id/titleTV"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Top"

            android:textStyle="bold"
            android:textSize="@dimen/product_details_title" />

        <TextView
            android:id="@+id/descriptionTV"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/product_details_margin_middle"
            android:text="Bottom"
            android:textSize="@dimen/product_details_description_text_size" />

    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

There is an image and on its right, a title and description. Both the title and description go out of the screen:

My recycler view in my fragment where it's being displayed (if it matters):

```<code><androidx.recyclerview.widget.RecyclerView
    android:id="@+id/productsRV"
    android:layout_marginStart="16dp"
    android:layout_marginEnd="16dp"
    android:layout_marginTop="16dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>
</code>```

答:
Assign End Constraint too to your LinearLayout:

```<code>  <LinearLayout
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginStart="5dp"
    android:gravity="top"
    android:orientation="vertical"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toEndOf="@+id/photoIV"
    app:layout_constraintTop_toTopOf="@id/photoIV">
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have an item.xml being used in a recycler view, but the text goes out of the screen. I tried to rely on this answer,

You can avoid all of this by giving each textview a width of match_parent and an appropriate layout_weight.

but I find it confusing as I'm not sure where the

width="0"

should be implemented.

My item.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/productLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginBottom="@dimen/product_recycler_view_margin">

    <ImageView
        android:id="@+id/photoIV"
        android:layout_width="@dimen/product_image_size"
        android:layout_height="@dimen/product_image_size"
        android:scaleType="centerCrop"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="@dimen/product_image_size"
        android:orientation="vertical"
        android:gravity="top"
        android:layout_marginStart="@dimen/product_details_margin_left"
        app:layout_constraintStart_toEndOf="@+id/photoIV"
        app:layout_constraintTop_toTopOf="@id/photoIV">

        <TextView
            android:id="@+id/titleTV"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Top"

            android:textStyle="bold"
            android:textSize="@dimen/product_details_title" />

        <TextView
            android:id="@+id/descriptionTV"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/product_details_margin_middle"
            android:text="Bottom"
            android:textSize="@dimen/product_details_description_text_size" />

    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

There is an image and on its right, a title and description. Both the title and description go out of the screen:

My recycler view in my fragment where it's being displayed (if it matters):

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/productsRV"
    android:layout_marginStart="16dp"
    android:layout_marginEnd="16dp"
    android:layout_marginTop="16dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

Body:
Assign End Constraint too to your LinearLayout:

  <LinearLayout
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginStart="5dp"
    android:gravity="top"
    android:orientation="vertical"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toEndOf="@+id/photoIV"
    app:layout_constraintTop_toTopOf="@id/photoIV">


问:
declaring a variable blocks my code
is something wrong here?
declaring those variables stops the execution of my code :(

```<code>var color = $('fieldset input[type=checkbox]').data("color");
        if(color === orange){var bgy = '-1'}
        else{var bgy = '-37'};
</code>```

If you need more info please ask me :)

答:
Dude... whats orange in

```<code>if(color === orange){var bgy = '-1'}
</code>```

Use firebug :D

ContentLicense: CC BY-SA 3.0

Title: declaring a variable blocks my code

Body:
is something wrong here?
declaring those variables stops the execution of my code :(

var color = $('fieldset input[type=checkbox]').data("color");
        if(color === orange){var bgy = '-1'}
        else{var bgy = '-37'};

If you need more info please ask me :)

Body:
Dude... whats orange in

if(color === orange){var bgy = '-1'}

Use firebug :D


答:
you can try to change LinearLayout like</p>

```<code><LinearLayout
        android:layout_width="0dp"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_height="@dimen/product_image_size"
        android:orientation="vertical"
        android:gravity="top"
        android:layout_marginStart="@dimen/product_details_margin_left"
        app:layout_constraintStart_toEndOf="@+id/photoIV"
        app:layout_constraintTop_toTopOf="@id/photoIV">
</code>```

Title: Text goes out of screen in recycler view item

Body:
you can try to change LinearLayout like

<LinearLayout
        android:layout_width="0dp"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_height="@dimen/product_image_size"
        android:orientation="vertical"
        android:gravity="top"
        android:layout_marginStart="@dimen/product_details_margin_left"
        app:layout_constraintStart_toEndOf="@+id/photoIV"
        app:layout_constraintTop_toTopOf="@id/photoIV">


问:
Crontab never executes in Windows Subsystem Linux
I set up some cronjobs a while back using crontab -e. My crontab includes the following line:

```<code>* * * * * /usr/bin/touch /home/blah/MADEBYCRON
</code>```

It's been weeks since I did this. I have never seen /home/blah/MADEBYCRON. I set permissions on my home directory so it should be able to create files in this directory, so why does this file never exist?

/var/log/syslog does not exist.

答:
Ensure that the cron service is running. I use WSL with cron every day for my local backups using rsync so this should work.

Use which cron to check its installed, mine says /usr/sbin/cron.

Use crontab -l to list your configured jobs.

Use ps aux | grep cron to look see if cron is running, you should see /usr/sbin/cron if it is.

Use service cron status to check if the service is started.

Use sudo service cron start to start the cron service if it is not running.

Body:
I set up some cronjobs a while back using crontab -e. My crontab includes the following line:

* * * * * /usr/bin/touch /home/blah/MADEBYCRON

It's been weeks since I did this. I have never seen /home/blah/MADEBYCRON. I set permissions on my home directory so it should be able to create files in this directory, so why does this file never exist?

/var/log/syslog does not exist.


问:
DocuSign OrgAdmin API > Unauthorized when updating users
I use Authorization code grant flow

When trying to update user from OrgAdmin API I always get “Unauthorized”:

```<code>{
    "error": "unauthorized",
    "error_description": "Not Authorized",
    "reference_id": "7da40c89-bb98-4eb2-829b-5ef604267175"
}
</code>```

Checked those endpoints:

POST https://api-d.docusign.net/management/v2/organizations/{{organizationId}}/users    (https://developers.docusign.com/orgadmin-api/reference/Users/Users/createUser)

POST https://api-d.docusign.net/management/v2/organizations/{{organizationId}}/accounts/{{accountId}}/users    (https://developers.docusign.com/orgadmin-api/reference/Users/Users/addUsers)

I have already checked:

"user_write" permission is on my list of requested scopes
https://account-d.docusign.com/oauth/auth?response_type=code&scope=user_write user_read&client_id=xxxx-...&state=xxxxxx&redirect_uri=http://localhost:51820

The user that calls the APIs is actually OrgAdmin (checked from the Admin UI)

I am out of ideas. What could be wrong here?

答:
Seems like ambiguous error response.

The problem was in below part of user creation JSON

```<code>"auto_activate_memberships" : "true"
</code>```

When I changed it to "false", I was able to create users normally.

Body:
I use Authorization code grant flow

When trying to update user from OrgAdmin API I always get “Unauthorized”:

{
    "error": "unauthorized",
    "error_description": "Not Authorized",
    "reference_id": "7da40c89-bb98-4eb2-829b-5ef604267175"
}

Checked those endpoints:

POST https://api-d.docusign.net/management/v2/organizations/{{organizationId}}/users    (https://developers.docusign.com/orgadmin-api/reference/Users/Users/createUser)

POST https://api-d.docusign.net/management/v2/organizations/{{organizationId}}/accounts/{{accountId}}/users    (https://developers.docusign.com/orgadmin-api/reference/Users/Users/addUsers)

I have already checked:

"user_write" permission is on my list of requested scopes
https://account-d.docusign.com/oauth/auth?response_type=code&scope=user_write user_read&client_id=xxxx-...&state=xxxxxx&redirect_uri=http://localhost:51820

The user that calls the APIs is actually OrgAdmin (checked from the Admin UI)

I am out of ideas. What could be wrong here?

Body:
Seems like ambiguous error response.

The problem was in below part of user creation JSON

"auto_activate_memberships" : "true"

When I changed it to "false", I was able to create users normally.


问:
CI/CD pipeline with PostgreSQL failed with "Database is uninitialized and superuser password is not specified" error
I'm using Bitbucket pipeline with PosgreSQL for CI/CD. According to this documentation PostgreSQL service has been described in bitbucket-pipelines.yml this way:

```<code>definitions:
  services:
    postgres:
      image: postgres:9.6-alpine
</code>```

It worked just fine until now. But all my latest pipelines failed with following error:

```<code>   Error: Database is uninitialized and superuser password is not specified.
   You must specify POSTGRES_PASSWORD for the superuser. Use
   "-e POSTGRES_PASSWORD=password" to set it in "docker run".

   You may also use POSTGRES_HOST_AUTH_METHOD=trust to allow all connections
   without a password. This is *not* recommended. See PostgreSQL
   documentation about "trust":
   https://www.postgresql.org/docs/current/auth-trust.html
</code>```

How can I fix it? There was no changes in bitbucket-pipelines.yml file which could be the reason of such error..

答:
Looks like the reason is docker image's updates (github issue). Latest versions do not allow to connect to DB without a password from anywhere. So you need to specify username/password:

```<code>definitions:
  services:
    postgres:
      image: postgres:9.6-alpine
      environment:
         POSTGRES_DB: pipelines
         POSTGRES_USER: test_user
         POSTGRES_PASSWORD: test_user_password
</code>```

Or if you still don't want to use password, you can just set POSTGRES_HOST_AUTH_METHOD=trust environment variable:

```<code>definitions:
  services:
    postgres:
      image: postgres:9.6-alpine
      environment:
        POSTGRES_HOST_AUTH_METHOD: trust
</code>```

Body:
I'm using Bitbucket pipeline with PosgreSQL for CI/CD. According to this documentation PostgreSQL service has been described in bitbucket-pipelines.yml this way:

definitions:
  services:
    postgres:
      image: postgres:9.6-alpine

It worked just fine until now. But all my latest pipelines failed with following error:

   Error: Database is uninitialized and superuser password is not specified.
   You must specify POSTGRES_PASSWORD for the superuser. Use
   "-e POSTGRES_PASSWORD=password" to set it in "docker run".

   You may also use POSTGRES_HOST_AUTH_METHOD=trust to allow all connections
   without a password. This is *not* recommended. See PostgreSQL
   documentation about "trust":
   https://www.postgresql.org/docs/current/auth-trust.html

How can I fix it? There was no changes in bitbucket-pipelines.yml file which could be the reason of such error..

Body:
Looks like the reason is docker image's updates (github issue). Latest versions do not allow to connect to DB without a password from anywhere. So you need to specify username/password:

definitions:
  services:
    postgres:
      image: postgres:9.6-alpine
      environment:
         POSTGRES_DB: pipelines
         POSTGRES_USER: test_user
         POSTGRES_PASSWORD: test_user_password

Or if you still don't want to use password, you can just set POSTGRES_HOST_AUTH_METHOD=trust environment variable:

definitions:
  services:
    postgres:
      image: postgres:9.6-alpine
      environment:
        POSTGRES_HOST_AUTH_METHOD: trust


答:
You are set wrap content for the Linearlayout so it's would take content width as width(upto screen width). so you have define fixed width </p>

```<code>android:layout_width="0dp"
app:layout_constraintEnd_toEndOf="parent"
</code>```

Body:
You are set wrap content for the Linearlayout so it's would take content width as width(upto screen width). so you have define fixed width

android:layout_width="0dp"
app:layout_constraintEnd_toEndOf="parent"


问:
How to open overlay dropdown for outside of responsive table?
In my case, I have used bootstrap dropdown multi-select inside td where I have also use table responsive class just because of it the dropdown not showing properly. responsive "overflow: hidden" property is hiding that dropdown. Please check below screenshot.

答:
I talked with bootstrap team and they gave me this solution

Add this property in css: transform: translate3d(0px, 0px, 0px);


问:
How to get current ion-slide in html element id in Ionic?
I am using ion-slide and in slide, I added an HTML video element, I want to get the ID of active ion-slide video element when slide change.

here my ts code:

```<code>@ViewChild(IonSlides, { static: false }) slides: IonSlides;

slideOpts = {
  direction: 'vertical'
};

mainArray = [
  {
    id: 0,
    thumbnailUrl: 'https://i.picsum.photos/id/803/200/300.jpg',
    mp4: 'https://www.w3schools.com/html/mov_bbb.mp4',
    ogg: 'https://www.w3schools.com/html/mov_bbb.ogg'
  },
  {
    id: 1,
    thumbnailUrl: 'https://i.picsum.photos/id/803/200/300.jpg',
    mp4: 'https://www.w3schools.com/html/mov_bbb.mp4',
    ogg: 'https://www.w3schools.com/html/mov_bbb.ogg'
  },
  {
    id: 2,
    thumbnailUrl: 'https://i.picsum.photos/id/803/200/300.jpg',
    mp4: 'https://www.w3schools.com/html/mov_bbb.mp4',
    ogg: 'https://www.w3schools.com/html/mov_bbb.ogg'
  },
  {
    id: 3,
    thumbnailUrl: 'https://i.picsum.photos/id/803/200/300.jpg',
    mp4: 'https://www.w3schools.com/html/mov_bbb.mp4',
    ogg: 'https://www.w3schools.com/html/mov_bbb.ogg'
  }
];

playvideo() {
  let videoPlayer1: HTMLVideoElement = <HTMLVideoElement>document.getElementById(this.mainArray[this.index].id)
  videoPlayer1.pause();
  videoPlayer1.currentTime = 0;
  const playPromise = videoPlayer1.play();
  if (playPromise !== null) {
    playPromise.catch(() => {
      videoPlayer1.play();
      videoPlayer1.autoplay = true;
    })
  }
};

slideDidChange(ev: any) {
  console.log('slideDidChange: ', ev);
};

slideWillChange(ev: any) {
  console.log('slideWillChange: ', ev);
};
</code>```

Here my HTML

<ion-slides #slides [options]="slideOpts" (ionSlideDidChange)="slideDidChange(slides)"
  (ionSlideWillChange)="slideWillChange(slides)">
  <ion-slide *ngFor="let videoUrl of mainArray">
    <video [id]="videoUrl.id" poster='{{videoUrl.thumbnailUrl}}' preload="none" controls>
      <source src="{{videoUrl.mp4}}" type="video/mp4" autostart="false">
      <source src="{{videoUrl.ogg}}" type="video/ogg" autostart="false">
      Your browser does not support HTML5 video.
    </video>
  </ion-slide>
</ion-slides>
```

In this example, I am trying to play video of the active slide by HTML video element id. Please help...

答:
I hope I would follow your meaning, IonSlides provide the method that you can get the currentIndex with your IonSlides instance.

Get the current Index then you could get the current Array that the loop for. So we got a few lines to accomplish your requirement. And with the source code, ionSlideDidChange didn't accept any argument so that you would get null or undefined on your console.

```<code>//mention of args,do not put any , just rid it off.
slideDidChange() {
  let currentIndex = this.slides.getActiveIndex();
  let currentElementId = this.mainArray[currentIndex].id;
  this.playvideo(currentElementId);
};
</code>```

So that if you want to autoplay the video if your client is navigating to other slides. Replace the playvideo function args with the flexible id, it would seem like below code:

```<code>playvideo(videoElementId) {
  let videoPlayer: HTMLMediaElement = < HTMLMediaElement >document.getElementById(this.mainArray[this.index].id)
  //.***
  //. your code;
  //.***
};
</code>```

Finally , there is only HTMLMediaElement has the play and pause.The Promise logical you have to think about it.play method rejection support NotAllowedError and NotSupportedError, so you can take your null condtion off.You can following that simple code about async function:

```<code>async function playVideo(videoElementId: Number) {
  let videoPlayer: HTMLMediaElement = <HTMLMediaElement>document.getElementById(videoElementId);
  videoPlayer.pause();
  try {
    await videoPlayer.play();
  } catch(err) {
    await videoPlayer.play(); // with your logic
    videoPlayer.autoplay = true;
  }
}
</code>```

I hope this info will help you.

Body:
I am using ion-slide and in slide, I added an HTML video element, I want to get the ID of active ion-slide video element when slide change.

here my ts code:

@ViewChild(IonSlides, { static: false }) slides: IonSlides;

slideOpts = {
  direction: 'vertical'
};

mainArray = [
  {
    id: 0,
    thumbnailUrl: 'https://i.picsum.photos/id/803/200/300.jpg',
    mp4: 'https://www.w3schools.com/html/mov_bbb.mp4',
    ogg: 'https://www.w3schools.com/html/mov_bbb.ogg'
  },
  {
    id: 1,
    thumbnailUrl: 'https://i.picsum.photos/id/803/200/300.jpg',
    mp4: 'https://www.w3schools.com/html/mov_bbb.mp4',
    ogg: 'https://www.w3schools.com/html/mov_bbb.ogg'
  },
  {
    id: 2,
    thumbnailUrl: 'https://i.picsum.photos/id/803/200/300.jpg',
    mp4: 'https://www.w3schools.com/html/mov_bbb.mp4',
    ogg: 'https://www.w3schools.com/html/mov_bbb.ogg'
  },
  {
    id: 3,
    thumbnailUrl: 'https://i.picsum.photos/id/803/200/300.jpg',
    mp4: 'https://www.w3schools.com/html/mov_bbb.mp4',
    ogg: 'https://www.w3schools.com/html/mov_bbb.ogg'
  }
];

playvideo() {
  let videoPlayer1: HTMLVideoElement = <HTMLVideoElement>document.getElementById(this.mainArray[this.index].id)
  videoPlayer1.pause();
  videoPlayer1.currentTime = 0;
  const playPromise = videoPlayer1.play();
  if (playPromise !== null) {
    playPromise.catch(() => {
      videoPlayer1.play();
      videoPlayer1.autoplay = true;
    })
  }
};

slideDidChange(ev: any) {
  console.log('slideDidChange: ', ev);
};

slideWillChange(ev: any) {
  console.log('slideWillChange: ', ev);
};

Here my HTML

<ion-slides #slides [options]="slideOpts" (ionSlideDidChange)="slideDidChange(slides)"
  (ionSlideWillChange)="slideWillChange(slides)">
  <ion-slide *ngFor="let videoUrl of mainArray">
    <video [id]="videoUrl.id" poster='{{videoUrl.thumbnailUrl}}' preload="none" controls>
      <source src="{{videoUrl.mp4}}" type="video/mp4" autostart="false">
      <source src="{{videoUrl.ogg}}" type="video/ogg" autostart="false">
      Your browser does not support HTML5 video.
    </video>
  </ion-slide>
</ion-slides>

In this example, I am trying to play video of the active slide by HTML video element id. Please help...

Body:
I hope I would follow your meaning, IonSlides provide the method that you can get the currentIndex with your IonSlides instance.

Get the current Index then you could get the current Array that the loop for. So we got a few lines to accomplish your requirement. And with the source code, ionSlideDidChange didn't accept any argument so that you would get null or undefined on your console.

//mention of args,do not put any , just rid it off.
slideDidChange() {
  let currentIndex = this.slides.getActiveIndex();
  let currentElementId = this.mainArray[currentIndex].id;
  this.playvideo(currentElementId);
};

So that if you want to autoplay the video if your client is navigating to other slides. Replace the playvideo function args with the flexible id, it would seem like below code:

playvideo(videoElementId) {
  let videoPlayer: HTMLMediaElement = < HTMLMediaElement >document.getElementById(this.mainArray[this.index].id)
  //.***
  //. your code;
  //.***
};

Finally , there is only HTMLMediaElement has the play and pause.The Promise logical you have to think about it.play method rejection support NotAllowedError and NotSupportedError, so you can take your null condtion off.You can following that simple code about async function:

async function playVideo(videoElementId: Number) {
  let videoPlayer: HTMLMediaElement = <HTMLMediaElement>document.getElementById(videoElementId);
  videoPlayer.pause();
  try {
    await videoPlayer.play();
  } catch(err) {
    await videoPlayer.play(); // with your logic
    videoPlayer.autoplay = true;
  }
}

I hope this info will help you.


问:
is it bad practice to call another interface method from a interface on a java interface?
For example i have an interface as following:

```<code>interface Test  {
    void a();
    void b();
}

class TestImpl implements Test {
    public void a() {
        // Do something
    }

    public void b() {
        // Do something
        a();
    }
}
</code>```

i think this is bad practice. is it true? or is there any theory on this?

答:
This is not a bad practice.
Look at the below example:

```<code>interface Task {
    boolean preConditionTask();
    void executeTask();
    boolean postConditionTask();
}

public class TaskImpl implements Task {

    boolean preConditionTask() {
        //Some logic.
    }

    boolean postConditionTask() {
        //Some logic.
    }

    void executeTask() {
        if (!preConditionTask()) {
            //Log or throw.
        }

        //Some task logic.

        if (!postConditionTask()) {
            //Log or throw.
        }
    }
}
</code>```

You have a contract that every task must implement.
The contract tell the implementer that every task have pre, post and execute logic.

Body:
For example i have an interface as following:

interface Test  {
    void a();
    void b();
}

class TestImpl implements Test {
    public void a() {
        // Do something
    }

    public void b() {
        // Do something
        a();
    }
}

i think this is bad practice. is it true? or is there any theory on this?

Body:
This is not a bad practice.
Look at the below example:

interface Task {
    boolean preConditionTask();
    void executeTask();
    boolean postConditionTask();
}

public class TaskImpl implements Task {

    boolean preConditionTask() {
        //Some logic.
    }

    boolean postConditionTask() {
        //Some logic.
    }

    void executeTask() {
        if (!preConditionTask()) {
            //Log or throw.
        }

        //Some task logic.

        if (!postConditionTask()) {
            //Log or throw.
        }
    }
}

You have a contract that every task must implement.
The contract tell the implementer that every task have pre, post and execute logic.


问:
How to find the date range between two orders from the Order table with respect to subsequent Customer_Ids?
For eg- lets say we have a customer_id =1 and he has placed 3 orders in 2 years and his

1st Order_date = '1st Jan 2015'

2nd Order_date = '5th June 2015'

3rd Order_date = '2nd Feb 2016'.

This has to be calculated yearly from the date he has placed his first order.

Please let me know how to achieve this scenario in HiveQL.

答:
select ord_rnk_1.customer_id,ord_rnk_1.order_id as 1st_order, ord_rnk_2.order_id as 2nd_order, ord_rnk_1.order_date as 1st_order_date, ord_rnk_2.order_date as 2nd_order_date,
CASE
WHEN nullif(ord_rnk_2.order_id,0)=0 THEN '1st purchase'
WHEN datediff(ord_rnk_2.order_date,ord_rnk_1.order_date) <=365 THEN 'repeat purchase'
ELSE '1st purchase'
end as customer_type
from
              (
                             select customer_id,order_id, order_date from
                             (select  customer_id,order_id, order_date,row_number() over(partition by customer_id order by order_date asc) rank   from
                               (select distinct customer_id, order_id, to_date(order_date,"dd/mm/yyyy") as order_date
                                from table_t1
                                ) abc
                             ) order_rank where order_rank.rank=1
              ) ord_rnk_1
left join
              (
                             select customer_id,order_id, order_date from
                             (select  customer_id,order_id, order_date,row_number() over(partition by customer_id order by order_date asc) rank

                              from
                              (select distinct customer_id, order_id, to_date(order_date,"dd/mm/yyyy") as order_date
                               from table_t1
                             ) abc
                             ) order_rank where order_rank.rank=2
              ) ord_rnk_2
on ord_rnk_1.customer_id=ord_rnk_2.customer_id


答:
Nope, that should work fine...only thing I'd suggest is this:

```<code>var bgy;
var color = $('fieldset input[type=checkbox]').data("color");
if(color === 'orange'){ bgy = '-1' } else { bgy = '-37' };
</code>```

Make sure jQuery's actually finding your element, and alert out the value of color to troubleshoot. Other than that, I'll need more code to go on...

Title: declaring a variable blocks my code

Body:
Nope, that should work fine...only thing I'd suggest is this:

var bgy;
var color = $('fieldset input[type=checkbox]').data("color");
if(color === 'orange'){ bgy = '-1' } else { bgy = '-37' };

Make sure jQuery's actually finding your element, and alert out the value of color to troubleshoot. Other than that, I'll need more code to go on...


问:
How to create config file for helm. Like how we can mention cert and key in helm config file
```<code>apiVersion: v1
kind: configMap
data:
 [service]
  port: 3000
  Environment: "dev"
 [database]
  name:
  host:
  port:
[kube]
  server:
  cert:
  key:
metadata:
  name:
  namespace:
</code>```

How we can add value when we create this file as helm config file

答:
As @Harsh Manvar mentioned in comments

you add values inside values.yaml which store the values and use that values inside helm chart.

There is a link to helm documentation about how to do it.

Specially part with

Values files can contain more structured content, too. For example, we could create a favorite section in our values.yaml file, and then add several keys there:

values.yaml

```<code>favorite:
  drink: coffee
  food: pizza
</code>```

ConfigMap

```<code>apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ .Release.Name }}-configmap
data:
  myvalue: "Hello World"
  drink: {{ .Values.favorite.drink }}
  food: {{ .Values.favorite.food }}
</code>```

Hope this answer your question.

Body:
apiVersion: v1
kind: configMap
data:
 [service]
  port: 3000
  Environment: "dev"
 [database]
  name:
  host:
  port:
[kube]
  server:
  cert:
  key:
metadata:
  name:
  namespace:

How we can add value when we create this file as helm config file

Body:
As @Harsh Manvar mentioned in comments

you add values inside values.yaml which store the values and use that values inside helm chart.

There is a link to helm documentation about how to do it.

Specially part with

Values files can contain more structured content, too. For example, we could create a favorite section in our values.yaml file, and then add several keys there:

values.yaml

favorite:
  drink: coffee
  food: pizza

ConfigMap

apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ .Release.Name }}-configmap
data:
  myvalue: "Hello World"
  drink: {{ .Values.favorite.drink }}
  food: {{ .Values.favorite.food }}

Hope this answer your question.


问:
python manage.py migrate does not create a table
I use postgresql and my python version is 3.7
I have tried all the commands

```<code>python manage.py makemigrations
</code>```

This creates a file in migrations named 0001_initial.py

```<code># Generated by Django 2.2.10 on 2020-02-17 12:01
</code>```

from django.db import migrations, models

class Migration(migrations.Migration):

```<code>initial = True

dependencies = [
]

operations = [
    migrations.CreateModel(
        name='Support',
        fields=[
            ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
            ('name', models.CharField(max_length=40)),
            ('email', models.EmailField(max_length=254)),
            ('message', models.TextField()),
        ],
    ),
]
</code>```

now when I pass the command to migrate,

```<code>python manage.py migrate
</code>```

It shows that 'No migrations to apply'

```<code>    (myvenv) C:\nid\project>python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, scholarship, sessions
Running migrations:
  No migrations to apply.
</code>```

This is my models.py class:

```<code>    from django.db import models
from django.utils import timezone

# Create your models here.

class Support(models.Model):
    name = models.CharField(max_length=40)
    email = models.EmailField()
    message = models.TextField()

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

I know that this question has been asked before. I checked them all but no answer is able to solve this problem. Please help

答:
In general, this means that the table already exists in your DB.
I suggest that you try to delete your table and then recreate it with py manage.py migrate.

Reply if you have further problems

Body:
I use postgresql and my python version is 3.7
I have tried all the commands

python manage.py makemigrations

This creates a file in migrations named 0001_initial.py

# Generated by Django 2.2.10 on 2020-02-17 12:01

from django.db import migrations, models

class Migration(migrations.Migration):

initial = True

dependencies = [
]

operations = [
    migrations.CreateModel(
        name='Support',
        fields=[
            ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
            ('name', models.CharField(max_length=40)),
            ('email', models.EmailField(max_length=254)),
            ('message', models.TextField()),
        ],
    ),
]

now when I pass the command to migrate,

python manage.py migrate

It shows that 'No migrations to apply'

    (myvenv) C:\nid\project>python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, scholarship, sessions
Running migrations:
  No migrations to apply.

This is my models.py class:

    from django.db import models
from django.utils import timezone

# Create your models here.

class Support(models.Model):
    name = models.CharField(max_length=40)
    email = models.EmailField()
    message = models.TextField()

    def __str__(self):
        return self.name

I know that this question has been asked before. I checked them all but no answer is able to solve this problem. Please help


问:
Is it a good practice to store data in nosql database like this?
So basically I'am building a todo app with vue.js + firestore.

In my db there is the todos collection which has some fields (doesn't matter) and the userId field.

If I create a TODO with user A, it saves the A user's ID to the userID field in the todos collection.

If I create a TODO with user B, it saves the B user's ID to the userID field in the todos collection.

.

and so on

.

.

So if I log in with differend users, it shows me each users todos based on the userId field in the todos collection.

Now, is this a good practice to link data to users like this in the nosql world ?

答: Yes, Even if you have 10k+ document and your database structure is perfect then you can do what you want - @Ashish


答:
Probably you need to use

if(color === 'orange')

other wise

orange will be treated as variable which is undefined.

Title: declaring a variable blocks my code

Body:
is something wrong here?
declaring those variables stops the execution of my code :(

var color = $('fieldset input[type=checkbox]').data("color");
        if(color === orange){var bgy = '-1'}
        else{var bgy = '-37'};

If you need more info please ask me :)


问:
Use Azure custom vision model with Node.js
i am new to Tensorflow.js so, i don't quite understand it completely.
I have trained an object detection model using Azure Custom Vision (customvision.ai) and as described in there documentation i exported the model for Tensorflow.js for offline use in my Node.js Project.

They have a very brief guide on Github (https://github.com/microsoft/customvision-tfjs) on how to use the model with Tensorflow.js, i tried following the steps but was not able to run it.

If anyone has experience with Tensorflow.js, please help me in this i am stuck on it for past 3 days.

This is the Code that i am trying to execute, i am getting Error

'await can only be used with async functions'

even though the loadModelAsync() function is Async.

```<code>const cvstfjs = require('@microsoft/customvision-tfjs');

let model = new cvstfjs.ObjectDetectionModel();
await model.loadModelAsync('model.json');
const image = document.getElementById('image');
const result = await model.executeAsync(image);
</code>```

答:
As the error says, you will need to wrap any await calls in an async function:

const cvstfjs = require('@microsoft/customvision-tfjs');

async function doThings() {
  let model = new cvstfjs.ObjectDetectionModel();
  await model.loadModelAsync('model.json');
  const image = document.getElementById('image');
  const result = await model.executeAsync(image);
  return result;
}

doThings().then((result) => {
  console.log(result);
});
```

Body:
i am new to Tensorflow.js so, i don't quite understand it completely.
I have trained an object detection model using Azure Custom Vision (customvision.ai) and as described in there documentation i exported the model for Tensorflow.js for offline use in my Node.js Project.

They have a very brief guide on Github (https://github.com/microsoft/customvision-tfjs) on how to use the model with Tensorflow.js, i tried following the steps but was not able to run it.

If anyone has experience with Tensorflow.js, please help me in this i am stuck on it for past 3 days.

This is the Code that i am trying to execute, i am getting Error

'await can only be used with async functions'

even though the loadModelAsync() function is Async.

const cvstfjs = require('@microsoft/customvision-tfjs');

let model = new cvstfjs.ObjectDetectionModel();
await model.loadModelAsync('model.json');
const image = document.getElementById('image');
const result = await model.executeAsync(image);


问:
PyCharm inserting tab characters even though I have specified to use only spaces
I am using PyCharm on Windows, below is the version information:

```<code>PyCharm 2019.1 EAP (Community Edition)
Build #PC-191.5849.23, built on February 27, 2019
JRE: 11.0.2+159 amd64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Windows 10 10.0
</code>```

When I am editing code and hit enter it sometimes inserts a tab character when I expect it to insert only spaces, as I have configured the editor to always use 4 spaces per indentation level.  For example, if I have a long line that I want the editor to split nicely for me I may hit enter between two parameters in a function signature, with the expectation that the indentation provided by the editor will use spaces only rather than tab characters, but I get tabs instead of 4 spaces.

So the following code is split correctly, but instead of spaces in the second line before the second parameter I have tab characters:

```<code>example_function(arg1,
                 arg2)
</code>```

I have unchecked "Use tab character" in Settings->Editor->Code Style->Python->Tabs and Indents, so this seems to be affected by another setting.

When can I manage this behavior?

答: LOL - I have the exact opposite problem. I want to use TAB characters, I have 'Use tab character' checked and it refuses to insert TAB characters, only spaces. Something is seriously wrong with PyCharm's handling of indentation. Using version 2019.3.3 (Community Edition)</p>

Body:
I am using PyCharm on Windows, below is the version information:

PyCharm 2019.1 EAP (Community Edition)
Build #PC-191.5849.23, built on February 27, 2019
JRE: 11.0.2+159 amd64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Windows 10 10.0

When I am editing code and hit enter it sometimes inserts a tab character when I expect it to insert only spaces, as I have configured the editor to always use 4 spaces per indentation level.  For example, if I have a long line that I want the editor to split nicely for me I may hit enter between two parameters in a function signature, with the expectation that the indentation provided by the editor will use spaces only rather than tab characters, but I get tabs instead of 4 spaces.

So the following code is split correctly, but instead of spaces in the second line before the second parameter I have tab characters:

example_function(arg1,
                 arg2)

I have unchecked "Use tab character" in Settings->Editor->Code Style->Python->Tabs and Indents, so this seems to be affected by another setting.

When can I manage this behavior?


问:
Update value in specific graph
I would like to update values in a specific graph. When I call this query I get two triples in two different graphs:

```<code>select *
where {
  GRAPH ?g {
    ?s ?p ?o .
    FILTER(?s = <http://mre.zcu.cz/id/2285692c932c88f8673a162ef7b5c997993da41cc>) .
    FILTER(?p = ds:diagDetail).
    FILTER(?o = 123)
  }
}
</code>```

But when I try to update these values with this query nothing happened. The server returns success, but triples don't change. What am I doing wrong?

```<code>DELETE {?s ?p ?o}
INSERT {?s ?p 12345}
where {
  GRAPH ?g {
    ?s ?p ?o .
    FILTER(?s = <http://mre.zcu.cz/id/2285692c932c88f8673a162ef7b5c997993da41cc>) .
    FILTER(?p = ds:diagDetail).
    FILTER(?o = 123)
  }
}
</code>```

答:
Try including the GRAPH keyword in the DELETE and INSERT statements.

```<code>DELETE {GRAPH ?g {?s ?p ?o   } }
INSERT {GRAPH ?g {?s ?p 12345} }
where {
  GRAPH ?g {
    ?s ?p ?o .
    FILTER(?s = <http://mre.zcu.cz/id/2285692c932c88f8673a162ef7b5c997993da41cc>) .
    FILTER(?p = ds:diagDetail).
    FILTER(?o = 123)
  }
}
</code>```

Otherwise it may be doing the changes in the "default graph", but not changing the triples in the actual graphs where they "live".

Title: Update value in specific graph

Body:
I would like to update values in a specific graph. When I call this query I get two triples in two different graphs:

select *
where {
  GRAPH ?g {
    ?s ?p ?o .
    FILTER(?s = <http://mre.zcu.cz/id/2285692c932c88f8673a162ef7b5c997993da41cc>) .
    FILTER(?p = ds:diagDetail).
    FILTER(?o = 123)
  }
}

But when I try to update these values with this query nothing happened. The server returns success, but triples don't change. What am I doing wrong?

DELETE {?s ?p ?o}
INSERT {?s ?p 12345}
where {
  GRAPH ?g {
    ?s ?p ?o .
    FILTER(?s = <http://mre.zcu.cz/id/2285692c932c88f8673a162ef7b5c997993da41cc>) .
    FILTER(?p = ds:diagDetail).
    FILTER(?o = 123)
  }
}

Body:
Try including the GRAPH keyword in the DELETE and INSERT statements.

DELETE {GRAPH ?g {?s ?p ?o   } }
INSERT {GRAPH ?g {?s ?p 12345} }
where {
  GRAPH ?g {
    ?s ?p ?o .
    FILTER(?s = <http://mre.zcu.cz/id/2285692c932c88f8673a162ef7b5c997993da41cc>) .
    FILTER(?p = ds:diagDetail).
    FILTER(?o = 123)
  }
}

Otherwise it may be doing the changes in the "default graph", but not changing the triples in the actual graphs where they "live".


问:
Start Process Acts Differently in Blue Prism
I have batch file for opening Dataloader application which is provided by Salesforce. When I double click to the bat file, it opens normally. However, when I use start process action in Blue Prism, it acts different. Do you have any idea why I am facing that?

答:
The .bat file provided by Salesforce most likely launches Dataloader with some program arguments.

Open the .bat file to confirm this, and then copy the arguments into the Arguments input of the Blue Prism action.


问:
Optimize API for reducing the segments and eliminating ES deleted docs not working
This is in continuation of my previous question Does huge number of deleted doc count affects ES query performance related to deleted docs in my ES index.

As pointed in the answer, I used optimize API as I am using the ES 1.X version where force merge API is not available but after reading about optimize API github link(provided earlier as couldn't find it on ES site) by Say Bannon founder of elastic, looks like it does the same work.

I got the success message for my index after running the optimize API, but I don't see total count of deleted docs decreasing and I am worried as when I checked the segments of my index using segments API, I see there are more than 25 segments for each shard and every shard is holding 250-1 gb of data in memory and almost 500k docs, while I see there are some shards where there is few deleted docs.

So my question are:

My index is having multiple shards across multiple data nodes and when  I ran optimize API using only 1 node URL, then does it only merges the segments on that node?

In segment API result it shows the node-id like "node": "f2hsqeamadnaskda", while I am using KOPF plugin and have custom names for my data nodes, so How can I relate this cryptic node name to my human readable node name to identify whether statement 1 is correct or not?

As there is no documentation available on optimize API, is it possible to merge segments on all shards across all nodes in single shot? and do I need to make index read-only before applying it?

答:
@Nirmal has answered your first two questions, so:

As there is no documentation available on optimize API, is it possible to merge segments on all shards across all nodes in single shot? and do I need to make index read-only before applying it?

There is documentation available for 1.x: https://www.elastic.co/guide/en/elasticsearch/reference/1.7/indices-optimize.html. You are probably looking for calls like these:

GET <index_pattern>/_cat/segments: List all segments in all the shards (can be thousands). Also lists deleted docs.

POST <index_pattern>/_optimize?max_num_segments=1: Force merge all segments to 1 single segment per shard. Do this when the index is no longer being written to. It helps to reduce load on CPU/RAM on the data nodes.

POST <index_pattern>/_optimize?only_expunge_deletes=true: only remove deleted docs

Finally, you can use * as <index_pattern> to just do all indices on the whole cluster.


问:
crypt() not returning standard MD5 Hash?
I'm trying to use the crypt() function found in <crypt.h> in C, and when I attempt to hash a string in MD5 for example, it returns something different than a standard MD5 hash would produce from a tool such as md5sum. Example/Proof:

hash.c:

#include <stdio.h>
#include <crypt.h>

#define MD5 "$1$"

int main() {

        const char string[] = "helloworld";
        char * hash = crypt(string, MD5);

        printf("%s\n",hash);

        return 0;
}
```

<p>I compile with <code>gcc -o hash hash.c -lcrypt</code> and run:</p>

<pre class="lang-sh prettyprint-override"><code>./hash
$1$$edK86ZB1Vvaz2eneY.itb.
</code>```

From my knowledge of UNIX systems, the format of the output of crypt matches the password format of UNIX users whereas the first part is the hash ID/type, the second part is the salt and the third is the actual hash - $id$salt$hash. Yet the ACTUAL standard MD5 hash of helloworld is fc5e038d38a57032085441e7fe7010b0. Is there any way to produce this hash using crypt()? Many thanks!

答:
The string returned by the glibc implementation of crypt() is not just a simple hash of the salt + password encoded into base 16.

If you look at the source code of the MD5 version, you'll see among other things a loop that takes a previous MD5 hash and hashes that, for one thousand repetitions. Then it's turned into a string with repeated use of a function named __b64_from_24bit() that encodes 3 bytes of the final MD5 hash at a time (not in linear order) into what I assume is base 64.

This is why what you see looks nothing like the output of md5sum or the like.

Body:
I'm trying to use the crypt() function found in <crypt.h> in C, and when I attempt to hash a string in MD5 for example, it returns something different than a standard MD5 hash would produce from a tool such as md5sum. Example/Proof:

hash.c:

#include <stdio.h>
#include <crypt.h>

#define MD5 "$1$"

int main() {

        const char string[] = "helloworld";
        char * hash = crypt(string, MD5);

        printf("%s\n",hash);

        return 0;
}

I compile with gcc -o hash hash.c -lcrypt and run:

./hash
$1$$edK86ZB1Vvaz2eneY.itb.

From my knowledge of UNIX systems, the format of the output of crypt matches the password format of UNIX users whereas the first part is the hash ID/type, the second part is the salt and the third is the actual hash - $id$salt$hash. Yet the ACTUAL standard MD5 hash of helloworld is fc5e038d38a57032085441e7fe7010b0. Is there any way to produce this hash using crypt()? Many thanks!


问:
How do I implement RichTextEditor in Flash?
I'm looking at this example: and for the life of me I don't see how to utilize this in Flash.  I don't want to build a Flex app... I want to implement this object in my Flash code.  But I'm not having any luck importing mx.controls or getting an instance of this component. It's not in my component's library, either.  Is there some lib I'm missing? Or am I just attempting the impossible here?</p>

答:
This is the one I would go with it is an open source rich text editor.

http://code.google.com/p/as3texteditor/


问:
How do I display a final score and high score on gameover screen?
I am using libgdx and I am trying to figure out how to display the final score my players achieve, and the overall high score for their games when the game goes to the game over screen. I am unsure as to how to bring the score integer over from the game screen to the game over screen.</p>

答:
It's probably not the best way, but you can keep the score in the main class that extends Game.

import com.badlogic.gdx.Game;

public class MyGame extends Game {
    private int score;

    // Add getters and setters
}
```

<p>Then in your screen classes you can do:</p>

<pre class="lang-java prettyprint-override"><code>MyGame myGame = (MyGame) Gdx.app.getApplicationListener();
// Then you can set
myGame.setScore(score);
// or get the score
int score = myGame.getScore();
</code>```

If you have multiple values to store, you can create a class and keep an instance of it in your MyGame class. You will put the score and other properties in this class.

You can also create a static method in MyGame class that do the cast for you:

public static MyGame get() {
    return (MyGame) Gdx.app.getApplicationListener();
}
```

Then you can do MyGame.get().setScore(score);
or: int score = MyGame.get().getScore();

Body:
It's probably not the best way, but you can keep the score in the main class that extends Game.

import com.badlogic.gdx.Game;

public class MyGame extends Game {
    private int score;

    // Add getters and setters
}

Then in your screen classes you can do:

MyGame myGame = (MyGame) Gdx.app.getApplicationListener();
// Then you can set
myGame.setScore(score);
// or get the score
int score = myGame.getScore();

If you have multiple values to store, you can create a class and keep an instance of it in your MyGame class. You will put the score and other properties in this class.

You can also create a static method in MyGame class that do the cast for you:

public static MyGame get() {
    return (MyGame) Gdx.app.getApplicationListener();
}

Then you can do MyGame.get().setScore(score);
or: int score = MyGame.get().getScore();


问:
How to change links in jsp to buttons
I faced with the following problem:

```<code><%@ page contentType="text/html;charset=UTF-8" language="java"%>
<html>
<head>
<title>Lab2</title>
</head>
<body>
    <p>
    <form>
        Period: <input type="number" name="period" size="50"> <br>
        Faculty: <input type="text" name="faculty" size="50"> <br>
        <a href="${pageContext.request.contextPath}/calculatePaymentForSeveralSemesters?value=<%=request.getParameter("period")%>&faculty=<%=request.getParameter("faculty")%>">Calculate payment for several semesters</a>
        <a href="${pageContext.request.contextPath}/showTwoSmallestFaculties">Show two smallest faculties</a>
        <input type="submit">
    </form>
    </p>
</body>
</html>
</code>```

Now I have to enter data to the inputs, then click on Submit and only then I can click on the link. But is there any way to navigate to another pages by clicking on the button and passing parameters to other pages? I will appreciate any help, thanks in advance!

答:
But is there any way to navigate to another pages by clicking on the
  button and passing parameters to other pages?

Yeah. You can just pass the values as inputs within a form:

```<code>   <form method="get" action="${pageContext.request.contextPath}/calculatePaymentForSeveralSemesters">
        Period: <input type="number" name="period" value="${period}" size="50"> <br>
        Faculty: <input type="text" name="faculty" value="${faculty} size="50"> <br>
        <button type="submit">Calculate payment for several semesters</button>
    </form>

   <form method="get"  action="${pageContext.request.contextPath}/showTwoSmallestFaculties">
        Period: <input type="number" name="period" value="${period}" size="50"> <br>
        Faculty: <input type="text" name="faculty" value="${faculty} size="50"> <br>
        <button type="submit">Show two smallest faculties</button>
    </form>
</code>```

You could also just do it with javascript...

```<code>    Period: <input id="period" type="number" name="period" value="${period}" size="50"> <br>
    Faculty: <input id="faculty" type="text" name="faculty" value="${faculty} size="50"> <br>
   <button type="submit" onclick="showFaculties">Show two smallest faculties</button>
   <button type="submit" onclick="calculatepayments">Calculate payment for several semesters</button>

<script>

var period = document.getElementById("period").value;
var faculty = document.getElementById("faculty").value;

function showFaculties(){
     window.location = "/calculatePaymentForSeveralSemesters?value="+period+"&faculty="+faculty;
}
function calculatepayments(){
     window.location = "/showTwoSmallestFaculties"
}

<script>
</code>```

Also, scriptlets are highly discouraged against... you don't need to do this:

```<code><%=request.getParameter("period")%>
</code>```

just this is fine:

```<code>${period}
</code>```

Why scriptlets are discouraged:

How to avoid Java code in JSP files?

Title: How to change links in jsp to buttons

Body:
I faced with the following problem:

<%@ page contentType="text/html;charset=UTF-8" language="java"%>

<title>Lab2</title>

    <form>
        Period: <input type="number" name="period" size="50">

        Faculty: <input type="text" name="faculty" size="50">

        <a href="${pageContext.request.contextPath}/calculatePaymentForSeveralSemesters?value=<%=request.getParameter("period")%>&faculty=<%=request.getParameter("faculty")%>">Calculate payment for several semesters
        Show two smallest faculties
        <input type="submit">
    </form>

Now I have to enter data to the inputs, then click on Submit and only then I can click on the link. But is there any way to navigate to another pages by clicking on the button and passing parameters to other pages? I will appreciate any help, thanks in advance!

Body:
But is there any way to navigate to another pages by clicking on the
  button and passing parameters to other pages?

Yeah. You can just pass the values as inputs within a form:

   <form method="get" action="${pageContext.request.contextPath}/calculatePaymentForSeveralSemesters">
        Period: <input type="number" name="period" value="${period}" size="50"> <br>
        Faculty: <input type="text" name="faculty" value="${faculty} size="50"> <br>
        <button type="submit">Calculate payment for several semesters</button>
    </form>

   <form method="get"  action="${pageContext.request.contextPath}/showTwoSmallestFaculties">
        Period: <input type="number" name="period" value="${period}" size="50"> <br>
        Faculty: <input type="text" name="faculty" value="${faculty} size="50"> <br>
        <button type="submit">Show two smallest faculties</button>
    </form>

You could also just do it with javascript...

    Period: <input id="period" type="number" name="period" value="${period}" size="50"> <br>
    Faculty: <input id="faculty" type="text" name="faculty" value="${faculty} size="50"> <br>
   <button type="submit" onclick="showFaculties">Show two smallest faculties</button>
   <button type="submit" onclick="calculatepayments">Calculate payment for several semesters</button>

<script>

var period = document.getElementById("period").value;
var faculty = document.getElementById("faculty").value;

function showFaculties(){
     window.location = "/calculatePaymentForSeveralSemesters?value="+period+"&faculty="+faculty;
}
function calculatepayments(){
     window.location = "/showTwoSmallestFaculties"
}

<script>

Also, scriptlets are highly discouraged against... you don't need to do this:

<%=request.getParameter("period")%>

just this is fine:

${period}

Why scriptlets are discouraged:

How to avoid Java code in JSP files?


问:
Access class members without copying this or mutex variable
I'm trying to create a simple Worker class, which will create a number of threads and a set of tasks for the threads to run. This is educational, but I have already tried asking classmates and searching for different answers, and I think there is something "simple"/fundamental I'm missing here.

I'm having some issues regarding where my mutex variable should be set. I believe I would want one for each of my Worker objects, as the threads created by each object are completely unrelated. Right now, I'm trying to pass this to the lambda method that adds to the set of threads, but this copies the mutex, which deletes it. Is there a way to copy each class member I need independently, or should I create a copy constructor? I'm only trying to pass the class variables I need to the lambda. Here is my code:

```<code>// TDAT2004Task2.cpp : Defines the entry point for the application.
//

#include <functional>
#include <iostream>
#include <list>
#include <vector>
#include <mutex>
#include <thread>

using namespace std;

class Worker {
    int threads;

    mutable mutex tasks_mutex;

    vector<thread> worker_threads;
    list<function<void()>> tasks;

public:

    Worker(int threadAmount) {
        threads = threadAmount;
    }

    void start() {
        for (int i = 0; i < threads; i++) {
            //This is the place errors occur. I'm copying the this element, and thus deleting my
            //mutex variable.
            worker_threads.emplace_back([this] {
                while (true) {
                    function<void()> task;
                    {
                        lock_guard<mutex> lock(tasks_mutex);
                        if (!tasks.empty()) {
                            task = *tasks.begin();
                            tasks.pop_front();
                        }
                    }
                    if (task) {
                        task();
                    }
                }
                });
        }
        for (auto& thread : worker_threads) {
            thread.join();
        }
    }

    void post(function<void()> function) {
        lock_guard<mutex> lock(tasks_mutex);
        tasks.emplace_back(function);
    }
};

int main()
{
    //This does not compile.
    Worker worker_threads = Worker(4);
}
</code>```

My error message in VS:

```<code>>------ Build All started: Project: TDAT2004Task2, Configuration: x64-Debug ------
  [1/2] C:\PROGRA~2\MICROS~2\2019\COMMUN~1\VC\Tools\MSVC\1424~1.283\bin\HostX64\x64\cl.exe  /nologo /TP   /DWIN32 /D_WINDOWS /W3 /GR /EHsc /MDd /Zi /Ob0 /Od /RTC1 /showIncludes /FoTDAT2004Task2\CMakeFiles\TDAT2004Task2.dir\TDAT2004Task2.cpp.obj /FdTDAT2004Task2\CMakeFiles\TDAT2004Task2.dir\ /FS -c ..\..\..\TDAT2004Task2\TDAT2004Task2.cpp
  FAILED: TDAT2004Task2/CMakeFiles/TDAT2004Task2.dir/TDAT2004Task2.cpp.obj
  C:\PROGRA~2\MICROS~2\2019\COMMUN~1\VC\Tools\MSVC\1424~1.283\bin\HostX64\x64\cl.exe  /nologo /TP   /DWIN32 /D_WINDOWS /W3 /GR /EHsc /MDd /Zi /Ob0 /Od /RTC1 /showIncludes /FoTDAT2004Task2\CMakeFiles\TDAT2004Task2.dir\TDAT2004Task2.cpp.obj /FdTDAT2004Task2\CMakeFiles\TDAT2004Task2.dir\ /FS -c ..\..\..\TDAT2004Task2\TDAT2004Task2.cpp
C:\Users\Even\source\repos\TDAT2004Task2\TDAT2004Task2\TDAT2004Task2.cpp(74): error C2280: 'Worker::Worker(const Worker &)': attempting to reference a deleted function
  ..\..\..\TDAT2004Task2\TDAT2004Task2.cpp(69): note: compiler has generated 'Worker::Worker' here
  ..\..\..\TDAT2004Task2\TDAT2004Task2.cpp(69): note: 'Worker::Worker(const Worker &)': function was implicitly deleted because a data member invokes a deleted or inaccessible function 'std::mutex::mutex(const std::mutex &)'
  C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.24.28314\include\mutex(92): note: 'std::mutex::mutex(const std::mutex &)': function was explicitly deleted
  ninja: build stopped: subcommand failed.
</code>```

Error message from cpp in the console:

```<code>C:\Users\Even\source\repos\TDAT2004Task2\TDAT2004Task2>gcc TDAT2004Task2.cpp
TDAT2004Task2.cpp: In function 'int main()':
TDAT2004Task2.cpp:74:34: error: use of deleted function 'Worker::Worker(Worker&&)'
  Worker worker_threads = Worker(4);
                                  ^
TDAT2004Task2.cpp:18:7: note: 'Worker::Worker(Worker&&)' is implicitly deleted because the default definition would be ill-formed:
 class Worker {
       ^~~~~~
TDAT2004Task2.cpp:18:7: error: use of deleted function 'std::mutex::mutex(const std::mutex&)'
In file included from /usr/lib/gcc/x86_64-pc-cygwin/7.4.0/include/c++/mutex:43:0,
                 from TDAT2004Task2.cpp:13:
/usr/lib/gcc/x86_64-pc-cygwin/7.4.0/include/c++/bits/std_mutex.h:97:5: note: declared here
     mutex(const mutex&) = delete;
     ^~~~~
</code>```

Thank you for any responses! Please point at any stupid mistakes I've done, I'm just trying to learn the best practices.

答:
The problem was, that you defined a copy-constructor. Therefor you do not have a default move contructor.

I do not see how you can have a correct copy-constructor, since std::thread can not be copied, therefore a std::vector<std::thread> can not be copied.

A default-move-constructor should work for your case.

So to be explicit add the lines:

```<code>public:

   Worker(const Worker&) = delete;
   Worker& operator=(const Worker&) = delete;
   Worker(Worker&&) = default;
   Worker& operator=(Worker&&) = default;
</code>```

to your Worker class.

Body:
I'm trying to create a simple Worker class, which will create a number of threads and a set of tasks for the threads to run. This is educational, but I have already tried asking classmates and searching for different answers, and I think there is something "simple"/fundamental I'm missing here.

I'm having some issues regarding where my mutex variable should be set. I believe I would want one for each of my Worker objects, as the threads created by each object are completely unrelated. Right now, I'm trying to pass this to the lambda method that adds to the set of threads, but this copies the mutex, which deletes it. Is there a way to copy each class member I need independently, or should I create a copy constructor? I'm only trying to pass the class variables I need to the lambda. Here is my code:

// TDAT2004Task2.cpp : Defines the entry point for the application.
//

#include <functional>
#include <iostream>
#include <list>
#include <vector>
#include <mutex>
#include <thread>

using namespace std;

class Worker {
    int threads;

    mutable mutex tasks_mutex;

    vector<thread> worker_threads;
    list<function<void()>> tasks;

public:

    Worker(int threadAmount) {
        threads = threadAmount;
    }

    void start() {
        for (int i = 0; i < threads; i++) {
            //This is the place errors occur. I'm copying the this element, and thus deleting my
            //mutex variable.
            worker_threads.emplace_back([this] {
                while (true) {
                    function<void()> task;
                    {
                        lock_guard<mutex> lock(tasks_mutex);
                        if (!tasks.empty()) {
                            task = *tasks.begin();
                            tasks.pop_front();
                        }
                    }
                    if (task) {
                        task();
                    }
                }
                });
        }
        for (auto& thread : worker_threads) {
            thread.join();
        }
    }

    void post(function<void()> function) {
        lock_guard<mutex> lock(tasks_mutex);
        tasks.emplace_back(function);
    }
};

int main()
{
    //This does not compile.
    Worker worker_threads = Worker(4);
}

My error message in VS:

>------ Build All started: Project: TDAT2004Task2, Configuration: x64-Debug ------
  [1/2] C:\PROGRA~2\MICROS~2\2019\COMMUN~1\VC\Tools\MSVC\1424~1.283\bin\HostX64\x64\cl.exe  /nologo /TP   /DWIN32 /D_WINDOWS /W3 /GR /EHsc /MDd /Zi /Ob0 /Od /RTC1 /showIncludes /FoTDAT2004Task2\CMakeFiles\TDAT2004Task2.dir\TDAT2004Task2.cpp.obj /FdTDAT2004Task2\CMakeFiles\TDAT2004Task2.dir\ /FS -c ..\..\..\TDAT2004Task2\TDAT2004Task2.cpp
  FAILED: TDAT2004Task2/CMakeFiles/TDAT2004Task2.dir/TDAT2004Task2.cpp.obj
  C:\PROGRA~2\MICROS~2\2019\COMMUN~1\VC\Tools\MSVC\1424~1.283\bin\HostX64\x64\cl.exe  /nologo /TP   /DWIN32 /D_WINDOWS /W3 /GR /EHsc /MDd /Zi /Ob0 /Od /RTC1 /showIncludes /FoTDAT2004Task2\CMakeFiles\TDAT2004Task2.dir\TDAT2004Task2.cpp.obj /FdTDAT2004Task2\CMakeFiles\TDAT2004Task2.dir\ /FS -c ..\..\..\TDAT2004Task2\TDAT2004Task2.cpp
C:\Users\Even\source\repos\TDAT2004Task2\TDAT2004Task2\TDAT2004Task2.cpp(74): error C2280: 'Worker::Worker(const Worker &)': attempting to reference a deleted function
  ..\..\..\TDAT2004Task2\TDAT2004Task2.cpp(69): note: compiler has generated 'Worker::Worker' here
  ..\..\..\TDAT2004Task2\TDAT2004Task2.cpp(69): note: 'Worker::Worker(const Worker &)': function was implicitly deleted because a data member invokes a deleted or inaccessible function 'std::mutex::mutex(const std::mutex &)'
  C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.24.28314\include\mutex(92): note: 'std::mutex::mutex(const std::mutex &)': function was explicitly deleted
  ninja: build stopped: subcommand failed.

Error message from cpp in the console:

C:\Users\Even\source\repos\TDAT2004Task2\TDAT2004Task2>gcc TDAT2004Task2.cpp
TDAT2004Task2.cpp: In function 'int main()':
TDAT2004Task2.cpp:74:34: error: use of deleted function 'Worker::Worker(Worker&&)'
  Worker worker_threads = Worker(4);
                                  ^
TDAT2004Task2.cpp:18:7: note: 'Worker::Worker(Worker&&)' is implicitly deleted because the default definition would be ill-formed:
 class Worker {
       ^~~~~~
TDAT2004Task2.cpp:18:7: error: use of deleted function 'std::mutex::mutex(const std::mutex&)'
In file included from /usr/lib/gcc/x86_64-pc-cygwin/7.4.0/include/c++/mutex:43:0,
                 from TDAT2004Task2.cpp:13:
/usr/lib/gcc/x86_64-pc-cygwin/7.4.0/include/c++/bits/std_mutex.h:97:5: note: declared here
     mutex(const mutex&) = delete;
     ^~~~~

Thank you for any responses! Please point at any stupid mistakes I've done, I'm just trying to learn the best practices.

Body:
The problem was, that you defined a copy-constructor. Therefor you do not have a default move contructor.

I do not see how you can have a correct copy-constructor, since std::thread can not be copied, therefore a std::vector<std::thread> can not be copied.

A default-move-constructor should work for your case.

So to be explicit add the lines:

public:

   Worker(const Worker&) = delete;
   Worker& operator=(const Worker&) = delete;
   Worker(Worker&&) = default;
   Worker& operator=(Worker&&) = default;

to your Worker class.


问:
How to fix a "NameError: name 'color' is not defined"?
here is my code :

```<code>size = (1280, 850)
Win = pygame.display.set_mode(size)
class Particle:
    color = (255, 255, 0)
    ID = 0

    def __init__(self, rect):
        Particle.ID += 1
        self.color = (color)
        self.ID = Particle.ID
        self.rect = rect

    def move(self, x, y):
        self.rect.move(x, y)

    def draw(self):
        pygame.draw.rect(Win, self.color, self.rect)

    def collide(self, rect1):
        return self.rect.colliderect(rect1)
</code>```

When I run my project, I have : "self.color = (color)
NameError: name 'color' is not defined" but color is defined...It is at the beginning of my class "Particle"...

Thank you to help me !

答:
I cannot comment yet.

Try this:

```<code>self.color = (color) -> self.color = color
</code>```

Edit:
Let me correct, I do not have the full context of your implementation of the class. You have to initialize the class as an object because the funciton draw cals the color in the self container. Hence you have to create the object, then call the draw function from the object. Thus Particle.draw() will not work because the classes initializer is not called.

Thus:

```<code>particle = Particle()
particle.draw()
</code>```

Body:
here is my code :

size = (1280, 850)
Win = pygame.display.set_mode(size)
class Particle:
    color = (255, 255, 0)
    ID = 0

    def __init__(self, rect):
        Particle.ID += 1
        self.color = (color)
        self.ID = Particle.ID
        self.rect = rect

    def move(self, x, y):
        self.rect.move(x, y)

    def draw(self):
        pygame.draw.rect(Win, self.color, self.rect)

    def collide(self, rect1):
        return self.rect.colliderect(rect1)

When I run my project, I have : "self.color = (color)
NameError: name 'color' is not defined" but color is defined...It is at the beginning of my class "Particle"...

Thank you to help me !

Body:
I cannot comment yet.

Try this:

self.color = (color) -> self.color = color

Edit:
Let me correct, I do not have the full context of your implementation of the class. You have to initialize the class as an object because the funciton draw cals the color in the self container. Hence you have to create the object, then call the draw function from the object. Thus Particle.draw() will not work because the classes initializer is not called.

Thus:

particle = Particle()
particle.draw()


问:
How to update a particular column on behalf of id in sqlite android
I want to update Flag column in sqlite table from 0 to 1 so when the data is send to server the flag update from 0 to 1. Here is my code :

Create table Code :

```<code>db.execSQL(" CREATE TABLE " + Order_Master + " ( " + KEY_Order_No + " INTEGER PRIMARY KEY AUTOINCREMENT , " + KEY_Order_Date + " DATE , " + KEY_Member_Code + " VARCHAR (200) NOT NULL , " + KEY_Table_No + " VARCHAR(100) , " +
                  KEY_WAITER_NAME + " VARCHAR (100) NOT NULL , " + KEY_HH_CODE + " VARCHAR (100) NOT NULL ," + KEY_CHILD_NAME + " VARCHAR (200) NOT NULL , " + KEY_CHILD_STATUS + " VARCHAR (2) NOT NULL , "
                  + KEY_SALES_TYPE + " VARCHAR (100) NOT NULL , " +  KEY_AMOUNT + " VARCHAR (100) NOT NULL , " + KEY_FLAG + " INTEGER DEFAULT NULL ) ; ");
</code>```

Insert into table code :

```<code>public boolean insertMaster  (ContentValues contentValues)
    {
        SQLiteDatabase db = this.getWritableDatabase();

        db.insert("Order_Master", null, contentValues);
        return true;
    }
</code>```

now I need to update the last column "flag" from 0 to 1. Can any one help me how can I create the update method?

答:
use this method to update value

public void updateStatus(String id , int status){

SQLiteDatabase db = this.getWritableDatabase();

ContentValues data = new ContentValues();

data.put("status", status);

db.update(TableName, data, "columnName" + " = "+id , null);

}

Body:
I want to update Flag column in sqlite table from 0 to 1 so when the data is send to server the flag update from 0 to 1. Here is my code :

Create table Code :

db.execSQL(" CREATE TABLE " + Order_Master + " ( " + KEY_Order_No + " INTEGER PRIMARY KEY AUTOINCREMENT , " + KEY_Order_Date + " DATE , " + KEY_Member_Code + " VARCHAR (200) NOT NULL , " + KEY_Table_No + " VARCHAR(100) , " +
                  KEY_WAITER_NAME + " VARCHAR (100) NOT NULL , " + KEY_HH_CODE + " VARCHAR (100) NOT NULL ," + KEY_CHILD_NAME + " VARCHAR (200) NOT NULL , " + KEY_CHILD_STATUS + " VARCHAR (2) NOT NULL , "
                  + KEY_SALES_TYPE + " VARCHAR (100) NOT NULL , " +  KEY_AMOUNT + " VARCHAR (100) NOT NULL , " + KEY_FLAG + " INTEGER DEFAULT NULL ) ; ");

Insert into table code :

public boolean insertMaster  (ContentValues contentValues)
    {
        SQLiteDatabase db = this.getWritableDatabase();

        db.insert("Order_Master", null, contentValues);
        return true;
    }

now I need to update the last column "flag" from 0 to 1. Can any one help me how can I create the update method?


问:
Increase font size at button click
I  have a table  and in the end there is a button, when click on button text size in the rows of the table should be double in size. Sorry I am new to JQuery so my question seems to be silly.</p>

答:
If your page has only one table then try this

```<code>$(document).ready(function(){
  $("button").click(function(){
    $("tr").css("font-size","200%");
  });
});
</code>```

Here tr is the table row and 200% means double text size

Title: Increase font size at button click

Body:
If your page has only one table then try this

$(document).ready(function(){
  $("button").click(function(){
    $("tr").css("font-size","200%");
  });
});

Here tr is the table row and 200% means double text size


问:
Print the result of a Python def
I want to read the date and time of a image by using Pillow.
And now I want to print the result of the def to be shure I got the Date and Time. But when I type print(defname) I just get some weird numbers as the output.

My code:

```<code>import os
import time
import shutil
import re
from PIL import Image, ExifTags
from PIL.ExifTags import TAGS

def get_date_taken(path):
    return Image.open(r"E:\insert_folder\DSC_3389.jpg")._getexif()[36867]

print(get_date_taken)
</code>```

One more thing... If you understand what I want to do and if you understand my code, could you pls check if there is any fault in my code?
Thanks to you guys! <3

答:
You have to execute your function:

It is

```<code>print(get_date_taken(""))
</code>```

not

```<code>print(get_date_taken)
</code>```

Title: Print the result of a Python def

Body:
I want to read the date and time of a image by using Pillow.
And now I want to print the result of the def to be shure I got the Date and Time. But when I type print(defname) I just get some weird numbers as the output.

My code:

import os
import time
import shutil
import re
from PIL import Image, ExifTags
from PIL.ExifTags import TAGS

def get_date_taken(path):
    return Image.open(r"E:\insert_folder\DSC_3389.jpg")._getexif()[36867]

print(get_date_taken)

One more thing... If you understand what I want to do and if you understand my code, could you pls check if there is any fault in my code?
Thanks to you guys! <3

Body:
You have to execute your function:

It is

print(get_date_taken(""))

not

print(get_date_taken)


问:
How to simplify user input
How can I simplify this code?

I check every input for an error, but in the way that I do, the code is duplicated.

```<code>long houseNumberOfFloors;
while (true) {
  System.out.print("Enter valid house number of floors: ");
  try {
    houseNumberOfFloors = Long.parseLong(br.readLine());
  } catch (NumberFormatException e) {
    continue;
  }
  if (FlatAttrValidator.checkHouseNumberOfFloors(houseNumberOfFloors)) {
    break;
  }
}

Integer houseNumberOfLifts;
while (true) {
  System.out.print("Enter valid house number of lifts: ");
  try {
    houseNumberOfLifts = Integer.parseInt(br.readLine());
  } catch (NumberFormatException e) {
    continue;
  }
  if (FlatAttrValidator.checkHouseNumberOfLifts(houseNumberOfLifts)) {
    break;
  }
}
</code>```

答:
You can pass conversion and validation as function(s).

```<code>private <T> T ask(BufferedReader br, String question, Function<String, T> converter) {
    Objects.requireNonNull(converter);
    while (true) {
        System.out.print(question);
        String answer = br.readLine();
        try {
            T result = converter.apply(answer);
            if (result != null) {
                return result;
            }
        } catch (RuntimeException e) {
        }
    }
}

int houseNumberOfLifts = (Integer) ask(br, "Enter valid house number of lifts: ",
    answer -> {
        int lifts = Integer.parseInt(answer);
        return FlatAttrValidator.checkHouseNumberOfLifts(lifts) ? lifts : null;
});
</code>```

Here answer -> declares a parameter answer

Title: How to simplify user input

Body:
How can I simplify this code?

I check every input for an error, but in the way that I do, the code is duplicated.

long houseNumberOfFloors;
while (true) {
  System.out.print("Enter valid house number of floors: ");
  try {
    houseNumberOfFloors = Long.parseLong(br.readLine());
  } catch (NumberFormatException e) {
    continue;
  }
  if (FlatAttrValidator.checkHouseNumberOfFloors(houseNumberOfFloors)) {
    break;
  }
}

Integer houseNumberOfLifts;
while (true) {
  System.out.print("Enter valid house number of lifts: ");
  try {
    houseNumberOfLifts = Integer.parseInt(br.readLine());
  } catch (NumberFormatException e) {
    continue;
  }
  if (FlatAttrValidator.checkHouseNumberOfLifts(houseNumberOfLifts)) {
    break;
  }
}

Body:
You can pass conversion and validation as function(s).

private <T> T ask(BufferedReader br, String question, Function<String, T> converter) {
    Objects.requireNonNull(converter);
    while (true) {
        System.out.print(question);
        String answer = br.readLine();
        try {
            T result = converter.apply(answer);
            if (result != null) {
                return result;
            }
        } catch (RuntimeException e) {
        }
    }
}

int houseNumberOfLifts = (Integer) ask(br, "Enter valid house number of lifts: ",
    answer -> {
        int lifts = Integer.parseInt(answer);
        return FlatAttrValidator.checkHouseNumberOfLifts(lifts) ? lifts : null;
});

Here answer -> declares a parameter answer


问:
Angular2 how to handle value of date pipe is null
I have template using date pipe like this

```<code>{{value | date: 'dd/MM/yyyy'}}
</code>```

this value is null

How to handle this if my value null i got string 'object not match'?

答:
checked with Angular 8x</p>

```{{ (value !== "null") ? (value | date: 'dd/MM/yyyy') : "-" }} ```

Body:
I have template using date pipe like this

{{value | date: 'dd/MM/yyyy'}}

this value is null

How to handle this if my value null i got string 'object not match'?

Body:
checked with Angular 8x

{{ (value !== "null") ? (value | date: 'dd/MM/yyyy') : "-" }}


问:
How to send variable from php to a bash script that is asking for user input and need to click enter?
```<code>#!/usr/bin/python

import os
import sys

client=sys.argv[1]
homeDir="/home/vpnUsers"

os.system("cd /etc/openvpn/easy-rsa/")
os.system("./easyrsa build-client-full %s" %(client))
os.system("cp /etc/openvpn/client-template.txt %s/%s.ovpn" %(homeDir,client))
</code>```

At os.system("./easyrsa build-client-full %s" %(client)) if I run it manually on terminal it ask 2 times for a password, so If I do it manually I can enter a password, click enter and its done. How can I do this but with python?

Lets supose the sys.argv[2] its the password and it should be written at the this command when it ask for password.

Ps: the args come from php.

答:
Solved it!

Pexpect

This library will talk with the script. Easy to use.

pip install pexpect

Then on your script python just import it

import pexpect

Example code for my situation

```<code> localcmd='/path/to/script/easyrsa build-client-full "arg"'

 def localOutput(localcmd):
        child = pexpect.spawn (localcmd)
        child.expect ('Enter PEM pass phrase:')
        child.sendline ('password')
        child.expect ('Verifying - Enter PEM pass phrase:')
        child.sendline ('password')
        child.expect(pexpect.EOF)
        return child.before

localout=localOutput(localcmd)
</code>```

Body:
#!/usr/bin/python

import os
import sys

client=sys.argv[1]
homeDir="/home/vpnUsers"

os.system("cd /etc/openvpn/easy-rsa/")
os.system("./easyrsa build-client-full %s" %(client))
os.system("cp /etc/openvpn/client-template.txt %s/%s.ovpn" %(homeDir,client))

At os.system("./easyrsa build-client-full %s" %(client)) if I run it manually on terminal it ask 2 times for a password, so If I do it manually I can enter a password, click enter and its done. How can I do this but with python?

Lets supose the sys.argv[2] its the password and it should be written at the this command when it ask for password.

Ps: the args come from php.

Body:
Solved it!

Pexpect

This library will talk with the script. Easy to use.

pip install pexpect

Then on your script python just import it

import pexpect

Example code for my situation

 localcmd='/path/to/script/easyrsa build-client-full "arg"'

 def localOutput(localcmd):
        child = pexpect.spawn (localcmd)
        child.expect ('Enter PEM pass phrase:')
        child.sendline ('password')
        child.expect ('Verifying - Enter PEM pass phrase:')
        child.sendline ('password')
        child.expect(pexpect.EOF)
        return child.before

localout=localOutput(localcmd)


问:
How to change app/public to app/something in Laravel storage
It's very strange. I change in filesystems.php

```<code>'FILESYSTEM_DRIVER', 'public'
</code>```

and

```<code>'root' => storage_path('app/files')
</code>```

Then run command

```<code>php artisan storage:link
</code>```

But when I write in blade

```<code>{{ asset('storage/files/picture.png') }}
</code>```

a picture don't show.
When I open page source code, than I see

```<code><img src="http://site.ru/storage/files/picture.png" >
</code>```

But it doesn't show. Why?

Folder structure:

```<code>site.ru\storage\app\files\picture.png
</code>```

答:
Because the storage:link command is hard coded to link the app/public folder.

However, you can manually create the link to your custom folder and it should work fine as well.

Body:
It's very strange. I change in filesystems.php

'FILESYSTEM_DRIVER', 'public'

and

'root' => storage_path('app/files')

Then run command

php artisan storage:link

But when I write in blade

{{ asset('storage/files/picture.png') }}

a picture don't show.
When I open page source code, than I see

But it doesn't show. Why?

Folder structure:

site.ru\storage\app\files\picture.png


问:
Template or abstract base class?
If I want to make a class adaptable, and make it possible to select different algorithms from the outside -- what is the best implementation in C++?

I see mainly two possibilities:

Use an abstract base class and pass concrete object in

Use a template

Here is a little example, implemented in the various versions:

Version 1: Abstract base class

```<code>class Brake {
public: virtual void stopCar() = 0;
};

class BrakeWithABS : public Brake {
public: void stopCar() { ... }
};

class Car {
  Brake* _brake;
public:
  Car(Brake* brake) : _brake(brake) { brake->stopCar(); }
};
</code>```

Version 2a: Template

```<code>template<class Brake>
class Car {
  Brake brake;
public:
  Car(){ brake.stopCar(); }
};
</code>```

Version 2b: Template and private inheritance

```<code>template<class Brake>
class Car : private Brake {
  using Brake::stopCar;
public:
  Car(){ stopCar(); }
};
</code>```

Coming from Java, I am naturally inclined to always use version 1, but the templates versions seem to be preferred often, e.g. in STL code? If that's true, is it just because of memory efficiency etc (no inheritance, no virtual function calls)?

I realize there is not a big difference between version 2a and 2b, see C++ FAQ.

Can you comment on these possibilities?

答:
Other options:

Use the Visitor Pattern (let external code work on your class).

Externalize some part of your class, for example via iterators, that generic iterator-based code can work on them. This works best if your object is a container of other objects.

See also the Strategy Pattern (there are c++ examples inside)

ContentLicense: CC BY-SA 2.5

Title: Template or abstract base class?

Body:
If I want to make a class adaptable, and make it possible to select different algorithms from the outside -- what is the best implementation in C++?

I see mainly two possibilities:

Use an abstract base class and pass concrete object in

Use a template

Here is a little example, implemented in the various versions:

Version 1: Abstract base class

class Brake {
public: virtual void stopCar() = 0;
};

class BrakeWithABS : public Brake {
public: void stopCar() { ... }
};

class Car {
  Brake* _brake;
public:
  Car(Brake* brake) : _brake(brake) { brake->stopCar(); }
};

Version 2a: Template

template<class Brake>
class Car {
  Brake brake;
public:
  Car(){ brake.stopCar(); }
};

Version 2b: Template and private inheritance

template<class Brake>
class Car : private Brake {
  using Brake::stopCar;
public:
  Car(){ stopCar(); }
};

Coming from Java, I am naturally inclined to always use version 1, but the templates versions seem to be preferred often, e.g. in STL code? If that's true, is it just because of memory efficiency etc (no inheritance, no virtual function calls)?

I realize there is not a big difference between version 2a and 2b, see C++ FAQ.

Can you comment on these possibilities?

OwnerDisplayName: Assaf


问:
Is it worth learning Smarty for PHP templating?
I'm building a simple 10-page site using an MVC-like architecture. Is it worth learning the Smarty templating engine?</p>

答: A templating language is a good choice when you're dynamically generating HTML. Be it Smarty or something else (for PHP), Razor or Forms (for ASP.NET), or something entirely different (John Resig's client-side micro-templating framework, perhaps).</p>


答:
You are not calling the function, you are just printing a pointer to that function - this the memory address where the function is stored. In order to execute the function, add parenthesis.

get_date_taken("your\path\here")

Also, what you are calling def and defname are called functions in Python.

Title: Print the result of a Python def


问:
Custom Deserialization of Generic Types in Jackson Kotlin/Java
With this data model...

TestClass.kt

```<code>data class TestClass (val bar: Optional<Double>?)
</code>```

My goal is to deserialize the following json values as such:

```<code>{"foo": 3.5}  --> foo = 3.5
{"foo": null} --> foo = Optional.empty() // This is currently my problem. foo is null and I can't seem to fix it
{}            --> foo = null
</code>```

I've seen the solution here and tried this, but the breakpoints in my "deserialize" method never seem to hit.

OptionalDeserializer.java

```<code>import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import java.io.IOException;
import java.util.Optional;

public class OptionalDeserializer extends JsonDeserializer<Optional<?>> implements ContextualDeserializer {
    private JavaType valueType;

    @Override
    public JsonDeserializer<?> createContextual(DeserializationContext context, BeanProperty property) {
        this.valueType = property.getType().containedType(0);
        return this;
    }

    @Override
    public Optional<?> deserialize(final JsonParser parser, final DeserializationContext context) throws IOException {
        final JsonNode node = parser.getCodec().readTree(parser);

        return node.isNull()
                ? Optional.empty()
                : Optional.of(context.readValue(parser, valueType));
    }

}
</code>```

TestDeserialization.kt

```<code>fun main(): {
    val objectMapper = ObjectMapper().registerModule(KotlinModule())

    val module = SimpleModule()
    module.addDeserializer(Optional::class.java, OptionalDeserializer())
    objectMapper.registerModule(module)

    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL)

    objectMapper.configure(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN, true)
    objectMapper.configure(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS, true)
    objectMapper.nodeFactory = JsonNodeFactory.withExactBigDecimals(true)

    val inputJson = """{"foo" : null}"""

    val expectedObject = TestClass(foo = Optional.empty())

    val actualObject = objectMapper.readValue(inputJson, TestClassBravo::class.java)

    assertEquals(expectedObject, actualObject)
}
</code>```

build.gradle (for version info)

```<code>compile 'com.fasterxml.jackson.core:jackson-databind:2.9.8'
compile 'com.fasterxml.jackson.module:jackson-module-kotlin:2.9.8'
</code>```

答:
There are two ways you can handle this.

It would be easier not to use a custom serializer, but rely on the jackson default Jdk8Module (see here)

If you want your custom Deserializer, you need to specify the null access pattern, else the deserializer will not be called for null values:

Code for 2:

```<code>// In OptionalDeserializer

@Override
public AccessPattern getNullAccessPattern() {
    return AccessPattern.CONSTANT;
}
</code>```

Body:
With this data model...

TestClass.kt

data class TestClass (val bar: Optional<Double>?)

My goal is to deserialize the following json values as such:

{"foo": 3.5}  --> foo = 3.5
{"foo": null} --> foo = Optional.empty() // This is currently my problem. foo is null and I can't seem to fix it
{}            --> foo = null

I've seen the solution here and tried this, but the breakpoints in my "deserialize" method never seem to hit.

OptionalDeserializer.java

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import java.io.IOException;
import java.util.Optional;

public class OptionalDeserializer extends JsonDeserializer<Optional<?>> implements ContextualDeserializer {
    private JavaType valueType;

    @Override
    public JsonDeserializer<?> createContextual(DeserializationContext context, BeanProperty property) {
        this.valueType = property.getType().containedType(0);
        return this;
    }

    @Override
    public Optional<?> deserialize(final JsonParser parser, final DeserializationContext context) throws IOException {
        final JsonNode node = parser.getCodec().readTree(parser);

        return node.isNull()
                ? Optional.empty()
                : Optional.of(context.readValue(parser, valueType));
    }

}

TestDeserialization.kt

fun main(): {
    val objectMapper = ObjectMapper().registerModule(KotlinModule())

    val module = SimpleModule()
    module.addDeserializer(Optional::class.java, OptionalDeserializer())
    objectMapper.registerModule(module)

    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL)

    objectMapper.configure(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN, true)
    objectMapper.configure(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS, true)
    objectMapper.nodeFactory = JsonNodeFactory.withExactBigDecimals(true)

    val inputJson = """{"foo" : null}"""

    val expectedObject = TestClass(foo = Optional.empty())

    val actualObject = objectMapper.readValue(inputJson, TestClassBravo::class.java)

    assertEquals(expectedObject, actualObject)
}

build.gradle (for version info)

compile 'com.fasterxml.jackson.core:jackson-databind:2.9.8'
compile 'com.fasterxml.jackson.module:jackson-module-kotlin:2.9.8'

Body:
There are two ways you can handle this.

It would be easier not to use a custom serializer, but rely on the jackson default Jdk8Module (see here)

If you want your custom Deserializer, you need to specify the null access pattern, else the deserializer will not be called for null values:

Code for 2:

// In OptionalDeserializer

@Override
public AccessPattern getNullAccessPattern() {
    return AccessPattern.CONSTANT;
}


答: PHP is a decent templating language itself. Unless there is need for advanced features, custom solutions will only complicate what sounds like a fairly simple setup.</p>

Title: Is it worth learning Smarty for PHP templating?

Body: I'm building a simple 10-page site using an MVC-like architecture. Is it worth learning the Smarty templating engine?


问:
How to configure Varnish in an API-platform project? [Response size limit issue]
Sometimes in my preproduction and production environment, the varnish container send me this error:

```<code>Error (null) Backend fetch failed
Backend fetch failed

Guru Meditation:
XID: (null)
</code>```

This is due to the size of the body response.

So I did implement this test in my Postman test collection:

```<code>pm.test("Size is under 3Ko", function () {
    pm.expect(pm.response.responseSize).to.be.below(3000);
});
</code>```

To be sure that this error does not not appear again.

But I am wondering how can I configure it properly to accept a reasonable size of response?

This my configuration:

Api Platform 2.5.1
  VCL 4.0

答:
Varnish documentation states that the default maximum size of an HTTP response is 32 KB.
You can tune this by setting the http_resp_size runtime parameter.

Here's an example of an increased http_resp_size value:

varnishd -p http_resp_size=1M

If that doesn't help, please share the varnishlog output for that specific page, as well as the associated VCL code.

If you're unsure whether or not your http_resp_size was set to the correct value, you can run the following command on your Varnish server:

```<code>    $ varnishadm param.show http_resp_size
</code>```

Hope this helps.

Body:
Sometimes in my preproduction and production environment, the varnish container send me this error:

Error (null) Backend fetch failed
Backend fetch failed

Guru Meditation:
XID: (null)

This is due to the size of the body response.

So I did implement this test in my Postman test collection:

pm.test("Size is under 3Ko", function () {
    pm.expect(pm.response.responseSize).to.be.below(3000);
});

To be sure that this error does not not appear again.

But I am wondering how can I configure it properly to accept a reasonable size of response?

This my configuration:

Api Platform 2.5.1
  VCL 4.0

Body:
Varnish documentation states that the default maximum size of an HTTP response is 32 KB.
You can tune this by setting the http_resp_size runtime parameter.

Here's an example of an increased http_resp_size value:

varnishd -p http_resp_size=1M

If that doesn't help, please share the varnishlog output for that specific page, as well as the associated VCL code.

If you're unsure whether or not your http_resp_size was set to the correct value, you can run the following command on your Varnish server:

    $ varnishadm param.show http_resp_size

Hope this helps.