问:
Android- making 2 buttons side by side
Hey guys so I did look at other questions regarding this and I even looked online and I see nothing wrong with my code but every time I try to make a AVD to check out how the app looks the buttons dont show side by side but in android studio render screen it does.

If anyone could help I would be really thankful!

This is once i load the AVD in android studio

This is how is shows in the render in android studio

```<code>    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.jarvis.imquest.MainActivity">

    <ImageView
        android:id="@+id/image_message"
        android:src="@drawable/ic_message"
        android:layout_marginTop="20dp"
        android:layout_centerHorizontal="true"
        android:layout_width="100dp"
        android:layout_height="100dp" />

    <LinearLayout
        android:orientation="vertical"
        android:layout_below="@+id/image_message"
        android:id="@+id/group_login"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <EditText
                android:id="@+id/main_editLogin"
                android:hint="Enter Username"
                android:padding="5dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"/>
        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <EditText
                android:id="@+id/main_editPassword"
                android:hint="Enter Password"
                android:padding="5dp"
                android:inputType="textPassword"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"/>
        </android.support.design.widget.TextInputLayout>
    </LinearLayout>

    <LinearLayout
        android:layout_below="@+id/group_login"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:weightSum="2">

        <Button
            android:layout_weight="1"
            android:id="@+id/main_btnLogin"
            android:background="@color/colorPrimaryDark"
            android:textColor="@color/colorAccent"
            android:text="Login"
            android:layout_marginRight="5dp"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            style="@style/Widget.AppCompat.Button.Borderless"
            />

        <Button
            android:layout_weight="1"
            android:id="@+id/main_btnSignup"
            android:background="@color/colorPrimaryDark"
            android:textColor="@color/colorAccent"
            android:text="SignUp"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            style="@style/Widget.AppCompat.Button.Borderless"
            />
    </LinearLayout>

</RelativeLayout>
</code>```

答:
try this </p>

```<code>    <LinearLayout
    android:layout_below="@+id/group_login"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >

    <Button
        android:id="@+id/main_btnLogin"
        android:background="@color/colorPrimaryDark"
        android:textColor="@color/colorAccent"
        android:text="Login"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        style="@style/Widget.AppCompat.Button.Borderless"
        />

    <Button
        android:id="@+id/main_btnSignup"
        android:background="@color/colorPrimaryDark"
        android:textColor="@color/colorAccent"
        android:text="SignUp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        style="@style/Widget.AppCompat.Button.Borderless"
        />
</LinearLayout>
</code>```

Title: Android- making 2 buttons side by side

Body:
Hey guys so I did look at other questions regarding this and I even looked online and I see nothing wrong with my code but every time I try to make a AVD to check out how the app looks the buttons dont show side by side but in android studio render screen it does.

If anyone could help I would be really thankful!

This is once i load the AVD in android studio

This is how is shows in the render in android studio

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.jarvis.imquest.MainActivity">

    <ImageView
        android:id="@+id/image_message"
        android:src="@drawable/ic_message"
        android:layout_marginTop="20dp"
        android:layout_centerHorizontal="true"
        android:layout_width="100dp"
        android:layout_height="100dp" />

    <LinearLayout
        android:orientation="vertical"
        android:layout_below="@+id/image_message"
        android:id="@+id/group_login"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <EditText
                android:id="@+id/main_editLogin"
                android:hint="Enter Username"
                android:padding="5dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"/>
        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <EditText
                android:id="@+id/main_editPassword"
                android:hint="Enter Password"
                android:padding="5dp"
                android:inputType="textPassword"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"/>
        </android.support.design.widget.TextInputLayout>
    </LinearLayout>

    <LinearLayout
        android:layout_below="@+id/group_login"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:weightSum="2">

        <Button
            android:layout_weight="1"
            android:id="@+id/main_btnLogin"
            android:background="@color/colorPrimaryDark"
            android:textColor="@color/colorAccent"
            android:text="Login"
            android:layout_marginRight="5dp"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            style="@style/Widget.AppCompat.Button.Borderless"
            />

        <Button
            android:layout_weight="1"
            android:id="@+id/main_btnSignup"
            android:background="@color/colorPrimaryDark"
            android:textColor="@color/colorAccent"
            android:text="SignUp"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            style="@style/Widget.AppCompat.Button.Borderless"
            />
    </LinearLayout>

</RelativeLayout>

Body:
try this

    <LinearLayout
    android:layout_below="@+id/group_login"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >

    <Button
        android:id="@+id/main_btnLogin"
        android:background="@color/colorPrimaryDark"
        android:textColor="@color/colorAccent"
        android:text="Login"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        style="@style/Widget.AppCompat.Button.Borderless"
        />

    <Button
        android:id="@+id/main_btnSignup"
        android:background="@color/colorPrimaryDark"
        android:textColor="@color/colorAccent"
        android:text="SignUp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        style="@style/Widget.AppCompat.Button.Borderless"
        />
</LinearLayout>


来源: stackexchange

问:
I need help converting my driver user interface code
I have a custom driver I have written.

Here is the source code to communicate to the driver in C:

```<code>#include <windows.h>
#include <stdio.h>

/*********************************************************
* Main Function Entry
*
*********************************************************/
int _cdecl main(void)
{
HANDLE hFile;
DWORD dwReturn;

hFile = CreateFile("\\\\.\\Example", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);

if(hFile)
{
WriteFile(hFile, "Hello from user mode!", sizeof("Hello from user mode!"), &dwReturn, NULL);
CloseHandle(hFile);
}

return 0;
}
</code>```

I want to be able to do this in .NET preferaly in VB.NET.

Does anyone know how to do the conversion?

答: The simplest is to use P/Invoke to OpenFile, WriteFile and CloseHandle.</p>

ContentLicense: CC BY-SA 2.5

Body:
I have a custom driver I have written.

Here is the source code to communicate to the driver in C:

#include <windows.h>
#include <stdio.h>

/*********************************************************
* Main Function Entry
*
*********************************************************/
int _cdecl main(void)
{
HANDLE hFile;
DWORD dwReturn;

hFile = CreateFile("\\\\.\\Example", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);

if(hFile)
{
WriteFile(hFile, "Hello from user mode!", sizeof("Hello from user mode!"), &dwReturn, NULL);
CloseHandle(hFile);
}

return 0;
}

I want to be able to do this in .NET preferaly in VB.NET.

Does anyone know how to do the conversion?


问:
Unable to read lines using multithread in java
I am trying to read and print the lines in a csv file.I need to use multi threading for the same.There are 10 lines in the file,if I provide 2 threads(no of threads is  user input dependent) it should read all the 10 lines,where each line should be read and printed once by any of the thread.

But I am unable to successfully execute it.If I provide 2 threads,it will read 2 lines(random lines),doesn't read the remaining  and terminate the program.
I am trying to write the code for it.

main class:

```<code>import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class ThreadMain implements Runnable {

    String name;
    static Map<Integer, Boolean> map = new HashMap<Integer, Boolean>();

    public synchronized static Map<Integer, Boolean> getMap() {
        return map;
    }

    public synchronized static void setMap(Map<Integer, Boolean> map) {
        ThreadMain.map = map;
    }

    public ThreadMain(String s) {
        name = s;
    }

    public void run() {
        ThreadReader.Reader(name);
    }

    @SuppressWarnings("rawtypes")
    public static void main(String[] args) {

        Scanner scan = null;
        boolean repeat = false;
        int threads;

        do {
            try {
                scan = new Scanner(System.in);
                System.out.print("Enter no. of threads: ");
                threads = Integer.parseInt(scan.nextLine());

                // Initializing map
                int i;
                for (i = 1; i <= 10; i++) {
                    map.put(i, false);
                }

                ExecutorService executor = Executors.newFixedThreadPool(threads);
                for (i = 1; i <= threads; i++) {
                    executor.execute(new ThreadMain("Thread #" + "is "+i));
                    System.out.println("Started Thread: " + i);
                }

                executor.shutdown();
                while (!executor.isTerminated()) {
                }
                try {
                   executor.awaitTermination(5, TimeUnit.NANOSECONDS);
                } catch (InterruptedException e) {
                    System.out.println("Error in terminating threads...");
                }
                // System.out.println(finished);

                // Printing key-value pairs
                // Set set = map.entrySet();
                Set set = ThreadMain.getMap().entrySet();
                Iterator iterator = set.iterator();
                while (iterator.hasNext()) {
                    Map.Entry mentry = (Map.Entry) iterator.next();
                    System.out.print("Key: " + mentry.getKey()  );
                    System.out.println(" & Value: "+mentry.getValue());
                }
            } catch (NumberFormatException e) {
                repeat = true;
                System.out.println("Invalid number format...");
                System.out.println("");
            } catch (IllegalArgumentException e) {
                repeat = true;
                System.out.println("Invalid input format...");
                System.out.println("");
            } catch (Exception e) {
                System.out.println("Error...");
                // e.printStackTrace();
            }
        } while (repeat);

        scan.close();
    }

}
</code>```

file read(runnable class):

```<code>import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Random;

public class ThreadReader {

    public static void Reader(String threadName) {

       // ThreadReaderCheck check = null;
        BufferedReader br = null;
        String line = null;
        Random rand;
        int randomInt;
        boolean generate;
        int i;

        try {
            //check = new ThreadReaderCheck();
            br = new BufferedReader(new FileReader("ThreadCSV.csv"));
                synchronized (br) {
                    // Generating random number
                    generate = false;
                    rand = new Random();

                    do {
                        randomInt = rand.nextInt(11);

                        if (randomInt == 0) {
                            generate = true;
                        } else {
                            System.out.println(threadName + " " + randomInt);
                            if (randomInt > 0 && randomInt < 11) {
                                line = br.readLine();
                                System.out.println(threadName + " " + ThreadMain.map.get(randomInt));
                                if (ThreadMain.map.get(randomInt) == false) {
                                    for (i = 1; i < randomInt; i++) {
                                        line = br.readLine();
                                    }
                                    if (line != null) {
                                        ThreadMain.map.put(randomInt, true);
                                        System.out.println(threadName + " " + line);
                                        Thread.sleep(1000);
                                        br.notifyAll();
                                    }
                                } else {
                                    generate = true;
                                }
                            }
                        }
                    } while (generate);
                }
        } catch (Exception e) {
            System.out.println("Error in reading from file...");
        } finally {
            try {
                br.close();
            } catch (Exception e) {
                System.out.println("Error while closing file...");
            }
        }

    }

}
</code>```

