问:
Getting error like 'Error eacces mkdir' while run 'npm install -g create-react-app' command
When I try to install reactjs by npm install -g create-react-app command in Ubuntu I am getting an error as following. please help me remove these error.

giving me this error-

```<code>npm ERR! Error: EACCES, mkdir '/home/veomit10/tmp/npm-6710-iquektSI'
npm ERR!  { [Error: EACCES, mkdir '/home/veomit10/tmp/npm-6710-iquektSI']
npm ERR!   errno: 3,
npm ERR!   code: 'EACCES',
npm ERR!   path: '/home/veomit10/tmp/npm-6710-iquektSI' }
npm ERR!
npm ERR! Please try running this command again as root/Administrator.

npm ERR! System Linux 4.4.0-144-generic
npm ERR! command "/usr/bin/nodejs" "/usr/bin/npm" "install" "-g" "react-native-cli"
npm ERR! cwd /home/veomit10/reactApp
npm ERR! node -v v0.10.25
npm ERR! npm -v 1.3.10
npm ERR! path /home/veomit10/tmp/npm-6710-iquektSI
npm ERR! code EACCES
npm ERR! errno 3
npm ERR! stack Error: EACCES, mkdir '/home/veomit10/tmp/npm-6710-iquektSI'
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     /home/veomit10/reactApp/npm-debug.log
npm ERR! not ok code 0
</code>```

Thanks in advance.

答:
it seems you are trying to install it from a non-root user so in this case, you have to have the root permissions in order to install a global node modules.

just try to run commands from the root user, run this first
sudo su

after that run:
npm install -g create-react-app

if you still having error '/usr/bin/env: node: No such file or directory'

try to run this command ln -s /usr/bin/nodejs /usr/bin/node and re install creat-react-app again.

Body:
When I try to install reactjs by npm install -g create-react-app command in Ubuntu I am getting an error as following. please help me remove these error.

giving me this error-

npm ERR! Error: EACCES, mkdir '/home/veomit10/tmp/npm-6710-iquektSI'
npm ERR!  { [Error: EACCES, mkdir '/home/veomit10/tmp/npm-6710-iquektSI']
npm ERR!   errno: 3,
npm ERR!   code: 'EACCES',
npm ERR!   path: '/home/veomit10/tmp/npm-6710-iquektSI' }
npm ERR!
npm ERR! Please try running this command again as root/Administrator.

npm ERR! System Linux 4.4.0-144-generic
npm ERR! command "/usr/bin/nodejs" "/usr/bin/npm" "install" "-g" "react-native-cli"
npm ERR! cwd /home/veomit10/reactApp
npm ERR! node -v v0.10.25
npm ERR! npm -v 1.3.10
npm ERR! path /home/veomit10/tmp/npm-6710-iquektSI
npm ERR! code EACCES
npm ERR! errno 3
npm ERR! stack Error: EACCES, mkdir '/home/veomit10/tmp/npm-6710-iquektSI'
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     /home/veomit10/reactApp/npm-debug.log
npm ERR! not ok code 0

Thanks in advance.


来源: stackexchange

问:
Rotated ImageView edges are not smooth (jagged)
Sample NG ImageView: NG Rotated ImageView

In iOS, i can easily solve this jagged-edges-problem by view.layer.allowsEdgeAntialiasing = true. What is the best way to solve this in Android?

What I already tried:

I referred to this post Bitmap not drawn anti-aliased and set android:layerType="software" but result is still NG.

```<code><ImageView
        android:id="@+id/imageView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layerType="software"
        android:rotation="5"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/pic" />
</code>```

Expected result: smooth (anti-aliased) edges

Actual result: not smooth (jagged) edges

答:
So after experimenting for a while, this is the best that I could achieve:

1) Test output:
NG vs OK

2) NG output source

*xml only (under ConstraintLayout)

```<code><ImageView android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           app:layout_constraintTop_toTopOf="parent"
           app:layout_constraintStart_toStartOf="parent"
           app:layout_constraintEnd_toEndOf="parent"
           app:layout_constraintBottom_toBottomOf="parent"
           android:id="@+id/test3"
           app:srcCompat="@drawable/sampleImg"
           android:rotation="5"/>
</code>```

3) OK output source

*xml (under ConstraintLayout)

```<code><test.ntfry.imageview_rotate_antialias.MyImageView
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           app:layout_constraintTop_toTopOf="parent"
           app:layout_constraintStart_toStartOf="parent"
           app:layout_constraintEnd_toEndOf="parent"
           app:layout_constraintBottom_toBottomOf="parent"
           android:id="@+id/test2"/>
</code>```

*Custom ImageView class

```<code>class MyImageView : AppCompatImageView {

    private val mPaint = Paint(Paint.ANTI_ALIAS_FLAG)
    private val mMatrix = Matrix()
    private var mRotatedBitmap: Bitmap? = null
    private val mRotation = 5F

    constructor(context: Context) : super(context, null) {
        init()
    }
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        init()
    }
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        init()
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        setMeasuredDimension(mRotatedBitmap!!.width, mRotatedBitmap!!.height)
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        canvas?.drawBitmap(mRotatedBitmap!!, 0f, 0f, mPaint)
    }

    private fun init() {
        // https://stackoverflow.com/questions/14378573/bitmap-not-drawn-anti-aliased
        setLayerType(LAYER_TYPE_SOFTWARE, null)

        // get source image and set-apply rotation through matrix
        val sourceBitmap = BitmapFactory.decodeResource(resources, R.drawable.sampleImg)
        mMatrix.postRotate(mRotation)
        mRotatedBitmap = Bitmap.createBitmap(sourceBitmap, 0, 0, sourceBitmap.width, sourceBitmap.height, mMatrix, true)
    }
}
</code>```

4) If you have a better solution, by all means please comment/share your idea! Thanks^^

ContentLicense: CC BY-SA 4.0

Body:
Sample NG ImageView: NG Rotated ImageView

In iOS, i can easily solve this jagged-edges-problem by view.layer.allowsEdgeAntialiasing = true. What is the best way to solve this in Android?

What I already tried:

I referred to this post Bitmap not drawn anti-aliased and set android:layerType="software" but result is still NG.

<ImageView
        android:id="@+id/imageView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layerType="software"
        android:rotation="5"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/pic" />

Expected result: smooth (anti-aliased) edges

Actual result: not smooth (jagged) edges

Body:
So after experimenting for a while, this is the best that I could achieve:

1) Test output:
NG vs OK

2) NG output source

*xml only (under ConstraintLayout)

<ImageView android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           app:layout_constraintTop_toTopOf="parent"
           app:layout_constraintStart_toStartOf="parent"
           app:layout_constraintEnd_toEndOf="parent"
           app:layout_constraintBottom_toBottomOf="parent"
           android:id="@+id/test3"
           app:srcCompat="@drawable/sampleImg"
           android:rotation="5"/>

3) OK output source

*xml (under ConstraintLayout)

<test.ntfry.imageview_rotate_antialias.MyImageView
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           app:layout_constraintTop_toTopOf="parent"
           app:layout_constraintStart_toStartOf="parent"
           app:layout_constraintEnd_toEndOf="parent"
           app:layout_constraintBottom_toBottomOf="parent"
           android:id="@+id/test2"/>

*Custom ImageView class

class MyImageView : AppCompatImageView {

    private val mPaint = Paint(Paint.ANTI_ALIAS_FLAG)
    private val mMatrix = Matrix()
    private var mRotatedBitmap: Bitmap? = null
    private val mRotation = 5F

    constructor(context: Context) : super(context, null) {
        init()
    }
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        init()
    }
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        init()
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        setMeasuredDimension(mRotatedBitmap!!.width, mRotatedBitmap!!.height)
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        canvas?.drawBitmap(mRotatedBitmap!!, 0f, 0f, mPaint)
    }

    private fun init() {
        // https://stackoverflow.com/questions/14378573/bitmap-not-drawn-anti-aliased
        setLayerType(LAYER_TYPE_SOFTWARE, null)

        // get source image and set-apply rotation through matrix
        val sourceBitmap = BitmapFactory.decodeResource(resources, R.drawable.sampleImg)
        mMatrix.postRotate(mRotation)
        mRotatedBitmap = Bitmap.createBitmap(sourceBitmap, 0, 0, sourceBitmap.width, sourceBitmap.height, mMatrix, true)
    }
}

4) If you have a better solution, by all means please comment/share your idea! Thanks^^


