问:
How do i return a powerpoint (.pptx) file from REST response in springMVC
I am generating a powerpoint file(.pptx) and i would like to return back this file when a REST call happens. But now am able to get only .File type extension.

```<code>@RequestMapping(value = "/ImageManagerPpt/{accessionId}", method = RequestMethod.GET, produces = "application/ppt")
public ResponseEntity<InputStreamResource> createPptforAccessionId(@PathVariable("accessionId") String accessionId,HttpServletResponse response) throws IOException** {
      System.out.println("Creating PPT for Patient Details with id " + accessionId);
      File pptFile = imageManagerService.getPptForAccessionId(accessionId);
      if (pptFile == null) {
          System.out.println("Patient Id with id " + accessionId + " not found");
          return new ResponseEntity<InputStreamResource>(HttpStatus.NOT_FOUND);
      }
      InputStream stream = null;
      try {
          stream = new FileInputStream(pptFile);
      } catch (FileNotFoundException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
      }
      ClassPathResource classpathfile = new ClassPathResource("Titlelayout3.pptx");
      InputStreamResource inputStreamResource = new InputStreamResource(stream);

      return ResponseEntity.ok().contentLength(classpathfile.contentLength())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new InputStreamResource(classpathfile.getInputStream()));
}
</code>```

-Bharat

答:
Have you tried, this?

```<code>InputStream stream = new InputStream(pptFile);
org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());
response.flushBuffer();
</code>```

You will get file as you put into the InputStream.

Body:
I am generating a powerpoint file(.pptx) and i would like to return back this file when a REST call happens. But now am able to get only .File type extension.

@RequestMapping(value = "/ImageManagerPpt/{accessionId}", method = RequestMethod.GET, produces = "application/ppt")
public ResponseEntity<InputStreamResource> createPptforAccessionId(@PathVariable("accessionId") String accessionId,HttpServletResponse response) throws IOException** {
      System.out.println("Creating PPT for Patient Details with id " + accessionId);
      File pptFile = imageManagerService.getPptForAccessionId(accessionId);
      if (pptFile == null) {
          System.out.println("Patient Id with id " + accessionId + " not found");
          return new ResponseEntity<InputStreamResource>(HttpStatus.NOT_FOUND);
      }
      InputStream stream = null;
      try {
          stream = new FileInputStream(pptFile);
      } catch (FileNotFoundException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
      }
      ClassPathResource classpathfile = new ClassPathResource("Titlelayout3.pptx");
      InputStreamResource inputStreamResource = new InputStreamResource(stream);

      return ResponseEntity.ok().contentLength(classpathfile.contentLength())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new InputStreamResource(classpathfile.getInputStream()));
}

-Bharat

Body:
Have you tried, this?

InputStream stream = new InputStream(pptFile);
org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());
response.flushBuffer();

You will get file as you put into the InputStream.


来源: stackexchange

问:
How do you uppercase only certain parts of a single string that's in format "Town comma Initials"?
I have a single location field where people can enter whatever they want, but generally they will enter something in the format of "Town, Initials".  So for example, these entries...

```<code>New york, Ny
columbia, sc
charleston
washington, DC
BISMARCK, ND
</code>```

would ideally become...

```<code>New York, NY
Columbia, SC
Charleston
Washington, DC
Bismarck, ND
</code>```

Obviously I can use ucfirst() on the string to handle the first character, but these are things I'm not sure how to do (if they can be done at all)...

Capitalizing everything after a comma

Lowercasing everything before the comma (aside from the first character)

Is this easily doable or do I need to use some sort of regex function?

答:
You could simply chop it up and fix it.

```<code><?php
$geo = 'New york, Ny
columbia, sc
charleston
washington, DC
BISMARCK, ND';
$geo = explode(PHP_EOL, $geo);

foreach ($geo as $str) {

    // chop
    $str = explode(',', $str);

    // fix
    echo
    (!empty($str[0]) ? ucwords(strtolower(trim($str[0]))) : null).
    (!empty($str[1]) ? ', '.strtoupper(trim($str[1])) : null).PHP_EOL;
}
</code>```

https://3v4l.org/ojl2M

Though you should not trust the user to enter the correct format. Instead find a huge list of all states and auto complete them in. Perhaps something like https://gist.github.com/maxrice/2776900 - then validate against it.

ContentLicense: CC BY-SA 3.0

Body:
I have a single location field where people can enter whatever they want, but generally they will enter something in the format of "Town, Initials".  So for example, these entries...

New york, Ny
columbia, sc
charleston
washington, DC
BISMARCK, ND

would ideally become...

New York, NY
Columbia, SC
Charleston
Washington, DC
Bismarck, ND

Obviously I can use ucfirst() on the string to handle the first character, but these are things I'm not sure how to do (if they can be done at all)...

Capitalizing everything after a comma

Lowercasing everything before the comma (aside from the first character)

Is this easily doable or do I need to use some sort of regex function?

Body:
You could simply chop it up and fix it.

<?php
$geo = 'New york, Ny
columbia, sc
charleston
washington, DC
BISMARCK, ND';
$geo = explode(PHP_EOL, $geo);

foreach ($geo as $str) {

    // chop
    $str = explode(',', $str);

    // fix
    echo
    (!empty($str[0]) ? ucwords(strtolower(trim($str[0]))) : null).
    (!empty($str[1]) ? ', '.strtoupper(trim($str[1])) : null).PHP_EOL;
}

https://3v4l.org/ojl2M

Though you should not trust the user to enter the correct format. Instead find a huge list of all states and auto complete them in. Perhaps something like https://gist.github.com/maxrice/2776900 - then validate against it.