Thanks in Advance.

答:
You will need to build a thread 'lock' so that once a thread is completed, it can finish writing even if the next thread is ready. You can use 'wait' and 'notify' to build this. Insert the code before using print / println to check if the thread is ready and send all other threads the 'wait' signal. This will result in the threads no longer colliding and keep the code output clean.

A great online resource that will help learn to build this into your code is available at: https://www.youtube.com/watch?v=fjMTaVykOpc

ContentLicense: CC BY-SA 3.0

Body:
I am trying to read and print the lines in a csv file.I need to use multi threading for the same.There are 10 lines in the file,if I provide 2 threads(no of threads is  user input dependent) it should read all the 10 lines,where each line should be read and printed once by any of the thread.

But I am unable to successfully execute it.If I provide 2 threads,it will read 2 lines(random lines),doesn't read the remaining  and terminate the program.
I am trying to write the code for it.

main class:

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class ThreadMain implements Runnable {

    String name;
    static Map<Integer, Boolean> map = new HashMap<Integer, Boolean>();

    public synchronized static Map<Integer, Boolean> getMap() {
        return map;
    }

    public synchronized static void setMap(Map<Integer, Boolean> map) {
        ThreadMain.map = map;
    }

    public ThreadMain(String s) {
        name = s;
    }

    public void run() {
        ThreadReader.Reader(name);
    }

    @SuppressWarnings("rawtypes")
    public static void main(String[] args) {

        Scanner scan = null;
        boolean repeat = false;
        int threads;

        do {
            try {
                scan = new Scanner(System.in);
                System.out.print("Enter no. of threads: ");
                threads = Integer.parseInt(scan.nextLine());

                // Initializing map
                int i;
                for (i = 1; i <= 10; i++) {
                    map.put(i, false);
                }

                ExecutorService executor = Executors.newFixedThreadPool(threads);
                for (i = 1; i <= threads; i++) {
                    executor.execute(new ThreadMain("Thread #" + "is "+i));
                    System.out.println("Started Thread: " + i);
                }

                executor.shutdown();
                while (!executor.isTerminated()) {
                }
                try {
                   executor.awaitTermination(5, TimeUnit.NANOSECONDS);
                } catch (InterruptedException e) {
                    System.out.println("Error in terminating threads...");
                }
                // System.out.println(finished);

                // Printing key-value pairs
                // Set set = map.entrySet();
                Set set = ThreadMain.getMap().entrySet();
                Iterator iterator = set.iterator();
                while (iterator.hasNext()) {
                    Map.Entry mentry = (Map.Entry) iterator.next();
                    System.out.print("Key: " + mentry.getKey()  );
                    System.out.println(" & Value: "+mentry.getValue());
                }
            } catch (NumberFormatException e) {
                repeat = true;
                System.out.println("Invalid number format...");
                System.out.println("");
            } catch (IllegalArgumentException e) {
                repeat = true;
                System.out.println("Invalid input format...");
                System.out.println("");
            } catch (Exception e) {
                System.out.println("Error...");
                // e.printStackTrace();
            }
        } while (repeat);

        scan.close();
    }

}

file read(runnable class):

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Random;

public class ThreadReader {

    public static void Reader(String threadName) {

       // ThreadReaderCheck check = null;
        BufferedReader br = null;
        String line = null;
        Random rand;
        int randomInt;
        boolean generate;
        int i;

        try {
            //check = new ThreadReaderCheck();
            br = new BufferedReader(new FileReader("ThreadCSV.csv"));
                synchronized (br) {
                    // Generating random number
                    generate = false;
                    rand = new Random();

                    do {
                        randomInt = rand.nextInt(11);

                        if (randomInt == 0) {
                            generate = true;
                        } else {
                            System.out.println(threadName + " " + randomInt);
                            if (randomInt > 0 && randomInt < 11) {
                                line = br.readLine();
                                System.out.println(threadName + " " + ThreadMain.map.get(randomInt));
                                if (ThreadMain.map.get(randomInt) == false) {
                                    for (i = 1; i < randomInt; i++) {
                                        line = br.readLine();
                                    }
                                    if (line != null) {
                                        ThreadMain.map.put(randomInt, true);
                                        System.out.println(threadName + " " + line);
                                        Thread.sleep(1000);
                                        br.notifyAll();
                                    }
                                } else {
                                    generate = true;
                                }
                            }
                        }
                    } while (generate);
                }
        } catch (Exception e) {
            System.out.println("Error in reading from file...");
        } finally {
            try {
                br.close();
            } catch (Exception e) {
                System.out.println("Error while closing file...");
            }
        }

    }

}

Thanks in Advance.


问:
How to generate JWT Token with IdentityModel Extensions for .NET 5
I am using  IdentityModel Extensions for .NET version 4 to generate JWT token with symmetric key and SHA256 as below and it works perfectly:

```<code>var tokenDescriptor = new SecurityTokenDescriptor
{
    Subject = new ClaimsIdentity(claims),

    TokenIssuerName = Issuer,
    AppliesToAddress = Audience,

    Lifetime = new Lifetime(now, expirationTime),

    SigningCredentials = new SigningCredentials(
        new InMemorySymmetricSecurityKey(symmetricKey),
        "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256",
        "http://www.w3.org/2001/04/xmlenc#sha256"),
};

var securityToken = tokenHandler.CreateToken(tokenDescriptor);
var token = tokenHandler.WriteToken(securitytoken);
</code>```

But when I tried to upgrade to IdentityModel Extensions for .NET 5 as below code:

```<code>var tokenDescriptor = new SecurityTokenDescriptor
{
    Subject = new ClaimsIdentity(claims),

    Issuer = Issuer,
    Audience = Audience,

    Expires = expirationTime,
    SigningCredentials = new SigningCredentials(
        new SymmetricSecurityKey(symmetricKey), "SHA256")
};

var securityToken = tokenHandler.CreateToken(tokenDescriptor);
var token = tokenHandler.WriteToken(stoken);
</code>```

I got exception:

IDX10634: Unable to create the SignatureProvider.

SignatureAlgorithm: 'SHA256', SecurityKey: 'Microsoft.IdentityModel.Tokens.SymmetricSecurityKey'
is not supported.

What's wrong with the new code using version 5.

答:
Here is the solution, it's working </p>

