问:
Express ENOENT: no such file or directory, stat '/index.html'
I'm having some trouble debugging this issue. Pretty much I have a Node.js that serves a React application and also acts as a REST API. The server runs on port 8080 by default.

import express, {Request, Response} from 'express';
import path from 'path';
import helmet from 'helmet';
import morgan from 'morgan';
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import {ENVIRONMENT, PORT} from '../util/secrets';
// Import API Routes
import * as home from './controllers/home';

// Create express server
const app = express();

// Add middleware
app.use(helmet());
app.use(morgan('combined'));

// Define API routes
app.get('/api/', home.get);

// Configure environment settings
if (ENVIRONMENT === 'development') {
    // ...
} else {
    // Configure Static Files (Production)
    app.use(express.static("./"));

    // Serve React Static Files (Production)
    app.get('*', (req: Request, res: Response) => {
        res.sendFile(path.resolve(__dirname, "/index.html"));
    });
}

// Start server
app.listen(PORT, () => {
    console.log(`Express started on http://localhost:${PORT}/ in ${ENVIRONMENT} mode.`);
});

export default app;
module.exports = app;
```

<p>Basically I go to localhost:8080 and my app renders just fine. <strong>However</strong> when I go to localhost:8080/login I get the following response from the server:</p>

<pre class="lang-sh prettyprint-override"><code>Error: ENOENT: no such file or directory, stat '/index.html'
/index.html
</code>```

Here are the morgan logs:

::ffff:172.17.0.1 - - [19/Feb/2020:03:01:18 +0000] "GET / HTTP/1.1" 304 - "-" "Mozilla/5.0 (Windows NT 10.0; Win64
; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36"
::ffff:172.17.0.1 - - [19/Feb/2020:03:01:18 +0000] "GET /app.bundle.js HTTP/1.1" 304 - "http://localhost:8080/" "M
ozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36
"
Error: ENOENT: no such file or directory, stat '/index.html'
/index.html
::ffff:172.17.0.1 - - [19/Feb/2020:03:01:20 +0000] "GET /login HTTP/1.1" 404 195 "-" "Mozilla/5.0 (Windows NT 10.0
; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36"

```

<p>Why does it render my app on <code>localhost:8080</code> but not <code>localhost:8080/login</code></p>

<p>Dist Folder:</p>

```dist
  img
  app.bundle.js
  index.html
  server.bundle.js
```

答:
webPack is replacing __dirname with something else sine webpack is designed to package things differently that your typical file system layout.  I don't quite understand why you're even running webpack on server-side code and resources.

in your webpack.config.js add the following:

{
  target: 'node',
  node: {
    __dirname: false // disables webpack from changing what __dirname does
  },
}
```

<p>Also, <code>path.resolve()</code> is not doing what you think it's doing.  It's not really the right choice here, <code>path.join()</code> is a better fit.</p>

<p>Change this:</p>

```path.resolve(__dirname, "/index.html")
```

<p>to this:</p>

```path.join(__dirname, "/index.html")
```

You could probably make it work with path.resolve(__dirname, "index.html"), but I think path.join() is the more appropriate choice here.

FYI, path.resolve(__dirname, "/index.html") results in "/index.html" which is not what you want.

Body:
I'm having some trouble debugging this issue. Pretty much I have a Node.js that serves a React application and also acts as a REST API. The server runs on port 8080 by default.

import express, {Request, Response} from 'express';
import path from 'path';
import helmet from 'helmet';
import morgan from 'morgan';
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import {ENVIRONMENT, PORT} from '../util/secrets';
// Import API Routes
import * as home from './controllers/home';

// Create express server
const app = express();

// Add middleware
app.use(helmet());
app.use(morgan('combined'));

// Define API routes
app.get('/api/', home.get);

// Configure environment settings
if (ENVIRONMENT === 'development') {
    // ...
} else {
    // Configure Static Files (Production)
    app.use(express.static("./"));

    // Serve React Static Files (Production)
    app.get('*', (req: Request, res: Response) => {
        res.sendFile(path.resolve(__dirname, "/index.html"));
    });
}

// Start server
app.listen(PORT, () => {
    console.log(`Express started on http://localhost:${PORT}/ in ${ENVIRONMENT} mode.`);
});

export default app;
module.exports = app;

Basically I go to localhost:8080 and my app renders just fine. However when I go to localhost:8080/login I get the following response from the server:

Error: ENOENT: no such file or directory, stat '/index.html'
/index.html

Here are the morgan logs:

::ffff:172.17.0.1 - - [19/Feb/2020:03:01:18 +0000] "GET / HTTP/1.1" 304 - "-" "Mozilla/5.0 (Windows NT 10.0; Win64
; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36"
::ffff:172.17.0.1 - - [19/Feb/2020:03:01:18 +0000] "GET /app.bundle.js HTTP/1.1" 304 - "http://localhost:8080/" "M
ozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36
"
Error: ENOENT: no such file or directory, stat '/index.html'
/index.html
::ffff:172.17.0.1 - - [19/Feb/2020:03:01:20 +0000] "GET /login HTTP/1.1" 404 195 "-" "Mozilla/5.0 (Windows NT 10.0
; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36"

Why does it render my app on localhost:8080 but not localhost:8080/login

Dist Folder:

dist
  img
  app.bundle.js
  index.html
  server.bundle.js

Body:
webPack is replacing __dirname with something else sine webpack is designed to package things differently that your typical file system layout.  I don't quite understand why you're even running webpack on server-side code and resources.

in your webpack.config.js add the following:

{
  target: 'node',
  node: {
    __dirname: false // disables webpack from changing what __dirname does
  },
}

Also, path.resolve() is not doing what you think it's doing.  It's not really the right choice here, path.join() is a better fit.

Change this:

path.resolve(__dirname, "/index.html")

to this:

path.join(__dirname, "/index.html")

You could probably make it work with path.resolve(__dirname, "index.html"), but I think path.join() is the more appropriate choice here.

FYI, path.resolve(__dirname, "/index.html") results in "/index.html" which is not what you want.


来源: stackexchange

问:
androidx ViewModel MutableLiveData LiveData
I am new to Kotlin and Android programming. I cannot figure out why onChanged didnt show up in the first two examples but the last sample is ok. Any suggestions will be greater appreciated. </p>

```<code>var liveDataTest:MutableLiveData<String> = MutableLiveData("ABC")
liveDataTest.observe(this, androidx.lifecycle.Observer() {
 //Cannot find "override fun onChanged"
})
</code>```

```<code>var liveDataTest:LiveData<String> = MutableLiveData("ABC")
liveDataTest.observe(this, androidx.lifecycle.Observer() {
 //Cannot find "override fun onChanged"
})
</code>```

```<code>class test:androidx.lifecycle.Observer<String>{
    override fun onChanged(t: String?) {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }
}
</code>```

答:
Your syntax is wrong in the first two. If you want to pass an anonymous class like that, the syntax is to use the object keyword, and since Observer is an interface, not a class, you don't need to call its constructor with the ().

```<code>liveDataTest.observe(this, object: androidx.lifecycle.Observer {
    override fun onChanged(t: String?) {
        TODO("not implemented")
    }
})
</code>```

But since this is single function Java-defined interface, you can simplify the syntax using a lambda:

```<code>liveDataTest.observe(this) {
    TODO("not implemented")
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am new to Kotlin and Android programming. I cannot figure out why onChanged didnt show up in the first two examples but the last sample is ok. Any suggestions will be greater appreciated.

var liveDataTest:MutableLiveData<String> = MutableLiveData("ABC")
liveDataTest.observe(this, androidx.lifecycle.Observer() {
 //Cannot find "override fun onChanged"
})

var liveDataTest:LiveData<String> = MutableLiveData("ABC")
liveDataTest.observe(this, androidx.lifecycle.Observer() {
 //Cannot find "override fun onChanged"
})

class test:androidx.lifecycle.Observer<String>{
    override fun onChanged(t: String?) {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }
}

Body:
Your syntax is wrong in the first two. If you want to pass an anonymous class like that, the syntax is to use the object keyword, and since Observer is an interface, not a class, you don't need to call its constructor with the ().

liveDataTest.observe(this, object: androidx.lifecycle.Observer {
    override fun onChanged(t: String?) {
        TODO("not implemented")
    }
})

But since this is single function Java-defined interface, you can simplify the syntax using a lambda:

liveDataTest.observe(this) {
    TODO("not implemented")
}


问:
How to make firebase storage reference to a certain bucket?

I create a new bucket in a region near from my users location (asia-southeast1) so hopefully it will fetch the image faster in the client side, I want to upload image and also to download image from that new bucket.

but I don't how to make reference to that new bucket. usually I use the code below in Android to create reference for default bucket

```<code>val ref = FirebaseStorage.getInstance().reference.child("profilePicture")
</code>```

so how to download and upload image from that bucket? I assume that I have to make some change when creating the reference, but I don't know how to pointing the reference to that new bucket

答:
After getting info from @samthecodingman and testing it, I can set a reference to use a certain bucket using the code below

```<code>FirebaseStorage.getInstance("gs://yourBucketNameHere").reference.child("profilePicture")
</code>```

Don't forget to add gs:// in your string as documented here.

Body:
I create a new bucket in a region near from my users location (asia-southeast1) so hopefully it will fetch the image faster in the client side, I want to upload image and also to download image from that new bucket.

but I don't how to make reference to that new bucket. usually I use the code below in Android to create reference for default bucket

val ref = FirebaseStorage.getInstance().reference.child("profilePicture")

so how to download and upload image from that bucket? I assume that I have to make some change when creating the reference, but I don't know how to pointing the reference to that new bucket

Body:
After getting info from @samthecodingman and testing it, I can set a reference to use a certain bucket using the code below

FirebaseStorage.getInstance("gs://yourBucketNameHere").reference.child("profilePicture")

Don't forget to add gs:// in your string as documented here.


问:
How to check if a remote server supports PHP?
I often have clients who do not know if their server supports PHP (their website is HTML web site). At the moment, I send them hello.php file, they upload it and then I check it remotely if their server supports PHP. As you see this takes day or two and it's just a waste of time.

Can I myself any how check if their server supports PHP (via web browser or console tool)? If the domain is for example www.my-client.com, what would be the syntax?

Thanks

PS. I have an access to Linux console so I could use it as well

答:
Not very reliable (but a quick check) is requesting a non existing path (404) returns information about the server and its setup.
For example, on my machine I get the following in the footer which I could parse for 'PHP':

Apache/2.2.14 (Unix) DAV/2
  mod_ssl/2.2.14 OpenSSL/0.9.8l
  PHP/5.3.1 mod_perl/2.0.4 Perl/v5.10.1

ContentLicense: CC BY-SA 3.0


问:
How to execute a non compiled testNg test case in Java web application programmatically?
I am running test cases (TestNg testcases) programmatically, using java, by creating testng xml through code. Running Perfectly okay.

Problem:

I want to execute testcases which are being uploaded live, meaning my server is running and I am uploading new recorded test cases( they are not compiled, passing .java file) into this running server which are passed to above created testng xml java code. But I am getting error i.e
Cannot find class in classpath: com.packagename.SampleTestNgTestcase
While I rerun my server and call this functionality, it execute the test case.

I have been browsing and trying to find solution by practicing the techniques to compile a TestNg testcase, yet no success, as no where getting how to compile a test case.

Any help regarding what is the way I can execute the non-compiled test cases or other way, how to compile the testcase.java file programmatically, is greatly appreciated.
If needed more detailed information about the question clearance, I will!

答:
Compiling a TestNG test class is in no way different from you compiling a regular java class.

Assuming that you don't have any issues with your CLASSPATH (the below code does not account for that), here's a simple example that you can use to get started.

Reference: Most of the implementation is heavily inspired and drawn from this blog.

Lets assume that you have a text file called sample.txt whose contents are as below:

```<code>package foo.bar;
import org.testng.annotations.Test;