问:
SGX Sign enclave cannot attestate the built enclave: Key file format is not correct
I managed to generate my Enclave (https://github.com/pc-magas/myFirstEnclave) but as far as I know I need to generate an rsa key in order to sign it. So I run:

```<code>openssl genrsa -out $(KEY_FILE) 2048
</code>```

And then I run the following command to sign it:

```<code>sgx_sign -key (^key_generated)above^ -enclave enclave.o -out enclave.so -config Enclave.config.xml
</code>```

But I get the following error:

Key file format is not correct.

Edit 2:

I tried to generate the key via ssh_keygen but still the same error.

What kind of format is needed in order to sign an enclave?

Edit 3:

I also tried to generate the key with:

openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout ~/.sgx/MyEnclave.pem

Still same result

答:
Intel® Software Guard Extensions Developer Reference specifies that SGX enclave signature key file should follow the PEM format which contains an unencrypted RSA 3072-bit key, the public exponent must be 3.

See  page 20 (on version 2.0 November 2017) - OpenSSL Examples, for the following command line to generate the private key:

openssl genrsa -out private_key.pem -3 3072

Body:
I managed to generate my Enclave (https://github.com/pc-magas/myFirstEnclave) but as far as I know I need to generate an rsa key in order to sign it. So I run:

openssl genrsa -out $(KEY_FILE) 2048

And then I run the following command to sign it:

sgx_sign -key (^key_generated)above^ -enclave enclave.o -out enclave.so -config Enclave.config.xml

But I get the following error:

Key file format is not correct.

Edit 2:

I tried to generate the key via ssh_keygen but still the same error.

What kind of format is needed in order to sign an enclave?

Edit 3:

I also tried to generate the key with:

openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout ~/.sgx/MyEnclave.pem

Still same result


问:
regex comma separated delimiter
I'm trying to split my column by comma delimiter. So the column has multiple values like; 139,239,338,323. For some reason the following code will work for the first column but the rest of the columns come empty.

```<code>SELECT
Regexp_extract(StringToParse,r'^(?:[^,\/]*,\/){0}([^,\/]*),\/?') as Word0,
Regexp_extract(StringToParse,r'^(?:[^,\/]*,\/){1}([^,\/]*),\/?') as Word1,
Regexp_extract(StringToParse,r'^(?:[^,\/]*,\/){2}([^,\/]*),\/?') as Word2,
Regexp_extract(StringToParse,r'^(?:[^,\/]*,\/){3}([^,\/]*),\/?') as Word3,
Regexp_extract(StringToParse,r'^(?:[^,\/]*,\/){4}([^,\/]*),\/?') as Word4,
Regexp_extract(StringToParse,r'^(?:[^,\/]*,\/){5}([^,\/]*),\/?') as Word5,
Regexp_extract(StringToParse,r'^(?:[^,\/]*,\/){6}([^,\/]*),\/?') as Word6,
Regexp_extract(StringToParse,r'^(?:[^,\/]*,\/){7}([^,\/]*),\/?') as Word7,
Regexp_extract(StringToParse,r'^(?:[^,\/]*,\/){8}([^,\/]*),\/?') as Word8,
Regexp_extract(StringToParse,r'^(?:[^,\/]*,\/){9}([^,\/]*),\/?') as Word9
FROM
(SELECT event_list AS StringToParse FROM `mytable.2017`)
</code>```

答:
Try below for BigQuery Standard SQL

#standardSQL
SELECT
  SPLIT(StringToParse)[SAFE_OFFSET (0)] AS Word0,
  SPLIT(StringToParse)[SAFE_OFFSET (1)] AS Word1,
  SPLIT(StringToParse)[SAFE_OFFSET (2)] AS Word2,
  SPLIT(StringToParse)[SAFE_OFFSET (3)] AS Word3,
  SPLIT(StringToParse)[SAFE_OFFSET (4)] AS Word4,
  SPLIT(StringToParse)[SAFE_OFFSET (5)] AS Word5,
  SPLIT(StringToParse)[SAFE_OFFSET (6)] AS Word6,
  SPLIT(StringToParse)[SAFE_OFFSET (7)] AS Word7,
  SPLIT(StringToParse)[SAFE_OFFSET (8)] AS Word8,
  SPLIT(StringToParse)[SAFE_OFFSET (9)] AS Word9
FROM
  (SELECT event_list AS StringToParse FROM `mytable.2017`)
```

<p>you can test / play with above using dummy data as below   </p>

<pre class="lang-sql prettyprint-override"><code>#standardSQL
WITH `mytable.2017` AS (
  SELECT '139,239,338,323' AS event_list UNION ALL
  SELECT '123,456,789,135'
)
SELECT
  SPLIT(StringToParse)[SAFE_OFFSET (0)] AS Word0,
  SPLIT(StringToParse)[SAFE_OFFSET (1)] AS Word1,
  SPLIT(StringToParse)[SAFE_OFFSET (2)] AS Word2,
  SPLIT(StringToParse)[SAFE_OFFSET (3)] AS Word3,
  SPLIT(StringToParse)[SAFE_OFFSET (4)] AS Word4,
  SPLIT(StringToParse)[SAFE_OFFSET (5)] AS Word5,
  SPLIT(StringToParse)[SAFE_OFFSET (6)] AS Word6,
  SPLIT(StringToParse)[SAFE_OFFSET (7)] AS Word7,
  SPLIT(StringToParse)[SAFE_OFFSET (8)] AS Word8,
  SPLIT(StringToParse)[SAFE_OFFSET (9)] AS Word9
FROM
  (SELECT event_list AS StringToParse FROM `mytable.2017`)
</code>```

Meantime, if for some reason you have to use regular expressions in this query - try below

#standardSQL
SELECT
  REGEXP_EXTRACT_ALL(StringToParse, r'([^,\/]*),\/?')[SAFE_OFFSET(0)]  AS Word0,
  REGEXP_EXTRACT_ALL(StringToParse, r'([^,\/]*),\/?')[SAFE_OFFSET(1)]  AS Word1,
  REGEXP_EXTRACT_ALL(StringToParse, r'([^,\/]*),\/?')[SAFE_OFFSET(2)]  AS Word2,
  REGEXP_EXTRACT_ALL(StringToParse, r'([^,\/]*),\/?')[SAFE_OFFSET(3)]  AS Word3,
  REGEXP_EXTRACT_ALL(StringToParse, r'([^,\/]*),\/?')[SAFE_OFFSET(4)]  AS Word4,
  REGEXP_EXTRACT_ALL(StringToParse, r'([^,\/]*),\/?')[SAFE_OFFSET(5)]  AS Word5,
  REGEXP_EXTRACT_ALL(StringToParse, r'([^,\/]*),\/?')[SAFE_OFFSET(6)]  AS Word6,
  REGEXP_EXTRACT_ALL(StringToParse, r'([^,\/]*),\/?')[SAFE_OFFSET(7)]  AS Word7,
  REGEXP_EXTRACT_ALL(StringToParse, r'([^,\/]*),\/?')[SAFE_OFFSET(8)]  AS Word8,
  REGEXP_EXTRACT_ALL(StringToParse, r'([^,\/]*),\/?')[SAFE_OFFSET(9)]  AS Word9
FROM
  (SELECT event_list AS StringToParse FROM `mytable.2017`)
```

Of course, in all above examples you can simplify code by introducing subquery for SPLIT of REGEXP_EXTRACT_ALL and then just select each array's element in outer select

Title: regex comma separated delimiter

Body:
I'm trying to split my column by comma delimiter. So the column has multiple values like; 139,239,338,323. For some reason the following code will work for the first column but the rest of the columns come empty.

SELECT
Regexp_extract(StringToParse,r'^(?:[^,\/]*,\/){0}([^,\/]*),\/?') as Word0,
Regexp_extract(StringToParse,r'^(?:[^,\/]*,\/){1}([^,\/]*),\/?') as Word1,
Regexp_extract(StringToParse,r'^(?:[^,\/]*,\/){2}([^,\/]*),\/?') as Word2,
Regexp_extract(StringToParse,r'^(?:[^,\/]*,\/){3}([^,\/]*),\/?') as Word3,
Regexp_extract(StringToParse,r'^(?:[^,\/]*,\/){4}([^,\/]*),\/?') as Word4,
Regexp_extract(StringToParse,r'^(?:[^,\/]*,\/){5}([^,\/]*),\/?') as Word5,
Regexp_extract(StringToParse,r'^(?:[^,\/]*,\/){6}([^,\/]*),\/?') as Word6,
Regexp_extract(StringToParse,r'^(?:[^,\/]*,\/){7}([^,\/]*),\/?') as Word7,
Regexp_extract(StringToParse,r'^(?:[^,\/]*,\/){8}([^,\/]*),\/?') as Word8,
Regexp_extract(StringToParse,r'^(?:[^,\/]*,\/){9}([^,\/]*),\/?') as Word9
FROM
(SELECT event_list AS StringToParse FROM `mytable.2017`)

Body:
Try below for BigQuery Standard SQL

#standardSQL
SELECT
  SPLIT(StringToParse)[SAFE_OFFSET (0)] AS Word0,
  SPLIT(StringToParse)[SAFE_OFFSET (1)] AS Word1,
  SPLIT(StringToParse)[SAFE_OFFSET (2)] AS Word2,
  SPLIT(StringToParse)[SAFE_OFFSET (3)] AS Word3,
  SPLIT(StringToParse)[SAFE_OFFSET (4)] AS Word4,
  SPLIT(StringToParse)[SAFE_OFFSET (5)] AS Word5,
  SPLIT(StringToParse)[SAFE_OFFSET (6)] AS Word6,
  SPLIT(StringToParse)[SAFE_OFFSET (7)] AS Word7,
  SPLIT(StringToParse)[SAFE_OFFSET (8)] AS Word8,
  SPLIT(StringToParse)[SAFE_OFFSET (9)] AS Word9
FROM
  (SELECT event_list AS StringToParse FROM `mytable.2017`)

you can test / play with above using dummy data as below

#standardSQL
WITH `mytable.2017` AS (
  SELECT '139,239,338,323' AS event_list UNION ALL
  SELECT '123,456,789,135'
)
SELECT
  SPLIT(StringToParse)[SAFE_OFFSET (0)] AS Word0,
  SPLIT(StringToParse)[SAFE_OFFSET (1)] AS Word1,
  SPLIT(StringToParse)[SAFE_OFFSET (2)] AS Word2,
  SPLIT(StringToParse)[SAFE_OFFSET (3)] AS Word3,
  SPLIT(StringToParse)[SAFE_OFFSET (4)] AS Word4,
  SPLIT(StringToParse)[SAFE_OFFSET (5)] AS Word5,
  SPLIT(StringToParse)[SAFE_OFFSET (6)] AS Word6,
  SPLIT(StringToParse)[SAFE_OFFSET (7)] AS Word7,
  SPLIT(StringToParse)[SAFE_OFFSET (8)] AS Word8,
  SPLIT(StringToParse)[SAFE_OFFSET (9)] AS Word9
FROM
  (SELECT event_list AS StringToParse FROM `mytable.2017`)

Meantime, if for some reason you have to use regular expressions in this query - try below

#standardSQL
SELECT
  REGEXP_EXTRACT_ALL(StringToParse, r'([^,\/]*),\/?')[SAFE_OFFSET(0)]  AS Word0,
  REGEXP_EXTRACT_ALL(StringToParse, r'([^,\/]*),\/?')[SAFE_OFFSET(1)]  AS Word1,
  REGEXP_EXTRACT_ALL(StringToParse, r'([^,\/]*),\/?')[SAFE_OFFSET(2)]  AS Word2,
  REGEXP_EXTRACT_ALL(StringToParse, r'([^,\/]*),\/?')[SAFE_OFFSET(3)]  AS Word3,
  REGEXP_EXTRACT_ALL(StringToParse, r'([^,\/]*),\/?')[SAFE_OFFSET(4)]  AS Word4,
  REGEXP_EXTRACT_ALL(StringToParse, r'([^,\/]*),\/?')[SAFE_OFFSET(5)]  AS Word5,
  REGEXP_EXTRACT_ALL(StringToParse, r'([^,\/]*),\/?')[SAFE_OFFSET(6)]  AS Word6,
  REGEXP_EXTRACT_ALL(StringToParse, r'([^,\/]*),\/?')[SAFE_OFFSET(7)]  AS Word7,
  REGEXP_EXTRACT_ALL(StringToParse, r'([^,\/]*),\/?')[SAFE_OFFSET(8)]  AS Word8,
  REGEXP_EXTRACT_ALL(StringToParse, r'([^,\/]*),\/?')[SAFE_OFFSET(9)]  AS Word9
FROM
  (SELECT event_list AS StringToParse FROM `mytable.2017`)

Of course, in all above examples you can simplify code by introducing subquery for SPLIT of REGEXP_EXTRACT_ALL and then just select each array's element in outer select


问:
How to use relative paths without including the context root name?
To working my static file (CSS, JS) I have to write absolute path like /AppName/templates/style/main.css. Is there any solution, that I could write relative path like style/main.css?

答:
If your actual concern is the dynamicness of the webapp context (the "AppName" part), then just retrieve it dynamically by HttpServletRequest#getContextPath().

    <link rel="stylesheet" href="${pageContext.request.contextPath}/templates/style/main.css" />

    link

```

<p>If you want to set a base path for all relative links so that you don't need to repeat <code>${pageContext.request.contextPath}</code> in <em>every</em> relative link, use the <code><base></code> tag. Here's an example with help of JSTL functions.</p>

<pre class="lang-html prettyprint-override"><code><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
...
<head>
    <c:set var="url">${pageContext.request.requestURL}</c:set>
    <base href="${fn:substring(url, 0, fn:length(url) - fn:length(pageContext.request.requestURI))}${pageContext.request.contextPath}/" />
    <link rel="stylesheet" href="templates/style/main.css" />
    <script src="templates/js/main.js"></script>
    <script>var base = document.getElementsByTagName("base")[0].href;</script>
</head>
<body>
    link
</body>
</code>```

This way every relative link (i.e. not starting with / or a scheme) will become relative to the <base>.

This is by the way not specifically related to Tomcat in any way. It's just related to HTTP/HTML basics. You would have the same problem in every other webserver.

See also:

Browser can't access/find relative resources like CSS, images and links when calling a Servlet which forwards to a JSP

Is it recommended to use the <base> html tag?

ContentLicense: CC BY-SA 2.5

Body:
If your actual concern is the dynamicness of the webapp context (the "AppName" part), then just retrieve it dynamically by HttpServletRequest#getContextPath().

<head>
    <link rel="stylesheet" href="${pageContext.request.contextPath}/templates/style/main.css" />
    <script src="${pageContext.request.contextPath}/templates/js/main.js"></script>
    <script>var base = "${pageContext.request.contextPath}";</script>
</head>
<body>
    <a href="${pageContext.request.contextPath}/pages/foo.jsp">link</a>
</body>

If you want to set a base path for all relative links so that you don't need to repeat ${pageContext.request.contextPath} in every relative link, use the <base> tag. Here's an example with help of JSTL functions.

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
...
<head>
    <c:set var="url">${pageContext.request.requestURL}</c:set>
    <base href="${fn:substring(url, 0, fn:length(url) - fn:length(pageContext.request.requestURI))}${pageContext.request.contextPath}/" />
    <link rel="stylesheet" href="templates/style/main.css" />
    <script src="templates/js/main.js"></script>
    <script>var base = document.getElementsByTagName("base")[0].href;</script>
</head>
<body>
    <a href="pages/foo.jsp">link</a>
</body>

This way every relative link (i.e. not starting with / or a scheme) will become relative to the <base>.

This is by the way not specifically related to Tomcat in any way. It's just related to HTTP/HTML basics. You would have the same problem in every other webserver.

See also:

Browser can't access/find relative resources like CSS, images and links when calling a Servlet which forwards to a JSP

Is it recommended to use the <base> html tag?


问:
3 finger swipe gesture
In an iOS app I've seen that swiping with three fingers from top to bottom triggers an action.

I'm trying to do the same but even cross platform.

Since the gesture topic seems to be an ingoing development at Xamarin, I would like to ask if this gesture recognition is already built-in in the current Xamarin.Forms version (and cross-platform), or if I have to use a third party solution or try to program it myself.

I haven't been able to find a clear statement as the discussions and projects are so widely spread and perhaps not up to date anymore.

答: I created a small sample to how to add swipe gesture in Xamarin forms take a look on this. https://github.com/ricardoromo/SwipeGestureEffectXF, if you have any question feel free to ask.</p>

Title: 3 finger swipe gesture


问:
Android Studio cannot decrypt message in AES

hi, i try to implement aes in some open source code messaging application. for encrypted message, its work find to me. but i have difficulty to decrypt back message.

in this class, i can encrypted message and it work fine.

MessageActivity.java

```<code>    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.message);

    messageView = (TextView) findViewById(R.id.message_view);

    final Button button = (Button) findViewById(R.id.btn_send);
    final EditText message = (EditText) findViewById(R.id.edit_message);

    this.setTitle("Group Chat");

    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            String str = message.getText().toString();
            byte[] cipherText = null;
            try {
                cipherText = AESEncryption.encryptText(str, AESEncryption.thisKey());
            } catch (Exception e) {
                e.printStackTrace();
            }
            String msgStr = new String(cipherText);
            addMessage("This phone", str);
            message.setText("");

            // Send to other clients as a group chat message
            for (AllEncompasingP2PClient c : MeshNetworkManager.routingTable.values()) {
                if (c.getMac().equals(MeshNetworkManager.getSelf().getMac()))
                    continue;
                Sender.queuePacket(new Packet(Packet.TYPE.MESSAGE, msgStr.getBytes(), c.getMac(),
                        WiFiDirectBroadcastReceiver.MAC));
            }

        }
    });