```<code>using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;

using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;

namespace ConsoleApplication2
{

private class JWT
{
private bool verbose = false;
public  string GenerateJWT()
{
    DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);

    RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
    // Provide proper private key
    string privateSecretKey = "OfED+KgbZxtu4e4+JSQWdtSgTnuNixKy1nMVAEww8QL3IN3idcNgbNDSSaV4491Fo3sq2aGSCtYvekzs7JwXJnNAyvDSJjfK/7M8MpxSMnm1vMscBXyiYFXhGC4wqWlYBE828/5DNyw3QZW5EjD7hvDrY5OlYd4smCTa53helNnJz5NT9HQaDbE2sMwIDAQABAoIBAEs63TvT94njrPDP3A/sfCEXg1F2y0D/PjzUhM1aJGcRiOUXnGlYdViGhLnnJoNZTZm9qI1LT0NWcDA5NmBN6gcrk2EApyTt1D1i4AQ66rYoTF9iEC4Wye28v245BYESA6IIelgIxXGsVyllERsbTkaphzibbYfHmvwMxkn135Zfzd/NOXl/O32vYIomzrNEP+tN2WXhhG8c8+iZ8PErBV3CqrYogYy97d2CeQbXcpd5unPiU4TK0nnzeBAXdgeYuJHFC45YHl9UvShRoe6CHR47ceIGp6WMc5BTyyTkZpctuYJTwaChdj/QuRSkTYmn6jFL+MRfYQJ8VVwSVo5DbkECgYEA4/YIMKcwObYcSuHzgkMwH645CRDoy9M98eptAoNLdJBHYz23U5IbGL1+qHDDCPXxKs9ZG7EEqyWezq42eoFoebLA5O6/xrYXoaeIb094dbCF4D932hAkgAaAZkZVsSiWDCjYSV+JoWX4NVBcIL9yyHRhaaPVULTRbPsZQWq9+hMCgYEA48j4RGO7CaVpgUVobYasJnkGSdhkSCd1VwgvHH3vtuk7/JGUBRaZc0WZGcXkAJXnLh7QnDHOzWASdaxVgnuviaDi4CIkmTCfRqPesgDR2Iu35iQsH7P2/o1pzhpXQS/Ct6J7/GwJTqcXCvp4tfZDbFxS8oewzp4RstILj+pDyWECgYByQAbOy5xB8GGxrhjrOl1OI3V2c8EZFqA/NKy5y6/vlbgRpwbQnbNy7NYj+Y/mV80tFYqldEzQsiQrlei78Uu5YruGgZogL3ccj+izUPMgmP4f6+9XnSuN9rQ3jhy4k4zQP1BXRcim2YJSxhnGV+1hReLknTX2IwmrQxXfUW4xfQKBgAHZW8qSVK5bXWPjQFnDQhp92QM4cnfzegxe0KMWkp+VfRsrw1vXNx";

    rsa = DecodeRSAPrivateKey(FromBase64Url(privateSecretKey));
    //convert to csp format
    var bytes = rsa.ExportCspBlob(false);
    var publicKey = Convert.ToBase64String(bytes);
    //

    RsaSecurityKey _signingKey = new RsaSecurityKey(rsa);
    Microsoft.IdentityModel.Tokens.SigningCredentials signingCredentials =
           new Microsoft.IdentityModel.Tokens.SigningCredentials(_signingKey, SecurityAlgorithms.RsaSha256);

    JwtHeader head = new JwtHeader(signingCredentials);
    head.Add("kid", "lzo-firstpublickey");

    string sNewGuid = Guid.NewGuid().ToString("n");

    var claims = new[]
          {
              new Claim(JwtRegisteredClaimNames.Iss, "s6BhdRkqt3"),
              new Claim(JwtRegisteredClaimNames.Sub, "s6BhdRkqt3"),
              new Claim(JwtRegisteredClaimNames.Aud, "https://cis.ncrs/connect/token"),
              new Claim(JwtRegisteredClaimNames.Jti,  sNewGuid),
              new Claim(JwtRegisteredClaimNames.Exp, ((Int64)DateTime.Now.AddMinutes(55).Subtract(UnixEpoch).TotalSeconds).ToString(System.Globalization.CultureInfo.InvariantCulture), ClaimValueTypes.Integer64),
              new Claim(JwtRegisteredClaimNames.Iat, ((Int64)DateTime.Now.Subtract(UnixEpoch).TotalSeconds).ToString(System.Globalization.CultureInfo.InvariantCulture), ClaimValueTypes.Integer64)
          };

    JwtPayload payload = new JwtPayload(claims);
    JwtSecurityToken jwt = new JwtSecurityToken(head, payload);
    jwt.SigningKey = _signingKey;
    var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);
    return encodedJwt;
}

private static byte[] FromBase64Url(string base64Url)
{
    string base64 = string.Empty;
    if (!string.IsNullOrEmpty(base64Url))
    {
        string padded = base64Url.Length % 4 == 0
            ? base64Url : base64Url + "====".Substring(base64Url.Length % 4);
        base64 = padded.Replace("_", "/")
                                .Replace("-", "+");
    }
    return Convert.FromBase64String(base64);
}

private RSACryptoServiceProvider DecodeRSAPrivateKey(byte[] privkey)
{
    byte[] MODULUS, E, D, P, Q, DP, DQ, IQ;

    // ---------  Set up stream to decode the asn.1 encoded RSA private key  ------
    System.IO.MemoryStream mem = new System.IO.MemoryStream(privkey);
    System.IO.BinaryReader binr = new System.IO.BinaryReader(mem);    //wrap Memory Stream with BinaryReader for easy reading
    byte bt = 0;
    ushort twobytes = 0;
    int elems = 0;
    try
    {
        twobytes = binr.ReadUInt16();
        if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
            binr.ReadByte();        //advance 1 byte
        else if (twobytes == 0x8230)
            binr.ReadInt16();       //advance 2 bytes
        else
            return null;

        twobytes = binr.ReadUInt16();
        if (twobytes != 0x0102) //version number
            return null;
        bt = binr.ReadByte();
        if (bt != 0x00)
            return null;

        //------  all private key components are Integer sequences ----
        elems = GetIntegerSize(binr);
        MODULUS = binr.ReadBytes(elems);

        elems = GetIntegerSize(binr);
        E = binr.ReadBytes(elems);

        elems = GetIntegerSize(binr);
        D = binr.ReadBytes(elems);

        elems = GetIntegerSize(binr);
        P = binr.ReadBytes(elems);

        elems = GetIntegerSize(binr);
        Q = binr.ReadBytes(elems);

        elems = GetIntegerSize(binr);
        DP = binr.ReadBytes(elems);

        elems = GetIntegerSize(binr);
        DQ = binr.ReadBytes(elems);

        elems = GetIntegerSize(binr);
        IQ = binr.ReadBytes(elems);

        Console.WriteLine("showing components ..");
        if (verbose)
        {
            showBytes("\nModulus", MODULUS);
            showBytes("\nExponent", E);
            showBytes("\nD", D);
            showBytes("\nP", P);
            showBytes("\nQ", Q);
            showBytes("\nDP", DP);
            showBytes("\nDQ", DQ);
            showBytes("\nIQ", IQ);
        }

        // ------- create RSACryptoServiceProvider instance and initialize with public key -----
        RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
        RSAParameters RSAparams = new RSAParameters();
        RSAparams.Modulus = MODULUS;
        RSAparams.Exponent = E;
        RSAparams.D = D;
        RSAparams.P = P;
        RSAparams.Q = Q;
        RSAparams.DP = DP;
        RSAparams.DQ = DQ;
        RSAparams.InverseQ = IQ;
        RSA.ImportParameters(RSAparams);
        return RSA;
    }
    catch (Exception)
    {
        return null;
    }
    finally
    {
        binr.Close();
    }
}

private void showBytes(String info, byte[] data)
{
    Console.WriteLine("{0}  [{1} bytes]", info, data.Length);
    for (int i = 1; i <= data.Length; i++)
    {
        Console.Write("{0:X2}  ", data[i - 1]);
        if (i % 16 == 0)
            Console.WriteLine();
    }
    Console.WriteLine("\n\n");
}

private int GetIntegerSize(System.IO.BinaryReader binr)
{
    byte bt = 0;
    byte lowbyte = 0x00;
    byte highbyte = 0x00;
    int count = 0;
    bt = binr.ReadByte();
    if (bt != 0x02)     //expect integer
        return 0;
    bt = binr.ReadByte();

    if (bt == 0x81)
        count = binr.ReadByte();    // data size in next byte
    else
        if (bt == 0x82)
        {
            highbyte = binr.ReadByte(); // data size in next 2 bytes
            lowbyte = binr.ReadByte();
            byte[] modint = { lowbyte, highbyte, 0x00, 0x00 };
            count = BitConverter.ToInt32(modint, 0);
        }
        else
        {
            count = bt;     // we already have the data size
        }

    while (binr.ReadByte() == 0x00)
    {   //remove high order zeros in data
        count -= 1;
    }
    binr.BaseStream.Seek(-1, System.IO.SeekOrigin.Current);     //last     ReadByte wasn't a removed zero, so back up a byte
    return count;
}
}
}
</code>```

Body:
I am using  IdentityModel Extensions for .NET version 4 to generate JWT token with symmetric key and SHA256 as below and it works perfectly:

var tokenDescriptor = new SecurityTokenDescriptor
{
    Subject = new ClaimsIdentity(claims),

    TokenIssuerName = Issuer,
    AppliesToAddress = Audience,

    Lifetime = new Lifetime(now, expirationTime),

    SigningCredentials = new SigningCredentials(
        new InMemorySymmetricSecurityKey(symmetricKey),
        "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256",
        "http://www.w3.org/2001/04/xmlenc#sha256"),
};

var securityToken = tokenHandler.CreateToken(tokenDescriptor);
var token = tokenHandler.WriteToken(securitytoken);

But when I tried to upgrade to IdentityModel Extensions for .NET 5 as below code:

var tokenDescriptor = new SecurityTokenDescriptor
{
    Subject = new ClaimsIdentity(claims),

    Issuer = Issuer,
    Audience = Audience,

    Expires = expirationTime,
    SigningCredentials = new SigningCredentials(
        new SymmetricSecurityKey(symmetricKey), "SHA256")
};

var securityToken = tokenHandler.CreateToken(tokenDescriptor);
var token = tokenHandler.WriteToken(stoken);

I got exception:

IDX10634: Unable to create the SignatureProvider.

SignatureAlgorithm: 'SHA256', SecurityKey: 'Microsoft.IdentityModel.Tokens.SymmetricSecurityKey'
is not supported.

What's wrong with the new code using version 5.

Body:
Here is the solution, it's working

using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;

using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;

namespace ConsoleApplication2
{

private class JWT
{
private bool verbose = false;
public  string GenerateJWT()
{
    DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);

    RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
    // Provide proper private key
    string privateSecretKey = "OfED+KgbZxtu4e4+JSQWdtSgTnuNixKy1nMVAEww8QL3IN3idcNgbNDSSaV4491Fo3sq2aGSCtYvekzs7JwXJnNAyvDSJjfK/7M8MpxSMnm1vMscBXyiYFXhGC4wqWlYBE828/5DNyw3QZW5EjD7hvDrY5OlYd4smCTa53helNnJz5NT9HQaDbE2sMwIDAQABAoIBAEs63TvT94njrPDP3A/sfCEXg1F2y0D/PjzUhM1aJGcRiOUXnGlYdViGhLnnJoNZTZm9qI1LT0NWcDA5NmBN6gcrk2EApyTt1D1i4AQ66rYoTF9iEC4Wye28v245BYESA6IIelgIxXGsVyllERsbTkaphzibbYfHmvwMxkn135Zfzd/NOXl/O32vYIomzrNEP+tN2WXhhG8c8+iZ8PErBV3CqrYogYy97d2CeQbXcpd5unPiU4TK0nnzeBAXdgeYuJHFC45YHl9UvShRoe6CHR47ceIGp6WMc5BTyyTkZpctuYJTwaChdj/QuRSkTYmn6jFL+MRfYQJ8VVwSVo5DbkECgYEA4/YIMKcwObYcSuHzgkMwH645CRDoy9M98eptAoNLdJBHYz23U5IbGL1+qHDDCPXxKs9ZG7EEqyWezq42eoFoebLA5O6/xrYXoaeIb094dbCF4D932hAkgAaAZkZVsSiWDCjYSV+JoWX4NVBcIL9yyHRhaaPVULTRbPsZQWq9+hMCgYEA48j4RGO7CaVpgUVobYasJnkGSdhkSCd1VwgvHH3vtuk7/JGUBRaZc0WZGcXkAJXnLh7QnDHOzWASdaxVgnuviaDi4CIkmTCfRqPesgDR2Iu35iQsH7P2/o1pzhpXQS/Ct6J7/GwJTqcXCvp4tfZDbFxS8oewzp4RstILj+pDyWECgYByQAbOy5xB8GGxrhjrOl1OI3V2c8EZFqA/NKy5y6/vlbgRpwbQnbNy7NYj+Y/mV80tFYqldEzQsiQrlei78Uu5YruGgZogL3ccj+izUPMgmP4f6+9XnSuN9rQ3jhy4k4zQP1BXRcim2YJSxhnGV+1hReLknTX2IwmrQxXfUW4xfQKBgAHZW8qSVK5bXWPjQFnDQhp92QM4cnfzegxe0KMWkp+VfRsrw1vXNx";

    rsa = DecodeRSAPrivateKey(FromBase64Url(privateSecretKey));
    //convert to csp format
    var bytes = rsa.ExportCspBlob(false);
    var publicKey = Convert.ToBase64String(bytes);
    //

    RsaSecurityKey _signingKey = new RsaSecurityKey(rsa);
    Microsoft.IdentityModel.Tokens.SigningCredentials signingCredentials =
           new Microsoft.IdentityModel.Tokens.SigningCredentials(_signingKey, SecurityAlgorithms.RsaSha256);

    JwtHeader head = new JwtHeader(signingCredentials);
    head.Add("kid", "lzo-firstpublickey");

    string sNewGuid = Guid.NewGuid().ToString("n");