public class Example {
    @Test
    public void testMethod() {
        System.err.println("Hello world");
    }
}
</code>```

import java.nio.file.Path;

public class ClassInfo {
  String packageName;
  String className;
  String sourceCode;
  Path javaFile;
  Path classFile;
}
```

<pre class="lang-java prettyprint-override"><code>import static java.nio.charset.StandardCharsets.UTF_8;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.stream.Collectors;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import org.testng.TestNG;

public class DynamicTestNgExecutor {

  public static void main(String[] args) throws Exception {
    DynamicTestNgExecutor.runTests("src/test/resources/sample.txt", "foo.bar.Example");
  }

  public static void runTests(String sourcePath, String className) throws Exception {
    ClassInfo classInfo = parse(sourcePath, className);
    saveSource(classInfo);
    compileSource(classInfo);
    runClass(classInfo, className);
  }

  private static void runClass(ClassInfo classInfo, String className)
      throws MalformedURLException, ClassNotFoundException {
    URL classUrl = classInfo.javaFile.getParent().toFile().toURI().toURL();
    if (!classInfo.packageName.isEmpty()) {
      File file = classInfo.javaFile.toFile();
      int count = classInfo.packageName.split("\\Q.\\E").length;
      for (int i = 0; i <= count; i++) {
        file = file.getParentFile();
      }
      classUrl = file.toURI().toURL();
    }
    URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] {classUrl});
    Class<?> clazz = Class.forName(className, true, classLoader);
    TestNG testNG = new TestNG();
    testNG.setTestClasses(new Class[] {clazz});
    testNG.setVerbose(2);
    testNG.run();
  }

  public static ClassInfo parse(String sourcePath, String className) throws FileNotFoundException {
    InputStream stream = new FileInputStream(sourcePath);
    String separator = System.getProperty("line.separator");
    BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
    ClassInfo info = new ClassInfo();
    info.className = className;
    info.sourceCode = reader.lines().collect(Collectors.joining(separator));
    info.packageName = packageName(info.sourceCode);
    return info;
  }

  private static void compileSource(ClassInfo classInfo) {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    compiler.run(System.in, System.out, System.err, classInfo.javaFile.toFile().getAbsolutePath());
    classInfo.classFile = classInfo.javaFile.getParent().resolve(classInfo.className + ".class");
  }

  public static void saveSource(ClassInfo classInfo) throws IOException {
    String folder = folderName(classInfo.packageName);
    String tmpProperty = System.getProperty("java.io.tmpdir") + File.separator + folder;
    final boolean success = new File(tmpProperty).mkdirs();
    if (!success) {
      throw new IllegalStateException("Encountered problems when creating the package structure " + tmpProperty);
    }
    classInfo.javaFile = Paths.get(tmpProperty, simpleClassName(classInfo.className) + ".java");
    Files.write(classInfo.javaFile, classInfo.sourceCode.getBytes(UTF_8));
  }

  private static String simpleClassName(String className) {
    String[] parts = className.split("\\Q.\\E");
    if (parts.length == 1) {
      //No package name in the class
      return parts[0];
    }
    int lastButOne = parts.length - 1;
    return parts[lastButOne];
  }

  private static String folderName(String pkg) {
    if (pkg.isEmpty()) {
      return "";
    }
    pkg = pkg.replaceAll("\\Q.\\E", "/");
    return pkg;
  }

  private static String packageName(String source) {
    String separator = System.getProperty("line.separator");
    String pkg =
        Arrays.stream(source.split(separator))
            .filter(each -> each.contains("package"))
            .findAny()
            .orElse("");
    if (pkg.isEmpty()) {
      return "";
    }
    return pkg.replaceAll("package ", "").replaceAll(";", "");
  }
}
</code>```

Body:
Compiling a TestNG test class is in no way different from you compiling a regular java class.

Assuming that you don't have any issues with your CLASSPATH (the below code does not account for that), here's a simple example that you can use to get started.

Reference: Most of the implementation is heavily inspired and drawn from this blog.

Lets assume that you have a text file called sample.txt whose contents are as below:

package foo.bar;
import org.testng.annotations.Test;

public class Example {
    @Test
    public void testMethod() {
        System.err.println("Hello world");
    }
}

import java.nio.file.Path;

public class ClassInfo {
  String packageName;
  String className;
  String sourceCode;
  Path javaFile;
  Path classFile;
}

import static java.nio.charset.StandardCharsets.UTF_8;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.stream.Collectors;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import org.testng.TestNG;

public class DynamicTestNgExecutor {

  public static void main(String[] args) throws Exception {
    DynamicTestNgExecutor.runTests("src/test/resources/sample.txt", "foo.bar.Example");
  }

  public static void runTests(String sourcePath, String className) throws Exception {
    ClassInfo classInfo = parse(sourcePath, className);
    saveSource(classInfo);
    compileSource(classInfo);
    runClass(classInfo, className);
  }

  private static void runClass(ClassInfo classInfo, String className)
      throws MalformedURLException, ClassNotFoundException {
    URL classUrl = classInfo.javaFile.getParent().toFile().toURI().toURL();
    if (!classInfo.packageName.isEmpty()) {
      File file = classInfo.javaFile.toFile();
      int count = classInfo.packageName.split("\\Q.\\E").length;
      for (int i = 0; i <= count; i++) {
        file = file.getParentFile();
      }
      classUrl = file.toURI().toURL();
    }
    URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] {classUrl});
    Class<?> clazz = Class.forName(className, true, classLoader);
    TestNG testNG = new TestNG();
    testNG.setTestClasses(new Class[] {clazz});
    testNG.setVerbose(2);
    testNG.run();
  }

  public static ClassInfo parse(String sourcePath, String className) throws FileNotFoundException {
    InputStream stream = new FileInputStream(sourcePath);
    String separator = System.getProperty("line.separator");
    BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
    ClassInfo info = new ClassInfo();
    info.className = className;
    info.sourceCode = reader.lines().collect(Collectors.joining(separator));
    info.packageName = packageName(info.sourceCode);
    return info;
  }

  private static void compileSource(ClassInfo classInfo) {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    compiler.run(System.in, System.out, System.err, classInfo.javaFile.toFile().getAbsolutePath());
    classInfo.classFile = classInfo.javaFile.getParent().resolve(classInfo.className + ".class");
  }

  public static void saveSource(ClassInfo classInfo) throws IOException {
    String folder = folderName(classInfo.packageName);
    String tmpProperty = System.getProperty("java.io.tmpdir") + File.separator + folder;
    final boolean success = new File(tmpProperty).mkdirs();
    if (!success) {
      throw new IllegalStateException("Encountered problems when creating the package structure " + tmpProperty);
    }
    classInfo.javaFile = Paths.get(tmpProperty, simpleClassName(classInfo.className) + ".java");
    Files.write(classInfo.javaFile, classInfo.sourceCode.getBytes(UTF_8));
  }

  private static String simpleClassName(String className) {
    String[] parts = className.split("\\Q.\\E");
    if (parts.length == 1) {
      //No package name in the class
      return parts[0];
    }
    int lastButOne = parts.length - 1;
    return parts[lastButOne];
  }

  private static String folderName(String pkg) {
    if (pkg.isEmpty()) {
      return "";
    }
    pkg = pkg.replaceAll("\\Q.\\E", "/");
    return pkg;
  }

  private static String packageName(String source) {
    String separator = System.getProperty("line.separator");
    String pkg =
        Arrays.stream(source.split(separator))
            .filter(each -> each.contains("package"))
            .findAny()
            .orElse("");
    if (pkg.isEmpty()) {
      return "";
    }
    return pkg.replaceAll("package ", "").replaceAll(";", "");
  }
}


问:
Javascript Promise from scratch
I got an error writing a basic promise from scratch and don't know why this.status produces an error

class Promisify {
  constructor(fn) {
    this.status = 0; // 0 = unfulfilled, 1 = resolved, 2 = rejected
    this.result = undefined;
    this.error = undefined;
    this.thenFns = [];
    this.catchFns = [];
    this.finallyFn = undefined;

    try {
      fn(this._resolve, this._reject);
    } catch (e) {
      this._reject(e);
    }
  }

  // public methods
  then(fn) {
    this.thenFns.push(fn);
    this._doThen();
    return this;
  }

  catch(fn) {
    this.catchFns.push(fn);
    this._doCatch();
    return this;
  };

  finally(fn) {
    this.finallyFn = fn;
    return this;
  }

  // private methods
  _doThen() {
    if (this.status === 1) {
      while(this.thenFns.length) {
        this.thenFns.shift()(this.result);
      }
    }
  }

  _doCatch() {
    if (this.status === 2) {
      if (this.catchFns.length === 0) {
        console.error('uncaught error')
      }
      while(this.catchFns.length) {
        this.catchFns.shift()(this.error);
      }
    }
  }

  _resolve(r) {
    if(this.status)
      throw Error('cannot resolve, already handled');
    this.status = 1;
    this.result = r;
    this._doThen();
  }

  _reject(e) {
    if (this.status) throw Error('cannot reject, already handled');
    this.status = 2;
    this.error = e;
    this._doCatch();
  }
}```