问:
Google Play Developer API - "The current user has insufficient permissions to perform the requested operation."
I have a Google dev console process with Google Play Developer API is enabled and the project is linked to Google Play project.
In Google Dev console project, created OAuth Client ID (web application) (I'm an owner of the project). Using "client_id" and "client_secret" to authenticate.
Tried to using google-api-client in Python, Google Developer API Playground to send request to list reviews of our apps but got error: "The current user has insufficient permissions to perform the requested operation."
Details as below:
Request:

```<code>GET /androidpublisher/v2/applications/<package_name>/reviews
</code>```

Response:

```<code>"error": {
    "code": 401,
    "message": "The current user has insufficient permissions to perform the requested operation.",
    "errors": [
      {
        "domain": "androidpublisher",
        "message": "The current user has insufficient permissions to perform the requested operation.",
        "reason": "permissionDenied"
      }
    ]
  }
}
</code>```

Did I miss anything?

答:
I looked everywhere on the internet and found somewhere that you might need to wait for at least 24 hours.

Ensure you have done everything correctly as below.

Go to https://console.cloud.google.com

Create a project (or select existing project)

Create a service account with role Pub/Sub Admin

Go to https://console.cloud.google.com/apis/library and search for "Google Play Android Developer API"

Enable that API

Go to https://play.google.com/apps/publish

Go to Settings > Developer account > API Access

Link the project that you created in step 2

The service account will appear that you created in step 3

Grant access to it with Finance permission to the app in play console

Very important: Wait for at least 24 hours for changes to take effect.

ContentLicense: CC BY-SA 3.0

Body:
I have a Google dev console process with Google Play Developer API is enabled and the project is linked to Google Play project.
In Google Dev console project, created OAuth Client ID (web application) (I'm an owner of the project). Using "client_id" and "client_secret" to authenticate.
Tried to using google-api-client in Python, Google Developer API Playground to send request to list reviews of our apps but got error: "The current user has insufficient permissions to perform the requested operation."
Details as below:
Request:

GET /androidpublisher/v2/applications/<package_name>/reviews

Response:

"error": {
    "code": 401,
    "message": "The current user has insufficient permissions to perform the requested operation.",
    "errors": [
      {
        "domain": "androidpublisher",
        "message": "The current user has insufficient permissions to perform the requested operation.",
        "reason": "permissionDenied"
      }
    ]
  }
}

Did I miss anything?


问:
How can assigning a variable result in a serious performance drop while the execution order is (nearly) untouched?
When playing around with multithreading, I could observe some unexpected but serious performance issues related to AtomicLong (and classes using it, such as java.util.Random), for which I currently have no explanation. However, I created a minimalistic example, which basically consists of two classes: a class "Container", which keeps a reference to a volatile variable, and a class "DemoThread", which operates on an instance of "Container" during thread execution. Note that the references to "Container" and the volatile long are private, and never shared between threads (I know that there's no need to use volatile here, it's just for demonstration purposes) - thus, multiple instances of "DemoThread" should run perfectly parallel on a multiprocessor machine, but for some reason, they do not (Complete example is at the bottom of this post).

```<code>private static class Container  {

    private volatile long value;

    public long getValue() {
        return value;
    }

    public final void set(long newValue) {
        value = newValue;
    }
}

private static class DemoThread extends Thread {

    private Container variable;

    public void prepare() {
        this.variable = new Container();
    }

    public void run() {
        for(int j = 0; j < 10000000; j++) {
            variable.set(variable.getValue() + System.nanoTime());
        }
    }
}
</code>```

During my test, I repeatedly create 4 DemoThreads, which are then started and joined. The only difference in each loop is the time when "prepare()" gets called (which is obviously required for the thread to run, as it otherwise would result in a NullPointerException):

```<code>DemoThread[] threads = new DemoThread[numberOfThreads];
    for(int j = 0; j < 100; j++) {
        boolean prepareAfterConstructor = j % 2 == 0;
        for(int i = 0; i < threads.length; i++) {
            threads[i] = new DemoThread();
            if(prepareAfterConstructor) threads[i].prepare();
        }

        for(int i = 0; i < threads.length; i++) {
            if(!prepareAfterConstructor) threads[i].prepare();
            threads[i].start();
        }
        joinThreads(threads);
    }
</code>```

For some reason, if prepare() is executed immediately before starting the thread, it will take twice as more time to finish, and even without the "volatile" keyword, the performance differences were significant, at  least on two of the machines and OS'es I tested the code. Here's a short summary:

Mac OS Summary:

Java Version: 1.6.0_24

Java Class Version: 50.0

VM Vendor: Sun Microsystems Inc.

VM Version: 19.1-b02-334

VM Name: Java HotSpot(TM) 64-Bit Server VM

OS Name: Mac OS X

OS Arch: x86_64

OS Version: 10.6.5

Processors/Cores: 8

With volatile keyword:

Final results:

31979 ms. when prepare() was called after instantiation.

96482 ms. when prepare() was called before execution.

Without volatile keyword:

Final results:

26009 ms. when prepare() was called after instantiation.

35196 ms. when prepare() was called before execution.

Windows Summary:

Java Version: 1.6.0_24

Java Class Version: 50.0

VM Vendor: Sun Microsystems Inc.

VM Version: 19.1-b02

VM Name: Java HotSpot(TM) 64-Bit Server VM

OS Name: Windows 7

OS Arch: amd64

OS Version: 6.1

Processors/Cores: 4

With volatile keyword:

Final results:

18120 ms. when prepare() was called after instantiation.

36089 ms. when prepare() was called before execution.

Without volatile keyword:

Final results:

10115 ms. when prepare() was called after instantiation.

10039 ms. when prepare() was called before execution.

Linux Summary:

Java Version: 1.6.0_20

Java Class Version: 50.0

VM Vendor: Sun Microsystems Inc.

VM Version: 19.0-b09

VM Name: OpenJDK 64-Bit Server VM

OS Name: Linux

OS Arch: amd64

OS Version: 2.6.32-28-generic

Processors/Cores: 4

With volatile keyword:

Final results:

45848 ms. when prepare() was called after instantiation.

110754 ms. when prepare() was called before execution.

Without volatile keyword:

Final results:

37862 ms. when prepare() was called after instantiation.

39357 ms. when prepare() was called before execution.

Mac OS Details (volatile):

Test 1, 4 threads, setting variable in creation loop

Thread-2 completed after 653 ms.

Thread-3 completed after 653 ms.

Thread-4 completed after 653 ms.

Thread-5 completed after 653 ms.

Overall time: 654 ms.

Test 2, 4 threads, setting variable in start loop

Thread-7 completed after 1588 ms.

Thread-6 completed after 1589 ms.

Thread-8 completed after 1593 ms.

Thread-9 completed after 1593 ms.

Overall time: 1594 ms.

Test 3, 4 threads, setting variable in creation loop

Thread-10 completed after 648 ms.

Thread-12 completed after 648 ms.

Thread-13 completed after 648 ms.

Thread-11 completed after 648 ms.

Overall time: 648 ms.

Test 4, 4 threads, setting variable in start loop

Thread-17 completed after 1353 ms.

Thread-16 completed after 1957 ms.

Thread-14 completed after 2170 ms.

Thread-15 completed after 2169 ms.

Overall time: 2172 ms.

(and so on, sometimes one or two of the threads in the 'slow' loop finish as expected, but most times they don't).

The given example looks theoretically, as it is of no use, and 'volatile' is not needed here - however, if you'd use a 'java.util.Random'-Instance instead of the 'Container'-Class and call, for instance, nextInt() multiple times, the same effects will occur: The thread will be executed fast if you create the object in the Thread's constructor, but slow if you create it within the run()-method. I believe that the performance issues described in Java Random Slowdowns on Mac OS more than a year ago are related to this effect, but I have no idea why it is as it is - besides that I'm sure that it shouldn't be like that, as it would mean that it's always dangerous to create a new object within the run-method of a thread, unless you know that no volatile variables will get involved within the object graph. Profiling doesn't help, as the problem disappears in this case (same observation as in Java Random Slowdowns on Mac OS cont'd), and it also does not happen on a single-core-PC - so I'd guess that it's kind of a thread synchronization problem... however, the strange thing is that there's actually nothing to synchronize, as all variables are thread-local.

Really looking forward for any hints - and just in case you want to confirm or falsify the problem, see the test case below.

Thanks,

Stephan

```<code>public class UnexpectedPerformanceIssue {

private static class Container  {

    // Remove the volatile keyword, and the problem disappears (on windows)
    // or gets smaller (on mac os)
    private volatile long value;

    public long getValue() {
        return value;
    }

    public final void set(long newValue) {
        value = newValue;
    }
}

private static class DemoThread extends Thread {

    private Container variable;

    public void prepare() {
        this.variable = new Container();
    }

    @Override
    public void run() {
        long start = System.nanoTime();
        for(int j = 0; j < 10000000; j++) {
            variable.set(variable.getValue() + System.nanoTime());
        }
        long end = System.nanoTime();
        System.out.println(this.getName() + " completed after "
                +  ((end - start)/1000000) + " ms.");
    }
}

public static void main(String[] args) {
    System.out.println("Java Version: " + System.getProperty("java.version"));
    System.out.println("Java Class Version: " + System.getProperty("java.class.version"));

    System.out.println("VM Vendor: " + System.getProperty("java.vm.specification.vendor"));
    System.out.println("VM Version: " + System.getProperty("java.vm.version"));
    System.out.println("VM Name: " + System.getProperty("java.vm.name"));

    System.out.println("OS Name: " + System.getProperty("os.name"));
    System.out.println("OS Arch: " + System.getProperty("os.arch"));
    System.out.println("OS Version: " + System.getProperty("os.version"));
    System.out.println("Processors/Cores: " + Runtime.getRuntime().availableProcessors());

    System.out.println();
    int numberOfThreads = 4;

    System.out.println("\nReference Test (single thread):");
    DemoThread t = new DemoThread();
    t.prepare();
    t.run();

    DemoThread[] threads = new DemoThread[numberOfThreads];
    long createTime = 0, startTime = 0;
    for(int j = 0; j < 100; j++) {
        boolean prepareAfterConstructor = j % 2 == 0;
        long overallStart = System.nanoTime();
        if(prepareAfterConstructor) {
            System.out.println("\nTest " + (j+1) + ", " + numberOfThreads + " threads, setting variable in creation loop");
        } else {
            System.out.println("\nTest " + (j+1) + ", " + numberOfThreads + " threads, setting variable in start loop");
        }

        for(int i = 0; i < threads.length; i++) {
            threads[i] = new DemoThread();
            // Either call DemoThread.prepare() here (in odd loops)...
            if(prepareAfterConstructor) threads[i].prepare();
        }

        for(int i = 0; i < threads.length; i++) {
            // or here (in even loops). Should make no difference, but does!
            if(!prepareAfterConstructor) threads[i].prepare();
            threads[i].start();
        }
        joinThreads(threads);
        long overallEnd = System.nanoTime();
        long overallTime = (overallEnd - overallStart);
        if(prepareAfterConstructor) {
            createTime += overallTime;
        } else {
            startTime += overallTime;
        }
        System.out.println("Overall time: " + (overallTime)/1000000 + " ms.");
    }
    System.out.println("Final results:");
    System.out.println(createTime/1000000 + " ms. when prepare() was called after instantiation.");
    System.out.println(startTime/1000000 + " ms. when prepare() was called before execution.");
}

private static void joinThreads(Thread[] threads) {
    for(int i = 0; i < threads.length; i++) {
        try {
            threads[i].join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
</code>```

}

答:
Well, you're writing to a volatile variable, so I suspect that's forcing a memory barrier - undoing some optimization which can otherwise be achieved. The JVM doesn't know that that particular field isn't going to be observed on another thread.

EDIT: As noted, there are problems with the benchmark itself, such as printing while the timer is running. Also, it's usually a good idea to "warm up" the JIT before starting timing - otherwise you're measuring time which wouldn't be significant in a normal long-running process.

Body:
When playing around with multithreading, I could observe some unexpected but serious performance issues related to AtomicLong (and classes using it, such as java.util.Random), for which I currently have no explanation. However, I created a minimalistic example, which basically consists of two classes: a class "Container", which keeps a reference to a volatile variable, and a class "DemoThread", which operates on an instance of "Container" during thread execution. Note that the references to "Container" and the volatile long are private, and never shared between threads (I know that there's no need to use volatile here, it's just for demonstration purposes) - thus, multiple instances of "DemoThread" should run perfectly parallel on a multiprocessor machine, but for some reason, they do not (Complete example is at the bottom of this post).

private static class Container  {

    private volatile long value;

    public long getValue() {
        return value;
    }

    public final void set(long newValue) {
        value = newValue;
    }
}

private static class DemoThread extends Thread {

    private Container variable;

    public void prepare() {
        this.variable = new Container();
    }

    public void run() {
        for(int j = 0; j < 10000000; j++) {
            variable.set(variable.getValue() + System.nanoTime());
        }
    }
}

During my test, I repeatedly create 4 DemoThreads, which are then started and joined. The only difference in each loop is the time when "prepare()" gets called (which is obviously required for the thread to run, as it otherwise would result in a NullPointerException):

DemoThread[] threads = new DemoThread[numberOfThreads];
    for(int j = 0; j < 100; j++) {
        boolean prepareAfterConstructor = j % 2 == 0;
        for(int i = 0; i < threads.length; i++) {
            threads[i] = new DemoThread();
            if(prepareAfterConstructor) threads[i].prepare();
        }

        for(int i = 0; i < threads.length; i++) {
            if(!prepareAfterConstructor) threads[i].prepare();
            threads[i].start();
        }
        joinThreads(threads);
    }

For some reason, if prepare() is executed immediately before starting the thread, it will take twice as more time to finish, and even without the "volatile" keyword, the performance differences were significant, at  least on two of the machines and OS'es I tested the code. Here's a short summary:

Mac OS Summary:

Java Version: 1.6.0_24

Java Class Version: 50.0

VM Vendor: Sun Microsystems Inc.

VM Version: 19.1-b02-334

VM Name: Java HotSpot(TM) 64-Bit Server VM

OS Name: Mac OS X

OS Arch: x86_64

OS Version: 10.6.5

Processors/Cores: 8

With volatile keyword:

Final results:

31979 ms. when prepare() was called after instantiation.

96482 ms. when prepare() was called before execution.

Without volatile keyword:

Final results:

26009 ms. when prepare() was called after instantiation.

35196 ms. when prepare() was called before execution.

Windows Summary:

Java Version: 1.6.0_24

Java Class Version: 50.0

VM Vendor: Sun Microsystems Inc.

VM Version: 19.1-b02

VM Name: Java HotSpot(TM) 64-Bit Server VM

OS Name: Windows 7

OS Arch: amd64

OS Version: 6.1

Processors/Cores: 4

With volatile keyword:

Final results:

18120 ms. when prepare() was called after instantiation.

36089 ms. when prepare() was called before execution.

Without volatile keyword:

Final results:

10115 ms. when prepare() was called after instantiation.

10039 ms. when prepare() was called before execution.

Linux Summary:

Java Version: 1.6.0_20

Java Class Version: 50.0

VM Vendor: Sun Microsystems Inc.

VM Version: 19.0-b09

VM Name: OpenJDK 64-Bit Server VM

OS Name: Linux

OS Arch: amd64

OS Version: 2.6.32-28-generic

Processors/Cores: 4

With volatile keyword:

Final results:

45848 ms. when prepare() was called after instantiation.

110754 ms. when prepare() was called before execution.

Without volatile keyword:

Final results:

37862 ms. when prepare() was called after instantiation.

39357 ms. when prepare() was called before execution.

Mac OS Details (volatile):

Test 1, 4 threads, setting variable in creation loop

Thread-2 completed after 653 ms.

Thread-3 completed after 653 ms.

Thread-4 completed after 653 ms.

Thread-5 completed after 653 ms.

Overall time: 654 ms.

Test 2, 4 threads, setting variable in start loop

Thread-7 completed after 1588 ms.

Thread-6 completed after 1589 ms.

Thread-8 completed after 1593 ms.

Thread-9 completed after 1593 ms.

Overall time: 1594 ms.

Test 3, 4 threads, setting variable in creation loop

Thread-10 completed after 648 ms.

Thread-12 completed after 648 ms.

Thread-13 completed after 648 ms.

Thread-11 completed after 648 ms.

Overall time: 648 ms.

Test 4, 4 threads, setting variable in start loop

Thread-17 completed after 1353 ms.

Thread-16 completed after 1957 ms.

Thread-14 completed after 2170 ms.

Thread-15 completed after 2169 ms.

Overall time: 2172 ms.

(and so on, sometimes one or two of the threads in the 'slow' loop finish as expected, but most times they don't).

The given example looks theoretically, as it is of no use, and 'volatile' is not needed here - however, if you'd use a 'java.util.Random'-Instance instead of the 'Container'-Class and call, for instance, nextInt() multiple times, the same effects will occur: The thread will be executed fast if you create the object in the Thread's constructor, but slow if you create it within the run()-method. I believe that the performance issues described in Java Random Slowdowns on Mac OS more than a year ago are related to this effect, but I have no idea why it is as it is - besides that I'm sure that it shouldn't be like that, as it would mean that it's always dangerous to create a new object within the run-method of a thread, unless you know that no volatile variables will get involved within the object graph. Profiling doesn't help, as the problem disappears in this case (same observation as in Java Random Slowdowns on Mac OS cont'd), and it also does not happen on a single-core-PC - so I'd guess that it's kind of a thread synchronization problem... however, the strange thing is that there's actually nothing to synchronize, as all variables are thread-local.

Really looking forward for any hints - and just in case you want to confirm or falsify the problem, see the test case below.

Thanks,

Stephan

public class UnexpectedPerformanceIssue {

private static class Container  {

    // Remove the volatile keyword, and the problem disappears (on windows)
    // or gets smaller (on mac os)
    private volatile long value;

    public long getValue() {
        return value;
    }

    public final void set(long newValue) {
        value = newValue;
    }
}

private static class DemoThread extends Thread {

    private Container variable;

    public void prepare() {
        this.variable = new Container();
    }

    @Override
    public void run() {
        long start = System.nanoTime();
        for(int j = 0; j < 10000000; j++) {
            variable.set(variable.getValue() + System.nanoTime());
        }
        long end = System.nanoTime();
        System.out.println(this.getName() + " completed after "
                +  ((end - start)/1000000) + " ms.");
    }
}

public static void main(String[] args) {
    System.out.println("Java Version: " + System.getProperty("java.version"));
    System.out.println("Java Class Version: " + System.getProperty("java.class.version"));

    System.out.println("VM Vendor: " + System.getProperty("java.vm.specification.vendor"));
    System.out.println("VM Version: " + System.getProperty("java.vm.version"));
    System.out.println("VM Name: " + System.getProperty("java.vm.name"));

    System.out.println("OS Name: " + System.getProperty("os.name"));
    System.out.println("OS Arch: " + System.getProperty("os.arch"));
    System.out.println("OS Version: " + System.getProperty("os.version"));
    System.out.println("Processors/Cores: " + Runtime.getRuntime().availableProcessors());

    System.out.println();
    int numberOfThreads = 4;

    System.out.println("\nReference Test (single thread):");
    DemoThread t = new DemoThread();
    t.prepare();
    t.run();

    DemoThread[] threads = new DemoThread[numberOfThreads];
    long createTime = 0, startTime = 0;
    for(int j = 0; j < 100; j++) {
        boolean prepareAfterConstructor = j % 2 == 0;
        long overallStart = System.nanoTime();
        if(prepareAfterConstructor) {
            System.out.println("\nTest " + (j+1) + ", " + numberOfThreads + " threads, setting variable in creation loop");
        } else {
            System.out.println("\nTest " + (j+1) + ", " + numberOfThreads + " threads, setting variable in start loop");
        }

        for(int i = 0; i < threads.length; i++) {
            threads[i] = new DemoThread();
            // Either call DemoThread.prepare() here (in odd loops)...
            if(prepareAfterConstructor) threads[i].prepare();
        }

        for(int i = 0; i < threads.length; i++) {
            // or here (in even loops). Should make no difference, but does!
            if(!prepareAfterConstructor) threads[i].prepare();
            threads[i].start();
        }
        joinThreads(threads);
        long overallEnd = System.nanoTime();
        long overallTime = (overallEnd - overallStart);
        if(prepareAfterConstructor) {
            createTime += overallTime;
        } else {
            startTime += overallTime;
        }
        System.out.println("Overall time: " + (overallTime)/1000000 + " ms.");
    }
    System.out.println("Final results:");
    System.out.println(createTime/1000000 + " ms. when prepare() was called after instantiation.");
    System.out.println(startTime/1000000 + " ms. when prepare() was called before execution.");
}

private static void joinThreads(Thread[] threads) {
    for(int i = 0; i < threads.length; i++) {
        try {
            threads[i].join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

}


问:
How to set Gradient color background between two thumbs in range seek bar?
I am setting a MultiSlider, and I put it using "io.apptik.widget:multislider-holo:1.3" this gradle but now I want to put its color as gradient in my layout but I can't put background on thumbColor. So is there any way to fix this issue?

I tried to put the drawable in thumbColor, but it is not working and I can only put one color. But I want to put different color at both ends.

```<code><io.apptik.widget.MultiSlider

              //here i want to put the gradient color
                app:thumbColor="@drawable/abbbb"

                app:thumbNumber="2" />
</code>```

答:
Check out this library.

Just add it's code to your XML file

Body:
I am setting a MultiSlider, and I put it using "io.apptik.widget:multislider-holo:1.3" this gradle but now I want to put its color as gradient in my layout but I can't put background on thumbColor. So is there any way to fix this issue?

I tried to put the drawable in thumbColor, but it is not working and I can only put one color. But I want to put different color at both ends.

<io.apptik.widget.MultiSlider

              //here i want to put the gradient color
                app:thumbColor="@drawable/abbbb"

                app:thumbNumber="2" />


问:
How to update vue2-frappe chart?
I've been breaking my head over this for the last few hours and no matter where I look I can't seem to find the answer.

I'm using vue2-frappe as my chart library. I'm using a simple bar chart to display certain values by day. Everything was fine until my higher-ups decided they wanted to show a whole year's worth of values on this chart, meaning I have to add some pagination to it.

The problem is, now I can't figure out how to make the chart rerender. I've tried replacing the entire object I've bound the chart to, as well as manipulating specific values, but nothing seems to make the component rerender.

In the documentation for frappe.js, you can modify data via specific methods, but this being Vue I can't just call chart.update() like in normal .js. And if I inspect the component via vue dev tools, I can see it contains the modified data, it just doesn't redraw itself.

Anyone have an idea what to do?

答:
I would try to force update the view component.

VueJs reactivity can sometimes be confusing where you think it should react to changes but it doesn't.

You can force a view update like so:

```<code>// Globally
import Vue from 'vue';
Vue.forceUpdate();

// Using the component instance
export default {
    methods: {
        methodThatForcesUpdate() {
        // ...
        this.$forceUpdate();  // Notice we have to use a $ here
        // ...
    }
  }
}
</code>```

You can read about correct ways of re-rendering here: https://michaelnthiessen.com/force-re-render

There are caveats to this approach as outlined in vueJs's docs: https://v2.vuejs.org/v2/guide/list.html#Caveats

Note #

A force re-render wont update computed values, but your computed property shouldn't contain any external non-reactive variable anyway.

Note 2
The above article written by Michael Thiessen also states the best way in his opinion is key-changing which I think we all should be aware of.

I hope this puts you on the right track. It sounds like (with limited information) you could be replacing the data but using the same key.

Title: How to update vue2-frappe chart?

Body:
I would try to force update the view component.

VueJs reactivity can sometimes be confusing where you think it should react to changes but it doesn't.

You can force a view update like so:

// Globally
import Vue from 'vue';
Vue.forceUpdate();

// Using the component instance
export default {
    methods: {
        methodThatForcesUpdate() {
        // ...
        this.$forceUpdate();  // Notice we have to use a $ here
        // ...
    }
  }
}

You can read about correct ways of re-rendering here: https://michaelnthiessen.com/force-re-render

There are caveats to this approach as outlined in vueJs's docs: https://v2.vuejs.org/v2/guide/list.html#Caveats

Note #

A force re-render wont update computed values, but your computed property shouldn't contain any external non-reactive variable anyway.

Note 2
The above article written by Michael Thiessen also states the best way in his opinion is key-changing which I think we all should be aware of.

I hope this puts you on the right track. It sounds like (with limited information) you could be replacing the data but using the same key.


问:
Gaussian Mixture Models for pixel clustering
I have a small set of aerial images where different terrains visible in the image have been have been labelled by human experts. For example, an image may contain vegetation, river, rocky mountains, farmland etc. Each image may have one or more of these labelled regions. Using this small labeled dataset, I would like to fit a gaussian mixture model for each of the known terrain types. After this is complete, I would have N number of GMMs for each N types of terrains that I might encounter in an image.

Now, given a new image, I would like to determine for each pixel, which terrain it belongs to by assigning the pixel to the most probable GMM.
Is this the correct line of thought ? And if yes, how can I go about clustering an image using GMMs

答:
Its not clustering if you use labeled training data!

You can, however, use the labeling function of GMM clustering easily.

For this, compute the prior probabilities, mean and covariance matrixes, invert them. Then classify each pixel of the new image by the maximum probability density (weighted by prior probabilities) using the multivariate Gaussians from the training data.


问:
How to remove single quote of a string in a list
When String variable is included in list, it is having the single quote. I do not require that.

Tried to convert datatype. But, getting error while converting.

```<code>Table = 'temp'
ID = """(SELECT Contents FROM %s)""" % (Table)

list = [ID, 'test', 'new']

print(list)
</code>```

Expected Result:

```<code>[(SELECT Contents FROM temp), 'test', 'new']
</code>```

Actual Result:

```<code>['(SELECT Contents FROM temp)', 'test', 'new']
</code>```

答:
When you directly print a list, it encloses string types in quotes, and the entire list in [ ]. So you will have to manually construct a string for your specific output. Also, please avoid naming variables with the name of their class (list).

```<code>op = '[' + list[0] + ', ' + str(list[1:])[1:-1] + ']'
print(op)
# [(SELECT Contents FROM temp), 'test', 'new']
</code>```

To explain, taking the first item directly as a string means it will not have quotes. For the rest, I cast the slice of the list into a string (thus the items will have quotes), and then used [1:-1] to remove the first and last characters which were the enclosing [ ].

Body:
When String variable is included in list, it is having the single quote. I do not require that.

Tried to convert datatype. But, getting error while converting.

Table = 'temp'
ID = """(SELECT Contents FROM %s)""" % (Table)

list = [ID, 'test', 'new']

print(list)

Expected Result:

[(SELECT Contents FROM temp), 'test', 'new']

Actual Result:

['(SELECT Contents FROM temp)', 'test', 'new']

Body:
When you directly print a list, it encloses string types in quotes, and the entire list in [ ]. So you will have to manually construct a string for your specific output. Also, please avoid naming variables with the name of their class (list).

op = '[' + list[0] + ', ' + str(list[1:])[1:-1] + ']'
print(op)
# [(SELECT Contents FROM temp), 'test', 'new']

To explain, taking the first item directly as a string means it will not have quotes. For the rest, I cast the slice of the list into a string (thus the items will have quotes), and then used [1:-1] to remove the first and last characters which were the enclosing [ ].


问:
How to get next n days date from the given date
I am able to next 15 days date from current date, but when i tried to give custom date instead of current date, it not working.

```<code> let date = sharedAppDelegate.dueDate
 let givenDate = Utility.convertStringToDate(format: "yyyy-MM-dd",
dateString: date)

let futureDate = (givenDate as NSCalendar).date(byAdding: dateComponents, to: Date()) ?? Date()
</code>```

Third line gives error like Date? is not convertible to NSCalendar.
Expected result:- futureDate should be next 15 date from givenDate

答:
A Date is not a Calendar

You can use the Calendar to do calculations or comparisons on Date objects, in your case you want to use the Calendar to add x number of days to your starting date

Try

```<code>let startDate = Date()
let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: startDate)

print(tomorrow)
</code>```

OUTPUT:

Optional(2019-06-01 07:14:48 +0000)

Body:
I am able to next 15 days date from current date, but when i tried to give custom date instead of current date, it not working.

 let date = sharedAppDelegate.dueDate
 let givenDate = Utility.convertStringToDate(format: "yyyy-MM-dd",
dateString: date)

let futureDate = (givenDate as NSCalendar).date(byAdding: dateComponents, to: Date()) ?? Date()

Third line gives error like Date? is not convertible to NSCalendar.
Expected result:- futureDate should be next 15 date from givenDate

Body:
A Date is not a Calendar

You can use the Calendar to do calculations or comparisons on Date objects, in your case you want to use the Calendar to add x number of days to your starting date

Try

let startDate = Date()
let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: startDate)

print(tomorrow)

OUTPUT:

Optional(2019-06-01 07:14:48 +0000)


问:
WKWebView not opening URL with devanagari font in URL
I am trying to integrate a payment gateway integration of a bank. But the WKWebView doesn't load the URL.

The URL which I am trying to load in WKWebView is

Here is URL:
http://www.mpenagarpalika.gov.in/EasyPay20/EncDataPage.jsp?copr_id=3163&requestId=XXXX&customerRefNo=XXXX&amount=3937.000&version=1.0&type=PRD&currency=INR&returnURL=http%3a%2f%2fwww.mpenagarpalika.gov.in%2fwt_easypay1res%2fgetdecrypt&prePopulatedInfo=1000000001%7c0274%7cW10000011447%7cINR%7c3937.000&reserveField1=MN&reserveField2=WTax&reserveField3=Water_Tax&reserveField4=समीम&reserveField5=वार्ड%20क्र%2006%20%20जवाहरलाल&bankReferenceNumber=W10000011447&fromSenderIP=99.199.255.199

When I try to run the same URL on laptop browser then it's working fine.

I have tried these options:

```<code>let hiturl = paymentPageURL.addingPercentEncoding(withAllowedCharacters: CharacterSet(charactersIn: "!*'();:@&=+$,/?%#[]{} ").inverted)

let hiturl = paymentPageURL.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
</code>```

What am I doing wrong?

答:
I just bring a tested solution for you. Please try below code:

```<code>let sampleURL = "http://www.mpenagarpalika.gov.in/EasyPay20/EncDataPage.jsp?copr_id=3163&requestId=XXXX&customerRefNo=XXXX&amount=3937.000&version=1.0&type=PRD&currency=INR&returnURL=http%3a%2f%2fwww.mpenagarpalika.gov.in%2fwt_easypay1res%2fgetdecrypt&prePopulatedInfo=1000000001%7c0274%7cW10000011447%7cINR%7c3937.000&reserveField1=MN&reserveField2=WTax&reserveField3=Water_Tax&reserveField4=समीम&reserveField5=वार्ड%20क्र%2006%20%20जवाहरलाल&bankReferenceNumber=W10000011447&fromSenderIP=99.199.255.199/"

if let encoded = urlString.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed),
            let myURL = URL(string: encoded)
        {
            print(myURL)
            let myRequest = URLRequest(url: myURL)
            myWebView.load(myRequest)
        }
</code>```

And one more important thing, please don't forget to add below lines in info.plist for lazy loading, otherwise WKWebView can't able to load the url.

```<code><key>NSAppTransportSecurity</key>
<dict>
  <!--Include to allow all connections (DANGER)-->
  <key>NSAllowsArbitraryLoads</key>
      <true/>
</dict>
</code>```

Body:
I am trying to integrate a payment gateway integration of a bank. But the WKWebView doesn't load the URL.

The URL which I am trying to load in WKWebView is

Here is URL:
<a href="http://www.mpenagarpalika.gov.in/EasyPay20/EncDataPage.jsp?copr_id=3163&requestId=XXXX&customerRefNo=XXXX&amount=3937.000&version=1.0&type=PRD&currency=INR&returnURL=http%3a%2f%2fwww.mpenagarpalika.gov.in%2fwt_easypay1res%2fgetdecrypt&prePopulatedInfo=1000000001%7c0274%7cW10000011447%7cINR%7c3937.000&reserveField1=MN&reserveField2=WTax&reserveField3=Water_Tax&reserveField4=%E0%A4%B8%E0%A4%AE%E0%A5%80%E0%A4%AE&reserveField5=%E0%A4%B5%E0%A4%BE%E0%A4%B0%E0%A5%8D%E0%A4%A1%20%E0%A4%95%E0%A5%8D%E0%A4%B0%2006%20%20%E0%A4%9C%E0%A4%B5%E0%A4%BE%E0%A4%B9%E0%A4%B0%E0%A4%B2%E0%A4%BE%E0%A4%B2&bankReferenceNumber=W10000011447&fromSenderIP=99.199.255.199" rel="nofollow noreferrer">http://www.mpenagarpalika.gov.in/EasyPay20/EncDataPage.jsp?copr_id=3163&requestId=XXXX&customerRefNo=XXXX&amount=3937.000&version=1.0&type=PRD&currency=INR&returnURL=http%3a%2f%2fwww.mpenagarpalika.gov.in%2fwt_easypay1res%2fgetdecrypt&prePopulatedInfo=1000000001%7c0274%7cW10000011447%7cINR%7c3937.000&reserveField1=MN&reserveField2=WTax&reserveField3=Water_Tax&reserveField4=समीम&reserveField5=वार्ड%20क्र%2006%20%20जवाहरलाल&bankReferenceNumber=W10000011447&fromSenderIP=99.199.255.199

When I try to run the same URL on laptop browser then it's working fine.

I have tried these options:

let hiturl = paymentPageURL.addingPercentEncoding(withAllowedCharacters: CharacterSet(charactersIn: "!*'();:@&=+$,/?%#[]{} ").inverted)

let hiturl = paymentPageURL.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)

What am I doing wrong?

Body:
I just bring a tested solution for you. Please try below code:

let sampleURL = "http://www.mpenagarpalika.gov.in/EasyPay20/EncDataPage.jsp?copr_id=3163&requestId=XXXX&customerRefNo=XXXX&amount=3937.000&version=1.0&type=PRD&currency=INR&returnURL=http%3a%2f%2fwww.mpenagarpalika.gov.in%2fwt_easypay1res%2fgetdecrypt&prePopulatedInfo=1000000001%7c0274%7cW10000011447%7cINR%7c3937.000&reserveField1=MN&reserveField2=WTax&reserveField3=Water_Tax&reserveField4=समीम&reserveField5=वार्ड%20क्र%2006%20%20जवाहरलाल&bankReferenceNumber=W10000011447&fromSenderIP=99.199.255.199/"

if let encoded = urlString.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed),
            let myURL = URL(string: encoded)
        {
            print(myURL)
            let myRequest = URLRequest(url: myURL)
            myWebView.load(myRequest)
        }

And one more important thing, please don't forget to add below lines in info.plist for lazy loading, otherwise WKWebView can't able to load the url.

<key>NSAppTransportSecurity</key>
<dict>
  <!--Include to allow all connections (DANGER)-->
  <key>NSAllowsArbitraryLoads</key>
      <true/>
</dict>


问:
Retrieve part of a string from a full text
I hve a string variable which contains a text along with some dates in it. Now I would like to retrieve the date from the text. How I can do it.

```<code>String a ="I am ready at time -S 2019-06-16:00:00:00 and be there"
</code>```

Now I would like to retrieve 2019-06-16:00:00:00 from there. Date format will always be in the same format but I need to retrieve the date only from the text.

答:
Try using a regex matcher with the pattern:

```<code>\d{4}-\d{2}-\d{2}:\d{2}:\d{2}:\d{2}
</code>```

Sample code:

```<code>String a = "I am ready at time -S 2019-06-16:00:00:00 and be there";
String pattern = "\\d{4}-\\d{2}-\\d{2}:\\d{2}:\\d{2}:\\d{2}";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(a);
while (m.find()) {
     System.out.println("found a timestamp: " + m.group(0));
}
</code>```

Body:
I hve a string variable which contains a text along with some dates in it. Now I would like to retrieve the date from the text. How I can do it.

String a ="I am ready at time -S 2019-06-16:00:00:00 and be there"

Now I would like to retrieve 2019-06-16:00:00:00 from there. Date format will always be in the same format but I need to retrieve the date only from the text.

Body:
Try using a regex matcher with the pattern:

\d{4}-\d{2}-\d{2}:\d{2}:\d{2}:\d{2}

Sample code:

String a = "I am ready at time -S 2019-06-16:00:00:00 and be there";
String pattern = "\\d{4}-\\d{2}-\\d{2}:\\d{2}:\\d{2}:\\d{2}";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(a);
while (m.find()) {
     System.out.println("found a timestamp: " + m.group(0));
}


问:
Git History both rewritten and unchanged?
So I let Git rewrite history in all my branches over night, and when I looked for the results, I saw this:

```<code>      E:\zeus>git filter-branch -f --tree-filter "rm -rf ZeusSRC_Hardware_RPi_image_Raspberry Pi_außen_20.05.2019.zip" --prune-empty -- --all
      Rewrite fa2be75c64ca78a296c8f78fc363beebecbf92a1 (1526/1526) (2745 seconds passed, remaining 0 predicted)
      Ref 'refs/heads/Kunden' was rewritten
      Ref 'refs/heads/Sensor' was rewritten
      Ref 'refs/heads/Wetter' was rewritten
      Ref 'refs/heads/ZEUS-5' was rewritten
      Ref 'refs/heads/Zeus_Bug-13' was rewritten
      WARNING: Ref 'refs/heads/master' is unchanged
      Ref 'refs/remotes/origin/ADW' was rewritten
      WARNING: Ref 'refs/remotes/origin/master' is unchanged
      Ref 'refs/remotes/origin/Kunden' was rewritten
      Ref 'refs/remotes/origin/Metzger' was rewritten
      WARNING: Ref 'refs/remotes/origin/Mond' is unchanged
      Ref 'refs/remotes/origin/Sensor' was rewritten
      WARNING: Ref 'refs/remotes/origin/Sonne' is unchanged
      Ref 'refs/remotes/origin/Wetter' was rewritten
      WARNING: Ref 'refs/remotes/origin/ZEUS-2' is unchanged
      WARNING: Ref 'refs/remotes/origin/ZEUS-3' is unchanged
      Ref 'refs/remotes/origin/ZEUS-5' was rewritten
      Ref 'refs/remotes/origin/ZEUS_BUG-12' was rewritten
      WARNING: Ref 'refs/remotes/origin/ZEUS_BUG-4' is unchanged
      Ref 'refs/remotes/origin/ZEUS_BUG-6' was rewritten
      WARNING: Ref 'refs/remotes/origin/ZEUS_BUG-8' is unchanged
      Ref 'refs/remotes/origin/ZEUS_BUG-9' was rewritten
      Ref 'refs/remotes/origin/Zeus_Bug-13' was rewritten
      WARNING: Ref 'refs/remotes/origin/master' is unchanged
      WARNING: Ref 'refs/remotes/origin/metzger' is unchanged
      WARNING: Ref 'refs/remotes/origin/tempAddFirstCode' is unchanged
      Ref 'refs/stash' was rewritten
</code>```

So basically, git is showing me that it both did change and did not change stuff, somehow?

As I can see so far, the local parts were changed completely while the remotestuff has changed only partially.
The size of the repository stayed the same (8 Gig) but it should have been reduced to 4Gig.

So two things:
First, has someone an idea what could be the reason for this mixed result?
Im running this on Win10, no admin privileges, from git CMD.
Second, is such a result "problematic"? I mean, some stuff has changed and some hasnt. Should I remove and then clone the repository again, to have a clean basis for the next attempt?

答:
If a ref is unchanged, the ref's history has never contained the removed files and directories since its first commit.

The size has not become smaller, because the related objects are still there in the repository. They will be there for a long time until they are garbage-collected some day. If they are wiped out immediately, it means you can't roll back the refs in case you regret or you run git filter-branch by mistake.

Body:
So I let Git rewrite history in all my branches over night, and when I looked for the results, I saw this:

      E:\zeus>git filter-branch -f --tree-filter "rm -rf ZeusSRC_Hardware_RPi_image_Raspberry Pi_außen_20.05.2019.zip" --prune-empty -- --all
      Rewrite fa2be75c64ca78a296c8f78fc363beebecbf92a1 (1526/1526) (2745 seconds passed, remaining 0 predicted)
      Ref 'refs/heads/Kunden' was rewritten
      Ref 'refs/heads/Sensor' was rewritten
      Ref 'refs/heads/Wetter' was rewritten
      Ref 'refs/heads/ZEUS-5' was rewritten
      Ref 'refs/heads/Zeus_Bug-13' was rewritten
      WARNING: Ref 'refs/heads/master' is unchanged
      Ref 'refs/remotes/origin/ADW' was rewritten
      WARNING: Ref 'refs/remotes/origin/master' is unchanged
      Ref 'refs/remotes/origin/Kunden' was rewritten
      Ref 'refs/remotes/origin/Metzger' was rewritten
      WARNING: Ref 'refs/remotes/origin/Mond' is unchanged
      Ref 'refs/remotes/origin/Sensor' was rewritten
      WARNING: Ref 'refs/remotes/origin/Sonne' is unchanged
      Ref 'refs/remotes/origin/Wetter' was rewritten
      WARNING: Ref 'refs/remotes/origin/ZEUS-2' is unchanged
      WARNING: Ref 'refs/remotes/origin/ZEUS-3' is unchanged
      Ref 'refs/remotes/origin/ZEUS-5' was rewritten
      Ref 'refs/remotes/origin/ZEUS_BUG-12' was rewritten
      WARNING: Ref 'refs/remotes/origin/ZEUS_BUG-4' is unchanged
      Ref 'refs/remotes/origin/ZEUS_BUG-6' was rewritten
      WARNING: Ref 'refs/remotes/origin/ZEUS_BUG-8' is unchanged
      Ref 'refs/remotes/origin/ZEUS_BUG-9' was rewritten
      Ref 'refs/remotes/origin/Zeus_Bug-13' was rewritten
      WARNING: Ref 'refs/remotes/origin/master' is unchanged
      WARNING: Ref 'refs/remotes/origin/metzger' is unchanged
      WARNING: Ref 'refs/remotes/origin/tempAddFirstCode' is unchanged
      Ref 'refs/stash' was rewritten

So basically, git is showing me that it both did change and did not change stuff, somehow?

As I can see so far, the local parts were changed completely while the remotestuff has changed only partially.
The size of the repository stayed the same (8 Gig) but it should have been reduced to 4Gig.

So two things:
First, has someone an idea what could be the reason for this mixed result?
Im running this on Win10, no admin privileges, from git CMD.
Second, is such a result "problematic"? I mean, some stuff has changed and some hasnt. Should I remove and then clone the repository again, to have a clean basis for the next attempt?


问:
Is HAML a Better Tool for Experienced Ruby/Rails Developers?
One of the joys of being a new Ruby on Rails student/developer is the constant discovery of new Gems to make my life more fun or easier. Recently, I "discovered" HAML, which appears to be a fantastic tool for making ERB code even more readable than it already is. However, I wonder if it is a good idea for newer developers, like myself, to embrace a tool like HAML early on, or if it would be smarter to hold off until my expertise in plain Ruby / Rails code has matured. My worry, I suppose, is that embracing a tool like HAML too early might impede my full understanding of Ruby through the coding "shortcuts" it offers. What do you experienced coders say? </p>

答:
I would vote for the latter. It's better to stick to erb in my opinion, at least for now. The main reason is that you can use your time on learning more productive things, such as testing, routing, REST and other more important things.

It's also a matter of taste. Haml is good, but i find erb pretty good as well and just great for what i need to do. I was also thinking of switching to haml for quite some time, but in the end, i would just stick with erb and keep on studying other Rails matters.

You will notice some strong opinions on that subject. For instance, the Rails book by Fernandez solely uses haml, while agile rails uses erb. Find what suits you best, but preferably, do it after some time practicing rails.


问:
Apache default VirtualHost
How can I set a default VirtualHost in Apache?

Preferably, I want the default host not to be the same as the IP address host. Now I have something like this:

```<code>NameVirtualHost *

<VirtualHost *>
    ServerAdmin admin@example.com
    DocumentRoot /someOtherDir/
    ServerAlias ip.of.the.server
</VirtualHost>

<VirtualHost *>
    ServerAdmin admin@example.com
    DocumentRoot /someroot/
    ServerAlias example.com *.example.com
</VirtualHost *>
</code>```

If a domain is forwarded to my server, but isn't in this vhost.conf file, the files from /someOtherDir/ are loaded, as expected. But I want to be able to use a different root for the IP address itself and domains which aren't added to the vhost.conf file (yet). Is this possible?

答:
I had the same issue. I could fix it by adding the following in httpd.conf itself before the IncludeOptional directives for virtual hosts. Now localhost and the IP 192.168.x.x both points to the default test page of Apache. All other virtual hosts are working as expected.

```<code><VirtualHost *:80>
    DocumentRoot /var/www/html
</VirtualHost>
</code>```

Reference: https://httpd.apache.org/docs/2.4/vhosts/name-based.html#defaultvhost

Title: Apache default VirtualHost

Body:
How can I set a default VirtualHost in Apache?

Preferably, I want the default host not to be the same as the IP address host. Now I have something like this:

NameVirtualHost *

<VirtualHost *>
    ServerAdmin admin@example.com
    DocumentRoot /someOtherDir/
    ServerAlias ip.of.the.server
</VirtualHost>

<VirtualHost *>
    ServerAdmin admin@example.com
    DocumentRoot /someroot/
    ServerAlias example.com *.example.com
</VirtualHost *>

If a domain is forwarded to my server, but isn't in this vhost.conf file, the files from /someOtherDir/ are loaded, as expected. But I want to be able to use a different root for the IP address itself and domains which aren't added to the vhost.conf file (yet). Is this possible?

Body:
I had the same issue. I could fix it by adding the following in httpd.conf itself before the IncludeOptional directives for virtual hosts. Now localhost and the IP 192.168.x.x both points to the default test page of Apache. All other virtual hosts are working as expected.

<VirtualHost *:80>
    DocumentRoot /var/www/html
</VirtualHost>

Reference: https://httpd.apache.org/docs/2.4/vhosts/name-based.html#defaultvhost


问:
How to increment a particular value of a hash table without changing its key?
I am traversing over an array of numbers (0-9) and want to store there occurrence in hash table with that.

```<code>int ar[size]={0,2,0,1,4,6,8 ........ 8,6,7}; // array
auto hash=new int[10];   //here the value is initialized to zero

for(int i=0;i<size;i++)
  {
   //here i want to store the time a number occurred in the array with
   keys as number itself

  hash[ar[i]] = **valueof(hash[ar[i]])+1** // i want to do this
  }
</code>```

Edit

```<code>auto hash=new int[10]();
</code>```

答:
You can increment the value in place:

```<code>hash[ar[i]]++;
</code>```

Also:

```<code>// Not true:
auto hash=new int[10];   //here the value is initialized to zero
</code>```

You have to add a initializer:

```<code>auto hash=new int[10]();   //here the value is initialized to zero
</code>```

Reference:

If type is an array type, an array of objects is initialized.

If initializer is absent, each element is default-initialized

If initializer is an empty pair of parentheses, each element is value-initialized.

https://en.cppreference.com/w/cpp/language/new

Also, the heap allocation is not really needed, you could simply use int hash[10] = {0} or std::array<int, 10> hash; hash.fill(0).

Body:
I am traversing over an array of numbers (0-9) and want to store there occurrence in hash table with that.

int ar[size]={0,2,0,1,4,6,8 ........ 8,6,7}; // array
auto hash=new int[10];   //here the value is initialized to zero

for(int i=0;i<size;i++)
  {
   //here i want to store the time a number occurred in the array with
   keys as number itself

  hash[ar[i]] = **valueof(hash[ar[i]])+1** // i want to do this
  }

Edit

auto hash=new int[10]();

Body:
You can increment the value in place:

hash[ar[i]]++;

Also:

// Not true:
auto hash=new int[10];   //here the value is initialized to zero

You have to add a initializer:

auto hash=new int[10]();   //here the value is initialized to zero

Reference:

If type is an array type, an array of objects is initialized.

If initializer is absent, each element is default-initialized

If initializer is an empty pair of parentheses, each element is value-initialized.

https://en.cppreference.com/w/cpp/language/new

Also, the heap allocation is not really needed, you could simply use int hash[10] = {0} or std::array<int, 10> hash; hash.fill(0).


问:
Save and display product selected custom data in WooCommerce
I use the code, that on the product editing page shows the checkbox "Roast Level". When the manager clicks on this checkbox, a select box appears on the page of a single product, allowing the customer to select "Roast Level".

When selecting and adding a product to the cart, the selected value appears in the cart itself. This value is also shown on the checkout page, on the "Thank You" page, in the order, on the email notification, and on the order editing page in the admin panel.

Here is the code:

```<code>// Display Checkbox Field
add_action('woocommerce_product_options_general_product_data', 'roast_custom_field_add');

function roast_custom_field_add() {
    global $post;

    // Checkbox
    woocommerce_wp_checkbox(
            array(
                    'id' => '_roast_checkbox',
                    'label' => __('Roast Level', 'woocommerce'),
                    'description' => __('Enable roast level!', 'woocommerce')
            )
    );
}

// Save Checkbox Field
add_action('woocommerce_process_product_meta', 'roast_custom_field_save');

function roast_custom_field_save($post_id) {
    // Custom Product Checkbox Field
    $roast_checkbox = isset($_POST['_roast_checkbox']) ? 'yes' : 'no';
    update_post_meta($post_id, '_roast_checkbox', esc_attr($roast_checkbox));
}

// Display Select Box
add_action('woocommerce_before_add_to_cart_button', 'add_roast_custom_field', 0);

function add_roast_custom_field() {
    global $product;

    // If is single product page and have the "roast_checkbox" enabled we display the field
    if (is_product() && $product->get_meta('_roast_checkbox') === 'yes') {

            echo '<div>';

            woocommerce_form_field('roast_custom_options', array(
                    'type' => 'select',
                    'class' => array('my-field-class form-row-wide'),
                    'label' => __('Roast Level'),
                    'required' => false,
                    'options' => array(
                            '' => 'Please select',
                            'Blue' => 'Blue',
                            'Rare' => 'Rare',
                            'Medium Rare' => 'Medium Rare',
                            'Medium' => 'Medium',
                            'Medium Well' => 'Medium Well',
                            'Well Done' => 'Well Done'
                    )
            ), '');

            echo '</div>';
    }
}

// Add as custom cart item data
add_filter('woocommerce_add_cart_item_data', 'add_custom_cart_item_data', 10, 3);

function add_custom_cart_item_data($cart_item_data, $product_id, $variation_id) {
    if (isset($_POST['roast_custom_options'])) {
            $cart_item_data['roast_option'] = wc_clean($_POST['roast_custom_options']);
    }
    return $cart_item_data;
}

// Add custom fields values under cart item name in cart
add_filter('woocommerce_cart_item_name', 'roast_custom_field', 10, 3);

function roast_custom_field($item_name, $cart_item, $cart_item_key) {
    if (!is_cart())
            return $item_name;

    if (isset($cart_item['roast_option'])) {
            $item_name. = '<br /><div class="my-custom-class"><strong>'.__("Roast Level", "woocommerce").
            ':</strong> '.$cart_item['roast_option'].
            '</div>';
    }
    return $item_name;
}

// Display roast custom fields values under item name in checkout
add_filter('woocommerce_checkout_cart_item_quantity', 'roast_custom_checkout_cart_item_name', 10, 3);

function roast_custom_checkout_cart_item_name($item_qty, $cart_item, $cart_item_key) {
    if (isset($cart_item['roast_option'])) {
            $item_qty. = '<br /><div class="my-custom-class"><strong>'.__("Roast Level", "woocommerce").
            ':</strong> '.$cart_item['roast_option'].
            '</div>';
    }
    return $item_qty;
}

// Save chosen slelect field value to each order item as custom meta data and display it everywhere
add_action('woocommerce_checkout_create_order_line_item', 'save_order_item_product_fitting_color', 10, 4);

function save_order_item_product_fitting_color($item, $cart_item_key, $values, $order) {
    if (isset($values['_roast_option'])) {
            $key = __('Roast Level', 'woocommerce');
            $value = $values['_roast_option'];
            $item->update_meta_data($key, $value);
    }
}
</code>```

This code works well in the Storefront theme, but for some reason, it does not work in the theme I bought on Themeforest. Developers can not help, they say that I need to contact the person who wrote this code. And that's why...

I also use code that works in the Storefront and in the purchased theme. Here it is - Show custom fields on the order editing page in WooCommerce
, those. It works great in these two themes.

As I understand it, this is due to the syntax "echo". In the form of "Roast Level" this syntax is, therefore the form is shown. When displaying selected data in the cart or on the checkout page, this syntax is not.

UPDATE

Here is the code that doesn't work without "echo":

```<code>// Add custom fields values under cart item name in cart
add_filter('woocommerce_cart_item_name', 'roast_custom_field', 10, 3);

function roast_custom_field($item_name, $cart_item, $cart_item_key) {
    if (!is_cart())
            return $item_name;

    if (isset($cart_item['roast_option'])) {
            $item_name. = '<br /><div class="my-custom-class"><strong>'.__("Roast Level", "woocommerce").
        ':</strong> '.$cart_item['roast_option'].
        '</div>';
    }
    return $item_name;
}

// Display roast custom fields values under item name in checkout
add_filter('woocommerce_checkout_cart_item_quantity', 'roast_custom_checkout_cart_item_name', 10, 3);

function roast_custom_checkout_cart_item_name($item_qty, $cart_item, $cart_item_key) {
    if (isset($cart_item['roast_option'])) {
            $item_qty. = '<br /><div class="my-custom-class"><strong>'.__("Roast Level", "woocommerce").
        ':</strong> '.$cart_item['roast_option'].
        '</div>';
    }
    return $item_qty;
}

// Save chosen slelect field value to each order item as custom meta data and display it everywhere
add_action('woocommerce_checkout_create_order_line_item', 'save_order_item_product_fitting_color', 10, 4);

function save_order_item_product_fitting_color($item, $cart_item_key, $values, $order) {
    if (isset($values['_roast_option'])) {
            $key = __('Roast Level', 'woocommerce');
            $value = $values['_roast_option'];
            $item->update_meta_data($key, $value);
    }
}
</code>```

I ask to change my code so that it has the syntax "echo", so that the selected data is output using "echo". I will be glad for your help!

答:
Following Code should Work

```<code>/*---------------------------------------------------------------
*Display Select Box
---------------------------------------------------------------*/
add_action( 'woocommerce_before_add_to_cart_button', 'add_roast_custom_field', 0 );
function add_roast_custom_field() {
    global $product;

    // If is single product page and have the "roast_checkbox" enabled we display the field
    if ( is_product() && $product->get_meta( '_roast_checkbox' ) === 'yes' ) {

        echo '<div class="roast_select">';

        $select = woocommerce_form_field( 'roast_custom_options', array(
            'type'          => 'select',
            'class'         => array('my-field-class form-row-wide'),
            'label'         => __('Roast Level'),
            'required'      => false,
            'return'       => false,
            'options'   => array(
                ''      => 'Please select',
                'Blue'  => 'Blue',
                'Rare'  => 'Rare',
                'Medium Rare'   => 'Medium Rare',
                'Medium'    => 'Medium',
                'Medium Well'   => 'Medium Well',
                'Well Done' => 'Well Done'
            )
        ), '' );
        echo $select;
        echo '</div>';
    }
}
/*---------------------------------------------------------------
* Add as custom cart item data
---------------------------------------------------------------*/
add_filter( 'woocommerce_add_cart_item_data', 'add_custom_cart_item_data', 10, 21 );
function add_custom_cart_item_data($cart_item_data, $product_id, $variation_id ){

    if( isset( $_POST['roast_custom_options'] ) ) {
        $cart_item_data['roast_option'] = wc_clean( $_POST['roast_custom_options'] );
    }
    return $cart_item_data;
}
/*---------------------------------------------------------------
* Add custom fields values under cart item name in cart
---------------------------------------------------------------*/

add_filter( 'woocommerce_cart_item_name', 'roast_custom_field', 10, 21 );
function roast_custom_field( $item_name, $cart_item, $cart_item_key ) {
    if( ! is_cart() )
        return $item_name;

    if( isset($cart_item['roast_option']) ) {
        $item_name .= '<br /><div class="my-custom-class"><strong>' . __("Roast Level", "woocommerce") . ':</strong> ' . $cart_item['roast_option'] . '</div>';
    }
    return $item_name;
}

/*---------------------------------------------------------------
* Display roast custom fields values under item name in checkout
---------------------------------------------------------------*/

add_filter( 'woocommerce_checkout_cart_item_quantity', 'roast_custom_checkout_cart_item_name', 10, 21 );
function roast_custom_checkout_cart_item_name( $item_qty, $cart_item, $cart_item_key ) {
    if( isset($cart_item['roast_option']) ) {
        $item_qty .= '<br /><div class="my-custom-class"><strong>' . __("Roast Level", "woocommerce") . ':</strong> ' . $cart_item['roast_option'] . 'гр.</div>';
    }
    return $item_qty;
}

/*---------------------------------------------------------------
* Save chosen slelect field value to each order item as custom meta data and display it everywhere
---------------------------------------------------------------*/
add_action('woocommerce_checkout_create_order_line_item', 'save_order_item_product_fitting_color', 10, 21 );
function save_order_item_product_fitting_color( $item, $cart_item_key, $values, $order ) {
    if( isset($values['roast_option']) ) {
        $key = __('Roast Level', 'woocommerce');
        $value = $values['roast_option'];
        $item->update_meta_data( $key, $value ,$item->get_id());
    }
}

/*--------------------------------------------------------------------
The following code played the important role in your theme

Your add to cart form takes the values when user clicks on add to cart button
After it ajax runs and takes the values from the butoons custom attribute
like data-product_id, data-roast_custom_options So i have added it using jquery
check the code and your site. All the codesprovided by me working now.

--------------------------------------------------------------------*/

add_action('wp_footer','add_footer_script');
function add_footer_script(){
    ?>
    <script>
       jQuery('#roast_custom_options').on('change',function(){
           var roast_level = jQuery(this).val();
           /*console.log(roast_level); */
           var button = jQuery(this).closest('form').find('.add_to_cart_button'); console.log(button);
           jQuery(button).attr('data-roast_custom_options',roast_level);
        });

    </script>
    <?php
}
</code>```

Body:
I use the code, that on the product editing page shows the checkbox "Roast Level". When the manager clicks on this checkbox, a select box appears on the page of a single product, allowing the customer to select "Roast Level".

When selecting and adding a product to the cart, the selected value appears in the cart itself. This value is also shown on the checkout page, on the "Thank You" page, in the order, on the email notification, and on the order editing page in the admin panel.

Here is the code:

// Display Checkbox Field
add_action('woocommerce_product_options_general_product_data', 'roast_custom_field_add');

function roast_custom_field_add() {
    global $post;

    // Checkbox
    woocommerce_wp_checkbox(
            array(
                    'id' => '_roast_checkbox',
                    'label' => __('Roast Level', 'woocommerce'),
                    'description' => __('Enable roast level!', 'woocommerce')
            )
    );
}

// Save Checkbox Field
add_action('woocommerce_process_product_meta', 'roast_custom_field_save');

function roast_custom_field_save($post_id) {
    // Custom Product Checkbox Field
    $roast_checkbox = isset($_POST['_roast_checkbox']) ? 'yes' : 'no';
    update_post_meta($post_id, '_roast_checkbox', esc_attr($roast_checkbox));
}

// Display Select Box
add_action('woocommerce_before_add_to_cart_button', 'add_roast_custom_field', 0);

function add_roast_custom_field() {
    global $product;

    // If is single product page and have the "roast_checkbox" enabled we display the field
    if (is_product() && $product->get_meta('_roast_checkbox') === 'yes') {

            echo '
';

            woocommerce_form_field('roast_custom_options', array(
                    'type' => 'select',
                    'class' => array('my-field-class form-row-wide'),
                    'label' => __('Roast Level'),
                    'required' => false,
                    'options' => array(
                            '' => 'Please select',
                            'Blue' => 'Blue',
                            'Rare' => 'Rare',
                            'Medium Rare' => 'Medium Rare',
                            'Medium' => 'Medium',
                            'Medium Well' => 'Medium Well',
                            'Well Done' => 'Well Done'
                    )
            ), '');

            echo '
';
    }
}

// Add as custom cart item data
add_filter('woocommerce_add_cart_item_data', 'add_custom_cart_item_data', 10, 3);

function add_custom_cart_item_data($cart_item_data, $product_id, $variation_id) {
    if (isset($_POST['roast_custom_options'])) {
            $cart_item_data['roast_option'] = wc_clean($_POST['roast_custom_options']);
    }
    return $cart_item_data;
}

// Add custom fields values under cart item name in cart
add_filter('woocommerce_cart_item_name', 'roast_custom_field', 10, 3);

function roast_custom_field($item_name, $cart_item, $cart_item_key) {
    if (!is_cart())
            return $item_name;

    if (isset($cart_item['roast_option'])) {
            $item_name. = '

'.__("Roast Level", "woocommerce").
            ': '.$cart_item['roast_option'].
            '
';
    }
    return $item_name;
}

// Display roast custom fields values under item name in checkout
add_filter('woocommerce_checkout_cart_item_quantity', 'roast_custom_checkout_cart_item_name', 10, 3);

function roast_custom_checkout_cart_item_name($item_qty, $cart_item, $cart_item_key) {
    if (isset($cart_item['roast_option'])) {
            $item_qty. = '

'.__("Roast Level", "woocommerce").
            ': '.$cart_item['roast_option'].
            '
';
    }
    return $item_qty;
}

// Save chosen slelect field value to each order item as custom meta data and display it everywhere
add_action('woocommerce_checkout_create_order_line_item', 'save_order_item_product_fitting_color', 10, 4);

function save_order_item_product_fitting_color($item, $cart_item_key, $values, $order) {
    if (isset($values['_roast_option'])) {
            $key = __('Roast Level', 'woocommerce');
            $value = $values['_roast_option'];
            $item->update_meta_data($key, $value);
    }
}

This code works well in the Storefront theme, but for some reason, it does not work in the theme I bought on Themeforest. Developers can not help, they say that I need to contact the person who wrote this code. And that's why...

I also use code that works in the Storefront and in the purchased theme. Here it is - Show custom fields on the order editing page in WooCommerce
, those. It works great in these two themes.

As I understand it, this is due to the syntax "echo". In the form of "Roast Level" this syntax is, therefore the form is shown. When displaying selected data in the cart or on the checkout page, this syntax is not.

UPDATE

Here is the code that doesn't work without "echo":

// Add custom fields values under cart item name in cart
add_filter('woocommerce_cart_item_name', 'roast_custom_field', 10, 3);

function roast_custom_field($item_name, $cart_item, $cart_item_key) {
    if (!is_cart())
            return $item_name;

    if (isset($cart_item['roast_option'])) {
            $item_name. = '

'.__("Roast Level", "woocommerce").
        ': '.$cart_item['roast_option'].
        '
';
    }
    return $item_name;
}

// Display roast custom fields values under item name in checkout
add_filter('woocommerce_checkout_cart_item_quantity', 'roast_custom_checkout_cart_item_name', 10, 3);

function roast_custom_checkout_cart_item_name($item_qty, $cart_item, $cart_item_key) {
    if (isset($cart_item['roast_option'])) {
            $item_qty. = '

'.__("Roast Level", "woocommerce").
        ': '.$cart_item['roast_option'].
        '
';
    }
    return $item_qty;
}

// Save chosen slelect field value to each order item as custom meta data and display it everywhere
add_action('woocommerce_checkout_create_order_line_item', 'save_order_item_product_fitting_color', 10, 4);

function save_order_item_product_fitting_color($item, $cart_item_key, $values, $order) {
    if (isset($values['_roast_option'])) {
            $key = __('Roast Level', 'woocommerce');
            $value = $values['_roast_option'];
            $item->update_meta_data($key, $value);
    }
}

I ask to change my code so that it has the syntax "echo", so that the selected data is output using "echo". I will be glad for your help!

Body:
Following Code should Work

/*---------------------------------------------------------------
*Display Select Box
---------------------------------------------------------------*/
add_action( 'woocommerce_before_add_to_cart_button', 'add_roast_custom_field', 0 );
function add_roast_custom_field() {
    global $product;

    // If is single product page and have the "roast_checkbox" enabled we display the field
    if ( is_product() && $product->get_meta( '_roast_checkbox' ) === 'yes' ) {

        echo '<div class="roast_select">';

        $select = woocommerce_form_field( 'roast_custom_options', array(
            'type'          => 'select',
            'class'         => array('my-field-class form-row-wide'),
            'label'         => __('Roast Level'),
            'required'      => false,
            'return'       => false,
            'options'   => array(
                ''      => 'Please select',
                'Blue'  => 'Blue',
                'Rare'  => 'Rare',
                'Medium Rare'   => 'Medium Rare',
                'Medium'    => 'Medium',
                'Medium Well'   => 'Medium Well',
                'Well Done' => 'Well Done'
            )
        ), '' );
        echo $select;
        echo '</div>';
    }
}
/*---------------------------------------------------------------
* Add as custom cart item data
---------------------------------------------------------------*/
add_filter( 'woocommerce_add_cart_item_data', 'add_custom_cart_item_data', 10, 21 );
function add_custom_cart_item_data($cart_item_data, $product_id, $variation_id ){

    if( isset( $_POST['roast_custom_options'] ) ) {
        $cart_item_data['roast_option'] = wc_clean( $_POST['roast_custom_options'] );
    }
    return $cart_item_data;
}
/*---------------------------------------------------------------
* Add custom fields values under cart item name in cart
---------------------------------------------------------------*/

add_filter( 'woocommerce_cart_item_name', 'roast_custom_field', 10, 21 );
function roast_custom_field( $item_name, $cart_item, $cart_item_key ) {
    if( ! is_cart() )
        return $item_name;

    if( isset($cart_item['roast_option']) ) {
        $item_name .= '<br /><div class="my-custom-class"><strong>' . __("Roast Level", "woocommerce") . ':</strong> ' . $cart_item['roast_option'] . '</div>';
    }
    return $item_name;
}

/*---------------------------------------------------------------
* Display roast custom fields values under item name in checkout
---------------------------------------------------------------*/

add_filter( 'woocommerce_checkout_cart_item_quantity', 'roast_custom_checkout_cart_item_name', 10, 21 );
function roast_custom_checkout_cart_item_name( $item_qty, $cart_item, $cart_item_key ) {
    if( isset($cart_item['roast_option']) ) {
        $item_qty .= '<br /><div class="my-custom-class"><strong>' . __("Roast Level", "woocommerce") . ':</strong> ' . $cart_item['roast_option'] . 'гр.</div>';
    }
    return $item_qty;
}

/*---------------------------------------------------------------
* Save chosen slelect field value to each order item as custom meta data and display it everywhere
---------------------------------------------------------------*/
add_action('woocommerce_checkout_create_order_line_item', 'save_order_item_product_fitting_color', 10, 21 );
function save_order_item_product_fitting_color( $item, $cart_item_key, $values, $order ) {
    if( isset($values['roast_option']) ) {
        $key = __('Roast Level', 'woocommerce');
        $value = $values['roast_option'];
        $item->update_meta_data( $key, $value ,$item->get_id());
    }
}

/*--------------------------------------------------------------------
The following code played the important role in your theme

Your add to cart form takes the values when user clicks on add to cart button
After it ajax runs and takes the values from the butoons custom attribute
like data-product_id, data-roast_custom_options So i have added it using jquery
check the code and your site. All the codesprovided by me working now.

--------------------------------------------------------------------*/

add_action('wp_footer','add_footer_script');
function add_footer_script(){
    ?>
    <script>
       jQuery('#roast_custom_options').on('change',function(){
           var roast_level = jQuery(this).val();
           /*console.log(roast_level); */
           var button = jQuery(this).closest('form').find('.add_to_cart_button'); console.log(button);
           jQuery(button).attr('data-roast_custom_options',roast_level);
        });

    </script>
    <?php
}


问:
Passing context to a tooltip template from "ngFor" elements
I am trying to pass data to my ng-bootstrap tooltip template. Following this example https://ng-bootstrap.github.io/#/components/tooltip/examples#tplwithcontext , I am now stuck at adding the #t1="ngbTooltip" part. Because my elements are created by iterating over an array, I cannot manually add the #t1 part.

This is my best try:

https://stackblitz.com/edit/ngbs-tooltip-dyn

When hovering over one of the "cell *" table cells, I want the tooltip to render the appropriate template with the cell's data from tooltipData.
Any considerations and help are appreciated.

答:
Ok, so I have solved this, and posting this for reference.

The reason why I was struggling is that I was thinking that the content would be pulled dynamically. Opposed to that, the way it works is to render all the tooltips.

I have updated my Stackblitz https://stackblitz.com/edit/ngbs-tooltip-dyn for reference.


问:
Kotlin - Can't create two constructors with different List types parameters
I was trying to create the following class:

```<code>class MyClass {

    var foos: List<Foo> = listOf()

    constructor(foos: List<Foo>) {
        this.foos = foos
    }

    constructor(bars: List<Bar>) : super() {
        this.foos = bars.map { bar ->
            Foo(bar)
        }
    }
}
</code>```

However, I get an error saying:

Platform declaration clash: The following declarations have the same JVM signature ( (Ljava/util/List;)V):

I understand that they are both List objects, but they are typed with generics so I was sure it would not be a problem.

答:
You encounter this problem because in java there exists something called type erasure. And because kotlin uses the JVM it is also affected by this limitation. To give a TL;DR;

The generic type is retained in the .class file so java knows that the class (in your case List) is generic. But it can't keep track of the generic type of an instance. So instances List<Foo> and List<Bar> are both handled in their raw type form at runtime (List). Keep in mind that generics are only used at compile time to ensure type safety.

To overcome this limitation, you can make use of operator overloading in kotlin. The operator we're looking at is () which let's you invoke any instance. By using a companion object we can even make this
invoke look like a constructor, and be invoked like one (MyClass()). Your code can look like this:

```<code>class MyClass(var foos: List<Foo>) {
    companion object {
        operator fun invoke(bars: List<Bar>) = MyClass(bars.map(::Foo))
    }
}
</code>```

Which allows you to call it simply like this:

```<code>val mc1 = MyClass(foos) // calls constructor
val mc2 = MyClass(bars) // calls companion.invoke
</code>```

Body:
I was trying to create the following class:

class MyClass {

    var foos: List<Foo> = listOf()

    constructor(foos: List<Foo>) {
        this.foos = foos
    }

    constructor(bars: List<Bar>) : super() {
        this.foos = bars.map { bar ->
            Foo(bar)
        }
    }
}

However, I get an error saying:

Platform declaration clash: The following declarations have the same JVM signature ( (Ljava/util/List;)V):

I understand that they are both List objects, but they are typed with generics so I was sure it would not be a problem.

Body:
You encounter this problem because in java there exists something called type erasure. And because kotlin uses the JVM it is also affected by this limitation. To give a TL;DR;

The generic type is retained in the .class file so java knows that the class (in your case List) is generic. But it can't keep track of the generic type of an instance. So instances List<Foo> and List<Bar> are both handled in their raw type form at runtime (List). Keep in mind that generics are only used at compile time to ensure type safety.

To overcome this limitation, you can make use of operator overloading in kotlin. The operator we're looking at is () which let's you invoke any instance. By using a companion object we can even make this
invoke look like a constructor, and be invoked like one (MyClass()). Your code can look like this:

class MyClass(var foos: List<Foo>) {
    companion object {
        operator fun invoke(bars: List<Bar>) = MyClass(bars.map(::Foo))
    }
}

Which allows you to call it simply like this:

val mc1 = MyClass(foos) // calls constructor
val mc2 = MyClass(bars) // calls companion.invoke


问:
Determining if there are repeated elements in a list in Haskell
I'm trying to test lists for duplicates but when I compile and enter

```<code>repeated [1,2,3,4]
</code>```

it outputs True. What's wrong?

```<code>belongs :: Eq a => a -> [a] -> Bool
belongs n [] = False
belongs n (x:xs) | n == x = True
                 | otherwise = belongs n xs

repeated :: [Integer] -> Bool
repeated [] = False
repeated (x:xs) | belongs x xs = True
                | otherwise = belongs (head xs) xs
</code>```

答:
"belongs (head xs) xs" checks whether xs's head is within xs, which will always be true.

(Except when xs is empty, in which case your program will crash! "head" is a partial function, crashes with empty lists)

This would fix it (as pointed by @talex too, but I also suggest making it more general, there is no need to specialize it to Integer):

repeated :: Eq a => [a] -> Bool
repeated [] = False
repeated (x:xs) | belongs x xs = True
                | otherwise = repeated xs
```

Body:
I'm trying to test lists for duplicates but when I compile and enter

repeated [1,2,3,4]

it outputs True. What's wrong?

belongs :: Eq a => a -> [a] -> Bool
belongs n [] = False
belongs n (x:xs) | n == x = True
                 | otherwise = belongs n xs

repeated :: [Integer] -> Bool
repeated [] = False
repeated (x:xs) | belongs x xs = True
                | otherwise = belongs (head xs) xs


问:
eval to interpret new lines in bash
I have a previously run command $cmd, this command outputs multiple lines.

I would like to take the nth line of output from running an edited version of $cmd.

So far I have tried:

```<code>local -a lines

for line in $(eval "$(some_edit $cmd)");do
  lines+=("$line")
done

echo "${lines[$nth_line]}"
</code>```

I always echo everything when $nth_line is 1 and nothing for larger integers.

I always have $lines being an array of one string - which is all the lines.

I have tried combinations of ", but to no avail.

答:
I don't know if i understand you correct - you mean something like that?

```<code>#!/bin/bash
cmd="./script.sh"

# read stdout from $cmd into array lines
readarray lines < <($cmd)

# edit the second line
lines[1]=$'version: 0.99\n'

# loop over array and print lines
for line in "${lines[@]}"; do
   printf "%s" "$line"
done
</code>```

testscript for simulate $cmd

```<code>#!/bin/bash
echo "start"
echo
echo "do something"
echo
echo "end"
</code>```

output

```<code>start
version: 0.99
do something

end
</code>```

Title: eval to interpret new lines in bash

Body:
I have a previously run command $cmd, this command outputs multiple lines.

I would like to take the nth line of output from running an edited version of $cmd.

So far I have tried:

local -a lines

for line in $(eval "$(some_edit $cmd)");do
  lines+=("$line")
done

echo "${lines[$nth_line]}"

I always echo everything when $nth_line is 1 and nothing for larger integers.

I always have $lines being an array of one string - which is all the lines.

I have tried combinations of ", but to no avail.

Body:
I don't know if i understand you correct - you mean something like that?

#!/bin/bash
cmd="./script.sh"

# read stdout from $cmd into array lines
readarray lines < <($cmd)

# edit the second line
lines[1]=$'version: 0.99\n'

# loop over array and print lines
for line in "${lines[@]}"; do
   printf "%s" "$line"
done

testscript for simulate $cmd

#!/bin/bash
echo "start"
echo
echo "do something"
echo
echo "end"

output

start
version: 0.99
do something

end


问:
Adding a ssh key to an GCP instance using terraform works but shows error on the console
I am adding ssh-keys to my gce instance using this:

```<code>ssh-keys  = "${var.ssh_user_name}:${var.ssh_pub_key}"
</code>```

ssh_pub_key is the public key output variable of tls_private_key module which dynamically generates ssh-keys.

According to GCP ssh-key format , at the end of public key , user name should be appended but generating dynamic keys using tls_private_key  resource will not add the user name

After adding the ssh-keys , I am able to login to gcp instance using the private key but if I try to edit on gcp console I get the following error:

"The SSH key is in the wrong format"

This is due to user name not being added at the end

My problem is :

```<code>ssh-keys  = "${var.ssh_user_name}:${var.ssh_pub_key}"
</code>```

Shouldn't this be taking care of that? Is there another way to do this? If the ssh-key is really wrong then ssh shouldn't even be allowed . I have searched for all ways to add ssh-key at instance level in GCP through terraform, I am not able to find anything else

```<code>ssh-keys  = "${var.ssh_user_name}:${var.ssh_pub_key}"
</code>```

The var.ssh_pub_key has extra \n line character at the end and I cannot modify this is the output variable of key generation module.

答:
So user name is required in public key - not in private. So what about something simple like

"${var.ssh_user_name}:${var.ssh_pub_key} ${var.ssh_user_name}" - now terraform interpolation should make your public key in proper format

Edit:
So solution for \n character at the end in pure terraform is:

```<code>locals {
  ssh_pub_key_without_new_line = "${replace(var.ssh_pub_key, "\n", "")}"
}
</code>```

And then

"${var.ssh_user_name}:${local.ssh_pub_key_without_new_line} ${var.ssh_user_name}"

Body:
I am adding ssh-keys to my gce instance using this:

ssh-keys  = "${var.ssh_user_name}:${var.ssh_pub_key}"

ssh_pub_key is the public key output variable of tls_private_key module which dynamically generates ssh-keys.

According to GCP ssh-key format , at the end of public key , user name should be appended but generating dynamic keys using tls_private_key  resource will not add the user name

After adding the ssh-keys , I am able to login to gcp instance using the private key but if I try to edit on gcp console I get the following error:

"The SSH key is in the wrong format"

This is due to user name not being added at the end

My problem is :

ssh-keys  = "${var.ssh_user_name}:${var.ssh_pub_key}"

Shouldn't this be taking care of that? Is there another way to do this? If the ssh-key is really wrong then ssh shouldn't even be allowed . I have searched for all ways to add ssh-key at instance level in GCP through terraform, I am not able to find anything else

ssh-keys  = "${var.ssh_user_name}:${var.ssh_pub_key}"

The var.ssh_pub_key has extra \n line character at the end and I cannot modify this is the output variable of key generation module.

Body:
So user name is required in public key - not in private. So what about something simple like

"${var.ssh_user_name}:${var.ssh_pub_key} ${var.ssh_user_name}" - now terraform interpolation should make your public key in proper format

Edit:
So solution for \n character at the end in pure terraform is:

locals {
  ssh_pub_key_without_new_line = "${replace(var.ssh_pub_key, "\n", "")}"
}

And then

"${var.ssh_user_name}:${local.ssh_pub_key_without_new_line} ${var.ssh_user_name}"


问:
I'm getting an unusual error when I'm trying to start my react app. It says that CleanWebpackPlugin is not a constructor
So, I have made a react app before with the same kind of configuration for webpack but this is the first time I am seeing this. The clean webpack plugin is showing that the class doesn't has a constructor even when it does.

I tried to see if there were any import problems or something like that but everything checks out.

```<code>const path = require('path');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: {
    app: './src/index.js',
    style: './src/style.less'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        }
      },
      {
          test: /\.less$/,
          use: [{
              loader: 'style-loader'
          },
          {
              loader: 'css-loader'
          },
          {
              loader: 'less-loader'
          }
        ]
      }
    ]
  },
  plugins: [
    new CleanWebpackPlugin(),
    new HtmlWebpackPlugin({
      template: './public/index.html'
    }),
  ],
  output: {
    filename: '[name].bundle.js',
    path: path.resolve(__dirname, 'dist')
  }
};
</code>```

Here's the error that I get on my terminal

new CleanWebpackPlugin(),
    ^

TypeError: CleanWebpackPlugin is not a constructor

答:
```<code>const { CleanWebpackPlugin } = require('clean-webpack-plugin');
</code>```

Body:
So, I have made a react app before with the same kind of configuration for webpack but this is the first time I am seeing this. The clean webpack plugin is showing that the class doesn't has a constructor even when it does.

I tried to see if there were any import problems or something like that but everything checks out.

const path = require('path');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: {
    app: './src/index.js',
    style: './src/style.less'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        }
      },
      {
          test: /\.less$/,
          use: [{
              loader: 'style-loader'
          },
          {
              loader: 'css-loader'
          },
          {
              loader: 'less-loader'
          }
        ]
      }
    ]
  },
  plugins: [
    new CleanWebpackPlugin(),
    new HtmlWebpackPlugin({
      template: './public/index.html'
    }),
  ],
  output: {
    filename: '[name].bundle.js',
    path: path.resolve(__dirname, 'dist')
  }
};

Here's the error that I get on my terminal

new CleanWebpackPlugin(),
    ^

TypeError: CleanWebpackPlugin is not a constructor


答:
I would suggest to use regular expressions for that, like this:

private static final Pattern p = Pattern.compile("(\d{4}-\d{2}-\d{2}:\d{2}:\d{2}:\d{2})");
public static void main(String[] args) {

    String a = "I am ready at time -S 2019-06-16:00:00:00 and be there"

    // create matcher for pattern p and given string
    Matcher m = p.matcher(a);

    // if an occurrence if a pattern was found in the given string...
    if (m.find()) {
        // ...then you can use group() methods.
        System.out.println(m.group(0));
    }
}
```

Title: Retrieve part of a string from a full text

Body:
I hve a string variable which contains a text along with some dates in it. Now I would like to retrieve the date from the text. How I can do it.

String a ="I am ready at time -S 2019-06-16:00:00:00 and be there"

Now I would like to retrieve 2019-06-16:00:00:00 from there. Date format will always be in the same format but I need to retrieve the date only from the text.