    var claims = new[]
          {
              new Claim(JwtRegisteredClaimNames.Iss, "s6BhdRkqt3"),
              new Claim(JwtRegisteredClaimNames.Sub, "s6BhdRkqt3"),
              new Claim(JwtRegisteredClaimNames.Aud, "https://cis.ncrs/connect/token"),
              new Claim(JwtRegisteredClaimNames.Jti,  sNewGuid),
              new Claim(JwtRegisteredClaimNames.Exp, ((Int64)DateTime.Now.AddMinutes(55).Subtract(UnixEpoch).TotalSeconds).ToString(System.Globalization.CultureInfo.InvariantCulture), ClaimValueTypes.Integer64),
              new Claim(JwtRegisteredClaimNames.Iat, ((Int64)DateTime.Now.Subtract(UnixEpoch).TotalSeconds).ToString(System.Globalization.CultureInfo.InvariantCulture), ClaimValueTypes.Integer64)
          };

    JwtPayload payload = new JwtPayload(claims);
    JwtSecurityToken jwt = new JwtSecurityToken(head, payload);
    jwt.SigningKey = _signingKey;
    var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);
    return encodedJwt;
}

private static byte[] FromBase64Url(string base64Url)
{
    string base64 = string.Empty;
    if (!string.IsNullOrEmpty(base64Url))
    {
        string padded = base64Url.Length % 4 == 0
            ? base64Url : base64Url + "====".Substring(base64Url.Length % 4);
        base64 = padded.Replace("_", "/")
                                .Replace("-", "+");
    }
    return Convert.FromBase64String(base64);
}

private RSACryptoServiceProvider DecodeRSAPrivateKey(byte[] privkey)
{
    byte[] MODULUS, E, D, P, Q, DP, DQ, IQ;

    // ---------  Set up stream to decode the asn.1 encoded RSA private key  ------
    System.IO.MemoryStream mem = new System.IO.MemoryStream(privkey);
    System.IO.BinaryReader binr = new System.IO.BinaryReader(mem);    //wrap Memory Stream with BinaryReader for easy reading
    byte bt = 0;
    ushort twobytes = 0;
    int elems = 0;
    try
    {
        twobytes = binr.ReadUInt16();
        if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
            binr.ReadByte();        //advance 1 byte
        else if (twobytes == 0x8230)
            binr.ReadInt16();       //advance 2 bytes
        else
            return null;

        twobytes = binr.ReadUInt16();
        if (twobytes != 0x0102) //version number
            return null;
        bt = binr.ReadByte();
        if (bt != 0x00)
            return null;

        //------  all private key components are Integer sequences ----
        elems = GetIntegerSize(binr);
        MODULUS = binr.ReadBytes(elems);

        elems = GetIntegerSize(binr);
        E = binr.ReadBytes(elems);

        elems = GetIntegerSize(binr);
        D = binr.ReadBytes(elems);

        elems = GetIntegerSize(binr);
        P = binr.ReadBytes(elems);

        elems = GetIntegerSize(binr);
        Q = binr.ReadBytes(elems);

        elems = GetIntegerSize(binr);
        DP = binr.ReadBytes(elems);

        elems = GetIntegerSize(binr);
        DQ = binr.ReadBytes(elems);

        elems = GetIntegerSize(binr);
        IQ = binr.ReadBytes(elems);

        Console.WriteLine("showing components ..");
        if (verbose)
        {
            showBytes("\nModulus", MODULUS);
            showBytes("\nExponent", E);
            showBytes("\nD", D);
            showBytes("\nP", P);
            showBytes("\nQ", Q);
            showBytes("\nDP", DP);
            showBytes("\nDQ", DQ);
            showBytes("\nIQ", IQ);
        }

        // ------- create RSACryptoServiceProvider instance and initialize with public key -----
        RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
        RSAParameters RSAparams = new RSAParameters();
        RSAparams.Modulus = MODULUS;
        RSAparams.Exponent = E;
        RSAparams.D = D;
        RSAparams.P = P;
        RSAparams.Q = Q;
        RSAparams.DP = DP;
        RSAparams.DQ = DQ;
        RSAparams.InverseQ = IQ;
        RSA.ImportParameters(RSAparams);
        return RSA;
    }
    catch (Exception)
    {
        return null;
    }
    finally
    {
        binr.Close();
    }
}

private void showBytes(String info, byte[] data)
{
    Console.WriteLine("{0}  [{1} bytes]", info, data.Length);
    for (int i = 1; i <= data.Length; i++)
    {
        Console.Write("{0:X2}  ", data[i - 1]);
        if (i % 16 == 0)
            Console.WriteLine();
    }
    Console.WriteLine("\n\n");
}

private int GetIntegerSize(System.IO.BinaryReader binr)
{
    byte bt = 0;
    byte lowbyte = 0x00;
    byte highbyte = 0x00;
    int count = 0;
    bt = binr.ReadByte();
    if (bt != 0x02)     //expect integer
        return 0;
    bt = binr.ReadByte();

    if (bt == 0x81)
        count = binr.ReadByte();    // data size in next byte
    else
        if (bt == 0x82)
        {
            highbyte = binr.ReadByte(); // data size in next 2 bytes
            lowbyte = binr.ReadByte();
            byte[] modint = { lowbyte, highbyte, 0x00, 0x00 };
            count = BitConverter.ToInt32(modint, 0);
        }
        else
        {
            count = bt;     // we already have the data size
        }

    while (binr.ReadByte() == 0x00)
    {   //remove high order zeros in data
        count -= 1;
    }
    binr.BaseStream.Seek(-1, System.IO.SeekOrigin.Current);     //last     ReadByte wasn't a removed zero, so back up a byte
    return count;
}
}
}


问:
ExpressJS - How to change the value of key in the url of a get request
So I am developing custom pagination functionality with express and mongoose. I have a get parameter called page and I need to change the value for every different page. The problem is that the way I do it it keeps appending "page" key-value pairs to the url like this "&page=1&page=1&page=1". That is because I don't simply change the value of "page" but I append the key-value pair each time like so:

```<code>currentPageUrl: req.originalUrl + '&page=' + currentPage
</code>```

I need just to change the value of the "page" key. How can I accomplish this? Any advice, express helper function or custom solution would help a lot. Thanks in advance!

答:
Try using the URL library. Refer to this page. https://nodejs.org/docs/latest/api/url.html#url_url_parse_urlstring_parsequerystring_slashesdenotehost

You can tweak your url however you would like to.

So in your case I would get url.origin and url.pathname but it would depend on what you want to get.

Body:
So I am developing custom pagination functionality with express and mongoose. I have a get parameter called page and I need to change the value for every different page. The problem is that the way I do it it keeps appending "page" key-value pairs to the url like this "&page=1&page=1&page=1". That is because I don't simply change the value of "page" but I append the key-value pair each time like so:

currentPageUrl: req.originalUrl + '&page=' + currentPage

I need just to change the value of the "page" key. How can I accomplish this? Any advice, express helper function or custom solution would help a lot. Thanks in advance!


答:
If you know that the page=xxx param is already there, you can use .replace():

```<code>currentPageUrl: req.originalUrl.replace(/page=[^&]+/, "page=" + currentPage)
</code>```

If you don't know for sure whether it is there, then you have to test for it first:

```<code>let newUrl;
if (req.originalUrl.indexOf("page=") !== -1) {
    newUrl = req.originalUrl.replace(/page=[^&]+/, "page=" + currentPage);
} else if (req.originalUrl.indexOf("?") === -1) {
    newUrl = req.originalUrl + "?page=" + currentPage);
} else {
    newUrl = req.originalUrl + "&page=" + currentPage);
}
</code>```

Various test cases:

function updatePage(origUrl, currentPage) {
    let newUrl;
    if (origUrl.indexOf("page=") !== -1) {
        newUrl = origUrl.replace(/page=[^&]+/, "page=" + currentPage);
    } else if (origUrl.indexOf("?") === -1) {
        newUrl = origUrl + "?page=" + currentPage;
    } else {
        newUrl = origUrl + "&page=" + currentPage;
    }
    return newUrl;
}

// test cases
console.log(updatePage("http://somedomain.com/somePath?page=3", 5));
console.log(updatePage("http://somedomain.com/somePath?whatever=something&page=3", 5));
console.log(updatePage("http://somedomain.com/somePath", 5));
console.log(updatePage("http://somedomain.com/somePath?page=3&whatever=something", 5));```
</div>
</div>
</p>

<hr>

<p>You could also use the <code>url</code> library to parse the URL into its parts, change one part, then regenerate the full URL:</p>

``` const url = require('url');

 let parsedUrl = url.parse(req.originalUrl, true);
 parsedUrl.query.page = currentPage;
 delete parsedUrl.search;
 let newUrl = url.format(parsedUrl);
```

Title: ExpressJS - How to change the value of key in the url of a get request

Body:
If you know that the page=xxx param is already there, you can use .replace():

currentPageUrl: req.originalUrl.replace(/page=[^&]+/, "page=" + currentPage)

If you don't know for sure whether it is there, then you have to test for it first:

let newUrl;
if (req.originalUrl.indexOf("page=") !== -1) {
    newUrl = req.originalUrl.replace(/page=[^&]+/, "page=" + currentPage);
} else if (req.originalUrl.indexOf("?") === -1) {
    newUrl = req.originalUrl + "?page=" + currentPage);
} else {
    newUrl = req.originalUrl + "&page=" + currentPage);
}

Various test cases:

function updatePage(origUrl, currentPage) {
    let newUrl;
    if (origUrl.indexOf("page=") !== -1) {
        newUrl = origUrl.replace(/page=[^&]+/, "page=" + currentPage);
    } else if (origUrl.indexOf("?") === -1) {
        newUrl = origUrl + "?page=" + currentPage;
    } else {
        newUrl = origUrl + "&page=" + currentPage;
    }
    return newUrl;
}

// test cases
console.log(updatePage("http://somedomain.com/somePath?page=3", 5));
console.log(updatePage("http://somedomain.com/somePath?whatever=something&page=3", 5));
console.log(updatePage("http://somedomain.com/somePath", 5));
console.log(updatePage("http://somedomain.com/somePath?page=3&whatever=something", 5));

You could also use the url library to parse the URL into its parts, change one part, then regenerate the full URL:

 const url = require('url');

 let parsedUrl = url.parse(req.originalUrl, true);
 parsedUrl.query.page = currentPage;
 delete parsedUrl.search;
 let newUrl = url.format(parsedUrl);


问:
How to check if C++ abstract method is defined at runtime
How to check if C++ abstract method is defined at runtime

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

class BBase: public ABase{
public:
 virtual void do1(){}
};

class CBase: public ABase{
public:
};

ABase * base = rand() % 2 ? new BBase() : new CBase();
if(&(base->do1) != 0)
  base->do1();
</code>```