答:
A simple promise build from scratch</p>

```<code>

class Promisify
{
  constructor(fn)
  {
    this._function1 = fn;
  }

  finally()
  {
    console.log('finally executed');
  }

  catch(error)
  {
    console.log('catch executed');
    return this;
  }

  then(resolve, reject)
  {
    try
    {
      this._function1(resolve, reject);
      return this;
    }
    catch(err)
    {
       this.catch(err);
       return this;
    }

    this.finally();

  }

}

let promise = new Promisify(function(resolve, reject)
{
    console.log('promise executed');

    resolve('resolved');
})

promise
.then(function(input)
{
   console.log(input);
})
.then(function(input)
{
   console.log('second then');
})
</code>```

Title: Javascript Promise from scratch

Body:
A simple promise build from scratch

class Promisify
{
  constructor(fn)
  {
    this._function1 = fn;
  }

  finally()
  {
    console.log('finally executed');
  }

  catch(error)
  {
    console.log('catch executed');
    return this;
  }

  then(resolve, reject)
  {
    try
    {
      this._function1(resolve, reject);
      return this;
    }
    catch(err)
    {
       this.catch(err);
       return this;
    }

    this.finally();

  }

}

let promise = new Promisify(function(resolve, reject)
{
    console.log('promise executed');

    resolve('resolved');
})

promise
.then(function(input)
{
   console.log(input);
})
.then(function(input)
{
   console.log('second then');
})


问:
Environment.getExternalStoragePublicDirectory() in Android 10
how can I get

/storage/emulated/0/Download
```
<p>in android 10</p>
<p>this method:</p>
<pre class="lang-java prettyprint-override"><code>Environment.getExternalStoragePublicDirectory()
</code>```

is deprecated is there an alternative way to get or can I use
hardcoded path or is this not recommended?

答:
To improve user privacy, direct access to shared/external storage devices is deprecated. When an app targets Build.VERSION_CODES.Q, the path returned from this method is no longer directly accessible to apps.Apps can continue to access content stored on shared/external storage by migrating to alternatives such as Context#getExternalFilesDir(String), MediaStore, or Intent#ACTION_OPEN_DOCUMENT.

https://developer.android.com/reference/android/content/Context.html#getExternalFilesDir(java.lang.String)

https://developer.android.com/reference/android/provider/MediaStore.html

https://developer.android.com/reference/android/content/Intent.html#ACTION_OPEN_DOCUMENT

Body:
how can I get

/storage/emulated/0/Download

in android 10

this method:

Environment.getExternalStoragePublicDirectory()

is deprecated is there an alternative way to get or can I use
hardcoded path or is this not recommended?


问:
Django: convert cURL to python requests
I have cURL code that I need to convert to python code using requests library. I want to use this inside django backend software.
I tried several ways but I am getting some erros. Can someone help me with this?
Here is the cURL code:</p>

```<code>    curl -XPOST -H 'cache-control: no-cache' -H 'content-type: application/json' -H
'X-Client-Id: asdf1234' -H 'X-Client-Secret: qwer9876' -d '{
"planId":"BASIC", "planName":"Basic subscription plan", "amount":12,
"intervalType":"week", "intervals":2,"description":"This is the standard plan
for our services"}' 'https://test.cashfree.com/api/v2/subscription-plans'
</code>```

答:
In future, you can use a handy converter like this:</p>

```<code>import requests

headers = {
    'cache-control': 'no-cache',
    'content-type': 'application/json',
    'X-Client-Id': 'asdf1234',
    'X-Client-Secret': 'qwer9876',
}

data = '{"planId":"BASIC", "planName":"Basic subscription plan", "amount":12,"intervalType":"week", "intervals":2,"description":"This is the standard planfor our services"}'

response = requests.post('https://test.cashfree.com/api/v2/subscription-plans', headers=headers, data=data)
</code>```

Title: Django: convert cURL to python requests

Body:
I have cURL code that I need to convert to python code using requests library. I want to use this inside django backend software.
I tried several ways but I am getting some erros. Can someone help me with this?
Here is the cURL code:

    curl -XPOST -H 'cache-control: no-cache' -H 'content-type: application/json' -H
'X-Client-Id: asdf1234' -H 'X-Client-Secret: qwer9876' -d '{
"planId":"BASIC", "planName":"Basic subscription plan", "amount":12,
"intervalType":"week", "intervals":2,"description":"This is the standard plan
for our services"}' 'https://test.cashfree.com/api/v2/subscription-plans'

Body:
In future, you can use a handy converter like this:

import requests

headers = {
    'cache-control': 'no-cache',
    'content-type': 'application/json',
    'X-Client-Id': 'asdf1234',
    'X-Client-Secret': 'qwer9876',
}

data = '{"planId":"BASIC", "planName":"Basic subscription plan", "amount":12,"intervalType":"week", "intervals":2,"description":"This is the standard planfor our services"}'

response = requests.post('https://test.cashfree.com/api/v2/subscription-plans', headers=headers, data=data)


问:
How to iterate over a nested Ruby hash to add a new key/value pair based on existing key/value data?

I have a nested hash of data:

```<code>munsters = {
  "Herman" => { "age" => 32, "gender" => "male" },
  "Lily" => { "age" => 30, "gender" => "female" },
  "Grandpa" => { "age" => 402, "gender" => "male" },
  "Eddie" => { "age" => 10, "gender" => "male" },
  "Marilyn" => { "age" => 23, "gender" => "female"}
}
</code>```

I want to loop through the hash for each member and look up their age in the nested hash.

For each member, I want to add a new key/value pair to the existing nested hash called "age_group".

The value of each member's "age_group" will be dependent on their age. For example, if the age is above 65 years I want to have their age_group read "senior", etc.

Problems I'm running into:

I'm confused how I would access just the "age" key_value pair of the nested hash when the first key is different for each member of the family. Meaning, I can't do something like munsters["age"] because that returns nil (assuming because "age" is nested).

If I had a simple (un-nested) hash it's pretty straightforward. Example of a non-nested hash:

```<code>ages = { "Herman" => 32, "Lily" => 30, "Grandpa" => 402, "Eddie" => 10 }
</code>```

I would then likely loop though like this:

```<code>age_group = {}

ages.each do |k, v|
  if v >= 65
    puts "#{k}'s age of #{v} makes them a senior!"
    age_group.merge!("age_group": "senior")
  elsif v > 17 && v < 65
    puts "#{k}'s age of #{v} makes them an adult"
    age_group.merge!("age_group": "adult")
  else
    puts "#{k}'s age of #{v} makes them a kid."
    age_group.merge!("age_group": "kid")
  end
end
</code>```

For the nested hash, I'm able to access the entire nested hash like this:

```<code>munsters.each do |k, v|
  v.each do |k2, v2|
    p "k2 is #{k2} and v2 is #{v2}"
  end
end
</code>```

But that still only returns the entire nested hash to the console instead of just the age:

k2 is age and v2 is 32
k2 is gender and v2 is male
```

答:
```<code>def age_group(age)
  case age
  when 0..17 then "kid"
  when 18..64 then "adult"
  else "senior"
  end
end
</code>```

```<code>munsters.each_value { |h| h["age_group"] = age_group(h["age"]) }
  #=> {"Herman" =>{"age"=>32,  "gender"=>"male",   "age_group"=>"adult"},
  #    "Lily"   =>{"age"=>30,  "gender"=>"female", "age_group"=>"adult"},
  #    "Grandpa"=>{"age"=>402, "gender"=>"male",   "age_group"=>"senior"},
  #    "Eddie"  =>{"age"=>10,  "gender"=>"male",   "age_group"=>"kid"},
  #    "Marilyn"=>{"age"=>23,  "gender"=>"female", "age_group"=>"adult"}}
</code>```

This return value is the new value of munsters.

Body:
I have a nested hash of data:

munsters = {
  "Herman" => { "age" => 32, "gender" => "male" },
  "Lily" => { "age" => 30, "gender" => "female" },
  "Grandpa" => { "age" => 402, "gender" => "male" },
  "Eddie" => { "age" => 10, "gender" => "male" },
  "Marilyn" => { "age" => 23, "gender" => "female"}
}

I want to loop through the hash for each member and look up their age in the nested hash.

For each member, I want to add a new key/value pair to the existing nested hash called "age_group".

The value of each member's "age_group" will be dependent on their age. For example, if the age is above 65 years I want to have their age_group read "senior", etc.

Problems I'm running into:

I'm confused how I would access just the "age" key_value pair of the nested hash when the first key is different for each member of the family. Meaning, I can't do something like munsters["age"] because that returns nil (assuming because "age" is nested).

If I had a simple (un-nested) hash it's pretty straightforward. Example of a non-nested hash:

ages = { "Herman" => 32, "Lily" => 30, "Grandpa" => 402, "Eddie" => 10 }

I would then likely loop though like this:

age_group = {}

ages.each do |k, v|
  if v >= 65
    puts "#{k}'s age of #{v} makes them a senior!"
    age_group.merge!("age_group": "senior")
  elsif v > 17 && v < 65
    puts "#{k}'s age of #{v} makes them an adult"
    age_group.merge!("age_group": "adult")
  else
    puts "#{k}'s age of #{v} makes them a kid."
    age_group.merge!("age_group": "kid")
  end
end

For the nested hash, I'm able to access the entire nested hash like this:

munsters.each do |k, v|
  v.each do |k2, v2|
    p "k2 is #{k2} and v2 is #{v2}"
  end
end

But that still only returns the entire nested hash to the console instead of just the age:

k2 is age and v2 is 32
k2 is gender and v2 is male

Body:
def age_group(age)
  case age
  when 0..17 then "kid"
  when 18..64 then "adult"
  else "senior"
  end
end

munsters.each_value { |h| h["age_group"] = age_group(h["age"]) }
  #=> {"Herman" =>{"age"=>32,  "gender"=>"male",   "age_group"=>"adult"},
  #    "Lily"   =>{"age"=>30,  "gender"=>"female", "age_group"=>"adult"},
  #    "Grandpa"=>{"age"=>402, "gender"=>"male",   "age_group"=>"senior"},
  #    "Eddie"  =>{"age"=>10,  "gender"=>"male",   "age_group"=>"kid"},
  #    "Marilyn"=>{"age"=>23,  "gender"=>"female", "age_group"=>"adult"}}

This return value is the new value of munsters.


问:
Why is my javascript function not found by the page it is embedded in?
I have a page that has a simple javascript in the header portion of the page:

```<code><script type="text/javascript">
    function doLogout() {
        var conf = confirm("Really log out?");
        if (conf === true) {      //changed == to === for boolean comparison
            $.post("logout.aspx");
        }
    }