</code>```

Receiver.java

```<code>/////////////// this messsage receiver part///////////////////////

byte[] thisMsg = p.getData();
String decryptedText = null;
 try {
 decryptedText = AESEncryption.decryptText(thisMsg, AESEncryption.thisKey());
 } catch (Exception e) {
  e.printStackTrace();
 }

final String message = p.getSenderMac() + " says:\n" + decryptedText;
final String msg = new String(p.getData());
final String name = p.getSenderMac();

//////////////////////////////////////

if (!MeshNetworkManager.routingTable.contains(p.getSenderMac())) {
    /*
     * Update your routing table if for some reason this
    * guy isn't in it
   */
MeshNetworkManager.routingTable.put(p.getSenderMac(),
new AllEncompasingP2PClient(p.getSenderMac(), p.getSenderIP(),
p.getSenderMac(),
MeshNetworkManager.getSelf().getGroupOwnerMac()));
}

activity.runOnUiThread(new Runnable() {

@Override
public void run() {
if (activity.isVisible) {
Toast.makeText(activity, message, Toast.LENGTH_LONG).show();
} else {
MessageActivity.addMessage(name, msg);
}
}
    });
updatePeerList();
</code>```

AESEncryption.java

```<code>import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
//import javax.xml.bind.DatatypeConverter;