This gives error.

Thanks,
Max

答:
Assuming you remember to make do1() virtual you could check &ABase::do1, &BBase::do1 and &CBase::do1 at runtime. I am not convinced that comparing &ABase::do1 and &CBase::do1 will return the same value just because CBase has not overridden the function, and whether just because it does on one system means it always will.

Whilst you may be able to test these at runtime you would not be able to use the information to create an object of the class CBase if it is not abstract as it will fail to compile when it is.

You could instead do it the "C" way though: have a table of function pointers that can be NULL, check if one of them is NULL, and create a struct of such an instance or invoke it if it isn't.

Body:
How to check if C++ abstract method is defined at runtime

class ABase{
public:
 virtual void do1() = 0;
};

class BBase: public ABase{
public:
 virtual void do1(){}
};

class CBase: public ABase{
public:
};

ABase * base = rand() % 2 ? new BBase() : new CBase();
if(&(base->do1) != 0)
  base->do1();

This gives error.

Thanks,
Max


问:
I installed reFInd on my macbook pro 2016 with --alldrivers and now it powers up with a black screen
I tried to install Ubuntu on another partition, reFInd was working fine but after selecting Install Ubuntu only a black screen showed up. I used nomodeset but it didn't work either. So I thought ./install.sh --alldrivers would work I reinstalled reFInd and now my macbook powers up into a black screen.

答: Alright the CMD + ALT + R + P solved the problem I uninstalled reFInd if anybody got Ubuntu working on Macbook Pro 2016 please let me know ty</p>


问:
I want to implement a function about I/O in Android studio: see if ‘list.txt’ exists then initialize a listview with the strings in the file
Requirements:
When the application is executed, it should now check to see if ‘list.txt’ exists. If it does, it should initialize the To Do List with the file contents. If it does not, do not open the stream to list.txt.

And my code is:

```<code>public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener,TextToSpeech.OnInitListener {

    private ArrayList<String> noteList = new ArrayList<>();
    private ArrayAdapter<String> adapter = null;
    private EditText input;
    private ListView listview;
    String noteText; //text of the note
    private TextToSpeech speaker;

    private int clickedIndex; //starting from 0
    private int indexEndPos;
    private boolean clicked; // initialized to false
    private static final String tag = "Widgets";

    private final String file = "list.txt";

    private OutputStreamWriter out;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        input = (EditText) findViewById(R.id.inputField);
        listview = (ListView) findViewById(R.id.list);
        listview.setOnItemClickListener(this);

// open stream for reading
//Read text from file

        BufferedReader inputStream = null;
        try {
            inputStream =
                    new BufferedReader(new FileReader(file));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        String line;
        int i = 0;
        String[] text = new String[20];
        try {
            while ((line = inputStream.readLine())!= null) {
                text[i++] = line;
            }   inputStream.close();
            ArrayList<String> stringList = new ArrayList<String>(Arrays.asList(text));
            adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, text);
            listview.setAdapter(adapter);
            adapter.notifyDataSetChanged();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            out = new OutputStreamWriter(openFileOutput(file, MODE_PRIVATE));
        } catch (FileNotFoundException e3) {
            e3.printStackTrace();
        }
    }
</code>```

答:
```<code>File file = new File(<PATH_TO_DIRECTORY>, <FILE_NAME>);

if (file.exists()) {
    //Open the stream and get file contents
} else {
    //Don't open the stream and do whatever else
}
</code>```

A few extra tidbits:

If your file is stored in external storage, the directory path should be:

```<code>new File(Environment.getExternalStorageDirectory().getAbsolutePath(), <FILE_NAME>);
</code>```

^^Permissions are required to read from and write to external storage.

If your file is stored in your App's internal storage:

```<code>new File(context.getFilesDir().getAbsolutePath(), <FILE_NAME>);
</code>```

^^No permissions required, Contents not visible anywhere except your app.

If you're trying to read a file from the assets folder, you can get an InputStream of the file directly from AssetManager, which can be accessed with getAssets():

```<code>InputStream in = context.getAssets().open("list.txt");
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Requirements:
When the application is executed, it should now check to see if ‘list.txt’ exists. If it does, it should initialize the To Do List with the file contents. If it does not, do not open the stream to list.txt.

And my code is:

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener,TextToSpeech.OnInitListener {

    private ArrayList<String> noteList = new ArrayList<>();
    private ArrayAdapter<String> adapter = null;
    private EditText input;
    private ListView listview;
    String noteText; //text of the note
    private TextToSpeech speaker;

    private int clickedIndex; //starting from 0
    private int indexEndPos;
    private boolean clicked; // initialized to false
    private static final String tag = "Widgets";

    private final String file = "list.txt";

    private OutputStreamWriter out;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        input = (EditText) findViewById(R.id.inputField);
        listview = (ListView) findViewById(R.id.list);
        listview.setOnItemClickListener(this);

// open stream for reading
//Read text from file

        BufferedReader inputStream = null;
        try {
            inputStream =
                    new BufferedReader(new FileReader(file));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        String line;
        int i = 0;
        String[] text = new String[20];
        try {
            while ((line = inputStream.readLine())!= null) {
                text[i++] = line;
            }   inputStream.close();
            ArrayList<String> stringList = new ArrayList<String>(Arrays.asList(text));
            adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, text);
            listview.setAdapter(adapter);
            adapter.notifyDataSetChanged();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            out = new OutputStreamWriter(openFileOutput(file, MODE_PRIVATE));
        } catch (FileNotFoundException e3) {
            e3.printStackTrace();
        }
    }

Body:
File file = new File(<PATH_TO_DIRECTORY>, <FILE_NAME>);

if (file.exists()) {
    //Open the stream and get file contents
} else {
    //Don't open the stream and do whatever else
}

A few extra tidbits:

If your file is stored in external storage, the directory path should be:

new File(Environment.getExternalStorageDirectory().getAbsolutePath(), <FILE_NAME>);

^^Permissions are required to read from and write to external storage.

If your file is stored in your App's internal storage:

new File(context.getFilesDir().getAbsolutePath(), <FILE_NAME>);

^^No permissions required, Contents not visible anywhere except your app.

If you're trying to read a file from the assets folder, you can get an InputStream of the file directly from AssetManager, which can be accessed with getAssets():

InputStream in = context.getAssets().open("list.txt");


问:
When is it appropriate to use synchronous ajax?
I was just reading another question about jQuery's synchronous ajax call, and I got to wondering:

What circumstances make a synchronous version of an ajax call beneficial/necessary?

Ideally I'd like an example, and why synchronous is better than standard ajax.

答:
The only reasonable example I can think of (that can't be worked around another way) is making a call in window.onbeforeunload, where you need it to be synchronous, or the page will move on and the request will never complete.

In this specific case using standard/asynchronous behavior, you're all but assured the request will die too early to have any impact, or ever contact the server.

I'm not saying I'm in favor of doing this, quite the opposite (as it negatively impacts the user's browsing speed).  But...there's not much option here.


问:
How to make a button that has different parts?
I want to make a button that looks similar to the Club Penguin button you click when you want to join a server.

In this picture you see that the button has three main parts, the emoji, the name, and the amount of people playing.

How can I make a button that is similar to this with multiple parts? Or would a div be better for this? Either way, I want the user to be able to click on it.

This is what I tried but i'm having difficulties.

```<code><div id="container">
  <button id="button">
    <div id="first">
      Emoji
    </div>
    <div id="second">
      Name
    </div>
    <div id="third">
      Player count
    </div>
  </button>
</div>
</code>```

CSS:

```<code>#button {
  width:400px;
}
#first {
  float:left;
}
#second {
  float:center;
}
#third {
  float:right;
}
</code>```

https://jsfiddle.net/rmozk80x/

答:
Try this:

```<code>#button {
width:400px;
}

#first {
float:left;
width: 33%;
text-align: left;
background-color:
}