</script>
</code>```

It uses jQuery to do an AJAX post to my logout page.  The only issue right now is that when I click on the link (logout) to fire this function, nothing happens.  I checked FireBug's console, and it told me that the function is not defined.  This has happened to me before, but I think I botched a bunch of code to fix it sometimes.

Does anyone know the proper way to fix this issue?

Edit

After doing a lot of googling and trying different things, I found this very concise and informative post. Apparently, as the linked article states, the way the script is referenced in the web site is important as it won't run properly otherwise!  Hopefully this information will be useful for more people.

答: I've had this occur when the page had been cached and so it didn't load the new script in. So to fix it clear all private data from Firefox. Not sure if that helps but it sure happened to me a bunch. </p>

OwnerDisplayName: Anders

ContentLicense: CC BY-SA 2.5

Body:
I have a page that has a simple javascript in the header portion of the page:

It uses jQuery to do an AJAX post to my logout page.  The only issue right now is that when I click on the link (logout) to fire this function, nothing happens.  I checked FireBug's console, and it told me that the function is not defined.  This has happened to me before, but I think I botched a bunch of code to fix it sometimes.

Does anyone know the proper way to fix this issue?

Edit

After doing a lot of googling and trying different things, I found this very concise and informative post. Apparently, as the linked article states, the way the script is referenced in the web site is important as it won't run properly otherwise!  Hopefully this information will be useful for more people.

LastEditorDisplayName: Anders


问:
More space between lines in TextView
I have a TextView with about 10 rows. I want to have the lines more separated from each other. I can't seem to find an attribute for doing that. I tried with: android:includeFontPadding="true" but the text got all weird like stretched or something. Is there any attribute that I don't know about to do that?

Thanks in advance.

答: You can use android:lineSpacingExtra="xxdp"</p>

Title: More space between lines in TextView


问:
Download remote file using laravel
I've a link that gets the image, but the image has been removed, renamed or moved to another place

```<code>public function index()
{
    $array = [
         { image:'https://imgimob.sobressai.com.br/fotos/765/475139/12768822_g.jpg' },
         { image:'http://imgimob.sobressai.com.br/fotos/765/475140/12768824_g.jpg' }
    ]
    for ($i = 0; $i < count($array); $i++) {
       if(!$contents = file_get_contents($array[$i]['image']))
       {
             return 'Not found!';
       else {
        Storage::disk('public')->put('default/teste.jpg', $contents);
       }
   }
}
</code>```

if the image no exist then I get this error

file_get_contents(http://imgimob.sobressai.com.br/fotos/765/475140/12768824_g.jpg): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found

I would link get to return "doesnt' exist" and download file if it does.

答:
You're not handling the warning properly. You can't just use ! in your if / else statement.

(I'm assuming you're using laravel with the methods above.)

You devise some sort of function / method for it. You could do it like so:

```<code>private function checkImage($url)
{
    $valid_types = ['image/png', 'image/jpeg']; // add more valid types that you want and so on
    $client = new \GuzzleHttp\Client();
    try {
        $response = $client->head($url);
        return
            !empty($response->getHeaders()['Content-Type'][0]) &&
            in_array($response->getHeaders()['Content-Type'][0], $valid_types, true);

    } catch (\Exception $e) {
        return false;
    }
}
</code>```

Then finally just use the method in your class:

```<code>$url = 'https://imgimob.sobressai.com.br/fotos/765/475140/12768824_g.jpg';
$exists = $this->checkImage($url);
echo $exists ? 'yay!' : 'does not exist'; // or do the echo inside the function whichever you prefer
</code>```

I used the ->head method above to just check and not include the body.

Edit:

For the purposes of actually donwloading the file. Just use the same code above, along with your Storage saving method to save the image. Using ->get():

```<code>$url = 'https://imgimob.sobressai.com.br/fotos/765/475139/12768822_g.jpg';
$valid_types = ['image/png', 'image/jpeg']; // add more valid types that you want and so on
$client = new \GuzzleHttp\Client();
try {
    $response = $client->get($url);
    if (
        !empty($response->getHeaders()['content-type'][0]) &&
        in_array($response->getHeaders()['content-type'][0], $valid_types, true)
    ) {
        Storage::disk('public')->put('default/teste.jpg', $response->getBody()->getContents());
    }

} catch (\Exception $e) {
    echo 'does not exist';
}
</code>```

Title: Download remote file using laravel

Body:
I've a link that gets the image, but the image has been removed, renamed or moved to another place

public function index()
{
    $array = [
         { image:'https://imgimob.sobressai.com.br/fotos/765/475139/12768822_g.jpg' },
         { image:'http://imgimob.sobressai.com.br/fotos/765/475140/12768824_g.jpg' }
    ]
    for ($i = 0; $i < count($array); $i++) {
       if(!$contents = file_get_contents($array[$i]['image']))
       {
             return 'Not found!';
       else {
        Storage::disk('public')->put('default/teste.jpg', $contents);
       }
   }
}

if the image no exist then I get this error

file_get_contents(http://imgimob.sobressai.com.br/fotos/765/475140/12768824_g.jpg): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found

I would link get to return "doesnt' exist" and download file if it does.

Body:
You're not handling the warning properly. You can't just use ! in your if / else statement.

(I'm assuming you're using laravel with the methods above.)

You devise some sort of function / method for it. You could do it like so:

private function checkImage($url)
{
    $valid_types = ['image/png', 'image/jpeg']; // add more valid types that you want and so on
    $client = new \GuzzleHttp\Client();
    try {
        $response = $client->head($url);
        return
            !empty($response->getHeaders()['Content-Type'][0]) &&
            in_array($response->getHeaders()['Content-Type'][0], $valid_types, true);

    } catch (\Exception $e) {
        return false;
    }
}

Then finally just use the method in your class:

$url = 'https://imgimob.sobressai.com.br/fotos/765/475140/12768824_g.jpg';
$exists = $this->checkImage($url);
echo $exists ? 'yay!' : 'does not exist'; // or do the echo inside the function whichever you prefer

I used the ->head method above to just check and not include the body.

Edit:

For the purposes of actually donwloading the file. Just use the same code above, along with your Storage saving method to save the image. Using ->get():

$url = 'https://imgimob.sobressai.com.br/fotos/765/475139/12768822_g.jpg';
$valid_types = ['image/png', 'image/jpeg']; // add more valid types that you want and so on
$client = new \GuzzleHttp\Client();
try {
    $response = $client->get($url);
    if (
        !empty($response->getHeaders()['content-type'][0]) &&
        in_array($response->getHeaders()['content-type'][0], $valid_types, true)
    ) {
        Storage::disk('public')->put('default/teste.jpg', $response->getBody()->getContents());
    }

} catch (\Exception $e) {
    echo 'does not exist';
}


问:
How to store Datetime to a variable in VBA to save in Excel database
I have this Datetime stamp that I got from a textbox(Named: DateTime), which I want to save in my Excel database.

I have researched online and on this website to no avail. One of the answers here says that I need to parse the DateTime first before saving it to a variable. So I followed the suggestion.

```<code>    Dim I1 As Variant
    Dim ConvertDate As Date

    I1 = Split(DateTime, Space(1))
    ConvertDate = DateValue(I1(4) & Space(1) & I1(1) & ", " & I1(2)) + TimeValue(I1(3))
</code>```

I used the code above but it is making a Subscript out of Range error. When I hover in each I1, the I1(4) is saying  "I1(4)=. It is not reading the Month. I1(1) says the day, I1(2) the Year and the I1(3) the time.

Is this the best method in saving DateTime as a variable? What error did I make?

答:
There are probably many ways to do this. I propose this method:

```<code>Sub test()
  Dim sDate As String
  Dim dt As Date

  sDate = "February 18, 2020 20:53:11"

  If IsDate(sDate) Then

    ' convert this format (mmmm d, yyyy hh:mm:ss) into an actual date variable
    dt = CDate(sDate)

    ' display it for debug purposes
    MsgBox dt

    ' store it into access (not part of your question despite your title)

  Else
    MsgBox sDate & " is not a valid date.", vbCritical
  End If

End Sub
</code>```

It will work in your specific case at least.

Body:
I have this Datetime stamp that I got from a textbox(Named: DateTime), which I want to save in my Excel database.

I have researched online and on this website to no avail. One of the answers here says that I need to parse the DateTime first before saving it to a variable. So I followed the suggestion.

    Dim I1 As Variant
    Dim ConvertDate As Date

    I1 = Split(DateTime, Space(1))
    ConvertDate = DateValue(I1(4) & Space(1) & I1(1) & ", " & I1(2)) + TimeValue(I1(3))

I used the code above but it is making a Subscript out of Range error. When I hover in each I1, the I1(4) is saying  "I1(4)=. It is not reading the Month. I1(1) says the day, I1(2) the Year and the I1(3) the time.

Is this the best method in saving DateTime as a variable? What error did I make?

Body:
There are probably many ways to do this. I propose this method:

Sub test()
  Dim sDate As String
  Dim dt As Date

  sDate = "February 18, 2020 20:53:11"

  If IsDate(sDate) Then

    ' convert this format (mmmm d, yyyy hh:mm:ss) into an actual date variable
    dt = CDate(sDate)

    ' display it for debug purposes
    MsgBox dt

    ' store it into access (not part of your question despite your title)

  Else
    MsgBox sDate & " is not a valid date.", vbCritical
  End If

End Sub

It will work in your specific case at least.


问:
Implementing filter of nested arrays in PHP/Wordpress
I have in the process of moving some code from the front-end (in JavaScript) to the server-side (which is PHP) where it will be filtered and sent out in an API call, and I can't seem to get the filter working properly on the back-end. The code takes an array of objects and filters it for the objects where a certain nested field (which is also an array of objects) contains certain values. The basic shape of the API:

```<code>{
  "id": 1217,
  "name": "Best product ever",
  "tags": [
      {
        "id": 125,
        "name": "Important Value",
        "slug": "important-value"
      },
      {
        "id": 157,
        "name": "Value",
        "slug": "value"
      },
      {
    "id": 180,
    "name": "Value",
    "slug": "value"
  },
  {
    "id": 126,
    "name": "Value",
    "slug": "value"
  },
  {
    "id": 206,
    "name": "Other Important Value",
    "slug": "other-important-value"
  }
}
</code>```

The working JS code:

```<code>let productAttributes = ['important-value', 'value', 'value', 'value', 'other-important-value'];

filterResults(results) {
let filteredResults = results.filter(product => {
  return product.tags.find(tag => {
    return tag.slug === this.productAttributes[0];
  });
});

if (this.productAttributes[0] !== 'certain important value') {
  filteredResults = filteredResults.filter(product => {
    return product.tags.find(tag => {
      return tag.slug === this.productAttributes[4];
    });
  });
}

return filteredResults;
}
</code>```

And the (not yet working) PHP code:

```<code>function get_awesome_products() {
 $baseRequest = 'https://myawesomeapi/wp-json/wc/v3/products/?
 consumer_key=xxxx&consumer_secret=xxxx&per_page=100&page=';
 for ($count = 1; $count <= 9; $count++ ) {
$request = wp_remote_get( $baseRequest . (string)$count);
$body = wp_remote_retrieve_body( $request );
$data = array_values( json_decode( $body, true ));

  if ($count < 2) {
    $completeProductList = $data;
  } else {
    $completeProductList = array_merge($completeProductList, $data);
  }
}
// The code above this comment is doing what I expect, the code below is not.

$filteredProducts = null;
foreach ($completeProductList as &$product) {
  $tagArray = $product['tags'];
  if (in_array($reg_test_array[0], $tagArray, true) &&
  in_array($reg_test_array[4], $tagArray, true))
  {
    array_push($filteredProducts, $product);
  }

  unset($product);
  return new WP_REST_Response($filteredProducts, 200);
</code>```

The impression I get is that I need to write a custom function to take the place of Array.prototype.find(), but I'm not strong in PHP and am having trouble wrapping my head around it.

EDIT: Edited to add example of object being filtered and additional PHP code

答:
You could also use the PHP equivalent function array_filter (among a few other array-specific functions) for this task.

Example:

```<code>// Your 0 and 4 index values from $reg_test_array
$importantTags = [ "important-value", "other-important-value" ];

$filteredProducts = array_filter($completeProductList, function($product) use ($importantTags) {
  return (bool)array_intersect($importantTags, array_column($product['tags'], 'slug'));
});

return new WP_REST_Response($filteredProducts , 200);

</code>```

Sandbox

Body:
I have in the process of moving some code from the front-end (in JavaScript) to the server-side (which is PHP) where it will be filtered and sent out in an API call, and I can't seem to get the filter working properly on the back-end. The code takes an array of objects and filters it for the objects where a certain nested field (which is also an array of objects) contains certain values. The basic shape of the API:

{
  "id": 1217,
  "name": "Best product ever",
  "tags": [
      {
        "id": 125,
        "name": "Important Value",
        "slug": "important-value"
      },
      {
        "id": 157,
        "name": "Value",
        "slug": "value"
      },
      {
    "id": 180,
    "name": "Value",
    "slug": "value"
  },
  {
    "id": 126,
    "name": "Value",
    "slug": "value"
  },
  {
    "id": 206,
    "name": "Other Important Value",
    "slug": "other-important-value"
  }
}

The working JS code:

let productAttributes = ['important-value', 'value', 'value', 'value', 'other-important-value'];

filterResults(results) {
let filteredResults = results.filter(product => {
  return product.tags.find(tag => {
    return tag.slug === this.productAttributes[0];
  });
});

if (this.productAttributes[0] !== 'certain important value') {
  filteredResults = filteredResults.filter(product => {
    return product.tags.find(tag => {
      return tag.slug === this.productAttributes[4];
    });
  });
}

return filteredResults;
}

And the (not yet working) PHP code:

function get_awesome_products() {
 $baseRequest = 'https://myawesomeapi/wp-json/wc/v3/products/?
 consumer_key=xxxx&consumer_secret=xxxx&per_page=100&page=';
 for ($count = 1; $count <= 9; $count++ ) {
$request = wp_remote_get( $baseRequest . (string)$count);
$body = wp_remote_retrieve_body( $request );
$data = array_values( json_decode( $body, true ));

  if ($count < 2) {
    $completeProductList = $data;
  } else {
    $completeProductList = array_merge($completeProductList, $data);
  }
}
// The code above this comment is doing what I expect, the code below is not.

$filteredProducts = null;
foreach ($completeProductList as &$product) {
  $tagArray = $product['tags'];
  if (in_array($reg_test_array[0], $tagArray, true) &&
  in_array($reg_test_array[4], $tagArray, true))
  {
    array_push($filteredProducts, $product);
  }

  unset($product);
  return new WP_REST_Response($filteredProducts, 200);

The impression I get is that I need to write a custom function to take the place of Array.prototype.find(), but I'm not strong in PHP and am having trouble wrapping my head around it.

EDIT: Edited to add example of object being filtered and additional PHP code

Body:
You could also use the PHP equivalent function array_filter (among a few other array-specific functions) for this task.

Example:

// Your 0 and 4 index values from $reg_test_array
$importantTags = [ "important-value", "other-important-value" ];

$filteredProducts = array_filter($completeProductList, function($product) use ($importantTags) {
  return (bool)array_intersect($importantTags, array_column($product['tags'], 'slug'));
});

return new WP_REST_Response($filteredProducts , 200);

Sandbox


问:
How can I separate the horizontal rule from the table. They are mixed together. I want the horizontal rule below my table
My horizontal rule is mixed up with part of the information on a table

So, my issue is to create two separate tables side by side, instead of one table below the other like usual. I did something that made it work but now my
 tag is mixed together with the tables.

Skills

      Sleeping
      ★★★★

      Eating
      ★★★

      Gaming
      ★★★★★

      Reading
      ★★★★★

```

That is the code. Can someone please help me put the horizontal rule below the table? As you can see from my code, the hr tag comes after closing the second table tag but my final output has mixed up the horizontal rule together with the table, instead of below it. What error have I made in my code? Any help would be appreciated, especially from my code. Somebody advise me on what's wrong with my code.

Also, I'm not pretty sure what is the work of the div tag since this was kinda an assignment if anybody can explain to me well, and why I put it in my code, I honestly don't know.

答:
Change the styles of the
s to be displayed as inline:

```<code><h3>Skills</h3>
<table style="display:inline">
   <tr>
      <td>Sleeping</td>
      <td>★★★★</td>
   </tr>
   <tr>
      <td>Eating</td>
      <td>★★★</td>
   </tr>
</table>
<table style="display: inline">
   <tr>
      <td>Gaming</td>
      <td>★★★★★</td>
   </tr>
   <tr>
      <td>Reading</td>
      <td>★★★★★</td>
</table>
<hr size="3" noshade="3">
</code>```

JSFiddle.

Body:
My horizontal rule is mixed up with part of the information on a table

So, my issue is to create two separate tables side by side, instead of one table below the other like usual. I did something that made it work but now my
 tag is mixed together with the tables.

Skills

      Sleeping
      ★★★★

      Eating
      ★★★

      Gaming
      ★★★★★

      Reading
      ★★★★★

That is the code. Can someone please help me put the horizontal rule below the table? As you can see from my code, the hr tag comes after closing the second table tag but my final output has mixed up the horizontal rule together with the table, instead of below it. What error have I made in my code? Any help would be appreciated, especially from my code. Somebody advise me on what's wrong with my code.

Also, I'm not pretty sure what is the work of the div tag since this was kinda an assignment if anybody can explain to me well, and why I put it in my code, I honestly don't know.

Body:
Change the styles of the <table>s to be displayed as inline:

<h3>Skills</h3>
<table style="display:inline">
   <tr>
      <td>Sleeping</td>
      <td>&#9733;&#9733;&#9733;&#9733;</td>
   </tr>
   <tr>
      <td>Eating</td>
      <td>&#9733;&#9733;&#9733;</td>
   </tr>
</table>
<table style="display: inline">
   <tr>
      <td>Gaming</td>
      <td>&#9733;&#9733;&#9733;&#9733;&#9733;</td>
   </tr>
   <tr>
      <td>Reading</td>
      <td>&#9733;&#9733;&#9733;&#9733;&#9733;</td>
</table>
<hr size="3" noshade="3">

JSFiddle.


问:
JavaScript firing too many events?
The handle mousemove events are amongst 3
s which are nested inside each other. Can't seem to find the issue which is causing too many events to get fired.

(function() {
  var boxes = [
    document.getElementById("box1"),
    document.getElementById("box2"),
    document.getElementById("box3"),
  ];

  boxes[0].addEventListener(
    "mousemove", function(event) { console.log("Box 1"); }
  );
  boxes[1].addEventListener(
    "mousemove", function(event) { console.log("Box 2"); }
  );
  boxes[2].addEventListener(
    "mousemove", function(event) { console.log("Box 3"); }
  );
})();

```

答:
Please try

boxes[0].addEventListener("mousemove", function(event) {
  event.preventDefault();
  event.stopPropogation();

  console.log("Box 1");
});```

Title: JavaScript firing too many events?


问:
How to improve performance in calculating greeks in DolphinDB?
I am using DolphinDB to calculate Greeks, I wrote it in vectorized way, and the performance is quite good. But I can't implement implied volatility in vectorized way which makes the performance very poor. How can I improve the performance of the following implementation?</p>

```<code>def GBlackScholes(future_price, strike, input_ttm, risk_rate, b_rate, input_vol, is_call) {
  ttm = input_ttm + 0.000000000000001;
  vol = input_vol + 0.000000000000001;

  d1 = (log(future_price/strike) + (b_rate + vol*vol/2) * ttm) / (vol * sqrt(ttm));
  d2 = d1 - vol * sqrt(ttm);

  if (is_call) {
    return future_price * exp((b_rate - risk_rate) * ttm) * cdfNormal(0, 1, d1) - strike * exp(-risk_rate*ttm) * cdfNormal(0, 1, d2);
  } else {
    return strike * exp(-risk_rate*ttm) * cdfNormal(0, 1, -d2) - future_price * exp((b_rate - risk_rate) * ttm) * cdfNormal(0, 1, -d1);
  }
}

def ImpliedVolatility(future_price, strike, ttm, risk_rate, b_rate, option_price, is_call) {
  high=5.0;
  low = 0.0;

  do {
    if (GBlackScholes(future_price, strike, ttm, risk_rate, b_rate, (high+low)/2, is_call) > option_price) {
      high = (high+low)/2;
    } else {
      low = (high + low) /2;
    }
  } while ((high-low) > 0.00001);

  return (high + low) /2;
}
</code>```

答:
DolphinDB 1.01 introduced just-in-time compilation (JIT) . JIT is perfect for non-vectorized operations such as binary-search for implied volatility.

To use JIT, simply add a notation @jit before user-defined functions.

Body:
I am using DolphinDB to calculate Greeks, I wrote it in vectorized way, and the performance is quite good. But I can't implement implied volatility in vectorized way which makes the performance very poor. How can I improve the performance of the following implementation?

def GBlackScholes(future_price, strike, input_ttm, risk_rate, b_rate, input_vol, is_call) {
  ttm = input_ttm + 0.000000000000001;
  vol = input_vol + 0.000000000000001;

  d1 = (log(future_price/strike) + (b_rate + vol*vol/2) * ttm) / (vol * sqrt(ttm));
  d2 = d1 - vol * sqrt(ttm);

  if (is_call) {
    return future_price * exp((b_rate - risk_rate) * ttm) * cdfNormal(0, 1, d1) - strike * exp(-risk_rate*ttm) * cdfNormal(0, 1, d2);
  } else {
    return strike * exp(-risk_rate*ttm) * cdfNormal(0, 1, -d2) - future_price * exp((b_rate - risk_rate) * ttm) * cdfNormal(0, 1, -d1);
  }
}

def ImpliedVolatility(future_price, strike, ttm, risk_rate, b_rate, option_price, is_call) {
  high=5.0;
  low = 0.0;

  do {
    if (GBlackScholes(future_price, strike, ttm, risk_rate, b_rate, (high+low)/2, is_call) > option_price) {
      high = (high+low)/2;
    } else {
      low = (high + low) /2;
    }
  } while ((high-low) > 0.00001);

  return (high + low) /2;
}


问:
Seeing logs in a different format while capturing network traffic using selenium-wire python
While capturing http requests of webservice from website backend seeing some logs are in different format. I'm using python logging as a format:

```<code>logging.basicConfig(format='%(asctime)s %(levelname)-4s %(message)s',
                    level=logging.INFO,
                    datefmt='%Y-%m-%d %H:%M:%S'`enter code here`,
                    filemode='a')

logging.info("%3s %s %s", request.response.status_code, driver.current_url, request.path)
</code>```

Just expect to see as an output:

```<code>2020-02-10 14:00:56 INFO  204   https://driver.current_url         https://request_path
</code>```

but besides this format, different log formats are also seen as shown below:

```<code>2020-02-10 13:35:08 INFO  Capturing request: https://request_path
2020-02-10 13:35:08 INFO  Capturing response: https://request_path 200 OK
</code>```

Can anyone help me that why seeing these logs?

答:
Python has the possibility to have multiple loggers. basicConfig configures the root logger, but it's possible other libraries configure their own loggers.

In order to configure those loggers, you would need to know the library's logger's name and call "getLogger(" the name ")" in order to get the logger to be able to configure it.

Please see Python's logging cookbook for more info.

Body:
While capturing http requests of webservice from website backend seeing some logs are in different format. I'm using python logging as a format:

logging.basicConfig(format='%(asctime)s %(levelname)-4s %(message)s',
                    level=logging.INFO,
                    datefmt='%Y-%m-%d %H:%M:%S'`enter code here`,
                    filemode='a')

logging.info("%3s %s %s", request.response.status_code, driver.current_url, request.path)

Just expect to see as an output:

2020-02-10 14:00:56 INFO  204   https://driver.current_url         https://request_path

but besides this format, different log formats are also seen as shown below:

2020-02-10 13:35:08 INFO  Capturing request: https://request_path
2020-02-10 13:35:08 INFO  Capturing response: https://request_path 200 OK

Can anyone help me that why seeing these logs?


问:
Android Rotating MapView
I am creating an application which trakcs down users path on a mapview. What I want to achieve when user takes a left turn for instance map should rotate it self in such a way that the head of the mapview should always point to upward direction. I hope that makes sense.

I came across Mr. Romain Guy's post an he says

I have done this in the past and it
  requires to create a custom ViewGroup
  that rotates the Canvas in the
  dispatchDraw() method. You also need
  to increase the size of the MapView
  (so that it draws enough pixels when
  rotated.) You will also need to rotate
  the touch events in
  dispatchTouchEvent(). Or if you use
  Android 3.0 you can simply call
  theMapView.rotate() :

Does anyone came accross some solution similiar to my question ? A working example would be excellent :)

答:
Keep in mind that it's not an ideal approach, because the text on the map is a static image and will rotate along with the map tiles (at some point it will be upside down).

Here's an example of how to put the MapView into your own Layout widget and rotate it. I've done it with the OpenStreetMaps, but it should be quite the same for Google Maps.

First create the "rotating" Layout widget

```<code>package com.eli.util;

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.widget.LinearLayout;

public class RotatingLinearLayout extends LinearLayout {

    private final int mDiagonal;
    private float mBearing;

    public RotatingLinearLayout(final Context pContext, final AttributeSet pAttrs) {
        super(pContext, pAttrs);
        final DisplayMetrics dm = pContext.getResources().getDisplayMetrics();
        mDiagonal = (int) Math.hypot(dm.widthPixels, dm.heightPixels);
    }

    public void setBearing(final float pBearing) {
        mBearing = pBearing;
    }

    @Override
    protected void dispatchDraw(final Canvas pCanvas) {
        pCanvas.rotate(-mBearing, getWidth() >> 1, getHeight() >> 1);
        super.dispatchDraw(pCanvas);
    }

    @Override
    protected void onMeasure(final int pWidthMeasureSpec,
            final int pHeightMeasureSpec) {
        final int widthMode = MeasureSpec.getMode(pWidthMeasureSpec);
        final int heightMode = MeasureSpec.getMode(pHeightMeasureSpec);
        super.onMeasure(MeasureSpec.makeMeasureSpec(mDiagonal, widthMode), MeasureSpec.makeMeasureSpec(mDiagonal, heightMode));
    }
}
</code>```

Surround by it your MapView in the layout.xml

```<code><com.eli.util.RotatingLinearLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/rotating_layout">
    <org.osmdroid.views.MapView
        android:id="@+id/map_view"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:enabled="true"
        android:clickable="true"/>
</com.eli.util.RotatingLinearLayout>
</code>```

Now, every time you receive a geo fix, update the bearing of the rotating layout and it should turn.

Title: Android Rotating MapView

Body:
Keep in mind that it's not an ideal approach, because the text on the map is a static image and will rotate along with the map tiles (at some point it will be upside down).

Here's an example of how to put the MapView into your own Layout widget and rotate it. I've done it with the OpenStreetMaps, but it should be quite the same for Google Maps.

First create the "rotating" Layout widget

package com.eli.util;

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.widget.LinearLayout;

public class RotatingLinearLayout extends LinearLayout {

    private final int mDiagonal;
    private float mBearing;

    public RotatingLinearLayout(final Context pContext, final AttributeSet pAttrs) {
        super(pContext, pAttrs);
        final DisplayMetrics dm = pContext.getResources().getDisplayMetrics();
        mDiagonal = (int) Math.hypot(dm.widthPixels, dm.heightPixels);
    }

    public void setBearing(final float pBearing) {
        mBearing = pBearing;
    }

    @Override
    protected void dispatchDraw(final Canvas pCanvas) {
        pCanvas.rotate(-mBearing, getWidth() >> 1, getHeight() >> 1);
        super.dispatchDraw(pCanvas);
    }

    @Override
    protected void onMeasure(final int pWidthMeasureSpec,
            final int pHeightMeasureSpec) {
        final int widthMode = MeasureSpec.getMode(pWidthMeasureSpec);
        final int heightMode = MeasureSpec.getMode(pHeightMeasureSpec);
        super.onMeasure(MeasureSpec.makeMeasureSpec(mDiagonal, widthMode), MeasureSpec.makeMeasureSpec(mDiagonal, heightMode));
    }
}

Surround by it your MapView in the layout.xml

<com.eli.util.RotatingLinearLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/rotating_layout">
    <org.osmdroid.views.MapView
        android:id="@+id/map_view"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:enabled="true"
        android:clickable="true"/>
</com.eli.util.RotatingLinearLayout>

Now, every time you receive a geo fix, update the bearing of the rotating layout and it should turn.


问:
Vertical rulers in Visual Studio Code

Rendering More than One Ruler in VS Code

VS Code's default configuration for a ruler is demonstrated below.

```<code>  "editor.ruler": 80
</code>```

The issue I am having with the default VS Code configuration (as shown above) is that it only renders a single ruler. In the Sublime Text Editor I can render as many rulers as I like using the following Sublime configuration.

```<code>  "rulers": [72, 80, 100, 120]
</code>```

Is it possible to render multiple rulers in V.S. Code. If it is possible, What does a multi-ruler configuration look like in VS Code?

答:
In v1.43 is the ability to separately color the vertical rulers.

See issue Support multiple rulers with different colors  - (in settings.json):

"editor.rulers": [
  {
    "column": 80,
    "color": "#ff00FF"
  },
  100,  // <- a ruler in the default color or as customized (with "editorRuler.foreground") at column 100
  {
    "column": 120,
    "color": "#ff0000"
  },
]
```
<p>To change the default color for a ruler:</p>
<pre class="lang-json prettyprint-override"><code>"workbench.colorCustomizations": {

  "editorRuler.foreground": "#fffa"
            // or "#ffffffaa" - the a's are alpha transparency values
}
</code>```

Title: Vertical rulers in Visual Studio Code

Body:
Rendering More than One Ruler in VS Code

VS Code's default configuration for a ruler is demonstrated below.

  "editor.ruler": 80

The issue I am having with the default VS Code configuration (as shown above) is that it only renders a single ruler. In the Sublime Text Editor I can render as many rulers as I like using the following Sublime configuration.

  "rulers": [72, 80, 100, 120]

Is it possible to render multiple rulers in V.S. Code. If it is possible, What does a multi-ruler configuration look like in VS Code?

Body:
In v1.43 is the ability to separately color the vertical rulers.

See issue Support multiple rulers with different colors  - (in settings.json):

"editor.rulers": [
  {
    "column": 80,
    "color": "#ff00FF"
  },
  100,  // <- a ruler in the default color or as customized (with "editorRuler.foreground") at column 100
  {
    "column": 120,
    "color": "#ff0000"
  },
]

To change the default color for a ruler:

"workbench.colorCustomizations": {

  "editorRuler.foreground": "#fffa"
            // or "#ffffffaa" - the a's are alpha transparency values
}


问:
Is there a way to version ~/.bashrc in-place by git, without copying to a different repo?
I'd like to version ~/.bashrc and ~/.bash_profile using git, best if in-place (at the actual location), rather than creating a new repo and copy the file over and do the versioning there.

Is there a way to do that? I think the difficulty is, if I create a repo at ~, it includes every folder in my home directory and is not desirable.

Is there some way to tell git: version only these files or folder, and disregard everything else and don't consider them to be submodules? If it can be like that, it might be a solution, except it seem like a super big repo to be at the home directory but at the same time ignoring almost everything.

答:
You could try gitignore.

```<code>cd ~
git init
echo '*' >> .git/info/exclude
echo '!.bashrc' >> .git/info/exclude
git add .bashrc
git commit -m'foo'
</code>```

The patterns ignore all except .bashrc.

```<code>*
!.bashrc
</code>```

Body:
You could try gitignore.

cd ~
git init
echo '*' >> .git/info/exclude
echo '!.bashrc' >> .git/info/exclude
git add .bashrc
git commit -m'foo'

The patterns ignore all except .bashrc.

*
!.bashrc


问:
Render a partial that uses helper methods to determine view
What Currently Works:

In my BookingsController#Index method, I have this

```<code>def index
    @user = current_user
    if @user.user_type == 'host'
      @bookings = Booking.where(host_id:@user.id, status: "#{params[:status]}")
    else @user.user_type == 'cleaner'
      @bookings = Booking.where(cleaner_id:@user.id, status: "#{params[:status]}")
    end
  end
</code>```

This sets the current user and determines which @bookings to display depending on the user_id and params.

In the views, in my index.html.erb file, I render bookings <%= render @bookings %> which i defined in the booking#index. I have a _booking.html.erb partial that gets rendered... Inside the _booking.html.erb partial, I am able to successfully return booking details , like this for instance,

```<code><div id='booking-time'><b>Unit Name:</b> <%= booking.unit.name %></div>
</code>```

will return the unit name. it recognizes the local variable booking and the fields that belong to it.

I'd Like to Refactor:

I want to refactor this and render a partial <%= render 'bookings/booking' %> in my index.html.erb file. This partial will render different helper methods that each route to different partials.

Currently my _booking.html.erb file has a bunch of conditional logic that is better suited for a helper... I've tried a bunch of different ways to accomplish this to no avail, usually due to undefined variables..what's an elegant way to accomplish this?

What I've Tried:

Here's  a method from my bookings_helper.rb` file:

```<code>  def incoming_to_cleaner_partial_path(bookings)
    return unless booking.status=='pending' && current_user.user_type =='cleaner' && booking.requested_by_id != current_user.id
      'bookings/booking_requests/incoming_to_cleaner'
  end
</code>```

I added logic to these methods to determine which partials to render.

in my modified _booking.html.erb file, I call these methods, I pass them a @bookings instance variable param.

```<code><%= render incoming_to_cleaner_partial_path(@bookings) %>
</code>```

I've also tried this without params.. Neither work..

lastly, I've tried calling a method determine_bookings_to_show inside the helper methods. This method contains the same logic from the controller...

```<code>def incoming_to_cleaner_partial_path
    determine_bookings_to_show
    return unless booking.status=='pending' && current_user.user_type =='cleaner' && booking.requested_by_id != current_user.id
      'bookings/booking_requests/incoming_to_cleaner'
  end

private

def determine_bookings_to_show
    @user = current_user
    if @user.user_type == 'host'
      @bookings = Booking.where(host_id:@user.id, status: "#{params[:status]}")
    else @user.user_type == 'cleaner'
      @bookings = Booking.where(cleaner_id:@user.id, status: "#{params[:status]}")
    end
  end
</code>```

My main issue is i'm having scope troubles with these partials...

答:
.. in my index [I want to] render different partials [depending on attributes of the booking] ..

I have used render(locals:) for this in the past.

# index.html.erb
@bookings.each do |b|
  render_booking(b)
end

# bookings_helper.rb
def render_booking(booking)
  if booking.status == 'pending'
    render partial: 'path/to/bookings/_pending', locals: { booking: booking }
  elsif booking.foobar?
    render partial: 'path/to/bookings/_foobar', locals: { booking: booking }
  else
    # etc.
  end
end
```

<p>Conditionals like this can get complicated, but until then, I think this is an appropriate, practical use of a helper method.</p>

```# bookings/_pending.html.erb

Pending Booking <%= booking.id %>

```

You will likely need to pass other locals:. I'd avoid using any instance variables in your partials.

Body:
What Currently Works:

In my BookingsController#Index method, I have this

def index
    @user = current_user
    if @user.user_type == 'host'
      @bookings = Booking.where(host_id:@user.id, status: "#{params[:status]}")
    else @user.user_type == 'cleaner'
      @bookings = Booking.where(cleaner_id:@user.id, status: "#{params[:status]}")
    end
  end

This sets the current user and determines which @bookings to display depending on the user_id and params.

In the views, in my index.html.erb file, I render bookings <%= render @bookings %> which i defined in the booking#index. I have a _booking.html.erb partial that gets rendered... Inside the _booking.html.erb partial, I am able to successfully return booking details , like this for instance,

Unit Name: <%= booking.unit.name %>

will return the unit name. it recognizes the local variable booking and the fields that belong to it.

I'd Like to Refactor:

I want to refactor this and render a partial <%= render 'bookings/booking' %> in my index.html.erb file. This partial will render different helper methods that each route to different partials.

Currently my _booking.html.erb file has a bunch of conditional logic that is better suited for a helper... I've tried a bunch of different ways to accomplish this to no avail, usually due to undefined variables..what's an elegant way to accomplish this?

What I've Tried:

Here's  a method from my bookings_helper.rb` file:

  def incoming_to_cleaner_partial_path(bookings)
    return unless booking.status=='pending' && current_user.user_type =='cleaner' && booking.requested_by_id != current_user.id
      'bookings/booking_requests/incoming_to_cleaner'
  end

I added logic to these methods to determine which partials to render.

in my modified _booking.html.erb file, I call these methods, I pass them a @bookings instance variable param.

<%= render incoming_to_cleaner_partial_path(@bookings) %>

I've also tried this without params.. Neither work..

lastly, I've tried calling a method determine_bookings_to_show inside the helper methods. This method contains the same logic from the controller...

def incoming_to_cleaner_partial_path
    determine_bookings_to_show
    return unless booking.status=='pending' && current_user.user_type =='cleaner' && booking.requested_by_id != current_user.id
      'bookings/booking_requests/incoming_to_cleaner'
  end

private

def determine_bookings_to_show
    @user = current_user
    if @user.user_type == 'host'
      @bookings = Booking.where(host_id:@user.id, status: "#{params[:status]}")
    else @user.user_type == 'cleaner'
      @bookings = Booking.where(cleaner_id:@user.id, status: "#{params[:status]}")
    end
  end

My main issue is i'm having scope troubles with these partials...

Body:
.. in my index [I want to] render different partials [depending on attributes of the booking] ..

I have used render(locals:) for this in the past.

# index.html.erb
@bookings.each do |b|
  render_booking(b)
end

# bookings_helper.rb
def render_booking(booking)
  if booking.status == 'pending'
    render partial: 'path/to/bookings/_pending', locals: { booking: booking }
  elsif booking.foobar?
    render partial: 'path/to/bookings/_foobar', locals: { booking: booking }
  else
    # etc.
  end
end

Conditionals like this can get complicated, but until then, I think this is an appropriate, practical use of a helper method.

# bookings/_pending.html.erb
<h1>Pending Booking <%= booking.id %></h1>

You will likely need to pass other locals:. I'd avoid using any instance variables in your partials.


问:
Two sets of curly braces using lambda functions?
I am wondering if someone could help me understand the following syntax snippet, specifically sections 1 and 2 (focusing on the two sets of curly brackets). Is it related to lamda function? If so, how?</p>

```<code>void Logger::LogContentionAndAllocations() {
    // 1
    LogDetail([&](AsyncDetail& detail) {
        {
            std::unique_lock<std::mutex> lock(tls_loggers_registerd_mutex_);
            for (auto tls_logger : tls_loggers_registerd_) {
                CollectTlsLoggerStats(tls_logger);
            }
        }
        //2.
        {
            std::unique_lock<std::mutex> lock(tls_logger_orphans_mutex_);
            for (auto& orphan : tls_logger_orphans_) {
                CollectTlsLoggerStats(orphan.get());
            }
        }

        detail("Log Contention Counters:");
        detail(std::to_string(swap_request_slots_retry_count_) + " : swap_request_slots_retry_count");
        detail(std::to_string(swap_request_slots_retry_retry_count_) + " : swap_request_slots_retry_retry_count");
        detail(std::to_string(swap_request_slots_retry_reencounter_count_) + " : swap_request_slots_retry_reencounter_count");
        detail(std::to_string(start_reading_entries_retry_count_) + " : start_reading_entries_retry_count");
        detail(std::to_string(tls_total_log_cas_fail_count_) + " : tls_total_log_cas_fail_count");
        detail(std::to_string(tls_total_swap_buffers_slot_retry_count_) + " : tls_total_swap_buffers_slot_retry_count");

        swap_request_slots_retry_count_ = 0;
        swap_request_slots_retry_retry_count_ = 0;

        swap_request_slots_retry_reencounter_count_ = 0;
        start_reading_entries_retry_count_ = 0;
        tls_total_log_cas_fail_count_ = 0;

        tls_total_swap_buffers_slot_retry_count_ = 0;
    });
}
</code>```

答: They're part of a lambda, yes. But all they're doing is creating their own scope. That is, after all, the purpose of curly braces in C++. More specifically, curly braces allow you to create a compound statement, and that compound statement will have its own local scope.</p>

Body:
I am wondering if someone could help me understand the following syntax snippet, specifically sections 1 and 2 (focusing on the two sets of curly brackets). Is it related to lamda function? If so, how?

void Logger::LogContentionAndAllocations() {
    // 1
    LogDetail([&](AsyncDetail& detail) {
        {
            std::unique_lock<std::mutex> lock(tls_loggers_registerd_mutex_);
            for (auto tls_logger : tls_loggers_registerd_) {
                CollectTlsLoggerStats(tls_logger);
            }
        }
        //2.
        {
            std::unique_lock<std::mutex> lock(tls_logger_orphans_mutex_);
            for (auto& orphan : tls_logger_orphans_) {
                CollectTlsLoggerStats(orphan.get());
            }
        }

        detail("Log Contention Counters:");
        detail(std::to_string(swap_request_slots_retry_count_) + " : swap_request_slots_retry_count");
        detail(std::to_string(swap_request_slots_retry_retry_count_) + " : swap_request_slots_retry_retry_count");
        detail(std::to_string(swap_request_slots_retry_reencounter_count_) + " : swap_request_slots_retry_reencounter_count");
        detail(std::to_string(start_reading_entries_retry_count_) + " : start_reading_entries_retry_count");
        detail(std::to_string(tls_total_log_cas_fail_count_) + " : tls_total_log_cas_fail_count");
        detail(std::to_string(tls_total_swap_buffers_slot_retry_count_) + " : tls_total_swap_buffers_slot_retry_count");

        swap_request_slots_retry_count_ = 0;
        swap_request_slots_retry_retry_count_ = 0;

        swap_request_slots_retry_reencounter_count_ = 0;
        start_reading_entries_retry_count_ = 0;
        tls_total_log_cas_fail_count_ = 0;

        tls_total_swap_buffers_slot_retry_count_ = 0;
    });
}


问:
Calculator in Android Studio
I have been trying to build a simple calculator in android studio.I am a beginner and have only basic knowledge of java.I am trying to accept values in a single text field instead of using two different text field.I have used a on click listener on my operator buttons and inside that on the equals button.But my application closes as soon as i click on the operator buttons.How can i use a single text view two accept two numbers or more and apply a mathematical operator on them?

edit:as I have already stated I have very little knowledge of java.I did a google search before posting this question.

```<code>        add.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            n.setText("");
            final float a = Float.parseFloat(n.getText().toString());
            n.setText("");
            equals.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    float b = Float.parseFloat(n.getText().toString());
                    float c = a + b;
                    ans.setText("" + c);
                    n.setText("");
                }
            });
        }
    });
</code>```

答:
```<code>**

> ***SIMPLE CALCULATOR CODE***

**

public class MainActivity extends AppCompatActivity {

    EditText edit;
    Button add, subtract, multiply, divide, equal,clr;
    TextView result;
    String operator;
    float temp1, temp2, sum;

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

        add = (Button) findViewById(R.id.addition);
        subtract = (Button) findViewById(R.id.subtraction);
        multiply = (Button) findViewById(R.id.multiplication);
        divide = (Button) findViewById(R.id.division);
        equal = (Button) findViewById(R.id.equal);
        result = (TextView) findViewById(R.id.result);
        edit = (EditText) findViewById(R.id.user_input);
        clr = (Button)findViewById(R.id.clear);

        try {
            //Additon
            add.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (temp1 == 0) {
                        temp1 = Float.parseFloat(edit.getText().toString());
                        operator = "+";
                        edit.setText("");
                    } else {

                        edit.setText("");
                    }
                }
            });

            //Division
            divide.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (temp1 == 0) {
                        temp1 = Float.parseFloat(edit.getText().toString());
                        operator = "/";

                        edit.setText("");
                    } else {
                        edit.setText("");
                    }
                }
            });

            //Subtract
            subtract.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (temp1 == 0) {
                        temp1 = Float.parseFloat(edit.getText().toString());
                        operator = "-";
                        edit.setText("");

                    } else {

                        edit.setText("");
                    }
                }
            });

            //Multiplication
            multiply.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (temp1 == 0) {
                        temp1 = Float.parseFloat(edit.getText().toString());
                        operator = "*";
                        edit.setText("");
                    } else {
                        edit.setText("");
                    }
                }
            });

            //Clear
            clr.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    temp1 = 0;
                    temp2 = 0;
                    edit.setText("");
                    result.setText("");

                }
            });

            //Equal
            equal.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (temp2 == 0) {
                        temp2 = Float.parseFloat(edit.getText().toString());
                        switch (operator) {
                            case "+":
                                sum = temp1 + temp2;

                                break;
                            case "-":
                                sum = temp1 - temp2;
                                break;
                            case "*":
                                sum = temp1 * temp2;
                                break;
                            case "/":
                                sum = temp1 / temp2;
                                break;

                        }
                        edit.setText(Float.toString(sum));
                        Toast.makeText(MainActivity.this,"RESULT IS DISPLAYED IN EDIT TEXT VIEW :", Toast.LENGTH_SHORT).show();
                        result.setText(Float.toString(temp1)+" "+operator+" "+Float.toString(temp2));

                    }

                    temp1 = 0;
                    temp2 = 0;
                }
            });
        } catch (Exception e) {
        }

    }
}
</code>```

Title: Calculator in Android Studio

Body:
I have been trying to build a simple calculator in android studio.I am a beginner and have only basic knowledge of java.I am trying to accept values in a single text field instead of using two different text field.I have used a on click listener on my operator buttons and inside that on the equals button.But my application closes as soon as i click on the operator buttons.How can i use a single text view two accept two numbers or more and apply a mathematical operator on them?

edit:as I have already stated I have very little knowledge of java.I did a google search before posting this question.

        add.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            n.setText("");
            final float a = Float.parseFloat(n.getText().toString());
            n.setText("");
            equals.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    float b = Float.parseFloat(n.getText().toString());
                    float c = a + b;
                    ans.setText("" + c);
                    n.setText("");
                }
            });
        }
    });