public class AESEncryption {

public static SecretKey getSecretEncryptionKey() throws Exception{
    KeyGenerator generator = KeyGenerator.getInstance("AES");
    generator.init(128); // The AES key size in number of bits
    SecretKey secKey = generator.generateKey();
    return secKey;
}

public static byte[] encryptText(String plainText,SecretKey secKey) throws Exception{
    // AES defaults to AES/ECB/PKCS5Padding in Java 7
    Cipher aesCipher = Cipher.getInstance("AES");
    aesCipher.init(Cipher.ENCRYPT_MODE, secKey);
    byte[] byteCipherText = aesCipher.doFinal(plainText.getBytes());
    return byteCipherText;
}

public static String decryptText(byte[] byteCipherText, SecretKey secKey) throws Exception {
    // AES defaults to AES/ECB/PKCS5Padding in Java 7
    Cipher aesCipher = Cipher.getInstance("AES");
    aesCipher.init(Cipher.DECRYPT_MODE, secKey);
    byte[] bytePlainText = aesCipher.doFinal(byteCipherText);
    return new String(bytePlainText);
}

public static SecretKey thisKey() throws Exception{

    SecretKey secKey = AESEncryption.getSecretEncryptionKey();

    return secKey;
}
</code>```

}

in this class where i code the decrypted message. but when i run the code, the messages not decrypt and show ciphert text instead.if someone can correct me, its will great.

答:
The same key must be used for both encryption and decryption for the same message.

It seems the same key is not being used for both encryption and decryption, both methods call SecretKey thisKey() which seems to generate a random key.

On encryption call SecretKey thisKey(), use it for encryption and save the key to use on decryption. On decryption do not call SecretKey thisKey(), use the key created for encryption.

Body:
hi, i try to implement aes in some open source code messaging application. for encrypted message, its work find to me. but i have difficulty to decrypt back message.

in this class, i can encrypted message and it work fine.

MessageActivity.java

    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.message);

    messageView = (TextView) findViewById(R.id.message_view);

    final Button button = (Button) findViewById(R.id.btn_send);
    final EditText message = (EditText) findViewById(R.id.edit_message);

    this.setTitle("Group Chat");

    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            String str = message.getText().toString();
            byte[] cipherText = null;
            try {
                cipherText = AESEncryption.encryptText(str, AESEncryption.thisKey());
            } catch (Exception e) {
                e.printStackTrace();
            }
            String msgStr = new String(cipherText);
            addMessage("This phone", str);
            message.setText("");

            // Send to other clients as a group chat message
            for (AllEncompasingP2PClient c : MeshNetworkManager.routingTable.values()) {
                if (c.getMac().equals(MeshNetworkManager.getSelf().getMac()))
                    continue;
                Sender.queuePacket(new Packet(Packet.TYPE.MESSAGE, msgStr.getBytes(), c.getMac(),
                        WiFiDirectBroadcastReceiver.MAC));
            }

        }
    });

Receiver.java

/////////////// this messsage receiver part///////////////////////

byte[] thisMsg = p.getData();
String decryptedText = null;
 try {
 decryptedText = AESEncryption.decryptText(thisMsg, AESEncryption.thisKey());
 } catch (Exception e) {
  e.printStackTrace();
 }

final String message = p.getSenderMac() + " says:\n" + decryptedText;
final String msg = new String(p.getData());
final String name = p.getSenderMac();

//////////////////////////////////////

if (!MeshNetworkManager.routingTable.contains(p.getSenderMac())) {
    /*
     * Update your routing table if for some reason this
    * guy isn't in it
   */
MeshNetworkManager.routingTable.put(p.getSenderMac(),
new AllEncompasingP2PClient(p.getSenderMac(), p.getSenderIP(),
p.getSenderMac(),
MeshNetworkManager.getSelf().getGroupOwnerMac()));
}

activity.runOnUiThread(new Runnable() {

@Override
public void run() {
if (activity.isVisible) {
Toast.makeText(activity, message, Toast.LENGTH_LONG).show();
} else {
MessageActivity.addMessage(name, msg);
}
}
    });
updatePeerList();

AESEncryption.java

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
//import javax.xml.bind.DatatypeConverter;

public class AESEncryption {

public static SecretKey getSecretEncryptionKey() throws Exception{
    KeyGenerator generator = KeyGenerator.getInstance("AES");
    generator.init(128); // The AES key size in number of bits
    SecretKey secKey = generator.generateKey();
    return secKey;
}

public static byte[] encryptText(String plainText,SecretKey secKey) throws Exception{
    // AES defaults to AES/ECB/PKCS5Padding in Java 7
    Cipher aesCipher = Cipher.getInstance("AES");
    aesCipher.init(Cipher.ENCRYPT_MODE, secKey);
    byte[] byteCipherText = aesCipher.doFinal(plainText.getBytes());
    return byteCipherText;
}

public static String decryptText(byte[] byteCipherText, SecretKey secKey) throws Exception {
    // AES defaults to AES/ECB/PKCS5Padding in Java 7
    Cipher aesCipher = Cipher.getInstance("AES");
    aesCipher.init(Cipher.DECRYPT_MODE, secKey);
    byte[] bytePlainText = aesCipher.doFinal(byteCipherText);
    return new String(bytePlainText);
}

public static SecretKey thisKey() throws Exception{

    SecretKey secKey = AESEncryption.getSecretEncryptionKey();

    return secKey;
}

}

in this class where i code the decrypted message. but when i run the code, the messages not decrypt and show ciphert text instead.if someone can correct me, its will great.


问:
Android equivalence of iOS ActionSheet
What is the Android equivalence of the UIActionSheet in the iOS SDK? I am working on a React-Native project and need to maintain the use of native controls where possible. I have not come across an npm package or other that makes use of the respective plartform 'actionsheet'. They all seem to use native actionsheet in iOS, and a javascript mock of the iOS actionsheet for Android (which makes it non-native on Android). If I can know what android shows where iOS shows an actionsheet then I can make use of the RN Android component for android and actionsheet for iOS. I hope this is a clear question.</p>

答:
For ActionSheet like in IOS you can use This Library

Usage

Add this dependency to your app level grsadle

```<code>dependencies {
    compile 'com.baoyz.actionsheet:library:1.1.7'
}
</code>```

Create ActionSheet and show

```<code>ActionSheet.createBuilder(this, getSupportFragmentManager())
            .setCancelButtonTitle("Cancel")
            .setOtherButtonTitles("Item1", "Item2", "Item3", "Item4")
            .setCancelableOnTouchOutside(true)
            .setListener(this).show();
</code>```

Methods

setCancelButtonTitle() Cancel button title, (String)

setOtherButtonTitles() Item buttons title，(String[])

setCancelableOnTouchOutside() Touch outside to close, (boolean)

setListener() set a Listener to listen event

show() Show ActionSheet, return ActionSheet Object，call dismiss() method of ActionSheet to close.

Title: Android equivalence of iOS ActionSheet

Body:
For ActionSheet like in IOS you can use This Library

Usage

Add this dependency to your app level grsadle

dependencies {
    compile 'com.baoyz.actionsheet:library:1.1.7'
}

Create ActionSheet and show

ActionSheet.createBuilder(this, getSupportFragmentManager())
            .setCancelButtonTitle("Cancel")
            .setOtherButtonTitles("Item1", "Item2", "Item3", "Item4")
            .setCancelableOnTouchOutside(true)
            .setListener(this).show();

Methods

setCancelButtonTitle() Cancel button title, (String)

setOtherButtonTitles() Item buttons title，(String[])

setCancelableOnTouchOutside() Touch outside to close, (boolean)

setListener() set a Listener to listen event

show() Show ActionSheet, return ActionSheet Object，call dismiss() method of ActionSheet to close.


问:
send variable to catch from outside of promise in NodeJS
I try to make bot for telegram and use telegram-node-bot for this. I unpload my bot on server, now makes some fixs and reload it. After this in my console I got telegram API errors with message that I cant send messages to users that was banned or blocked my bot. I can catch this errors easy if I try to send a message like this:

```<code>for(var i=0;i<users.length;i++){
  let uid = users[i].chatid;
  tg.api.sendMessage(uid, "Hello, world!")
    .catch(function(err) {
      console.log('err = '+JSON.stringify(err))
      console.log('uid = '+uid) // undefined
    })
}
</code>```

In output of this will be result like this:

```<code>err = {"_code":403,"_description":"Forbidden: bot was blocked by the user"}
</code>```

And... and this dont let me do nothing cuz uid still undefined, and I cant do nothing with this error. How to pass uid to this catch?

答:
You could try the following:

```<code>const Fail = function(detail)=>{this.detail=detail;};
Promise.all(
  users.map(
    user =>
      tg.api.sendMessage(user.chatid, "Hello, world!")
      .then(
        undefined,//do not handle resolve, do that later
        err => new fail([err,user])
      )
  )
)
.then(
  results => {
    const sucesses = results.filter(result=>(result&&result.constructor)!==Fail);
    const failures = results.filter(result=>(result&&result.constructor)===Fail);
    console.log("all chats completed ,"+failures.length+" failed");
    console.log(
      "failure details:"
    );
    failures.forEach(
      fail=>{
        cosnt [reason,user] = fail.detail;
        console.log("failed because:",reason,"for user:",user.chatid);
      }
    )
  }
);
</code>```

Please let me know if you need more help.

The reason your code didn't work:

Since your code actually shows no problems I have to guess that one of the users doesn't have a chatid or that you are using var uid or anything really.

A let binding is scoped within the for/while/if block but a var binding is scoped within a function (or global if outside a function).

Here I'm using let binding and see it outputs expected results:

```<code>var i = -1,numbers=[1,2,3,4,5],promises=[];
while(++i<5){
  let number = numbers[i]; // using let, should work as expected
  console.log("in in the while loop",number);
  promises.push(Promise.resolve("")
    .then(
      _=>console.log("In resolved promise number is now:",number)
    )
  );
}
console.log("after while loop",i);
Promise.all(promises)
.then(x=>console.log("all promises resolved"))
</code>```

This uses var binding so you get "unexpected" results

```<code>var i = -1,numbers=[1,2,3,4,5],promises=[];
while(++i<5){
  var number = numbers[i]; // using var, should have "unexpected" results
  console.log("in in the while loop",number);
  promises.push(Promise.resolve("")
    .then(
      _=>console.log("In resolved promise number is now (should be 5)",number)
    )
  );
}
console.log("after while loop",i);
Promise.all(promises)
.then(x=>console.log("all promises resolved"))
</code>```

Body:
I try to make bot for telegram and use telegram-node-bot for this. I unpload my bot on server, now makes some fixs and reload it. After this in my console I got telegram API errors with message that I cant send messages to users that was banned or blocked my bot. I can catch this errors easy if I try to send a message like this:

for(var i=0;i<users.length;i++){
  let uid = users[i].chatid;
  tg.api.sendMessage(uid, "Hello, world!")
    .catch(function(err) {
      console.log('err = '+JSON.stringify(err))
      console.log('uid = '+uid) // undefined
    })
}

In output of this will be result like this:

err = {"_code":403,"_description":"Forbidden: bot was blocked by the user"}

And... and this dont let me do nothing cuz uid still undefined, and I cant do nothing with this error. How to pass uid to this catch?

Body:
You could try the following:

const Fail = function(detail)=>{this.detail=detail;};
Promise.all(
  users.map(
    user =>
      tg.api.sendMessage(user.chatid, "Hello, world!")
      .then(
        undefined,//do not handle resolve, do that later
        err => new fail([err,user])
      )
  )
)
.then(
  results => {
    const sucesses = results.filter(result=>(result&&result.constructor)!==Fail);
    const failures = results.filter(result=>(result&&result.constructor)===Fail);
    console.log("all chats completed ,"+failures.length+" failed");
    console.log(
      "failure details:"
    );
    failures.forEach(
      fail=>{
        cosnt [reason,user] = fail.detail;
        console.log("failed because:",reason,"for user:",user.chatid);
      }
    )
  }
);

Please let me know if you need more help.

The reason your code didn't work:

Since your code actually shows no problems I have to guess that one of the users doesn't have a chatid or that you are using var uid or anything really.

A let binding is scoped within the for/while/if block but a var binding is scoped within a function (or global if outside a function).

Here I'm using let binding and see it outputs expected results:

var i = -1,numbers=[1,2,3,4,5],promises=[];
while(++i<5){
  let number = numbers[i]; // using let, should work as expected
  console.log("in in the while loop",number);
  promises.push(Promise.resolve("")
    .then(
      _=>console.log("In resolved promise number is now:",number)
    )
  );
}
console.log("after while loop",i);
Promise.all(promises)
.then(x=>console.log("all promises resolved"))

This uses var binding so you get "unexpected" results

var i = -1,numbers=[1,2,3,4,5],promises=[];
while(++i<5){
  var number = numbers[i]; // using var, should have "unexpected" results
  console.log("in in the while loop",number);
  promises.push(Promise.resolve("")
    .then(
      _=>console.log("In resolved promise number is now (should be 5)",number)
    )
  );
}
console.log("after while loop",i);
Promise.all(promises)
.then(x=>console.log("all promises resolved"))


问:
How to set the callbacks for Android Firebase Phone Authentication?
Im kinda new to firebase and android then I saw this new feature in android the firebase phone Auth. I was looking at this doucumentation Firebase Phone Auth and I am confused on Implementing this mCallbacks .. can someone pls guide me ?

```<code>PhoneAuthProvider.getInstance().verifyPhoneNumber(
                        phoneNum,
                        60,
                        TimeUnit.SECONDS,
                        this,
                        mCallbacks
</code>```

this confused me is I dont know what data type should I use to assign that callback. since there is no sample code I wish someone might able to guide me.

答: Instead of passing "this" inside the verifyPhoneNumber(..) method, Try to pass Activityname.this</p>

Body:
Im kinda new to firebase and android then I saw this new feature in android the firebase phone Auth. I was looking at this doucumentation Firebase Phone Auth and I am confused on Implementing this mCallbacks .. can someone pls guide me ?

PhoneAuthProvider.getInstance().verifyPhoneNumber(
                        phoneNum,
                        60,
                        TimeUnit.SECONDS,
                        this,
                        mCallbacks

this confused me is I dont know what data type should I use to assign that callback. since there is no sample code I wish someone might able to guide me.


问:
Azure Table Storage Concurrency Issue
It seems like concurrency conflicts with Azure throw an exception with a message containing the error code 412. Is there a good way to tell that an exception is thrown due to a concurrency problem other than checking if the error message of a StorageException contains 412 in the message? This seems like a really stringly typed approach.</p>

答:
Using "RequestInformation.HttpStatusCode seems to work for me</p>

```<code>    try
    {
        TableOperation operation = TableOperation.Merge(ent);
        retval = await table.ExecuteAsync(operation);
    }
    catch (StorageException sex)
    {
        if (sex.RequestInformation.HttpStatusCode == (int)HttpStatusCode.PreconditionFailed)
        {
            TableOperation retrieveOperation = TableOperation.Retrieve<BotSetting>(ent.PartitionKey, ent.RowKey);
            TableResult retrievedResult = await table.ExecuteAsync(retrieveOperation);
            if (retrievedResult.Result != null)
            {
                BotSetting bs = retrievedResult.Result as BotSetting;
                retval = await TryMerge(table, bs, tries--);
            }
        }
    }
</code>```

Title: Azure Table Storage Concurrency Issue

Body:
Using "RequestInformation.HttpStatusCode seems to work for me

    try
    {
        TableOperation operation = TableOperation.Merge(ent);
        retval = await table.ExecuteAsync(operation);
    }
    catch (StorageException sex)
    {
        if (sex.RequestInformation.HttpStatusCode == (int)HttpStatusCode.PreconditionFailed)
        {
            TableOperation retrieveOperation = TableOperation.Retrieve<BotSetting>(ent.PartitionKey, ent.RowKey);
            TableResult retrievedResult = await table.ExecuteAsync(retrieveOperation);
            if (retrievedResult.Result != null)
            {
                BotSetting bs = retrievedResult.Result as BotSetting;
                retval = await TryMerge(table, bs, tries--);
            }
        }
    }


问:
Proper way of non-blocking load of unrelated models for nested route in Ember
My routes look roughly like this:

```</p>

```/
  /sites
    /:site_id
      /settings
        /user-defined-params
          /:param_id
```

<p>```

Now in /user-defined-params I want to display table-list of parameters assigned to that given site. The models are not related, I mean site doesn't have collection of params as a relation, so I can't simply fetch them via this relation.

Should model() hook for my router return list of these params? By default the model seems to be site loaded from parent route (:site_id). What if loading takes some time and I'd like to actually display this table (so do actual transition) but then show kind of loading indicator waiting for table to fill in with the data.

When I try to load this in model() hook, transition blocks. When I try to load it in afterModel() hook, I don't have a way to assign it and make it available for template (other than force-assigning params property to site model, which seems to be wrong).

All the examples I've found over the Internet seem to be lacking this scenario, which I feel is one of the basic ones, so any hints on that? How should I load it (ideally without blocking transition)?

答:
The defaults in Ember's current router (as you have found) are to block UI loading completely until the promised returned in model hooks have resolved. However, there's interest in adjusting that so we can easily build non-blocking UI patterns with the built-in router.

Right now, the community consensus here is to use ember-concurrency and it's derived state (specifically the .isRunning aspect of tasks) to toggle between a loading state and a screen with the data rendered. It isn't a coincidence that ember-concurrency was built by the guy behind the first router and the current router re-think that is in-process.

One example of an approach to this is outlined here:
https://emberway.io/skeleton-screen-loading-in-ember-js-2f7ac2384d63

I personally prefer to use my route to do the initial task loading and the consume the data in the template. But in a more complex UI I also will go with container components as outlined in that article.

Body:
My routes look roughly like this:

```</p>

<pre><code>/
  /sites
    /:site_id
      /settings
        /user-defined-params
          /:param_id
</code></pre>

<p>```

Now in /user-defined-params I want to display table-list of parameters assigned to that given site. The models are not related, I mean site doesn't have collection of params as a relation, so I can't simply fetch them via this relation.

Should model() hook for my router return list of these params? By default the model seems to be site loaded from parent route (:site_id). What if loading takes some time and I'd like to actually display this table (so do actual transition) but then show kind of loading indicator waiting for table to fill in with the data.

When I try to load this in model() hook, transition blocks. When I try to load it in afterModel() hook, I don't have a way to assign it and make it available for template (other than force-assigning params property to site model, which seems to be wrong).

All the examples I've found over the Internet seem to be lacking this scenario, which I feel is one of the basic ones, so any hints on that? How should I load it (ideally without blocking transition)?


问:
I am trying to create multiple charts
with this dataset I am trying to plot by device category  using the ggplot as below and I keep getting the following error message (geom_path: Each group consists of only one observation. Do you need to adjust the group aesthetic?)
I tried using group= 1 but that didnt work ..any help much aprreciated ?</p>

```<code>head(gaDataExt)
      date deviceCategory users sessions pageviews
1 20171130        desktop     6        6        10
2 20171130         mobile    14       14        18
3 20171130         tablet     1        1         1
4 20171129        desktop    12       13        15
5 20171129         mobile    29       30        33
6 20171129         tablet     4        5         8

# multiple plots faceted by device categry.
ggplot(data = gaDataExt, mapping = aes(x = date, y = sessions),group = NULL ) +
  geom_line() +
  facet_grid(deviceCategory ~ .) +
  theme_bw() +
  ylim(0,NA)
</code>```

答:
```<code>df <- data.frame(date = c(rep(20171130, 3), rep(20171129, 3)),
                 deviceCategory = c('desktop', 'mobile', 'tablet'),
                 users = c(6, 14, 1, 12, 29, 4),
                 sessions = c(6, 14, 1, 13, 30, 5),
                 pageviews = c(10, 18, 1, 15, 33, 8))
</code>```

You can change to months easily using lubridate. This gives you the mean by month.

```<code>library(tidyverse)
library(lubridate)

df %>%
  mutate(date = ymd(date),
         month = month(date)) %>%
  group_by(deviceCategory) %>%
  summarise_all(funs(mean)) %>%
  ggplot(aes(month, sessions)) + geom_point() +
      facet_grid(deviceCategory~.) +
  theme_bw()
</code>```

Update, you could simply remove the mean and use the date:

```<code>df %>%
  mutate(date = ymd(date)) %>%
  ggplot(aes(date, sessions)) + geom_point() +
      facet_grid(deviceCategory~.) +
  theme_bw()
</code>```

Title: I am trying to create multiple charts

Body:
with this dataset I am trying to plot by device category  using the ggplot as below and I keep getting the following error message (geom_path: Each group consists of only one observation. Do you need to adjust the group aesthetic?)
I tried using group= 1 but that didnt work ..any help much aprreciated ?

head(gaDataExt)
      date deviceCategory users sessions pageviews
1 20171130        desktop     6        6        10
2 20171130         mobile    14       14        18
3 20171130         tablet     1        1         1
4 20171129        desktop    12       13        15
5 20171129         mobile    29       30        33
6 20171129         tablet     4        5         8

# multiple plots faceted by device categry.
ggplot(data = gaDataExt, mapping = aes(x = date, y = sessions),group = NULL ) +
  geom_line() +
  facet_grid(deviceCategory ~ .) +
  theme_bw() +
  ylim(0,NA)

Body:
df <- data.frame(date = c(rep(20171130, 3), rep(20171129, 3)),
                 deviceCategory = c('desktop', 'mobile', 'tablet'),
                 users = c(6, 14, 1, 12, 29, 4),
                 sessions = c(6, 14, 1, 13, 30, 5),
                 pageviews = c(10, 18, 1, 15, 33, 8))

You can change to months easily using lubridate. This gives you the mean by month.

library(tidyverse)
library(lubridate)

df %>%
  mutate(date = ymd(date),
         month = month(date)) %>%
  group_by(deviceCategory) %>%
  summarise_all(funs(mean)) %>%
  ggplot(aes(month, sessions)) + geom_point() +
      facet_grid(deviceCategory~.) +
  theme_bw()

Update, you could simply remove the mean and use the date:

df %>%
  mutate(date = ymd(date)) %>%
  ggplot(aes(date, sessions)) + geom_point() +
      facet_grid(deviceCategory~.) +
  theme_bw()


问:
How to use Altium with Git?
Altium has built in support for Subversion but we do have a need for version control at multiple sites.
WANdisco can synchronize multiple SVN repositories but it is expensive.
Has anyone used Altium with Git?
If so, how?</p>

答:
You can always use GIT outside of Altium - I have been doing so for many years.

Simply create a GIT repo based on your project folder.

On the downside, you do lose the functionality of Altium showing the differences between versions. Also, as far as I know, you can't do merges as the files Altium uses are not text based.

Edit: Altium are currently working to implement GIT as a version control option. https://bugcrunch.live.altium.com/#Idea/2379

Title: How to use Altium with Git?


答:
You can just use the SPLIT function instead. For example,</p>

```<code>SELECT
  parts[SAFE_OFFSET(0)] AS Word0,
  parts[SAFE_OFFSET(1)] AS Word1,
  parts[SAFE_OFFSET(2)] AS Word2,
  parts[SAFE_OFFSET(3)] AS Word3,
  parts[SAFE_OFFSET(4)] AS Word4,
  parts[SAFE_OFFSET(5)] AS Word5,
  parts[SAFE_OFFSET(6)] AS Word6,
  parts[SAFE_OFFSET(7)] AS Word7,
  parts[SAFE_OFFSET(8)] AS Word8,
  parts[SAFE_OFFSET(9)] AS Word9
FROM (
  SELECT SPLIT(event_list, ',') AS parts
  FROM `mytable.2017`
);
</code>```

Title: regex comma separated delimiter

Body:
You can just use the SPLIT function instead. For example,

SELECT
  parts[SAFE_OFFSET(0)] AS Word0,
  parts[SAFE_OFFSET(1)] AS Word1,
  parts[SAFE_OFFSET(2)] AS Word2,
  parts[SAFE_OFFSET(3)] AS Word3,
  parts[SAFE_OFFSET(4)] AS Word4,
  parts[SAFE_OFFSET(5)] AS Word5,
  parts[SAFE_OFFSET(6)] AS Word6,
  parts[SAFE_OFFSET(7)] AS Word7,
  parts[SAFE_OFFSET(8)] AS Word8,
  parts[SAFE_OFFSET(9)] AS Word9
FROM (
  SELECT SPLIT(event_list, ',') AS parts
  FROM `mytable.2017`
);


问:
Dealing One Card to Each Player Before Dealing a Second Card - Blackjack Game in Python
I have made the following code in Python. Where deck = deck_of_cards(). My question is how to I fix the second function so that it must deal a first card to each player before dealing a second card. The way it is right now seems to deal two cards to a player before dealing cards to the other players and I don't know how to fix it.</p>

```<code>import random
def deck_of_cards():
    suits = ['D', 'C', 'H', 'S']
    denominations = ['2', '3', '4', '5', '6', '7', '8',
                     '9', 'T', 'J', 'Q', 'K', 'A']
    deck = []
    for suit in suits:
        for denomination in denominations:
            ds = denomination + suit
            deck.append(ds)

    random.shuffle(deck)
    return deck

def deal_cards(deck, players):
    hands = []

    for j in range(players):
        player_hand = []
        for i in range(2):
            cards = deck.pop(0)
            player_hand.append(cards)

        hands.append(player_hand)
    return hands
</code>```

答:
You need to swap your for loops so you iterate over all players for the first cars, then the second:</p>

```<code>def deal_cards(deck, players):
    hands = [[] for player in range(players)]

    for _ in range(2):
        for hand in hands:
            hand.append(deck.pop(0))

    return hands
</code>```

Body:
I have made the following code in Python. Where deck = deck_of_cards(). My question is how to I fix the second function so that it must deal a first card to each player before dealing a second card. The way it is right now seems to deal two cards to a player before dealing cards to the other players and I don't know how to fix it.

import random
def deck_of_cards():
    suits = ['D', 'C', 'H', 'S']
    denominations = ['2', '3', '4', '5', '6', '7', '8',
                     '9', 'T', 'J', 'Q', 'K', 'A']
    deck = []
    for suit in suits:
        for denomination in denominations:
            ds = denomination + suit
            deck.append(ds)

    random.shuffle(deck)
    return deck

def deal_cards(deck, players):
    hands = []

    for j in range(players):
        player_hand = []
        for i in range(2):
            cards = deck.pop(0)
            player_hand.append(cards)

        hands.append(player_hand)
    return hands

Body:
You need to swap your for loops so you iterate over all players for the first cars, then the second:

def deal_cards(deck, players):
    hands = [[] for player in range(players)]

    for _ in range(2):
        for hand in hands:
            hand.append(deck.pop(0))

    return hands


问:
Database/Web servers as a Virtual Machines vs Bare Metal?
I manage a database (Oracle 8i) and web server (IIS) for about 50 simultaneous users on average and a theoretical limit of 100 simultaneous users. A mid level system.

We just got a dual-socket Quad-core XEON - 16GB RAM - SAS-RAID-10 beast and I am exploring the possibilities of taking these two separate servers and merging them into two virtual machines both running on the new server (Server 2009 Hyper-V).

1) In general, what are the performance penalties (as well as any gotchas and hidden consequences) of running both the database and web servers as virtual machines on one mega server vs running them on two separate slower boxes? Is it a big NO-NO or it is something worth trying for a mid-level system that will never need to scale?

2) What are the general performance penalties (in percentage) and gotchas for virtualizing just the database server? We run Oracle 8i (but are considering moving to MS SQL Server).

3) If only stress tests can determine an reasonable answer, what would be the easiest way to test these scenarios (tools / configuration).

Thanks in advance for any generous knowledge-sharing.

答:
Be aware that Oracle has its own guidelines on running in a virtual machine.

The product I work with utilizes Oracle on the back-end, and for heavy use, the overhead of a VM has had negative effects on it.

8i is well past EOL, and was around before virtualization was a Big Thing(tm), so moving to a new edition of Oracle might also be a good plan at the time your migrate to virtualization.

Oracle blog article on 11g in a VM - http://blogs.oracle.com/MingMan/2007/11/oracle_database_11g_successful.html

If you're concerned about timing, also be aware of known clock-drift issues in hypervisors, and available fixes (either from the OS or virtualization vendors).

OwnerDisplayName: Matias Nino

LastEditorDisplayName: Keltia

OwnerDisplayName: warren


问:
Java using multiple methods in the program
I have the following code on Java which works fine now but I'm wondering how to make the same program but with multiple methods (object oriented programming). Right now all the code is in the main method and I'd like to make it so it has at least one other method where the calculations are made and that method would be called in the main method.
The program asks the user different kinds of multiplication questions like 2*3, 9*5 and so on

```<code>import java.util.Random;
import javax.swing.JOptionPane;

public class Main {

  public static void main(String[] args) {

    Random number = new Random();

    while (true) {

        int nmb1 = number.nextInt(10) + 1;
        int nmb2 = number.nextInt(10) + 1;
        int multi = nmb1 * nmb2;
        int question;

        // read the user's input ...
        do {
            question = Integer.parseInt(JOptionPane.showInputDialog("How much is" + nmb1 + "*" + nmb2));

            if (question != multi) {
                JOptionPane.showMessageDialog(null, "Wrong, try again");
            }
        }
        while (question != multi);
        // .. and repeat until the user types the correct answer

        JOptionPane.showMessageDialog(null, "Right");
      }
   }
}
</code>```

If anyone can offer any help I would appreciate it.

答:
You can simply wrap up your calculation and user input in a method call multiplication() as shown in the code below. The method will return a boolean value to identify if the user has answer the question correctly. HTH.</p>

```<code>import java.util.Random;
import javax.swing.JOptionPane;

public class Main{

  public static void main(String[] args) {

      boolean correctAnswer;
      Random number = new Random();
      int nmb1;
      int nmb2;
      int multi;

    while (true) {
        nmb1 = number.nextInt(10) + 1;
        nmb2 = number.nextInt(10) + 1;
        multi = nmb1 * nmb2;

        // read the user's input ...
        do {
            correctAnswer = multiplication(nmb1,nmb2,multi);
        }
        while (correctAnswer != true);
        // .. and repeat until the user types the correct answer

        JOptionPane.showMessageDialog(null, "Right");
      }
   }

  public static boolean multiplication(int number1,int number2,int answer)
  {

      int question;

         question = Integer.parseInt(JOptionPane.showInputDialog("How much is" + number1 + "*" + number2));

          if (question != answer) {
              JOptionPane.showMessageDialog(null, "Wrong, try again");

              return false;
          }

      return true;

  }

}
</code>```

Body:
I have the following code on Java which works fine now but I'm wondering how to make the same program but with multiple methods (object oriented programming). Right now all the code is in the main method and I'd like to make it so it has at least one other method where the calculations are made and that method would be called in the main method.
The program asks the user different kinds of multiplication questions like 2*3, 9*5 and so on

import java.util.Random;
import javax.swing.JOptionPane;

public class Main {

  public static void main(String[] args) {

    Random number = new Random();

    while (true) {

        int nmb1 = number.nextInt(10) + 1;
        int nmb2 = number.nextInt(10) + 1;
        int multi = nmb1 * nmb2;
        int question;

        // read the user's input ...
        do {
            question = Integer.parseInt(JOptionPane.showInputDialog("How much is" + nmb1 + "*" + nmb2));

            if (question != multi) {
                JOptionPane.showMessageDialog(null, "Wrong, try again");
            }
        }
        while (question != multi);
        // .. and repeat until the user types the correct answer

        JOptionPane.showMessageDialog(null, "Right");
      }
   }
}

If anyone can offer any help I would appreciate it.

Body:
You can simply wrap up your calculation and user input in a method call multiplication() as shown in the code below. The method will return a boolean value to identify if the user has answer the question correctly. HTH.

import java.util.Random;
import javax.swing.JOptionPane;

public class Main{

  public static void main(String[] args) {

      boolean correctAnswer;
      Random number = new Random();
      int nmb1;
      int nmb2;
      int multi;

    while (true) {
        nmb1 = number.nextInt(10) + 1;
        nmb2 = number.nextInt(10) + 1;
        multi = nmb1 * nmb2;

        // read the user's input ...
        do {
            correctAnswer = multiplication(nmb1,nmb2,multi);
        }
        while (correctAnswer != true);
        // .. and repeat until the user types the correct answer

        JOptionPane.showMessageDialog(null, "Right");
      }
   }

  public static boolean multiplication(int number1,int number2,int answer)
  {

      int question;

         question = Integer.parseInt(JOptionPane.showInputDialog("How much is" + number1 + "*" + number2));

          if (question != answer) {
              JOptionPane.showMessageDialog(null, "Wrong, try again");

              return false;
          }

      return true;

  }

}


问:
Would it be possible to add more images at a certain checkpoint and resume training from that checkpoint?
I am evaluating tensorflow object detection API.
I have looked at a few articles that I found on the Internet and I am able to train the model and evaluate object detection successfully.

When I started training, there were about 100 images that are labeled.
I want to add two or three news images to TFrecord.
After adding those images, should I delete my model_output directory and start train.py or can I do that on top of existing checkpoints?

答:
Tensorflow supports restoring the status from a checkpoint as you can see from the official documentation:

https://www.tensorflow.org/programmers_guide/saved_model

```<code># Create some variables.
v1 = tf.get_variable("v1", shape=[3])
v2 = tf.get_variable("v2", shape=[5])

# Add ops to save and restore all the variables.
saver = tf.train.Saver()

# Later, launch the model, use the saver to restore variables from disk, and
# do some work with the model.
with tf.Session() as sess:
  # Restore variables from disk.
  saver.restore(sess, "/tmp/model.ckpt")
  print("Model restored.")
  # Check the values of the variables
  print("v1 : %s" % v1.eval())
  print("v2 : %s" % v2.eval())
</code>```

If you are not adding or deleting classes you don't need to restart your model. However pay attention to whether the learning rate has changed during your previous training. If your scheduler decreases the learning rate aggressively, you might not be able to learn the new images due to the learning rate being too small.

Body:
Tensorflow supports restoring the status from a checkpoint as you can see from the official documentation:

https://www.tensorflow.org/programmers_guide/saved_model

# Create some variables.
v1 = tf.get_variable("v1", shape=[3])
v2 = tf.get_variable("v2", shape=[5])

# Add ops to save and restore all the variables.
saver = tf.train.Saver()

# Later, launch the model, use the saver to restore variables from disk, and
# do some work with the model.
with tf.Session() as sess:
  # Restore variables from disk.
  saver.restore(sess, "/tmp/model.ckpt")
  print("Model restored.")
  # Check the values of the variables
  print("v1 : %s" % v1.eval())
  print("v2 : %s" % v2.eval())

If you are not adding or deleting classes you don't need to restart your model. However pay attention to whether the learning rate has changed during your previous training. If your scheduler decreases the learning rate aggressively, you might not be able to learn the new images due to the learning rate being too small.


问:
No package generated in VSTS build (for ASP.net project), so that release failed, why?

I'm using  Microsoft team foundation server 2018's build task to build the Asp.net project and then deploy it to Microsoft Azure Website.

The following MsBuild command should publish the website to a publishing package in the build agent's artifact directory:

```<code>"C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\msbuild.exe"
"C:\agent\_work\8\s\Altoro.sln" /nologo /nr:false /dl:CentralLogger,"C:\agent\_work\_tasks\VSBuild_71a9a2d3-a98a-4caa-96ab-affca411ecda\1.119.0\ps_modules\MSBuildHelpers\Microsoft.TeamFoundation.DistributedTask.MSBuild.Logger.dll";"RootDetailId=9ac05cfe-e8e9-42b6-a469-24e84f79ebe9|SolutionDir=C:\agent\_work\8\s"*ForwardingLogger,"C:\agent\_work\_tasks\VSBuild_71a9a2d3-a98a-4caa-96ab-affca411ecda\1.119.0\ps_modules\MSBuildHelpers\Microsoft.TeamFoundation.DistributedTask.MSBuild.Logger.dll"
/p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=true
/p:SkipInvalidConfigurations=true /p:PackageLocation="C:\agent\_work\8\a\\"
/p:platform="any cpu" /p:configuration="release" /p:VisualStudioVersion="15.0"
/p:_MSDeployUserAgent="TFS_2386aba1-5b25-4025-ba06-4677ece9a429_build_8_125"
</code>```

The build succeeded, however, there is no package generated, so the next release job failed with

'2017-12-02T07:36:56.2618898Z ##[warning]Folder “C:\agent_work\8\a”is empty。no content will be added to drop folder。

答:
To build ASP.NET website project, you should build *.publishproj instead of *.sln in Visual Studio build task

In your build definition -> unlink **\*.sln for Visual Studio build task -> specify the path to *.publishproj file -> save and build again.

Body:
I'm using  Microsoft team foundation server 2018's build task to build the Asp.net project and then deploy it to Microsoft Azure Website.

The following MsBuild command should publish the website to a publishing package in the build agent's artifact directory:

"C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\msbuild.exe"
"C:\agent\_work\8\s\Altoro.sln" /nologo /nr:false /dl:CentralLogger,"C:\agent\_work\_tasks\VSBuild_71a9a2d3-a98a-4caa-96ab-affca411ecda\1.119.0\ps_modules\MSBuildHelpers\Microsoft.TeamFoundation.DistributedTask.MSBuild.Logger.dll";"RootDetailId=9ac05cfe-e8e9-42b6-a469-24e84f79ebe9|SolutionDir=C:\agent\_work\8\s"*ForwardingLogger,"C:\agent\_work\_tasks\VSBuild_71a9a2d3-a98a-4caa-96ab-affca411ecda\1.119.0\ps_modules\MSBuildHelpers\Microsoft.TeamFoundation.DistributedTask.MSBuild.Logger.dll"
/p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=true
/p:SkipInvalidConfigurations=true /p:PackageLocation="C:\agent\_work\8\a\\"
/p:platform="any cpu" /p:configuration="release" /p:VisualStudioVersion="15.0"
/p:_MSDeployUserAgent="TFS_2386aba1-5b25-4025-ba06-4677ece9a429_build_8_125"

The build succeeded, however, there is no package generated, so the next release job failed with

'2017-12-02T07:36:56.2618898Z ##[warning]Folder “C:\agent_work\8\a”is empty。no content will be added to drop folder。


问:
Can not discover available Bluetooth devices
I am trying to discover devices. I am turning on my laptop's and other Bluetooth devices but discovery can't discover Bluetooth devices. I found a lot of questions about this problem but I could not find solution.

These are the permissions that I am requesting:

```<code><uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
</code>```

Here is my code:

```<code>import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Parcelable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;

public class ScanDevicesActivity extends AppCompatActivity {
    private final int REQUEST_ENABLE_BT = 21;
    private final String CUSTOM_INFO = "Custom info";
    private final String CUSTOM_ERROR = "Custom error";

    private boolean receiverIsRegistered = false;

    private BluetoothAdapter bluetoothAdapter;

    private ListView devicesList;
    private BluetoothDevicesAdapter bluetoothDevicesAdapter;
    private ArrayList<FoundBluetoothDeviceInfo> foundDevices = new ArrayList<>();

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

        listConfiguration();

        checkIfBluetoothDeviceIsSupported();
    }

    private void listConfiguration(){
        bluetoothDevicesAdapter = new BluetoothDevicesAdapter(this, android.R.layout.simple_list_item_1, foundDevices);

        //final ConnectThread[] connectThread = new ConnectThread[1];
        devicesList = findViewById(R.id.items_list);
        devicesList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                FoundBluetoothDeviceInfo clickedDevice = (FoundBluetoothDeviceInfo)devicesList.getItemAtPosition(i);
            }
        });
        devicesList.setAdapter(bluetoothDevicesAdapter);
    }

    private void checkIfBluetoothDeviceIsSupported(){
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if(bluetoothAdapter == null){
            Toast.makeText(this, "Bluetooth not supported", Toast.LENGTH_LONG).show();
            finish();
        }
    }

    private void checkIfBluetoothIsEnabled(){
        if (!bluetoothAdapter.isEnabled()){
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            discoverDevices();
        }else {
            discoverDevices();
        }
    }

    private void discoverDevices(){
        if ((bluetoothAdapter != null) && (bluetoothAdapter.startDiscovery() != false)) {
            // Register for broadcasts when a device is discovered.
            IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
            filter.addAction(BluetoothDevice.EXTRA_UUID);
            filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
            filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
            Log.i(CUSTOM_INFO, "Starting Discovery");
            registerReceiver(mReceiver, filter);
            receiverIsRegistered = true;
        }
    }

    // Create a BroadcastReceiver for ACTION_FOUND.
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            Log.i(CUSTOM_INFO, "ON RECEIVE");
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Discovery has found a device. Get the BluetoothDevice
                // object and its info from the Intent.
                Log.i(CUSTOM_INFO, "ACTION_FOUND");
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

                String deviceName = device.getName();
                int deviceType = device.getBluetoothClass().getDeviceClass();
                String deviceHardwareAddress = device.getAddress(); // MAC address

                FoundBluetoothDeviceInfo found = new FoundBluetoothDeviceInfo(deviceType, deviceName, deviceHardwareAddress);
                foundDevices.add(found);
                Log.i(CUSTOM_INFO, "Device added to list");
                bluetoothDevicesAdapter.notifyDataSetChanged();
            }else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){
                Log.i(CUSTOM_INFO, "DISCOVERY STARTED");
                if(bluetoothAdapter.startDiscovery())
                    Log.i(CUSTOM_INFO, "TRUE");
                else
                    Log.i(CUSTOM_INFO, "FALSE");
            }else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
                Log.i(CUSTOM_INFO, "DISCOVERY FINISHED");
            }
        }
    };

    public void searchButtonPressed(View view){

        if(receiverIsRegistered){
            this.unregisterReceiver(mReceiver);
            bluetoothAdapter.cancelDiscovery();
            receiverIsRegistered = false;
        }
        checkIfBluetoothIsEnabled();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        if ((requestCode == REQUEST_ENABLE_BT) && (resultCode == RESULT_OK)){
            discoverDevices();
        }else {
            Toast.makeText(this, "Bluetooth is required!", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        this.unregisterReceiver(mReceiver);
    }
}
</code>```

The log:

```<code>12/04 21:32:26: Launching app
$ adb install-multiple -r -t D:\AndroidProjects\OriginalController\app\build\intermediates\split-apk\debug\slices\slice_8.apk D:\AndroidProjects\OriginalController\app\build\outputs\apk\debug\app-debug.apk D:\AndroidProjects\OriginalController\app\build\intermediates\split-apk\debug\slices\slice_9.apk D:\AndroidProjects\OriginalController\app\build\intermediates\split-apk\debug\dep\dependencies.apk D:\AndroidProjects\OriginalController\app\build\intermediates\split-apk\debug\slices\slice_0.apk D:\AndroidProjects\OriginalController\app\build\intermediates\split-apk\debug\slices\slice_7.apk D:\AndroidProjects\OriginalController\app\build\intermediates\split-apk\debug\slices\slice_2.apk D:\AndroidProjects\OriginalController\app\build\intermediates\split-apk\debug\slices\slice_1.apk D:\AndroidProjects\OriginalController\app\build\intermediates\split-apk\debug\slices\slice_3.apk D:\AndroidProjects\OriginalController\app\build\intermediates\split-apk\debug\slices\slice_6.apk D:\AndroidProjects\OriginalController\app\build\intermediates\split-apk\debug\slices\slice_5.apk D:\AndroidProjects\OriginalController\app\build\intermediates\split-apk\debug\slices\slice_4.apk
Split APKs installed
$ adb shell am start -n "com.example.tafy.originalcontroller/com.example.tafy.originalcontroller.ScanDevicesActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER -D
Waiting for application to come online: com.example.tafy.originalcontroller | com.example.tafy.originalcontroller.test
Waiting for application to come online: com.example.tafy.originalcontroller | com.example.tafy.originalcontroller.test
Waiting for application to come online: com.example.tafy.originalcontroller | com.example.tafy.originalcontroller.test
Waiting for application to come online: com.example.tafy.originalcontroller | com.example.tafy.originalcontroller.test
Connecting to com.example.tafy.originalcontroller
Connected to the target VM, address: 'localhost:8600', transport: 'socket'
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
I/art: Late-enabling -Xcheck:jni
D/TidaProvider: TidaProvider()
V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@e8f07f1
I/art: Debugger is no longer active
I/art: Starting a blocking GC Instrumentation
W/ActivityThread: Application com.example.tafy.originalcontroller is waiting for the debugger on port 8100...
I/System.out: Sending WAIT chunk
I/art: Debugger is active
I/System.out: Debugger has connected
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: debugger has settled (1465)
W/System: ClassLoader referenced unknown path: /data/app/com.example.tafy.originalcontroller-1/lib/arm64
I/InstantRun: starting instant run server: is main process
W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
D/AccessibilityManager: current package=com.example.tafy.originalcontroller, accessibility manager mIsFinalEnabled=false, mOptimizeEnabled=true, mIsUiAutomationEnabled=false, mIsInterestedPackage=false
V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@d229de1
V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@ddf706
E/HAL: PATH3 /odm/lib64/hw/gralloc.qcom.so
E/HAL: PATH2 /vendor/lib64/hw/gralloc.qcom.so
E/HAL: PATH1 /system/lib64/hw/gralloc.qcom.so
E/HAL: PATH3 /odm/lib64/hw/gralloc.msm8953.so
E/HAL: PATH2 /vendor/lib64/hw/gralloc.msm8953.so
E/HAL: PATH1 /system/lib64/hw/gralloc.msm8953.so
D/ActivityThreadInjector: clearCachedDrawables.
I/Adreno: QUALCOMM build                   : 01d2d27, I3d52eaf367
          Build Date                       : 12/10/16
          OpenGL ES Shader Compiler Version: XE031.09.00.03
          Local Branch                     :
          Remote Branch                    :
          Remote Branch                    :
          Reconstruct Branch               :
I/OpenGLRenderer: Initialized EGL, version 1.4
D/OpenGLRenderer: Swap behavior 1
W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
I/art: Do partial code cache collection, code=30KB, data=23KB
I/art: After code cache collection, code=28KB, data=22KB
I/art: Increasing code cache capacity to 128KB
V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@8f3511e
I/Timeline: Timeline: Activity_launch_request time:21042198
I/Custom info: Starting Discovery
I/Custom info: ON RECEIVE
I/Custom info: DISCOVERY STARTED
I/Custom info: TRUE
I/Custom info: ON RECEIVE
I/Custom info: DISCOVERY FINISHED
</code>```

I would like to notice that this code is working in android 4.4.
I am working on android 7.

答:
Coincidentally I had this problem about a week ago.

Try to also add the Coarse Location permission. I have both Fine and Coarse on my application and it works with API 19 (Kit Kat), API 21 (Lollipop), API 23 (Marshmallow), and API 24 (Nougat).

```<code><uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
</code>```

Also make sure you request the permission before you reach this point in the app. So in onCreate add the following method to make sure your permissions are requested on higher versions of Android. I know I needed to add this code as well to get it working. You can use your own defined int for REQUEST_ID. It will pop up a prompt to the user when you load the app for higher versions of android.

```<code>private int androidVersion; //define at top of code as a variable

private void requestPermissions(){
androidVersion = Build.VERSION.SDK_INT;
        if (androidVersion >= 23){
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
                            Manifest.permission.ACCESS_COARSE_LOCATION,
                    }, REQUEST_ID);
        }
    }