#second {
float:left;
text-align: center;
}
#third {
float:right;
}
</code>```

Don't center Second, but align it left and align the contents as needed.
You can adjust the width of the first div too.

Body:
I want to make a button that looks similar to the Club Penguin button you click when you want to join a server.

In this picture you see that the button has three main parts, the emoji, the name, and the amount of people playing.

How can I make a button that is similar to this with multiple parts? Or would a div be better for this? Either way, I want the user to be able to click on it.

This is what I tried but i'm having difficulties.

  <button id="button">

      Emoji

      Name

      Player count

  </button>

CSS:

#button {
  width:400px;
}
#first {
  float:left;
}
#second {
  float:center;
}
#third {
  float:right;
}

https://jsfiddle.net/rmozk80x/

Body:
Try this:

#button {
width:400px;
}

#first {
float:left;
width: 33%;
text-align: left;
background-color:
}

#second {
float:left;
text-align: center;
}
#third {
float:right;
}

Don't center Second, but align it left and align the contents as needed.
You can adjust the width of the first div too.


问:
Can't find system.out.println()
I created a project, it asked me to select JDK version and finish.

I couldn't find system namespace in autocomplete.

I typed it manually but IDEA told me that system doesn't exist.

答: This can also happen because user has not created any main function or trying to test this directly in class without any function</p>

Title: Can't find system.out.println()


问:
How can you send what's app messages programmatically in android?
I am trying to implement a functionality similar to what Pushbullet does i.e reply to whats app messages programmatically without entering WhatsApp. </p>

<p>Any help will be appreciated, Thanks. </p>

答:
Careful : it's illegal
take a look at library :
https://github.com/tgalal/yowsup</p>

Body:
I am trying to implement a functionality similar to what Pushbullet does i.e reply to whats app messages programmatically without entering WhatsApp.

Any help will be appreciated, Thanks.


问:
How can I upload picture from android app to server?
I have developed a little part. It can take the picture only not storing now.I want to upload picture (using camera) from android app to server. I have used retrofit library, web service(asp.net). How can I do that?

MANIFEST:

```<code><uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
</code>```

CODE:

```<code>public class UploadPhotoActivity extends AppCompatActivity {
    static final int REQUEST_IMAGE_CAPTURE = 1;

    ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload_photo);

        imageView=(ImageView)findViewById(R.id.imageView);

    }

    public void SelectPhotoMethod(View view){

        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        }

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            Bundle extras = data.getExtras();
            Bitmap imageBitmap = (Bitmap) extras.get("data");
            imageView.setImageBitmap(imageBitmap);
        }
    }

}
</code>```

答:
You can use MultipartEntity to upload MultiPart image to server or

You can also use well known Volley or Retrofit library to upload image to server with minimal codes.

MultiPart

Uploading Camera Image, Video to Server with Progress Bar

Volley or Retrofit

Android Volley Tutorial to Upload Image to Server

Upload Image From Android App Using Retrofit 2

More Tutorials:

Upload File To Server

Android Upload Image using Android Upload Service

Hope this will help~

Body:
I have developed a little part. It can take the picture only not storing now.I want to upload picture (using camera) from android app to server. I have used retrofit library, web service(asp.net). How can I do that?

MANIFEST:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

CODE:

public class UploadPhotoActivity extends AppCompatActivity {
    static final int REQUEST_IMAGE_CAPTURE = 1;

    ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload_photo);

        imageView=(ImageView)findViewById(R.id.imageView);

    }

    public void SelectPhotoMethod(View view){

        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        }

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            Bundle extras = data.getExtras();
            Bitmap imageBitmap = (Bitmap) extras.get("data");
            imageView.setImageBitmap(imageBitmap);
        }
    }

}


问:
Changing server IP breaks webserver
I start with a new ubuntu instance, I install mysql and apapche or nginx. The server works, the security groups are fine. If I start and stop the server, the webserver still works.

If I give it an elastic IP the webserver stops working. If I create a new server with the image of that server, it doesn't work because it has a different IP, although I can always SSH in anytime. Its just when it changes IP from when I create and install the box, the webserver stops working. It has the same security group and the webserver is running

答:
Based upon your question, it is not clear what steps you are following. I will try and outline them, and hope this helps and is on the mark.

Create an image of you current server.
(The process of creation will bring down your server for a couple of minutes.)

Verify image creation - then create a new instance but chose the AMI you just created for the new instance.

Either make sure you assign a IP address (check the box) if you want a static IP, or leave it empty if  you will immediately assign an ElasticIP after setup to your new instance.

If you chose ElasticIP then if it is running on an old instance it will be removed from the old instance and placed on the new. If you use a new ElasticIP then of course, you create one and attach it.

5 Your new machine should be on either the static IP it was given, or the ElasticIP you attached to it.

If this is not clear start with the docs posted here.

It could be I did not fully understand the problem in your case but these are the basic steps.

Title: Changing server IP breaks webserver


问:
"error: file not specified" while importing XML file through maximo integration framework with XSLT in enterprise service
I'm working on XSLT in maximo.

I have written an XSLT for mapping external field name with maximo fields for invbalances. I have given the path of XSLT file (C:\mif\schema\external\sampleinv4.xsl) in enterprise service.

When I try to import an XML file I am getting the error

BMXAA4214E - An unknown error has occurred.

  Please contact your system administrator for assistance.

  Gather the logs from the  directory and determine where and why the error is thrown.

      com.ibm.xtq.xslt.jaxp.HandledRuntimeException:

  C:\mif\schema\external\sampleinv4.xsl (The system cannot find the file specified.)

but the file is specified in correct path.
XSLT file:

```<code><?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"         xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:maximoMappings="local" exclude-result-prefixes="xs">
    <xsl:output method="xml" encoding="UTF-8" indent="yes"/>
    <xsl:template match="/">
        <SyncTESTALCONINVBALANCE xmlns="http://www.ibm.com/maximo">
            <TESTALCONINVBALANCESet>
                <INVBALANCES>
                    <SITEID>
                        <xsl:value-of select="SITEID"/>
                    </SITEID>
                    <ITEMNUM>
                        <xsl:value-of select="ITEMNUM"/>
                    </ITEMNUM>
                    <ITEMSETID>
                        <xsl:value-of select="ITEMSETID"/>
                    </ITEMSETID>
                    <LOCATION>
                        <xsl:value-of select="LOCATION"/>
                    </LOCATION>
                    <BINNUM>
                        <xsl:value-of select="BINNUM"/>
                    </BINNUM>
                    <CURBAL>
                        <xsl:value-of select="ONHANDBAL"/>
                    </CURBAL>
                </INVBALANCES>
            </TESTALCONINVBALANCESet>
        </SyncTESTALCONINVBALANCE>
    </xsl:template>
</xsl:stylesheet>
</code>```

`
XML file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<SyncTESTALCONINVBALANCE xmlns="http://www.ibm.com/maximo"
                         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  creationDateTime="2017-03-22T18:37:26+05:30" transLanguage="EN"  baseLanguage="EN" messageID="7798510.1490188046810982972"  maximoVersion="7 6 20141117-2230 V7600-218" event="0">
    <TESTALCONINVBALANCESet>
        <INVBALANCES>
            <SITEID>FLEET</SITEID>
            <ITEMNUM>11R22.5GS-16</ITEMNUM>
            <ITEMSETID>SET1</ITEMSETID>
            <LOCATION>DALLAS</LOCATION>
            <BINNUM />
            <ONHANDBAL>16.0</ONHANDBAL>
        </INVBALANCES>
    </TESTALCONINVBALANCESet>
</SyncTESTALCONINVBALANCE>
</code>```

答: File name in XSLT path and filename in Error message seems to be different. After adding new XSLT please try restarting the app server.</p>

Body:
I'm working on XSLT in maximo.

I have written an XSLT for mapping external field name with maximo fields for invbalances. I have given the path of XSLT file (C:\mif\schema\external\sampleinv4.xsl) in enterprise service.

When I try to import an XML file I am getting the error

BMXAA4214E - An unknown error has occurred.

  Please contact your system administrator for assistance.

  Gather the logs from the  directory and determine where and why the error is thrown.

      com.ibm.xtq.xslt.jaxp.HandledRuntimeException:

  C:\mif\schema\external\sampleinv4.xsl (The system cannot find the file specified.)

but the file is specified in correct path.
XSLT file:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"         xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:maximoMappings="local" exclude-result-prefixes="xs">
    <xsl:output method="xml" encoding="UTF-8" indent="yes"/>
    <xsl:template match="/">
        <SyncTESTALCONINVBALANCE xmlns="http://www.ibm.com/maximo">
            <TESTALCONINVBALANCESet>
                <INVBALANCES>
                    <SITEID>
                        <xsl:value-of select="SITEID"/>
                    </SITEID>
                    <ITEMNUM>
                        <xsl:value-of select="ITEMNUM"/>
                    </ITEMNUM>
                    <ITEMSETID>
                        <xsl:value-of select="ITEMSETID"/>
                    </ITEMSETID>
                    <LOCATION>
                        <xsl:value-of select="LOCATION"/>
                    </LOCATION>
                    <BINNUM>
                        <xsl:value-of select="BINNUM"/>
                    </BINNUM>
                    <CURBAL>
                        <xsl:value-of select="ONHANDBAL"/>
                    </CURBAL>
                </INVBALANCES>
            </TESTALCONINVBALANCESet>
        </SyncTESTALCONINVBALANCE>
    </xsl:template>
</xsl:stylesheet>

`
XML file:

<?xml version="1.0" encoding="UTF-8"?>
<SyncTESTALCONINVBALANCE xmlns="http://www.ibm.com/maximo"
                         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  creationDateTime="2017-03-22T18:37:26+05:30" transLanguage="EN"  baseLanguage="EN" messageID="7798510.1490188046810982972"  maximoVersion="7 6 20141117-2230 V7600-218" event="0">
    <TESTALCONINVBALANCESet>
        <INVBALANCES>
            <SITEID>FLEET</SITEID>
            <ITEMNUM>11R22.5GS-16</ITEMNUM>
            <ITEMSETID>SET1</ITEMSETID>
            <LOCATION>DALLAS</LOCATION>
            <BINNUM />
            <ONHANDBAL>16.0</ONHANDBAL>
        </INVBALANCES>
    </TESTALCONINVBALANCESet>
</SyncTESTALCONINVBALANCE>


问:
Magento: Custom module works in localhost but not in server
Using magento 1.9 I have a custom module that should appear in the product view, it works fine on the xampp server in my localhost, but when i upload the module files to the server it doesnt work, despite it appear as enable in the System>Confinguration on Disable Modules Output.
Is it something on my code or is the server?

This is the in the csharls_productmeasure.xml inside app\etc\modules

```<code><?xml version="1.0" encoding="UTF-8"?>
    <config>
        <modules>
            <csharls_productmeasure>
                <active>true</active>
                <codePool>local</codePool>
            </csharls_productmeasure>
        </modules>
    </config>
</code>```

This is the config.xml inside of app\code\local\csharls\productmeasure\etc

```<code><?xml version="1.0" encoding="UTF-8"?>
 <config>
    <modules>
        <csharls_productmeasure>
        <version>0.0.1</version>
        </csharls_productmeasure>
    </modules>
    <global>
        <models>
            <productmeasure>
                <class>csharls_productmeasure_Model</class>
            </productmeasure>
        </models>
        <blocks>
            <productmeasure>
                <class>csharls_productmeasure_Block</class>
            </productmeasure>
        </blocks>
        <events>
          <sales_quote_add_item>
           <observers>
             <productmeasure>
                  <type>singleton</type>
                  <class>csharls_productmeasure_Model_Observer</class>
                    <method>updatePrice</method>
                  </productmeasure>
              </observers>
           </sales_quote_add_item>
       </events>
    </global>
    <frontend>
      <routers>
          <productmeasure>
                <use>standard</use>
                <args>
                    <module>csharls_productmeasure</module>
                    <frontName>productmeasure</frontName>
                </args>
            </productmeasure>
        </routers>
        <layout>
            <updates>
                <csharls_productmeasure>
                    <file>csharls_productmeasure.xml</file>
                </csharls_productmeasure>
            </updates>
        </layout>
    </frontend>
</config>
</code>```

答:
The problem appeared int the Server because it runs on linux while my XAMPP localhost is on Windows. Windows is not case sensitive while linux is case sensitive. So when i was creating the folders and files, i wrote the names in lowercase to avoid this but ironically that was the problem, in Magento the inital leter have to be Capital leter,

so my module folders were wrote in lowercase like this:

csharls/productmeasure/... it works in windows but not in linux.

I changed it to inital capital letter like this:

Csharls/Productmeasure/... this works in windows and linux.

Also changed the namespace of Blocks, controllers, Model files and the name of the files all of them has to be intial capitalLetter, all the references in the .xml files aswell.