问:
How to create virtual env with python3
I am using python 2.7 + virtualenv version 1.10.1 for running myproject projects. Due to some other projects requirement I have to work with other version of python(Python 3.5) and Django 1.9. For this I have installed python in my user directory. Also I have dowloaded and installed virtualenv( version - 15.1.0) into my user directory.
But whenever I am trying to create virtual env I am getting the below error

```<code>python virtualenv/virtualenv.py myproject
</code>```

```<code>Using base prefix '/home/myuser/python3'
New python executable in /home/mount/myuser/project_python3/myproject/bin/python
ERROR: The executable /home/mount/myuser/project_python3/myproject/bin/python is not functioning
ERROR: It thinks sys.prefix is '/home/myuser/python3' (should be '/home/mount/myuser/project_python3/myproject')
ERROR: virtualenv is not compatible with this system or executable
</code>```

Can anybody tell what I am doing wrong with this

答:
To create a virtual environment in python3:

virtualenv -p /usr/bin/python3 virtualenvname

After creating the virtual environment, we need to activate it using the below command:

source virtualenvname/bin/activate

to deactivate use the below command:

deactivate

Title: How to create virtual env with python3

Body:
I am using python 2.7 + virtualenv version 1.10.1 for running myproject projects. Due to some other projects requirement I have to work with other version of python(Python 3.5) and Django 1.9. For this I have installed python in my user directory. Also I have dowloaded and installed virtualenv( version - 15.1.0) into my user directory.
But whenever I am trying to create virtual env I am getting the below error

python virtualenv/virtualenv.py myproject

Using base prefix '/home/myuser/python3'
New python executable in /home/mount/myuser/project_python3/myproject/bin/python
ERROR: The executable /home/mount/myuser/project_python3/myproject/bin/python is not functioning
ERROR: It thinks sys.prefix is '/home/myuser/python3' (should be '/home/mount/myuser/project_python3/myproject')
ERROR: virtualenv is not compatible with this system or executable

Can anybody tell what I am doing wrong with this