</code>```

Body:
I am trying to discover devices. I am turning on my laptop's and other Bluetooth devices but discovery can't discover Bluetooth devices. I found a lot of questions about this problem but I could not find solution.

These are the permissions that I am requesting:

<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Here is my code:

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Parcelable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;

public class ScanDevicesActivity extends AppCompatActivity {
    private final int REQUEST_ENABLE_BT = 21;
    private final String CUSTOM_INFO = "Custom info";
    private final String CUSTOM_ERROR = "Custom error";

    private boolean receiverIsRegistered = false;

    private BluetoothAdapter bluetoothAdapter;

    private ListView devicesList;
    private BluetoothDevicesAdapter bluetoothDevicesAdapter;
    private ArrayList<FoundBluetoothDeviceInfo> foundDevices = new ArrayList<>();

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

        listConfiguration();

        checkIfBluetoothDeviceIsSupported();
    }

    private void listConfiguration(){
        bluetoothDevicesAdapter = new BluetoothDevicesAdapter(this, android.R.layout.simple_list_item_1, foundDevices);

        //final ConnectThread[] connectThread = new ConnectThread[1];
        devicesList = findViewById(R.id.items_list);
        devicesList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                FoundBluetoothDeviceInfo clickedDevice = (FoundBluetoothDeviceInfo)devicesList.getItemAtPosition(i);
            }
        });
        devicesList.setAdapter(bluetoothDevicesAdapter);
    }

    private void checkIfBluetoothDeviceIsSupported(){
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if(bluetoothAdapter == null){
            Toast.makeText(this, "Bluetooth not supported", Toast.LENGTH_LONG).show();
            finish();
        }
    }

    private void checkIfBluetoothIsEnabled(){
        if (!bluetoothAdapter.isEnabled()){
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            discoverDevices();
        }else {
            discoverDevices();
        }
    }

    private void discoverDevices(){
        if ((bluetoothAdapter != null) && (bluetoothAdapter.startDiscovery() != false)) {
            // Register for broadcasts when a device is discovered.
            IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
            filter.addAction(BluetoothDevice.EXTRA_UUID);
            filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
            filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
            Log.i(CUSTOM_INFO, "Starting Discovery");
            registerReceiver(mReceiver, filter);
            receiverIsRegistered = true;
        }
    }

    // Create a BroadcastReceiver for ACTION_FOUND.
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            Log.i(CUSTOM_INFO, "ON RECEIVE");
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Discovery has found a device. Get the BluetoothDevice
                // object and its info from the Intent.
                Log.i(CUSTOM_INFO, "ACTION_FOUND");
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

                String deviceName = device.getName();
                int deviceType = device.getBluetoothClass().getDeviceClass();
                String deviceHardwareAddress = device.getAddress(); // MAC address

                FoundBluetoothDeviceInfo found = new FoundBluetoothDeviceInfo(deviceType, deviceName, deviceHardwareAddress);
                foundDevices.add(found);
                Log.i(CUSTOM_INFO, "Device added to list");
                bluetoothDevicesAdapter.notifyDataSetChanged();
            }else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){
                Log.i(CUSTOM_INFO, "DISCOVERY STARTED");
                if(bluetoothAdapter.startDiscovery())
                    Log.i(CUSTOM_INFO, "TRUE");
                else
                    Log.i(CUSTOM_INFO, "FALSE");
            }else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
                Log.i(CUSTOM_INFO, "DISCOVERY FINISHED");
            }
        }
    };

    public void searchButtonPressed(View view){

        if(receiverIsRegistered){
            this.unregisterReceiver(mReceiver);
            bluetoothAdapter.cancelDiscovery();
            receiverIsRegistered = false;
        }
        checkIfBluetoothIsEnabled();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        if ((requestCode == REQUEST_ENABLE_BT) && (resultCode == RESULT_OK)){
            discoverDevices();
        }else {
            Toast.makeText(this, "Bluetooth is required!", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        this.unregisterReceiver(mReceiver);
    }
}

The log:

12/04 21:32:26: Launching app
$ adb install-multiple -r -t D:\AndroidProjects\OriginalController\app\build\intermediates\split-apk\debug\slices\slice_8.apk D:\AndroidProjects\OriginalController\app\build\outputs\apk\debug\app-debug.apk D:\AndroidProjects\OriginalController\app\build\intermediates\split-apk\debug\slices\slice_9.apk D:\AndroidProjects\OriginalController\app\build\intermediates\split-apk\debug\dep\dependencies.apk D:\AndroidProjects\OriginalController\app\build\intermediates\split-apk\debug\slices\slice_0.apk D:\AndroidProjects\OriginalController\app\build\intermediates\split-apk\debug\slices\slice_7.apk D:\AndroidProjects\OriginalController\app\build\intermediates\split-apk\debug\slices\slice_2.apk D:\AndroidProjects\OriginalController\app\build\intermediates\split-apk\debug\slices\slice_1.apk D:\AndroidProjects\OriginalController\app\build\intermediates\split-apk\debug\slices\slice_3.apk D:\AndroidProjects\OriginalController\app\build\intermediates\split-apk\debug\slices\slice_6.apk D:\AndroidProjects\OriginalController\app\build\intermediates\split-apk\debug\slices\slice_5.apk D:\AndroidProjects\OriginalController\app\build\intermediates\split-apk\debug\slices\slice_4.apk
Split APKs installed
$ adb shell am start -n "com.example.tafy.originalcontroller/com.example.tafy.originalcontroller.ScanDevicesActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER -D
Waiting for application to come online: com.example.tafy.originalcontroller | com.example.tafy.originalcontroller.test
Waiting for application to come online: com.example.tafy.originalcontroller | com.example.tafy.originalcontroller.test
Waiting for application to come online: com.example.tafy.originalcontroller | com.example.tafy.originalcontroller.test
Waiting for application to come online: com.example.tafy.originalcontroller | com.example.tafy.originalcontroller.test
Connecting to com.example.tafy.originalcontroller
Connected to the target VM, address: 'localhost:8600', transport: 'socket'
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
I/art: Late-enabling -Xcheck:jni
D/TidaProvider: TidaProvider()
V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@e8f07f1
I/art: Debugger is no longer active
I/art: Starting a blocking GC Instrumentation
W/ActivityThread: Application com.example.tafy.originalcontroller is waiting for the debugger on port 8100...
I/System.out: Sending WAIT chunk
I/art: Debugger is active
I/System.out: Debugger has connected
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: debugger has settled (1465)
W/System: ClassLoader referenced unknown path: /data/app/com.example.tafy.originalcontroller-1/lib/arm64
I/InstantRun: starting instant run server: is main process
W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
D/AccessibilityManager: current package=com.example.tafy.originalcontroller, accessibility manager mIsFinalEnabled=false, mOptimizeEnabled=true, mIsUiAutomationEnabled=false, mIsInterestedPackage=false
V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@d229de1
V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@ddf706
E/HAL: PATH3 /odm/lib64/hw/gralloc.qcom.so
E/HAL: PATH2 /vendor/lib64/hw/gralloc.qcom.so
E/HAL: PATH1 /system/lib64/hw/gralloc.qcom.so
E/HAL: PATH3 /odm/lib64/hw/gralloc.msm8953.so
E/HAL: PATH2 /vendor/lib64/hw/gralloc.msm8953.so
E/HAL: PATH1 /system/lib64/hw/gralloc.msm8953.so
D/ActivityThreadInjector: clearCachedDrawables.
I/Adreno: QUALCOMM build                   : 01d2d27, I3d52eaf367
          Build Date                       : 12/10/16
          OpenGL ES Shader Compiler Version: XE031.09.00.03
          Local Branch                     :
          Remote Branch                    :
          Remote Branch                    :
          Reconstruct Branch               :
I/OpenGLRenderer: Initialized EGL, version 1.4
D/OpenGLRenderer: Swap behavior 1
W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
I/art: Do partial code cache collection, code=30KB, data=23KB
I/art: After code cache collection, code=28KB, data=22KB
I/art: Increasing code cache capacity to 128KB
V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@8f3511e
I/Timeline: Timeline: Activity_launch_request time:21042198
I/Custom info: Starting Discovery
I/Custom info: ON RECEIVE
I/Custom info: DISCOVERY STARTED
I/Custom info: TRUE
I/Custom info: ON RECEIVE
I/Custom info: DISCOVERY FINISHED

I would like to notice that this code is working in android 4.4.
I am working on android 7.

Body:
Coincidentally I had this problem about a week ago.

Try to also add the Coarse Location permission. I have both Fine and Coarse on my application and it works with API 19 (Kit Kat), API 21 (Lollipop), API 23 (Marshmallow), and API 24 (Nougat).

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

Also make sure you request the permission before you reach this point in the app. So in onCreate add the following method to make sure your permissions are requested on higher versions of Android. I know I needed to add this code as well to get it working. You can use your own defined int for REQUEST_ID. It will pop up a prompt to the user when you load the app for higher versions of android.

private int androidVersion; //define at top of code as a variable

private void requestPermissions(){
androidVersion = Build.VERSION.SDK_INT;
        if (androidVersion >= 23){
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
                            Manifest.permission.ACCESS_COARSE_LOCATION,
                    }, REQUEST_ID);
        }
    }


问:
postgres: Querying across rows in multiple tables?
Is there a way to apply a single query across the concatenated rows of multiple tables?  I have several tables storing metrics data, where data is initially collected in 10 second intervals, but is periodically rolled up into 1 minute intervals in another table and ultimately into 10 minute intervals in a third table.

That is, I want to be able to do something like:

```<code>SELECT value FROM table1 + table2 + table3
  WHERE age(current_timestamp, time) > '2 days'
    AND metrics_name = 'foo';