The template csharls_prodcutmeasure.xml file and layout csharls_productmeasure.phtml file where the only ones that i didnt rename.

Body:
Using magento 1.9 I have a custom module that should appear in the product view, it works fine on the xampp server in my localhost, but when i upload the module files to the server it doesnt work, despite it appear as enable in the System>Confinguration on Disable Modules Output.
Is it something on my code or is the server?

This is the in the csharls_productmeasure.xml inside app\etc\modules

<?xml version="1.0" encoding="UTF-8"?>
    <config>
        <modules>
            <csharls_productmeasure>
                <active>true</active>
                <codePool>local</codePool>
            </csharls_productmeasure>
        </modules>
    </config>

This is the config.xml inside of app\code\local\csharls\productmeasure\etc

<?xml version="1.0" encoding="UTF-8"?>
 <config>
    <modules>
        <csharls_productmeasure>
        <version>0.0.1</version>
        </csharls_productmeasure>
    </modules>
    <global>
        <models>
            <productmeasure>
                <class>csharls_productmeasure_Model</class>
            </productmeasure>
        </models>
        <blocks>
            <productmeasure>
                <class>csharls_productmeasure_Block</class>
            </productmeasure>
        </blocks>
        <events>
          <sales_quote_add_item>
           <observers>
             <productmeasure>
                  <type>singleton</type>
                  <class>csharls_productmeasure_Model_Observer</class>
                    <method>updatePrice</method>
                  </productmeasure>
              </observers>
           </sales_quote_add_item>
       </events>
    </global>
    <frontend>
      <routers>
          <productmeasure>
                <use>standard</use>
                <args>
                    <module>csharls_productmeasure</module>
                    <frontName>productmeasure</frontName>
                </args>
            </productmeasure>
        </routers>
        <layout>
            <updates>
                <csharls_productmeasure>
                    <file>csharls_productmeasure.xml</file>
                </csharls_productmeasure>
            </updates>
        </layout>
    </frontend>
</config>


问:
Models load() usage
Can someone enligthen me ,what is the real usage of load method if setting post params can  be directly set to models attributes? Thanks

$model->load(Yii::$app->request->post());

vs

$model->attributes = Yii::$app->request->post();

答:
The main purpose of load($data, $formName) is to return boolean true if the expected $formName is found in $data. Thus, you can bypass the following:

```<code>if (isset($_POST['FormName'])) {
    $model->attributes = $_POST['FormName'];
    do_something_here;
}
</code>```

with

```<code>$post = Yii::$app->request->post();
if ($model->load($post)) {
    do_something_here;
}
</code>```

It's interesting for more, different kind of models:

```<code>$post = Yii::$app->request->post();
if ($modelA->load($post) && $modelB->load($post) && $modelC->load($post)) {
    do_something_if_all_models_are_loaded;
}
</code>```

Title: Models load() usage

Body:
The main purpose of load($data, $formName) is to return boolean true if the expected $formName is found in $data. Thus, you can bypass the following:

if (isset($_POST['FormName'])) {
    $model->attributes = $_POST['FormName'];
    do_something_here;
}

with

$post = Yii::$app->request->post();
if ($model->load($post)) {
    do_something_here;
}

It's interesting for more, different kind of models:

$post = Yii::$app->request->post();
if ($modelA->load($post) && $modelB->load($post) && $modelC->load($post)) {
    do_something_if_all_models_are_loaded;
}


问:
Using Laravel eloquent calculate total of like and passing into vue js file
Currently i am implementing a like system into my laravel project with Vue js. The scenario is after users liked the post. It will showing the total like of the post beside the like button. If using controller and passing data into view is easy to be done. But when change to Vue js i have no idea how to do it. This is my Like.vue file.

```<code><template>

<button class="btn btn-primary" v-if="!auth_user_likes_post" @click="like()">
    Support
</button>

<button class="btn btn-primary" v-else @click="unlike()">
    Unsupport
</button>
</code>```

```<code>export default {
    mounted(){

    },

    props: ['id'],

    computed: {
        likers() {
            var likers = []

            this.post.likes.forEach( (like) => {
                likers.push(like.user.id)
            })
            return likers
        },
        auth_user_likes_post() {
            var check_index = this.likers.indexOf(
                this.$store.state.auth_user.id
            )
            if (check_index === -1)
                return false
            else
                return true
        },
        post() {
            return this.$store.state.posts.find( (post) => {
                return post.id === this.id
            })
        }
    },
    methods: {
        like() {
            this.$http.get('/like/' + this.id)
                .then( (resp) => {
                    this.$store.commit('update_post_likes', {
                        id: this.id,
                        like: resp.body
                    })

                })
        },
        unlike() {
            this.$http.get('/unlike/' + this.id)
                .then( (response) => {
                    this.$store.commit('unlike_post', {
                        post_id: this.id,
                        like_id: response.body
                    })
                })
        }
    }
}
</code>```

The like and unlike functions has been done and working perfectly. Now i just need to show the total number.

This is Feed.vue file. The like was adding to this page.

```<code><div class="post-description">
                    <p>{{ post.content }}</p>
                    <div class="stats">
                        <like :id="post.id"></like>
                        <a href="#" class="stat-item">
                            <i class="fa fa-retweet icon"></i>12
                        </a>
                        <a href="#" class="stat-item">
                            <i class="fa fa-comments-o icon"></i>3
                        </a>
                    </div>
                </div>
</code>```

If my function cannot be achieved the expected scenario then can you recommend other ways which can do that?

答: I have the returned array with likers. But at beginning i never though using this could be achieved my goal. So this {{ likers.length }} actually can show the total number.</p>

Body:
Currently i am implementing a like system into my laravel project with Vue js. The scenario is after users liked the post. It will showing the total like of the post beside the like button. If using controller and passing data into view is easy to be done. But when change to Vue js i have no idea how to do it. This is my Like.vue file.

<template>

<button class="btn btn-primary" v-if="!auth_user_likes_post" @click="like()">
    Support
</button>

<button class="btn btn-primary" v-else @click="unlike()">
    Unsupport
</button>

export default {
    mounted(){

    },

    props: ['id'],

    computed: {
        likers() {
            var likers = []

            this.post.likes.forEach( (like) => {
                likers.push(like.user.id)
            })
            return likers
        },
        auth_user_likes_post() {
            var check_index = this.likers.indexOf(
                this.$store.state.auth_user.id
            )
            if (check_index === -1)
                return false
            else
                return true
        },
        post() {
            return this.$store.state.posts.find( (post) => {
                return post.id === this.id
            })
        }
    },
    methods: {
        like() {
            this.$http.get('/like/' + this.id)
                .then( (resp) => {
                    this.$store.commit('update_post_likes', {
                        id: this.id,
                        like: resp.body
                    })

                })
        },
        unlike() {
            this.$http.get('/unlike/' + this.id)
                .then( (response) => {
                    this.$store.commit('unlike_post', {
                        post_id: this.id,
                        like_id: response.body
                    })
                })
        }
    }
}

The like and unlike functions has been done and working perfectly. Now i just need to show the total number.

This is Feed.vue file. The like was adding to this page.

{{ post.content }}

                        <like :id="post.id"></like>

                            12

                            3

If my function cannot be achieved the expected scenario then can you recommend other ways which can do that?


问:
How to remove Blend for Visual Studio Express 2015?
I recently was trying to download Visual Studio Express and I mistakenly downloaded the Blend for Visual Studio Express 2015 which seems to be for Windows apps. I then downloaded the correct one which is Visual Studio Express for Desktop. It is now taking up 11 GB (although some of it may be being used by Desktop one as well) of my sweet SSD storage.

How can I fully remove the Blend for VS 2015 as there seems to be no uninstall in the control panel (I am guessing I will forcefully have to remove everything and re-install the desktop one again).

答:
In "C:\ProgramData\Package Cache\"
search for "Blend" then you can find Blend_Core and Blend_LP directories.

In these directories, right-click Blend_Core.msi and Blend_LP.msi then click Uninstall.


问:
how to distribute a java-application with libraries such as itext?
I have written an application in java. It uses iText, jXL and JAI.

How do I build a jar which contains all these libraries? Or do I have to force the user to install these too?

答:
As soon as you're dealing with external libraries, you should have a look at Maven. This tool is a builder such as Ant, but it is able to handle library dependencies automatically. With this builder, you'll be able to both embed your project's dependencies in your jar and also to allow users to build it on their own computer without downloading library dependencies manually.

Here is the project's website: http://maven.apache.org/

where you can find quick how-tos: http://maven.apache.org/users/index.html

and finally eBooks to go further: http://maven.apache.org/articles.html


问:
Difference between synchronized and re-entrant lock?
I have used the synchronized keyword and re-entrant locks in Java, but I don't understand how they differ, or which is appropriate for a given situation.

How do I decide when should I use synchronized and when I should use re-entrant locks?

答:
This site clearly mentioned difference between ReentrantLock and synchronized keyword in Java. I just copy and paste from there.

http://javarevisited.blogspot.in/2013/03/reentrantlock-example-in-java-synchronized-difference-vs-lock.html

1) Another significant difference between ReentrantLock and synchronized keyword is fairness. synchronized keyword doesn't support fairness. Any thread can acquire lock once released, no preference can be specified, on the other hand you can make ReentrantLock fair by specifying fairness property, while creating instance of ReentrantLock. Fairness property provides lock to longest waiting thread, in case of contention.

2) Second difference between synchronized and Reentrant lock is tryLock() method. ReentrantLock provides convenient tryLock() method, which acquires lock only if its available or not held by any other thread. This reduce blocking of thread waiting for lock in Java application.

3) One more worth noting difference between ReentrantLock and synchronized keyword in Java is, ability to interrupt Thread while waiting for Lock. In case of synchronized keyword, a thread can be blocked waiting for lock, for an indefinite period of time and there was no way to control that. ReentrantLock provides a method called lockInterruptibly(), which can be used to interrupt thread when it is waiting for lock. Similarly tryLock() with timeout can be used to timeout if lock is not available in certain time period.

4) ReentrantLock also provides convenient method to get List of all threads waiting for lock.


问:
Snippet from Cucumber Java TestNG looks strange
I am trying Cucumber for my Selenium Java + TestNG project.
Once I run the .feature file with empty stepdefinition, I should get a snippet that I can just copy paste to my step definition class. But I got a strange format that can't be used out of the box.

Given should be @Given , right?
There is no public void() .

What could be the cause?  Thank You.

2 Scenarios (2 undefined)
5 Steps (5 undefined)
0m0.000s
You can implement missing steps with the snippets below:
Given("^User is on Home Page$", () -> {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
});
When("^User enters UserName and Password$", () -> {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
});
Then("^He can visit the practice page$", () -> {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
});
When("^User LogOut from the Application$", () -> {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
});
Then("^he cannot visit practice page$", () -> {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
});```
</div>
</div>
</p>

<p>This is my <code>glue file</code></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>package glue;
import java.io.IOException;
import org.testng.annotations.Test;
import cucumber.api.CucumberOptions;
import cucumber.api.testng.AbstractTestNGCucumberTests;
import cucumber.api.testng.TestNGCucumberRunner;
@Test(groups = "cucumber")
@CucumberOptions(features = "C:\\Users\\workspace\\cucumber\\src\\test\\java\\feature\\logintest.feature",
glue = "C:\\Users\\workspace\\cucumber\\src\\test\\java\\glue\\Glue.java",
plugin = {"html:C:\\Users\\workspace\\cucumber\\logs"})

public class Glue extends AbstractTestNGCucumberTests {
    @Test(groups = "cucumber", description = "Runs Cucumber Features")
    public void runCukes() throws IOException {

    }
}</code>```

This is my .feature file

Feature: Login
Scenario: Successful Login with Valid Credentials
Given User is on Home Page
When User enters UserName and Password
Then He can visit the practice page
Scenario: Successful LogOut
When User LogOut from the Application
Then he cannot visit practice page```
</div>
</div>
</p>

<p>This is my dependencies </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code><!-- https://mvnrepository.com/artifact/info.cukes/cucumber-testng -->
<dependency>
    <groupId>info.cukes</groupId>
    <artifactId>cucumber-testng</artifactId>
    <version>1.2.5</version>
</dependency>

 <!-- https://mvnrepository.com/artifact/info.cukes/gherkin -->
<dependency>
    <groupId>info.cukes</groupId>
    <artifactId>gherkin</artifactId>
    <version>2.12.2</version>
</dependency>

<dependency>
    <groupId>info.cukes</groupId>
    <artifactId>cucumber-java8</artifactId>
    <version>1.2.5</version>
    <scope>test</scope>
</dependency></code>```

答:
You are using cucumber-java8 dependency, for that below is the format for stepDefintion file(make sure your java compiler version should be 1.8).

@Given Annotation will be in cucumber-java

Given Annotation will be in cucumber-java8

```<code>import cucumber.api.java8.En;

public class stepDefinitions implements En{

public stepDefinitions(){
    Given("^User is on Home Page$", () -> {
        // Write code here that turns the phrase above into concrete actions
        System.out.println("Test1");
    });

    When("^User enters UserName and Password$", () -> {
        // Write code here that turns the phrase above into concrete actions
        System.out.println("Test2");
    });

    Then("^He can visit the practice page$", () -> {
        // Write code here that turns the phrase above into concrete actions
        System.out.println("Test3");
    });

    When("^User LogOut from the Application$", () -> {
        // Write code here that turns the phrase above into concrete actions
        System.out.println("Test4");
    });

    Then("^he cannot visit practice page$", () -> {
        // Write code here that turns the phrase above into concrete actions
        System.out.println("Test5");
    });
   }
 }
</code>```

I executed it in my machine its working, try it and let me know if it works for you.

Link for reference:
http://codoid.com/cucumber-lambda-expressions/

Body:
I am trying Cucumber for my Selenium Java + TestNG project.
Once I run the .feature file with empty stepdefinition, I should get a snippet that I can just copy paste to my step definition class. But I got a strange format that can't be used out of the box.

Given should be @Given , right?
There is no public void() .

What could be the cause?  Thank You.

2 Scenarios (2 undefined)
5 Steps (5 undefined)
0m0.000s
You can implement missing steps with the snippets below:
Given("^User is on Home Page$", () -> {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
});
When("^User enters UserName and Password$", () -> {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
});
Then("^He can visit the practice page$", () -> {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
});
When("^User LogOut from the Application$", () -> {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
});
Then("^he cannot visit practice page$", () -> {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
});

This is my glue file

package glue;
import java.io.IOException;
import org.testng.annotations.Test;
import cucumber.api.CucumberOptions;
import cucumber.api.testng.AbstractTestNGCucumberTests;
import cucumber.api.testng.TestNGCucumberRunner;
@Test(groups = "cucumber")
@CucumberOptions(features = "C:\\Users\\workspace\\cucumber\\src\\test\\java\\feature\\logintest.feature",
glue = "C:\\Users\\workspace\\cucumber\\src\\test\\java\\glue\\Glue.java",
plugin = {"html:C:\\Users\\workspace\\cucumber\\logs"})

public class Glue extends AbstractTestNGCucumberTests {
    @Test(groups = "cucumber", description = "Runs Cucumber Features")
    public void runCukes() throws IOException {

    }
}

This is my .feature file

Feature: Login
Scenario: Successful Login with Valid Credentials
Given User is on Home Page
When User enters UserName and Password
Then He can visit the practice page
Scenario: Successful LogOut
When User LogOut from the Application
Then he cannot visit practice page

This is my dependencies

<dependency>
    <groupId>info.cukes</groupId>
    <artifactId>cucumber-testng</artifactId>
    <version>1.2.5</version>
</dependency>

<dependency>
    <groupId>info.cukes</groupId>
    <artifactId>gherkin</artifactId>
    <version>2.12.2</version>
</dependency>

<dependency>
    <groupId>info.cukes</groupId>
    <artifactId>cucumber-java8</artifactId>
    <version>1.2.5</version>
    <scope>test</scope>
</dependency>

Body:
You are using cucumber-java8 dependency, for that below is the format for stepDefintion file(make sure your java compiler version should be 1.8).

@Given Annotation will be in cucumber-java

Given Annotation will be in cucumber-java8

import cucumber.api.java8.En;

public class stepDefinitions implements En{

public stepDefinitions(){
    Given("^User is on Home Page$", () -> {
        // Write code here that turns the phrase above into concrete actions
        System.out.println("Test1");
    });

    When("^User enters UserName and Password$", () -> {
        // Write code here that turns the phrase above into concrete actions
        System.out.println("Test2");
    });

    Then("^He can visit the practice page$", () -> {
        // Write code here that turns the phrase above into concrete actions
        System.out.println("Test3");
    });

    When("^User LogOut from the Application$", () -> {
        // Write code here that turns the phrase above into concrete actions
        System.out.println("Test4");
    });

    Then("^he cannot visit practice page$", () -> {
        // Write code here that turns the phrase above into concrete actions
        System.out.println("Test5");
    });
   }
 }

I executed it in my machine its working, try it and let me know if it works for you.

Link for reference:
http://codoid.com/cucumber-lambda-expressions/


问:
Hyphens between buttons when commenting out white space
When I try to remove gaps between my buttons by commenting out the white space between them, these little black dashes appear instead, which are selectable using the tab button. I can make them non visable with text-decoration: false and I can remove the gap with margin-left: -4px but whatever it is is still there and is selected when using the tab button.

Why are these dashes there and how do I get rid of them?

HTML:

```<code><a target="_blank" a href= "https://Google.com">
<button class="button">
<strong>LinkedIn</strong><br>
</button></a><!--
--><a target="_blank" a href= "https://www.Google.com">
<button class="button">
<strong>GitHub</strong><br>
</button></a>
<br><!--
--><a target="_blank" a href= "https://www.Google.com">
<button class="button">
<strong>Stack Overflow</strong><br>
</button></a><!--
--><a target="_blank" a href= "https://www.Google.com">
<button class="button">
<strong>HackerRank</strong><br>
</button></a>
</code>```

CSS:

```<code>div{
    display: inline-block;
    white-space: normal;
    height: 623px;
    padding: 10px;
    padding-top: 0;
    padding-left: 0;
    vertical-align: top;
    border-bottom: 3px solid black;
    border: 1px solid black;
  width: 500px;
}

.button{
    background-color: rgb(224,184,219);
    border: 2px solid white;
    border-radius: 10px;
    color: white;
    display: inline-block;
    font-size: 16px;
    text-decoration: none;
    text-align: center;
    padding: 10px;
    width: 160px;
    height: 100px;
    transition-duration: 0.2s;
    -webkit-transition-duration:0.2s;
    cursor: pointer;
    outline: none;
}
.button:hover{
    background-color: white;
    color: rgb(224,184,219);
    outline: none;
}
:focus, :visited{
    border: 2px solid rgb(153,217,234);
    outline: none;
    outline: 0;
}
</code>```

JSFiddle: https://jsfiddle.net/mpbev9ay/1/

答:
If you use a browser inspector, like in Chrome, you can use the process of elimination to figure out where the line is coming from. From what I can tell, it's the newline that is within the a element but before the button element.

Some suggestions:

Comment out all the new lines/white-space, not just the few you already did

Use text-decoration: none; on the a element instead of the button element

Use font-size: 0; on the a element then font-size: 1rem; on the button

Body:
When I try to remove gaps between my buttons by commenting out the white space between them, these little black dashes appear instead, which are selectable using the tab button. I can make them non visable with text-decoration: false and I can remove the gap with margin-left: -4px but whatever it is is still there and is selected when using the tab button.

Why are these dashes there and how do I get rid of them?

HTML:

<button class="button">
LinkedIn

</button>
<button class="button">
GitHub

</button>

<button class="button">
Stack Overflow

</button>
<button class="button">
HackerRank

</button>

CSS:

div{
    display: inline-block;
    white-space: normal;
    height: 623px;
    padding: 10px;
    padding-top: 0;
    padding-left: 0;
    vertical-align: top;
    border-bottom: 3px solid black;
    border: 1px solid black;
  width: 500px;
}

.button{
    background-color: rgb(224,184,219);
    border: 2px solid white;
    border-radius: 10px;
    color: white;
    display: inline-block;
    font-size: 16px;
    text-decoration: none;
    text-align: center;
    padding: 10px;
    width: 160px;
    height: 100px;
    transition-duration: 0.2s;
    -webkit-transition-duration:0.2s;
    cursor: pointer;
    outline: none;
}
.button:hover{
    background-color: white;
    color: rgb(224,184,219);
    outline: none;
}
:focus, :visited{
    border: 2px solid rgb(153,217,234);
    outline: none;
    outline: 0;
}

JSFiddle: https://jsfiddle.net/mpbev9ay/1/