</code>```

I don't think a JOIN operation is the right solution here.  It looks like I can get the result I want using the UNION operator, which would look something like:

```<code>SELECT value from TABLE1 ...
  UNION SELECT value FROM table2 ...
  UNION SELECT value from TABLE3 ...
</code>```

Where ... is the contents of my WHERE clause (etc), but this gets messy very quickly if the individual SELECT queries are complicated (and fails the "don't repeat yourself" mantra).  Is there a different way of cracking this particular nut?

答:
Use a nested query with the UNION in the nested quer. And I highly recommend you use UNION ALL unless you want to eliminate duplicates, which you won't in this case, so use UNION ALL.

```<code>SELECT
    value
FROM (
    SELECT value, age, metrics_name FROM Table1
    UNION ALL SELECT value age, metrics_name FROM Table2
    UNION ALL SELECT value age, metrics_name FROM Table3
) AS All_Metrics
WHERE
    All_Metrics.age(current_timestamp, time) > '2 days'
    AND All_Metrics.metrics_name = 'foo';
</code>```

Body:
Is there a way to apply a single query across the concatenated rows of multiple tables?  I have several tables storing metrics data, where data is initially collected in 10 second intervals, but is periodically rolled up into 1 minute intervals in another table and ultimately into 10 minute intervals in a third table.

That is, I want to be able to do something like:

SELECT value FROM table1 + table2 + table3
  WHERE age(current_timestamp, time) > '2 days'
    AND metrics_name = 'foo';

I don't think a JOIN operation is the right solution here.  It looks like I can get the result I want using the UNION operator, which would look something like:

SELECT value from TABLE1 ...
  UNION SELECT value FROM table2 ...
  UNION SELECT value from TABLE3 ...

Where ... is the contents of my WHERE clause (etc), but this gets messy very quickly if the individual SELECT queries are complicated (and fails the "don't repeat yourself" mantra).  Is there a different way of cracking this particular nut?

Body:
Use a nested query with the UNION in the nested quer. And I highly recommend you use UNION ALL unless you want to eliminate duplicates, which you won't in this case, so use UNION ALL.

SELECT
    value
FROM (
    SELECT value, age, metrics_name FROM Table1
    UNION ALL SELECT value age, metrics_name FROM Table2
    UNION ALL SELECT value age, metrics_name FROM Table3
) AS All_Metrics
WHERE
    All_Metrics.age(current_timestamp, time) > '2 days'
    AND All_Metrics.metrics_name = 'foo';


问:
Creating dictionary from space separated key=value string in Python
I have string as follows:

```<code>s = 'key1=1234 key2="string with space" key3="SrtingWithoutSpace"'
</code>```

I want to convert in to a dictionary as follows:

```
key  | value
-----|--------
key1 | 1234
key2 | string with space
key3 | SrtingWithoutSpace
```

How do I do this in Python?

答:
Try this:

```<code>>>> import re
>>> dict(re.findall(r'(\S+)=(".*?"|\S+)', s))
{'key3': '"SrtingWithoutSpace"', 'key2': '"string with space"', 'key1': '1234'}
</code>```

If you also want to strip the quotes:

```<code>>>> {k:v.strip('"') for k,v in re.findall(r'(\S+)=(".*?"|\S+)', s)}
</code>```

Body:
I have string as follows:

s = 'key1=1234 key2="string with space" key3="SrtingWithoutSpace"'

I want to convert in to a dictionary as follows:

key  | value
-----|--------
key1 | 1234
key2 | string with space
key3 | SrtingWithoutSpace

How do I do this in Python?

Body:
Try this:

>>> import re
>>> dict(re.findall(r'(\S+)=(".*?"|\S+)', s))
{'key3': '"SrtingWithoutSpace"', 'key2': '"string with space"', 'key1': '1234'}

If you also want to strip the quotes:

>>> {k:v.strip('"') for k,v in re.findall(r'(\S+)=(".*?"|\S+)', s)}


问:
Set max-execution-time on a function
I am generating PDF files using pdfmake on client side (a cordova app).

The more complex the document definition is the longer pdfmake takes to produce the document.

Thus, my intention is to put a hard limit on how long it takes for pdfmake to produce the document, something like what timeout command do in bash, and indicate to user if it failed to complete.

Here's a snippet of what I'm trying to do:

```<code>runFor(10, function(){  // run this function for a maximum of 10s
  pdfMake.createPdf(documentDefinition).getBase64(function(b64buff){
     //do something with the result
  });
}, ontimeout);
</code>```

答:
One possibility is in JavaScript, the setInterval function.

```<code>var i =0;
setInterval(function(){i++;console.log(i)},1000);
</code>```

This snippet increases i by 1 every second. Now in the function you want to execute, make a check on i to see if it is big enough to divert the code to a interrupt. Just make sure to reset i when you restart the function.

Title: Set max-execution-time on a function

Body:
I am generating PDF files using pdfmake on client side (a cordova app).

The more complex the document definition is the longer pdfmake takes to produce the document.

Thus, my intention is to put a hard limit on how long it takes for pdfmake to produce the document, something like what timeout command do in bash, and indicate to user if it failed to complete.

Here's a snippet of what I'm trying to do:

runFor(10, function(){  // run this function for a maximum of 10s
  pdfMake.createPdf(documentDefinition).getBase64(function(b64buff){
     //do something with the result
  });
}, ontimeout);

Body:
One possibility is in JavaScript, the setInterval function.

var i =0;
setInterval(function(){i++;console.log(i)},1000);

This snippet increases i by 1 every second. Now in the function you want to execute, make a check on i to see if it is big enough to divert the code to a interrupt. Just make sure to reset i when you restart the function.